0% found this document useful (0 votes)
5 views9 pages

MLDA3

Uploaded by

X I S I R
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views9 pages

MLDA3

Uploaded by

X I S I R
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

DIGITAL ASSIGNMENT-3

MACHINE LEARNING
ELA

NAME: SHISIR PANDEY


REGNO:20BCE2873
1) DECISION TREE IMPLEMENTATION:
Dataset
NOW,SINCE THE MACHINE LEARNING ALGORITHM WORKS ON INTEGER
SO WE WILL CONVERT THE STRING TO THE INT.
2) SINGLE LAYER PERCEPTRON
IMPLEMENTATION:
CODE:
import numpy as np
import matplotlib.pyplot as plt

class Perceptron:
def __init__(self, learning_rate=0.1):
self.learning_rate = learning_rate

def train(self, X, y, epochs):


self.weights = np.zeros(X.shape[1])
self.bias = 0
errors = []
for epoch in range(epochs):
error = 0
for i in range(X.shape[0]):
y_pred = self.predict(X[i])
delta = y[i] - y_pred
self.weights += self.learning_rate * delta * X[i]
self.bias += self.learning_rate * delta
error += int(delta != 0.0)
errors.append(error)
return errors

def predict(self, x):


net = np.dot(self.weights, x) + self.bias
return 1 if net > 0 else 0

# Generate random data


np.random.seed(0)
X = np.random.randn(100, 2)
y = np.random.randint(2, size=100)

# Create and train the perceptron


p = Perceptron()
errors = p.train(X, y, epochs=10)
# Plot the decision boundary
x1 = np.linspace(-3, 3, 100)
x2 = -(p.weights[0] * x1 + p.bias) / p.weights[1]
plt.plot(x1, x2, color='red')

# Plot the data points


plt.scatter(X[:, 0], X[:, 1], c=y)

# Show the plot


plt.show()

SCREENSHOT:
3) KNN Algorithm implementation:
Code:
import numpy as np

X_train = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])

y_train = np.array(['a', 'b', 'c', 'd'])


X_test = np.array([[4, 5, 6]])

# Defining function for calculating Euclidean distance

def euclidean_distance(x1, x2):

return np.sqrt(np.sum((x1 - x2)**2))

# Defining function for KNN classification

def knn(X_train, y_train, X_test, k):

distances = [euclidean_distance(X_test, x) for x in X_train]

k_idx = np.argsort(distances)[:k]

k_nearest_labels = [y_train[i] for i in k_idx]

return max(set(k_nearest_labels), key=k_nearest_labels.count)

prediction = knn(X_train, y_train, X_test, k=3)

print(prediction)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy