AI and ML Lab Manual
AI and ML Lab Manual
Sub.Code : CS3491
Sub.Name : ARTIFICIAL INTELLIGENCE AND MACHINE LEARING LAB
Regulation : 2021
1
SYLLABUS
LIST OF EXPERIMENTS:
TOTAL: 30 PERIODS
2
LIST OF EXPERIMENTS
S.No Experiment 1 Pg.No Marks
Implementation of Uninformed search
1
algorithms (BFS, DFS)
Implementation of Informed search algorithms
2
(A*, memory-bounded A*)
3 Implement naïve Bayes models
3
Experiment 1: Implementation of Uninformed search algorithms (BFS)
AIM:
Write a Program to Implement Breadth First Search.
Procedure:
Create a graph with key – value pair.
Assign empty list as visited nodes.
Initialize a queue as queue.
Define the sub program as bfs and passing parameter as visited, graph and node.
Append the node in to visited and queue.
Creating loop to visit each node in Breadth First Search method.
Print the node which is visited in BFS method.
PROGRAM
graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}
visited = [] # List for visited nodes.
queue = [] #Initialize a queue
def bfs(visited, graph, node): #function for BFS
visited.append(node)
queue.append(node)
m = queue.pop(0)
4
for neighbour in graph[m]:
visited.append(neighbour)
queue.append(neighbour)
# Driver Code
OUTPUT
Result:
5
Experiment 2: Implementation of Uninformed search algorithms (DFS)
AIM:
Write a Program to Implement Depth First Search.
Procedure:
Create a graph with key – value pair.
Assign empty list as visited nodes.
Initialize a queue as queue.
Define the sub program as dfs and passing parameter as visited, graph and node.
Append the node in to visited and queue.
Creating loop to visit each node in Depth First Search method.
Print the node which is visited in DFS method.
PROGRAM
graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}
visited = set() # Set to keep track of visited nodes of graph.
print (node)
visited.add(node)
6
# Driver Code
OUTPUT
Result:
7
Experiment 3: Implementation of Informed search algorithms
(Hill Climbing Algorithm)
Aim:
Write a program to implement Hill Climbing Algorithm
Program:
import random
def randomSolution(tsp):
cities = list(range(len(tsp)))
solution = []
for i in range(len(tsp)):
solution.append(randomCity)
cities.remove(randomCity)
return solution
routeLength = 0
for i in range(len(solution)):
return routeLength
def getNeighbours(solution):
neighbours = []
for i in range(len(solution)):
neighbour = solution.copy()
neighbour[i] = solution[j]
neighbour[j] = solution[i]
8
neighbours.append(neighbour)
return neighbours
bestNeighbour = neighbours[0]
bestRouteLength = currentRouteLength
bestNeighbour = neighbour
def hillClimbing(tsp):
currentSolution = randomSolution(tsp)
neighbours = getNeighbours(currentSolution)
currentSolution = bestNeighbour
currentRouteLength = bestNeighbourRouteLength
neighbours = getNeighbours(currentSolution)
tsp = [
9
]
print(hillClimbing(tsp))
OUTPUT
Result:
10
Experiment 4: Implementation of Informed search algorithms
(A* Algorithm)
Aim:
Write a program to implement A* Algorithm.
Program:
def aStarAlgo(start_node, stop_node):
open_set = set(start_node)
closed_set = set()
g[start_node] = 0
parents[start_node] = start_node
n = None
for v in open_set:
n=v
pass
else:
#nodes 'm' not in first and last set are added to first
11
#n is set its parent
open_set.add(m)
parents[m] = n
#for each node m,compare its distance from start i.e g(m) to the
else:
#update g(m)
#change parent of m to n
parents[m] = n
if m in closed_set:
closed_set.remove(m)
open_set.add(m)
if n == None:
return None
if n == stop_node:
path = []
while parents[n] != n:
path.append(n)
12
n = parents[n]
path.append(start_node)
path.reverse()
return path
open_set.remove(n)
closed_set.add(n)
return None
def get_neighbors(v):
if v in Graph_nodes:
return Graph_nodes[v]
else:
return None
def heuristic(n):
H_dist = {
'A': 11,
'B': 6,
'C': 5,
'D': 7,
'E': 3,
'F': 6,
'G': 5,
13
'H': 3,
'I': 1,
'J': 0
return H_dist[n]
Graph_nodes = {
aStarAlgo('A', 'J')
OUTPUT
Result:
14
Experiment 5: Implement naïve Bayes models and Bayesian Networks
Aim:
Write a program to construct a Bayesian network considering medical data. Use this model to
demonstrate the diagnosis of heart patients using standard Heart Disease Data Set. You can
use Java/Python ML library classes/API.
Attribute Information:
-- Only 14 used
-- 1. #3 (age)
-- 2. #4 (sex)
-- 3. #9 (cp)
-- 4. #10 (trestbps)
-- 5. #12 (chol)
-- 6. #16 (fbs)
-- 7. #19 (restecg)
-- 8. #32 (thalach)
-- 9. #38 (exang)
-- 10. #40 (oldpeak)
-- 11. #41 (slope)
-- 12. #44 (ca)
-- 13. #51 (thal)
-- 14. #58 (num)
Program:
import numpy as np
import urllib
import pandas as pd
15
from pgmpy.inference import VariableElimination
names = ['age', 'sex', 'cp', 'trestbps', 'chol', 'fbs', 'restecg', 'thalach', 'exang', 'oldpeak', 'slope',
'ca', 'thal', 'heartdisease']
model.fit(heartDisease, estimator=MaximumLikelihoodEstimator)
HeartDisease_infer = VariableElimination(model)
q = HeartDisease_infer.query(variables=['heartdisease'])
print(q)
OUTPUT
╒════════════════╤════
│ heartdisease│ phi(heartdisease) │
╞══════════════════════
│ heartdisease_0 │0.5593 │
├─────────────────────┤
│ heartdisease_1 │0.4407 │
╘════════════════╧═════
Result:
16
Experiment 6: Build the Regression models in order to fit data points.
Select appropriate data set for your experiment and draw graphs.
Aim:
Write a program to build the Regression models in order to fit data points. Select appropriate
data set for your experiment and draw graphs.
Regression is a technique from statistics that is used to predict values of a desired target
quantity when the target quantity is continuous.
Program:
import matplotlib.pyplot as plt
import pandas as pd
17
iris = load_iris()
model = LinearRegression()
model.fit(X, y)
y_pred = model.predict(X)
plt.scatter(X, y, color='blue')
# Show plot
plt.show()
OUTPUT
18
Coefficient of determination (R-squared): 0.76
Result:
19
Experiment 7: Build decision trees and random forests
Aim:
Write a program to demonstrate the working of the decision tree based ID3 algorithm. Use an
appropriate data set for building the decision tree and apply this knowledge to classify a new
sample.
Program:
# Load libraries
import pandas as pd
from sklearn import metrics #Import scikit-learn metrics module for accuracy
calculation
df = pd.read_csv('zoo.csv')
feature_cols =
['feathers','eggs','milk','airborne','aquatic','predator','backbone','venomous','legs','tail'
]
X = df[feature_cols]
y = df['type']
clf = DecisionTreeClassifier()
clf = clf.fit(X_train,y_train)
y_pred = clf.predict(X_test)
print("Accuracy:",metrics.accuracy_score(y_test, y_pred))
20
from sklearn.tree import plot_tree
plt.figure(figsize=(20,10))
plt.savefig('diabetes.png')
Output:
Accuracy: 0.9354838709677419
Result:
21
Experiment 8: Build SVM Models
Aim:
Write a program to demonstrate the working of the SVM models. Use an appropriate data set
for building the SVM model and apply this knowledge to classify a new sample.
Program:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
dataset = pd.read_csv('Social_Network_Ads.csv')
X = dataset.iloc[:, [2, 3]].values
y = dataset.iloc[:, 4].values
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
from sklearn.svm import SVC
classifier = SVC(kernel = 'rbf', random_state = 0)
classifier.fit(X_train, y_train)
y_pred = classifier.predict(X_test)
from sklearn.metrics import confusion_matrix, accuracy_score
cm = confusion_matrix(y_test, y_pred)
print(cm)
accuracy_score(y_test,y_pred)
from matplotlib.colors import ListedColormap
X_set, y_set = X_test, y_test
X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1,
step = 0.01),np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))
22
plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(),
X2.ravel()]).T).reshape(X1.shape),
alpha=0.75, cmap=ListedColormap(('red', 'green')))
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
for i, j in enumerate(np.unique(y_set)):
plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],
c = ListedColormap(('red', 'green'))(i), label = j)
plt.title('SVM (Test set)')
plt.xlabel('Age')
plt.ylabel('Estimated Salary')
plt.legend()
plt.show()
OUTPUT
[[64 4]
[ 3 29]]
Result:
23
Experiment 9: Implement Ensemble techniques
Aim :
Write a program to demonstrate the working of the Ensemble techniques. Use an appropriate
data set for building the Ensemble techniques and apply this knowledge to classify a new
sample.
Program:
import pandas as pd
df = pd.read_csv('zoo.csv')
feature_cols =
['feathers','eggs','milk','airborne','aquatic','predator','backbone','venomous','legs','tail']
X = df[feature_cols]
y = df['type']
lr = LogisticRegression()
lr.fit(X_train, y_train)
rf = RandomForestClassifier(random_state=42)
rf.fit(X_train, y_train)
dt = DecisionTreeClassifier(random_state=42)
24
dt.fit(X_train, y_train)
testdata=[1,0,1,1,1,1,0,1,4,0]
lr_pred = lr.predict(X_new)
rf_pred = rf.predict(X_new)
dt_pred = dt.predict(X_new)
final_pred = pred_df.mode(axis=1)[0].values
print(pred_df)
print()
print("DECISION TREE")
class_names = df['type'].unique().tolist()
plt.figure(figsize=(20,10))
plt.savefig('Zoo.png')
25
Output:
Decision Tree
Result :
Thus the Ensemble Techniques Algorithm was successfully executed.
26
Experiment 9: Implement clustering algorithms
Aim:
To Write a python program to implement clustering algorithm.
Program:
import numpy as np
data = np.random.rand(100, 2)
k=3
kmeans = KMeans(n_clusters=k)
kmeans.fit(data)
labels = kmeans.labels_
27
# Get the centroids of the clusters
centroids = kmeans.cluster_centers_
for i in range(k):
plt.legend()
plt.show()
28
Output:
Result:
29