100% found this document useful (1 vote)
454 views

AI Lab manual-1

The AI Lab Manual provides Python implementations for various algorithms including Breadth First Search, Depth First Search, 8-Puzzle problem, N-Queens problem, Alpha-Beta Pruning, Forward and Backward Chaining, KNN for Iris dataset classification, Linear Regression, Naïve Bayesian Classifier, and SVM classifier. Each section includes code snippets and outputs demonstrating the functionality of the algorithms. The manual serves as a comprehensive guide for implementing fundamental AI algorithms in Python.

Uploaded by

abrahamsamuelus
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
454 views

AI Lab manual-1

The AI Lab Manual provides Python implementations for various algorithms including Breadth First Search, Depth First Search, 8-Puzzle problem, N-Queens problem, Alpha-Beta Pruning, Forward and Backward Chaining, KNN for Iris dataset classification, Linear Regression, Naïve Bayesian Classifier, and SVM classifier. Each section includes code snippets and outputs demonstrating the functionality of the algorithms. The manual serves as a comprehensive guide for implementing fundamental AI algorithms in Python.

Uploaded by

abrahamsamuelus
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

AI Lab Manual

1. Write a program to implement breadth first search using python.


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)

while queue: # Creating loop to visit each node


m = queue.pop(0)
print (m, end = " ")

for neighbour in graph[m]:


if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)

# Driver Code
print("Following is the Breadth-First Search")
bfs(visited, graph, '5') # function calling

BGS FGC AI lab manual


Output:
Following is the Breadth-First Search
5 37248

2. Write a Program to Implement Depth First Search using Python.

BGS FGC AI lab manual


Output:
following is the depth-first search
5
3
2
4
8
7

3.Write a Program to Implement 8-Puzzle problem using Python


class Solution:
def solve(self, board):
dict = {}
flatten = []
for i in range(len(board)):
flatten += board[i]
flatten = tuple(flatten)

dict[flatten] = 0

if flatten == (0, 1, 2, 3, 4, 5, 6, 7, 8):


return 0

return self.get_paths(dict)

def get_paths(self, dict):

BGS FGC AI lab manual


cnt = 0
while True:
current_nodes = [x for x in dict if dict[x] ==
cnt]
if len(current_nodes) == 0:
return -1

for node in current_nodes:


next_moves = self.find_next(node)
for move in next_moves:
if move not in dict:
dict[move] = cnt + 1
if move == (0, 1, 2, 3, 4, 5, 6, 7, 8):
return cnt + 1
cnt += 1

def find_next(self, node):


moves = {
0: [1, 3],
1: [0, 2, 4],
2: [1, 5],
3: [0, 4, 6],
4: [1, 3, 5, 7],
5: [2, 4, 8],
6: [3, 7],
7: [4, 6, 8],
8: [5, 7],
}

results = []
pos_0 = node.index(0)
for move in moves[pos_0]:
new_node = list(node)
new_node[move], new_node[pos_0] =
new_node[pos_0], new_node[move]
results.append(tuple(new_node))

return results
ob = Solution()
matrix = [
[3, 1, 2],
[4, 7, 5],
[6, 8, 0]
]
print(ob.solve(matrix))

BGS FGC AI lab manual


Output:
4

4.
Write a program to implement N-queens problem using python.

N=4
def printSolution(board):
for i in range(N):
for j in range(N):
print (board[i][j],end=' ')
print()
def isSafe(board, row, col):
for i in range(col):
if board[row][i] == 1:
return False
for i, j in zip(range(row, -1, -1), range(col, -1, -1)):
if board[i][j] == 1:
return False
for i, j in zip(range(row, N, 1), range(col, -1, -1)):
if board[i][j] == 1:
return False
return True
def solveNQUtil(board, col):
if col >= N:
return True
for i in range(N):
if isSafe(board, i, col):
board[i][col] = 1
if solveNQUtil(board, col + 1) == True:
return True
board[i][col] = 0
return False
def solveNQ():

BGS FGC AI lab manual


board = [ [0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]
]
if solveNQUtil(board, 0) == False:
print ("Solution does not exist")
return False
printSolution(board)
return True
solveNQ()

BGS FGC AI lab manual


Output:
0010
1000
0001
0 100

5. Write a Program to Implement Alpha-Beta Pruning using Python.


MAX, MIN = 1000, -1000
def minimax(depth, nodeIndex, maximizingPlayer,
values, alpha, beta):
if depth == 3:
return values[nodeIndex]

BGS FGC AI lab manual


if maximizingPlayer:

best = MIN
for i in range(0, 2):

val = minimax(depth + 1, nodeIndex * 2 + i,


False, values, alpha, beta)
best = max(best, val)
alpha = max(alpha, best)
if beta <= alpha:
break
return best

else:
best = MAX
for i in range(0, 2):

val = minimax(depth + 1, nodeIndex * 2 + i,


True, values, alpha, beta)
best = min(best, val)
beta = min(beta, best)

# Alpha Beta Pruning


if beta <= alpha:
break
return best

if __name__ == "__main__":

values = [3, 5, 6, 9, 1, 2, 0, -1]


print("The optimal value is :", minimax(0, 0, True, values, MIN, MAX))

BGS FGC AI lab manual


Output:
The optimal value is : 5

6.Write a program to implement forward chaining algorithm.

database = ["Croaks", "Eat Flies", "Shrimps", "Sings"]


