CS3491-AIML Lab Manual
CS3491-AIML Lab Manual
CS3491-AIML Lab Manual
NO:1
UNIFORMED SEARCH ALGORITHMS
DATE:
AIM:
ALGORITHM:
1. Create a graph
2. Initialize a starting node
3. Send the graph and initial node as parameters to the bfs function.
4. Mark the initial node as visited and push it into the queue
5. Explore the initial node and add its neighbours to the queue and remove the initial
node from the queue
6. Check if the neighbour node of an neighbouring node is already visited
7. If not,visit the neighbouring node neighbours and mark them as visited
8. Repeat this process until all the nodes in a graph are visited and the queue becomes
empty
PROGRAM:
from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def addEdge(self,u,v):
self.graph[u].append(v)
def BFS(self, s):
visited = [False] * (len(self.graph))
queue = []
queue.append(s)
visited[s] = True
while queue:
s = queue.pop(0)
print (s, end = " ")
for i in self.graph[s]:
if visited[i] == False:
queue.append(i)
visited[i] = True
g = Graph()
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)
print ("Following is Breadth First Traversal"
" (starting from vertex 2)")
g.BFS(2)
Output
Following is Breadth First Traversal (starting from vertex 2)
2031
2. (DFS) ALGORITHM:
PROGRAM:
from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def addEdge(self, u, v):
self.graph[u].append(v)
def DFSUtil(self, v, visited):
visited.add(v)
print(v, end=' ')
for neighbour in self.graph[v]:
if neighbour not in visited:
self.DFSUtil(neighbour, visited)
def DFS(self, v):
visited = set()
self.DFSUtil(v, visited)
if __name__ == "__main__":
g = Graph()
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)
print("Following is DFS from (starting from vertex 2)")
g.DFS(2)
Output
RESULT:
Thus the above programs are executed and the outputs are verified.
EX.NO:2
INFORMED SEARCH ALGORITHMS
DATE:
AIM:
1. Implement A* algorithm
ALGORITHM:
1. Firstly,Place the starting node into OPEN and find its f(n) value
2. Then remove the node from OPEN,having the smallest f(n) value. If it is a goal
node, then stop and return to success
3. Else remove the node from OPEN, and find all its successors
4. Find the f(n) value of all the successors,place them into OPEN,and place the
removed node into CLOSE
5. Go to Step-2
6. Exit
PROGRAM:
open_list = set([start_node])
closed_list = set([])
g = {}
g[start_node] = 0
parents = {}
parents[start_node] = start_node
for v in open_list:
if n == None or g[v] + self.h(v) < g[n] + self.h(n):
n = v;
if n == None:
print('Path does not exist!')
return None
if n == stop_node:
reconst_path = []
while parents[n] != n:
reconst_path.append(n)
n = parents[n]
reconst_path.append(start_node)
reconst_path.reverse()
else:
if g[m] > g[n] + weight:
g[m] = g[n] + weight
parents[m] = n
if m in closed_list:
closed_list.remove(m)
open_list.add(m)
open_list.remove(n)
closed_list.add(n)
OUTPUT:
Path found: ['A', 'B', 'D']
RESULT:
AIM:
ALGORITHM:
1. Importnecessarylibrariesandpackages
2. Load the dataset
3. Split the dataset into train data and test data
4. Load the Gaussian naïve Bayes algorithm
5. Train the algorithm with train data
6. Test the accuracy of the algorithm
PROGRAM:
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn import metrics
iris = load_iris()
X = iris.data
y=iris.target
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.4,random_state=1)
gnb = GaussianNB()
gnb.fit(X_train, y_train)
y_pred=gnb.predict(X_test)
print("GaussianNaiveBayesmodelaccuracy(in %):",metrics.accuracy_score(y_test, y_pred)*100)
OUTPUT:
RESULT:
ALGORITHM:
1. Import necessary packages and modules.
2. Load the Bayesian model
3. Initialize the Computation of joint probability and conditional probability Functions
4. Execute the probability functions for each node in the Bayesian network
5. Print the Joint Probability
PROGRAM:
import numpy as np
from scipy.stats import norm
node1 = ("Node1", [], {(): 0.5})
node2 = ("Node2", ["Node1"], {(True,): 0.7, (False,): 0.2})
node3 = ("Node3", ["Node1"], {(True,): 0.1, (False,): 0.8})
def compute_joint_prob(nodes):
joint_prob = 1.0
for node in nodes:
name, parents, cpt = node
parents_val_tuple = tuple(node_val[parent] for parent in parents)
prob = cpt[parents_val_tuple]
joint_prob *= prob
return joint_prob
def compute_cond_prob(node, node_val):
name, parents, cpt = node
parents_val_tuple = tuple(node_val[parent] for parent in parents)
prob = cpt[parents_val_tuple]
return prob
def sample_node(node, node_val):
prob = compute_cond_prob(node, node_val)
sample = np.random.binomial(1, prob)
return sample
node_val = {}
for node in [node1, node2, node3]:
sample = sample_node(node, node_val)
node_val[node[0]] = sample
joint_prob = compute_joint_prob([node1, node2, node3])
print("The joint probability is", joint_prob)
OUTPUT:
The joint probability is 0.08000000000000002
RESULT:
PROGRAM:
mymodel=list(map(myfunc,x))
print(mymodel)
plt.scatter(x, y)
plt.plot(x,mymodel)
plt.show()
OUTPUT:
RESULT:
AIM:
ALGORITHM:
PROGRAM:
2. Build random
forest ALGORITHM:
PROGRAM:
OUTPUT:
RESULT:
Thus the above programs are executed and the outputs are verified.
EX.NO:7
SVM MODEL
DATE:
AIM:
ALGORITHM:
PROGRAM:
OUTPUT:
RESULT:
AIM:
ALGORITHM:
PROGRAM:
OUTPUT:
RESULT:
AIM:
ALGORITHM:
PROGRAM:
OUTPUT:
RESULT:
AIM:
ALGORITHM:
PROGRAM:
impor tnumpy as np
import time
graphNodes=["a","b", "c","d", "e","f","g", "h"]
graphNodeIndices={}
for idx,node in enumerate(graphNodes):
graphNodeIndices[node] = idx
graphNodeNumStates={ "a"
: 3,
"b": 4,
"c": 5,
"d": 4,
"e": 3,
"f": 4,
"g": 5,
"h": 4
}
nodesToUpdate=["a","b","c","d","e","f","g","h"]
nodeParents = {
"a": [],
"b": [],
"c": ["a"],
"d":["a","b"],
"e":["a","c"],
"f": ["b", "d"],
"g": ["e"],
"h": ["f"]
}
tensorNodeOrder = {}
for nodeingraphNodes:
tensorNodeOrder[node]=[node]+nodeParents[node]
def randomTensorGenerator(shape):
return np.random.uniform(0.0,1.0,shape)
def conditionNodeOnParents(probTensor,node,tensorNodeOrder):
assert(node in tensorNodeOrder)
inferredDimension=tensorNodeOrder.index(node)
probTensor=probTensor/
np.expand_dims(np.sum(probTensor,inferredDimension),inferredDimension)
return probTensor
np.random.seed(0)
p = {}
for node in graphNodes:
tensorDimensions=[graphNodeNumStates[x]forxintensorNodeOrder[node]] p[node] =
randomTensorGenerator(tensorDimensions)
fornodein p:
p[node]=conditionNodeOnParents(p[node],tensorNodeOrder[node]
[0],tensorNodeOrder[node])
print("p("+node+"|" +str(nodeParents[node])+")dimensions:"+str(p[node].shape))
np.random.seed(int(time.time()))
phat={}
for node in p:
phat[node]=randomTensorGenerator(p[node].shape)
phat[node]=conditionNodeOnParents(phat[node],tensorNodeOrder[node]
[0],tensorNodeOrder[node])
print("phat("+node+"|"+str(nodeParents[node])+")dimensions:"+str(phat[node].shape))
OUTPUT:
RESULT:
AIM:
ALGORITHM:
PROGRAM:
RESULT:
AIM:
ALGORITHM:
PROGRAM:
OUTPUT:
RESULT: