Ai Lab
Ai Lab
Ai Lab
1 a)
class Graph:
def __init__(self, vertices):
self.V = vertices
self.adj = [[] for i in range(vertices)]
g = Graph(6)
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 3)
g.add_edge(1, 4)
g.add_edge(2, 4)
g.add_edge(3, 4)
g.add_edge(3, 5)
g.add_edge(4, 5)
print("BFS:")
g.bfs(0)
-----------------------------------------------------------------------------------
-------------------------------------
1 b)
class Graph:
def __init__(self, vertices):
self.V = vertices
self.adj = [[] for i in range(vertices)]
class Node:
def __init__(self, state, parent=None, g=0, h=0):
self.state = state
self.parent = parent
self.g = g
self.h = h
def f_score(self):
return self.g + self.h
class Graph:
def __init__(self, vertices, edges):
self.vertices = vertices
self.edges = edges
while open_list:
current_node = heapq.heappop(open_list)[1]
if current_node.state == goal_node.state:
path = []
while current_node:
path.append(current_node.state)
current_node = current_node.parent
return list(reversed(path))
closed_list.add(current_node.state)
for neighbor in graph.neighbors(current_node):
if neighbor.state in closed_list:
continue
new_g = current_node.g + 1
new_h = heuristic(neighbor.state, goal)
new_f = new_g + new_h
return None
print("A* Search:")
print(astar_search(graph, start, goal, heuristic))
-----------------------------------------------------------------------------------
-------------------------------------
2 b)
import heapq
class NaiveBayes:
def __init__(self):
self.features = list
self.likelihoods = {}
self.class_priors = {}
self.pred_priors = {}
self.X_train = np.array
self.y_train = np.array
self.train_size = int
self.num_feats = int
def _calc_class_prior(self):
""" P(c) - Prior Class Probability """
for outcome in np.unique(self.y_train):
outcome_count = sum(self.y_train == outcome)
self.class_priors[outcome] = outcome_count / self.train_size
def _calc_likelihoods(self):
""" P(x|c) - Likelihood """
for feature in self.features:
for outcome in np.unique(self.y_train):
outcome_count = sum(self.y_train == outcome)
feat_likelihood = self.X_train[feature][self.y_train[self.y_train
== outcome].index.values.tolist()].value_counts().to_dict()
for feat_val, count in feat_likelihood.items():
self.likelihoods[feature][feat_val + '_' + outcome] =
count/outcome_count
def _calc_predictor_prior(self):
""" P(x) - Evidence """
for feature in self.features:
feat_vals = self.X_train[feature].value_counts().to_dict()
for feat_val, count in feat_vals.items():
self.pred_priors[feature][feat_val] = count/self.train_size
def predict(self, X):
""" Calculates Posterior probability P(c|x) """
results = []
X = np.array(X)
for query in X:
probs_outcome = {}
for outcome in np.unique(self.y_train):
prior = self.class_priors[outcome]
likelihood = 1
evidence = 1
for feat, feat_val in zip(self.features, query):
likelihood *= self.likelihoods[feat][feat_val + '_' + outcome]
evidence *= self.pred_priors[feat][feat_val]
posterior = (likelihood * prior) / (evidence)
probs_outcome[outcome] = posterior
result = max(probs_outcome, key=lambda x: probs_outcome[x])
results.append(result)
return np.array(results)
if __name__ == "__main__":
# Weather Dataset
print("\nWeather Dataset:")
# Specify the path to your file in Google Drive
df = pd.read_table("/content/drive/MyDrive/TENNISDATACV/tennisdata.csv")
# Split features and target
X, y = pre_processing(df)
nb_clf = NaiveBayes()
nb_clf.fit(X, y)
print("Train Accuracy: {}".format(accuracy_score(y, nb_clf.predict(X))))
# Query 1:
query = np.array([['Rainy','Mild', 'Normal', 't']])
print("Query 1:- {} ---> {}".format(query, nb_clf.predict(query)))
# Query 2:
query = np.array([['Overcast','Cool', 'Normal', 't']])
print("Query 2:- {} ---> {}".format(query, nb_clf.predict(query)))
# Query 3:
query = np.array([['Sunny','Hot', 'High', 't']])
print("Query 3:- {} ---> {}".format(query, nb_clf.predict(query)))
-----------------------------------------------------------------------------------
-------------------------------------
4 )
from pgmpy.models import BayesianModel
from pgmpy.factors.discrete import TabularCPD
# Defining the model structure. We can define the network by just passing a list of
edges.
model = BayesianModel([('D', 'G'), ('I', 'G'), ('G', 'L'), ('I', 'S')])
# Check model checks for the network structure and CPDs and verifies that the CPDs
are correctly defined and sum to 1.
model.check_model()
-----------------------------------------------------------------------------------
-------------------------------------
5 a)
import matplotlib.pyplot as plt
from scipy import stats
x = [89, 43, 36, 36, 95, 10, 66, 34, 38, 20, 26, 29, 48, 64, 6, 5, 36, 66, 72, 40]
y = [21, 46, 3, 35, 67, 95, 53, 72, 58, 10, 26, 34, 90, 33, 38, 20, 56, 2, 47, 15]
def myfunc(x):
return slope * x + intercept
plt.scatter(x, y)
plt.plot(x, mymodel)
plt.show()
-----------------------------------------------------------------------------------
-------------------------------------
5b)
import numpy
import matplotlib.pyplot as plt
x = [1,2,3,5,6,7,8,9,10,12,13,14,15,16,18,19,21,22]
y = [100,90,80,60,60,55,60,65,70,70,75,76,78,79,90,99,99,100]
plt.scatter(x, y)
plt.plot(myline, mymodel(myline))
plt.show()
-----------------------------------------------------------------------------------
-------------------------------------
5c)
import pandas as pd
from sklearn import linear_model
# Predict CO2 emission for a car with weight 2300kg and volume 1300cm3
predictedCO2 = regr.predict([[2300, 1300]])
print(predictedCO2)
-----------------------------------------------------------------------------------
-------------------------------------
6)
import sys
import matplotlib
matplotlib.use('Agg')
import pandas as pd
from sklearn.tree import DecisionTreeClassifier, plot_tree
import matplotlib.pyplot as plt
from google.colab import drive
df = pd.read_csv(file_path)
d = {'YES': 1, 'NO': 0}
df['Go'] = df['Go'].map(d)
dtree = DecisionTreeClassifier()
dtree = dtree.fit(X, y)
-----------------------------------------------------------------------------------
-------------------------------------
11)import numpy as np
def sigmoid(z):
return 1/(1+np.exp(-z))
-----------------------------------------------------------------------------------
-------------------------------------