0% found this document useful (0 votes)
3 views

lab manual

The document is a lab manual detailing various machine learning algorithms and their implementations in Python, including A* Search, K-means clustering, Decision Trees, Agglomerative Clustering, and K-nearest neighbors. It provides code examples for each algorithm, along with explanations of the datasets used and the expected outputs. Additionally, it includes a section on probability calculations related to student absences on Fridays.

Uploaded by

nihalpj1
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

lab manual

The document is a lab manual detailing various machine learning algorithms and their implementations in Python, including A* Search, K-means clustering, Decision Trees, Agglomerative Clustering, and K-nearest neighbors. It provides code examples for each algorithm, along with explanations of the datasets used and the expected outputs. Additionally, it includes a section on probability calculations related to student absences on Fridays.

Uploaded by

nihalpj1
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Lab Manual

1. Implement A* Search Algorithm

A* Search Algorithm is a Path Finding Algorithm. It is similar to Breadth First


Search(BFS). It will search shortest path using heuristic value assigned to node
and actual cost from Source_node to Dest_node
Draw a polynomial regression line through the data points:
import numpy
import matplotlib.pyplot as plt
numpy.random.seed(2)

x = numpy.random.normal(3, 1, 100)
y = numpy.random.normal(150, 40, 100) / x

train_x = x[:80]
train_y = y[:80]

test_x = x[80:]
test_y = y[80:]

mymodel = numpy.poly1d(numpy.polyfit(train_x, train_y, 4))

myline = numpy.linspace(0, 6, 100)

plt.scatter(train_x, train_y)
plt.plot(myline, mymodel(myline))
plt.show()

output
2. K means

from sklearn.cluster import KMeans


import matplotlib.pyplot as plt

x = [4, 5, 10, 4, 3, 11, 14 , 6, 10, 12]


y = [21, 19, 24, 17, 16, 25, 24, 22, 21, 21]

plt.scatter(x, y)
plt.show()
data = list(zip(x, y))
inertias = []

for i in range(1,11):
kmeans = KMeans(n_clusters=i)
kmeans.fit(data)
inertias.append(kmeans.inertia_)

plt.plot(range(1,11), inertias, marker='o')


plt.title('Elbow method')
plt.xlabel('Number of clusters')
plt.ylabel('Inertia')
plt.show()

Output
3. Train data & test data accuracy

from sklearn import datasets


from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.tree import DecisionTreeClassifier

data = datasets.load_wine(as_frame = True)

X = data.data
y = data.target

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25,


random_state = 22)

dtree = DecisionTreeClassifier(random_state = 22)


dtree.fit(X_train,y_train)

y_pred = dtree.predict(X_test)

print("Train data accuracy:",accuracy_score(y_true = y_train, y_pred =


dtree.predict(X_train)))
print("Test data accuracy:",accuracy_score(y_true = y_test, y_pred = y_pred))

output
Train data accuracy: 1.0
Test data accuracy: 0.8222222222222222
4. AgglomerativeClustering
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import AgglomerativeClustering

x = [4, 5, 10, 4, 3, 11, 14 , 6, 10, 12]


y = [21, 19, 24, 17, 16, 25, 24, 22, 21, 21]

data = list(zip(x, y))

hierarchical_cluster = AgglomerativeClustering(n_clusters=2,
affinity='euclidean', linkage='ward')
labels = hierarchical_cluster.fit_predict(data)

plt.scatter(x, y, c=labels)
plt.show()

output

5. Dendrogram, linkage
import numpy as np
import matplotlib.pyplot as plt
from scipy.cluster.hierarchy import dendrogram, linkage

x = [4, 5, 10, 4, 3, 11, 14 , 6, 10, 12]


y = [21, 19, 24, 17, 16, 25, 24, 22, 21, 21]
data = list(zip(x, y))

linkage_data = linkage(data, method='ward', metric='euclidean')


dendrogram(linkage_data)

plt.show()

output

6. Implement k-nearest neighbours classification using python

''' Aim : Implement k-nearest neighbours classification using python.

=================================
Explanation:
=================================

===> To run this program you need to install the sklearn Module

===> Open Command propmt and then execute the following command to insta
ll sklearn Module

---> pip install scikit-learn

-----------------------------------------------
In this program, we are going to use iris dataset.And this dataset Split into
training(70%) and test set(30%).

The iris dataset conatins the following features

---> sepal length (cm)


---> sepal width (cm)
---> petal length (cm)
---> petal width (cm)

The Sample data in iris dataset format is [5.4 3.4 1.7 0.2]

Where 5.4 ---> sepal length (cm)


3.4 ---> sepal width (cm)
1.7 ---> petal length (cm)
0.2 ---> petal width (cm)

===============================
Source Code :
===============================

'''
# Import necessary modules
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
import random

# Loading data
data_iris = load_iris()

# To get list of target names


label_target = data_iris.target_names
print()
print("Sample Data from Iris Dataset")
print("*"*30)
# to display the sample data from the iris dataset
for i in range(10):
rn = random.randint(0,120)
print(data_iris.data[rn],"===>",label_target[data_iris.target[rn]])

# Create feature and target arrays


X = data_iris.data
y = data_iris.target

# Split into training and test set


X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size = 0.3, random_state=1)

print("The Training dataset length: ",len(X_train))


print("The Testing dataset length: ",len(X_test))
try:
nn = int(input("Enter number of neighbors :"))
knn = KNeighborsClassifier(nn)

knn.fit(X_train, y_train)
# to display the score
print("The Score is :",knn.score(X_test, y_test))
# To get test data from the user
test_data = input("Enter Test Data :").split(",")
for i in range(len(test_data)):
test_data[i] = float(test_data[i])
print()

v = knn.predict([test_data])
print("Predicted output is :",label_target[v])
except:
print("Please supply valid input......")
output
7. Given the following data, which specify classifications for nine
ombinationsof VAR1 and VAR2 predict a classification for a case
where VAR1=0.906and VAR2=0.606, using the result of k-means
clustering with 3 means (i.e., 3centroids

from sklearn.cluster import KMeans

import numpy as np
X = np.array([[1.713,1.586], [0.180,1.786], [0.353,1.240],
[0.940,1.566], [1.486,0.759], [1.266,1.106],[1.540,0.419],[0.459,1.799],[0.773,0
.186]])

y=np.array([0,1,1,0,1,0,1,1,1])
kmeans = KMeans(n_clusters=3, random_state=0).fit(X,y)
print("The input data is ")
print("VAR1 \t VAR2 \t CLASS")
i=0
for val in X:
print(val[0],"\t",val[1],"\t",y[i])
i+=1
print("="*20)
# To get test data from the user
print("The Test data to predict ")
test_data = []
VAR1 = float(input("Enter Value for VAR1 :"))
VAR2 = float(input("Enter Value for VAR2 :"))
test_data.append(VAR1)
test_data.append(VAR2)
print("="*20)
print("The predicted Class is : ",kmeans.predict([test_data]))
Output
The input data is
VAR1 VAR2 CLASS
1.713 1.586 0
0.18 1.786 1
0.353 1.24 1
0.94 1.566 0
1.486 0.759 1
1.266 1.106 0
1.54 0.419 1
0.459 1.799 1
0.773 0.186 1
====================
The Test data to predict
Enter Value for VAR1 :1.786
Enter Value for VAR2 :2.677
====================
The predicted Class is : [2]

8. The probability that it is Friday and that a student is absent is 3%

# The probability that it is Friday and that a student is absent is 3%

pAF=0.03
print("The probability that it is Friday and that a student is absent :",pAF)

# The probability that it is Friday is 20%


pF=0.2
print("The probability that it is Friday : ",pF)
# The probability that a student is absent given that today is Friday
pResult=(pAF/pF)

# Display the Result


print("The probability that a student is absent given that today is Friday :
",pResult * 100,"%")
output
The probability that it is Friday and that a student is absent : 0.03
The probability that it is Friday : 0.2
The probability that a student is absent given that today is Friday :
15.0 %

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