knowbase = ["Frog", "Canary", "Green", "Yellow"]
def display():
print("\ X is \n1.. croaks \n2. Eat files \n3. shrimps \n4.Sings",end='')
print("\n Select one",end='')
def main():
print("*-----Forward--Chaining-----*", end='')
display()
x = int(input())
print(" \n", end='')
if x == 1 or x == 2:
print(" Chance Of Frog ", end='')
elif x == 3 or x == 4:
print(" Chance of Canary ", end='')

BGS FGC AI lab manual


else:
print("\n-------In Valid Option Select --------", end='')
if x >= 1 and x <= 4:
print("\n X is ", end='')
print(database[x-1], end='')
print("\n Color Is 1.Green 2.Yellow", end='')
print("\n Select Option ", end='')
k = int(input())
if k == 1 and (x == 1 or x == 2): # frog0 and green1
print(" yes it is ", end='')
print(knowbase[0], end='')
print(" And Color Is ", end='')
print(knowbase[2], end='')
elif k == 2 and (x == 3 or x == 4): # canary1 and yellow3
print(" yes it is ", end='')
print(knowbase[1], end='')
print(" And Color Is ", end='')
print(knowbase[3], end='')
else:
print("\n---InValid Knowledge Database", end='')
if __name__ == "__main__":
main()

BGS FGC AI lab manual


Output:
*-----Forward--Chaining-----*\ X is
1.. croaks
2. Eat files
3. shrimps
4.Sings
Select one3

Chance of Canary
X is Shrimps
Color Is 1.Green 2.Yellow
Select Option 2
yes it is Canary And Color Is Yellow

7.Write a program to implement backward chaining algorithm.


database = ["Croaks", "Eat Flies", "Shrimps", "Sings"]
knowbase = ["Frog", "Canary"]
color = ["Green", "Yellow"]
def display():
print("\n X is \n1.frog \n2.canary ", end='')
print("\n Select One ", end='')
def main():
print("*-----Backward--Chaining-----*", end='')
display()
x = int(input())
print(" \n", end='')
if x == 1:
print(" Chance Of eating flies ", end='')
elif x == 2:
print(" Chance of shrimping ", end='')
else:
print("\n-------In Valid Option Select --------", end='')
if x >= 1 and x <= 2:
print("\n X is ", end='')
print(knowbase[x-1], end='')
print("\n1.green \n2.yellow")
k = int(input())
if k == 1 and x == 1: # frog0 and green1
print(" yes it is in ", end='')
print(color[0], end='')
print(" colour and will ", end='')
print(database[0])
elif k == 2 and x == 2: # canary1 and yellow3
print(" yes it is in", end='')
print(color[1], end='')
print(" Colour and will ", end='')
print(database[1])
else:
print("\n---InValid Knowledge Database", end='')
if __name__ == "__main__":

BGS FGC AI lab manual


main()

8.Write a program to implement KNN algorithm to classify Iris dataset. Print both correct
and wrong predictions.

import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
data = pd.read_csv('iris_csv.csv')
data.head()
X = data.iloc[:,:-1]
X.head()

BGS FGC AI lab manual


y = data.iloc[:,-1]
X_train,X_test,y_train,y_test =
train_test_split(X,y,test_size=0.2,random_state=42)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
knn = KNeighborsClassifier(n_neighbors=3)
knn.fit(X_train, y_train)
y_pred = knn.predict(X_test)

acc = accuracy_score(y_test,y_pred)
print("Accuracy",acc)

Output:
Accuracy 1.0

9. Train a random data sample using linear regression model and plot the graph

import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
np.random.seed(0)
X=2*np.random.rand(100,1)
y=4+3*X+np.random.randn(100,1)
model=LinearRegression()
model.fit(X,y)
X_new=np.array([[0],[2]])
y_pred=model.predict(X_new)
plt.scatter(X,y,color='blue')
plt.plot(X_new,y_pred,color='red')
plt.xlabel('X')
plt.ylabel('y')
plt.title('Linear Regression')
plt.show()

BGS FGC AI lab manual


Output:

10. 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.
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score, confusion_matrix
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
data = pd.read_csv('iris_csv.csv')
data.head()
X = data.iloc[:,:-1]

BGS FGC AI lab manual


X.head()
y = data.iloc[:,-1]
X_train,X_test,y_train,y_test =
train_test_split(X,y,test_size=0.2,random_state=42)
y_test.shape
X = preprocessing.StandardScaler().fit_transform(X)
naive_bayes = GaussianNB()
naive_bayes.fit(X_train,y_train)
y_pred = naive_bayes.predict(X_test)
acc = accuracy_score(y_test,y_pred)
print("Accuracy",acc)
conf_matrix = confusion_matrix(y_test,y_pred)
print("Confusion matrix")
print(conf_matrix)

Output:
Accuracy 1.0
Confusion matrix
[[10 0 0]
[ 0 9 0]
[ 0 0 11]]

11.Demonstrate the working of SVM classifier for a suitable data set(e.g., iris dataset)

import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score, confusion_matrix
from sklearn.datasets import load_iris
data = pd.read_csv('iris_csv.csv')
data.head()
X = data.iloc[:,:-1]
y = data.iloc[:,-1]
X_train, X_test, y_train, y_test = train_test_split(X, y,
test_size=0.2, random_state=42)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
svm_classifier = SVC(kernel='linear', random_state=42)
svm_classifier.fit(X_train, y_train)
y_pred = svm_classifier.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
conf_matrix = confusion_matrix(y_test, y_pred)
print("Confusion Matrix:")

BGS FGC AI lab manual


print(conf_matrix)

Accuracy: 0.9666666666666667
Confusion Matrix:
[[10 0 0]
[ 0 8 1]
[ 0 0 11]]

BGS FGC AI lab manual

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