AIML Lab Manual
AIML Lab Manual
AIML Lab Manual
Lab Manual
PSO’s
PSO1:- Ability to adapt to a rapidly changing environment by learning and employing new
programming skills and technologies.
PSO2:- Ability to use diverse knowledge across the domains with inter-personnel skills to
deliver the Industry need
Course Learning Objectives: This course (18CSL76) will enable students to:
Implement and evaluate AI and ML algorithms in and Python programming language.
Descriptions (if any):
Installation procedure of the required software must be demonstrated, carried out in groups and
documented in the journal.
Programs List:
1. Implement A* Search algorithm.
2. Implement AO* Search algorithm.
3. For a given set of training data examples stored in a .CSV file, implement and demonstrate the
Candidate-Elimination algorithm to output a description of the set of all hypotheses consistent with
the training examples.
4. 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.
5. Build an Artificial Neural Network by implementing the Back propagation algorithm and test the
Same using appropriate data sets.
6. Write a program to implement the naïve Bayesian classifier for a sample training data set stored as
a .CSV file. Compute the accuracy of the classifier, considering few test data sets.
7. Apply EM algorithm to cluster a set of data stored in a .CSV file. Use the same data set for
clustering using k-Means algorithm. Compare the results of these two algorithms and comment on
the quality of clustering. You can add Java/Python ML library classes/API in the program.
8. Write a program to implement k-Nearest Neighbour algorithm to classify the iris data set. Print
Both correct and wrong predictions. Java/Python ML library classes can be used for this problem.
9. Implement the non-parametric Locally Weighted Regression algorithm in order to fit data points.
Select appropriate data set for your experiment and draw graphs
PROGRAM.NO.1
Implement A* Search algorithm.
from collections import deque
class Graph:
def init (self, adjac_lis):
self.adjac_lis = adjac_lis
par = {}
par[start] = start
if n == None:
print('Path does not exist')
return None
if n == stop:
reconst_path = []
while par[n] != n:
reconst_path.append(n)
n = par[n]
reconst_path.append(start)
reconst_path.reverse()
print('Path found: {}'.format(reconst_path))
return reconst_path
open_lst.remove(n)
closed_lst.add(n)
adjac_lis = {
'A': [('B', 1), ('C', 3), ('D', 7)],
'B': [('D', 5)],
'C': [('D', 12)]
}
graph1 = Graph(adjac_lis)
graph1.a_star_algorithm('A', 'D')
OUTPUT:-
PROGRAM.No.2(AO* Algorithm)
AO* Algorithm
AO* Algorithm basically based on problem decomposition (Breakdown problem into small pieces)
When a problem can be divided into a set of sub problems, where each sub problem can be solved
separately and a combination of these will be a solution, AND-OR graphs or AND - OR trees are used
for representing the solution.
The decomposition of the problem or problem reduction generates AND arcs.
AND-OR Graph
class Graph:
def init (self, graph, heuristicNodeList,
startNode): # instantiate graph object with graph
topology, heuristic values, start node
self.graph = graph
self.H = heuristicNodeList
self.start = startNode
self.parent = {}
self.status = {}
self.solutionGraph = {}
def printSolution(self):
print("FOR GRAPH SOLUTION, TRAVERSE THE GRAPH FROM THE START
NODE:", self.start)
print("-
")
print(self.solutionGraph)
print("-
")
costToChildNodeListDict[minimumCost] = nodeList #
set the Minimum Cost child node/s
return minimumCost, costToChildNodeListDict[minimumCost] #
return Minimum Cost and Minimum Cost child node/s
print("Graph - 1")
Output:
Graph - 1
HEURISTIC VALUES : {'A': 1, 'B': 6, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 5, 'H': 7, 'I': 7, 'J': 1}
SOLUTION GRAPH : {}
PROCESSING NODE : A
10 ['B', 'C']
HEURISTIC VALUES : {'A': 10, 'B': 6, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 5, 'H': 7, 'I': 7, 'J': 1}
SOLUTION GRAPH : {}
PROCESSING NODE : B
6 ['G']
HEURISTIC VALUES : {'A': 10, 'B': 6, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 5, 'H': 7, 'I': 7, 'J': 1}
SOLUTION GRAPH : {}
PROCESSING NODE : A
10 ['B', 'C']
HEURISTIC VALUES : {'A': 10, 'B': 6, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 5, 'H': 7, 'I': 7, 'J': 1}
SOLUTION GRAPH : {}
PROCESSING NODE : G
8 ['I']
HEURISTIC VALUES : {'A': 10, 'B': 6, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 8, 'H': 7, 'I': 7, 'J': 1}
SOLUTION GRAPH : {}
PROCESSING NODE : B
8 ['H']
HEURISTIC VALUES : {'A': 10, 'B': 8, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 8, 'H': 7, 'I': 7, 'J': 1}
SOLUTION GRAPH : {}
PROCESSING NODE : A
12 ['B', 'C']
HEURISTIC VALUES : {'A': 12, 'B': 8, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 8, 'H': 7, 'I': 7, 'J': 1}
SOLUTION GRAPH : {}
PROCESSING NODE : I
0 []
HEURISTIC VALUES : {'A': 12, 'B': 8, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 8, 'H': 7, 'I': 0, 'J': 1}
PROCESSING NODE : G
1 ['I']
HEURISTIC VALUES : {'A': 12, 'B': 8, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 1, 'H': 7, 'I': 0, 'J': 1}
PROCESSING NODE : B
2 ['G']
HEURISTIC VALUES : {'A': 12, 'B': 2, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 1, 'H': 7, 'I': 0, 'J': 1}
PROCESSING NODE : A
6 ['B', 'C']
HEURISTIC VALUES : {'A': 6, 'B': 2, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 1, 'H': 7, 'I': 0, 'J': 1}
PROCESSING NODE : C
2 ['J']
HEURISTIC VALUES : {'A': 6, 'B': 2, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 1, 'H': 7, 'I': 0, 'J': 1}
PROCESSING NODE : A
6 ['B', 'C']
HEURISTIC VALUES : {'A': 6, 'B': 2, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 1, 'H': 7, 'I': 0, 'J': 1}
PROCESSING NODE : J
0 []
HEURISTIC VALUES : {'A': 6, 'B': 2, 'C': 2, 'D': 12, 'E': 2, 'F': 1, 'G': 1, 'H': 7, 'I': 0, 'J': 0}
SOLUTION GRAPH : {'I': [], 'G': ['I'], 'B': ['G'], 'J': []}
PROCESSING NODE : C
1 ['J']
HEURISTIC VALUES : {'A': 6, 'B': 2, 'C': 1, 'D': 12, 'E': 2, 'F': 1, 'G': 1, 'H': 7, 'I': 0, 'J': 0}
SOLUTION GRAPH : {'I': [], 'G': ['I'], 'B': ['G'], 'J': [], 'C': ['J']}
PROCESSING NODE : A
5 ['B', 'C']
FOR GRAPH SOLUTION, TRAVERSE THE GRAPH FROM THE START NODE: A
{'I': [], 'G': ['I'], 'B': ['G'], 'J': [], 'C': ['J'], 'A': ['B', 'C']}
For a given set of training data examples stored in a .CSV file, implement and demonstrate the
Candidate-Elimination algorithm to output a description of the set of all hypotheses consistent
with the training examples.
import numpy as np
import pandas as pd
specific_h = concepts[0].copy()
# find indices where we have empty rows, meaning those that are
unchanged
Final S:
['Sunny' 'Warm' '?' 'Strong' '?' '?']
Final G:
[['Sunny', '?', '?', '?', '?', '?'], ['?', 'Warm', '?', '?', '?', '?']]
import math
import csv
def load_csv(filename):
lines = csv.reader(open(filename, "r"))
dataset = list(lines)
headers = dataset.pop(0)
return dataset, headers
class Node:
def entropy(S):
attr = list(set(S))
if len(attr) == 1: # if all are +ve/-ve then entropy = 0
return 0
counts = [0, 0] # Only two values possible 'yes' or 'no'
for i in range(2):
counts[i] = sum([1 for x in S if attr[i] == x]) / (len(S) *
1.0)
sums = 0
for cnt in counts:
sums += -1 * cnt * math.log(cnt, 2)
return sums
print("The decision tree for the dataset using ID3 algorithm is ")
print_tree(node, 0)
Output:
import numpy as np
X = np.array(([2, 9], [1, 5], [3, 6]), dtype=float)
y = np.array(([92], [86], [89]), dtype=float)
X = X/np.amax(X, axis=0)
y = y/100
def sigmoid(x):
return 1/(1+np.exp(-x))
def derivatives_sigmoid(x):
return x*(1-x)
epoch = 7000
lr = 0.1
inputLayer_neurons = 2
hiddenLayer_neurons = 3
output_neurons = 1
wh = np.random.uniform(size=(inputLayer_neurons, hiddenLayer_neurons))
bh = np.random.uniform(size=(1, hiddenLayer_neurons))
wout = np.random.uniform(size=(hiddenLayer_neurons, output_neurons))
bout = np.random.uniform(size=(1, output_neurons))
for i in range(epoch):
hinp1 = np.dot(X, wh)
hinp = hinp1 + bh
hlayer_act = sigmoid(hinp)
outinp1 = np.dot(hlayer_act, wout)
outinp = outinp1 + bout
output = sigmoid(outinp)
EO = y - output
outgrad = derivatives_sigmoid(output)
d_output = EO * outgrad
EH = d_output.dot(wout.T)
hiddengrad = derivatives_sigmoid(hlayer_act)
d_hiddenlayer = EH * hiddengrad
wout += hlayer_act.T.dot(d_output)*lr
wh += X.T.dot(d_hiddenlayer)*lr
OUTPUT:-
Input:
[[0.66666667 1. ]
[0.33333333 0.55555556]
[1. 0.66666667]]
Actual Output:
[[0.92]
[0.86]
[0.89]]
Predicted output:
[[0.89871247]
[0.871736 ]
[0.89883643]]
import pandas as pd
msg=pd.read_csv('naivetext1.csv', names=['message', 'label'])
print('The dimensions of the dataset', msg.shape)
msg['labelnum']=msg.label.map({'pos': 1, 'neg': 0})
X=msg.message
y=msg.labelnum
#print(X)
#print(y)
#splitting the dataset into train and test data
data = pd.read_csv('data/ex.csv')
f1 = data['V1'].values f2 =
data['V2'].values X =
np.array(list(zip(f1, f2)))
print("x: ", X)
plt.show()
PROGRAM .NO.8(KNN)
Write a program to implement k-Nearest Neighbor algorithm to classify the iris data set. Print
both correct and wrong predictions. Java/Python ML library classes can be used for this
problem.
OUTPUT:-
accuracy 0.97 30
macro avg 0.96 0.97 0.97 30
weighted avg 0.97 0.97 0.97 30
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# set k here
ypred = localWeightRegression(X, mtip, 0.5)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.scatter(bill, tip, color='green')
ax.plot(xsort[:, 1], ypred[SortIndex], color='red', linewidth=5)
plt.xlabel('Total bill')
plt.ylabel('Tip')
plt.show()
OUTPUT:-