0% found this document useful (0 votes)
18 views29 pages

AI Lab Program SEM

Uploaded by

tk22417010
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
0% found this document useful (0 votes)
18 views29 pages

AI Lab Program SEM

Uploaded by

tk22417010
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/ 29

PROGRAM:(8 Puzzle)

import copy
from heapq import heappush, heappop
n=3
row = [1, 0, -1, 0]
col = [0, -1, 0, 1]
class priorityqueue:
def __init__(self):
self.heap = []
def push(self, k):
heappush(self.heap, k)
def pop(self):
return heappop(self.heap)
def empty(self):
return not self.heap
class node:
def __init__(self, mat, parent, empty_tile_pos, cost, level):
self.mat = mat
self.parent = parent
self.empty_tile_pos = empty_tile_pos
self.cost = cost
self.level = level
def __lt__(self, nxt):
return self.cost < nxt.cost
def calculatecost(mat, final):
count = 0
for i in range(n):
for j in range(n):
if (mat[i][j] and mat[i][j] != final[i][j]):
count += 1
return count
def newnode(mat, empty_tile_pos, new_empty_tile_pos,
parent, level, final):
new_mat = copy.deepcopy(mat)
x1 = empty_tile_pos[0]
y1 = empty_tile_pos[1]
x2 = new_empty_tile_pos[0]
y2 = new_empty_tile_pos[1]
new_mat[x1][y1], new_mat[x2][y2] = new_mat[x2][y2],
new_mat[x1][y1] cost = calculatecost(new_mat, final)
new_node = node(new_mat, parent, new_empty_tile_pos,
cost, level)
return new_node
def printmatrix(mat):
for i in range(n):
for j in range(n):
print("%d" % (mat[i][j]), end=' ')
print()
def issafe(x, y):
return x >= 0 and x < n and y >= 0 and y < n
def printpath(root):
if root == None:
return
printpath(root.parent)
printmatrix(root.mat)
print()
def solve(initial, empty_tile_pos, final):
pq = priorityqueue()
cost = calculatecost(initial, final)
root = node(initial, None, empty_tile_pos, cost, 0)
pq.push(root)
while not pq.empty():
minimum = pq.pop()
if minimum.cost == 0:
printpath(minimum)
return
for i in range(4):
new_tile_pos = [minimum.empty_tile_pos[0] + row[i],
minimum.empty_tile_pos[1] + col[i]]
if issafe(new_tile_pos[0], new_tile_pos[1]):
child = newnode(minimum.mat,
minimum.empty_tile_pos, new_tile_pos, minimum,
minimum.level + 1, final)
pq.push(child)
initial = [[1, 2, 3],
[5, 6, 0],
[7, 8, 4]]
final = [[1, 2, 3],
[5, 8, 6],
[0, 7, 4]]
empty_tile_pos = [1, 2]
solve(initial, empty_tile_pos, final)
OUTPUT:

123
560
784

123
506
784

123
586
704

123
586
074
PROGRAM:(8 Queens)

def is_safe(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, len(board), 1), range(col, -1, -1)):
if board[i][j] == 1:
return False
return True
def solve_n_queens(board, col):
if col >= len(board):
return True
for i in range(len(board)):
if is_safe(board, i, col):
board[i][col] = 1
if solve_n_queens(board, col + 1):
return True
board[i][col] = 0
return False
def print_solution(board):
for row in board:
print(' '.join(['Q' if x==1 else '*' for x in row]))
def solve_8_queens():
board = [[0 for _ in range(8)] for _ in range(8)]
if not solve_n_queens(board, 0):
print("No solution exists.")
else:
print_solution(board)
solve_8_queens()
OUTPUT:

Q*******
******Q*
****Q***
*******Q
*Q******
***Q****
*****Q**
**Q*****
PROGRAM:(Cryptarithmetic)

from itertools import permutations


def solve_cryptarithmetic():
for perm in permutations('0123456789',4):
t,o,g,u,=perm
to=int(t+o)
go=int(g+o)
out=int(o+u+t)
if to+go==out:
print(f"Solution found:TO={to},GO={go},OUT={out}")
solve_cryptarithmetic()
OUTPUT:

Solution found:TO=21,GO=81,OUT=102
PROGRAM:(A* Algorithm)

from collections import deque


class Graph:
def __init__(self, adjacency_list):
self.adj_list = adjacency_list
def get_neighbors(self, v):
return self.adj_list[v]
def h(self, n):
H = {'A':1, 'B':1, 'C':1, 'D':1}
return H[n]
def a_star_algorithm(self, start, stop):
open_set, closed_set = {start}, set()
g, parents = {start:0}, {start:start}
while open_set:
n = min(open_set, key=lambda x: g[x] + self.h(x))
if n == stop:
reconst_path = []
while parents[n] != n:
reconst_path.append(n)
n = parents[n]
reconst_path.append(start)
reconst_path.reverse()
print('Path found: {}'.format(reconst_path))
return reconst_path
for m, weight in self.get_neighbors(n):
if m not in open_set and m not in closed_set:
open_set.add(m)
parents[m] = n
g[m] = g[n] + weight
elif g[m] > g[n] + weight:
g[m], parents[m] = g[n] + weight, n
if m in closed_set:
closed_set.remove(m)
open_set.add(m)
open_set.remove(n)
closed_set.add(n)
print('Path does not exist!')
return None
adj_list = {'A': [('B', 1), ('C', 3), ('D', 7)], 'B': [('D', 5)], 'C': [('D', 12)]}
graph1 = Graph(adj_list)
graph1.a_star_algorithm('A', 'D')
OUTPUT:

P a th fo u n d : ['A ', 'B ', 'D ']


PROGRAM:(MINI – MAX)

MAX,MIN=1000,-1000
def minimax(depth, nodeIndex, maximizingPlayer, values,
alpha, beta):
if depth == 3:
return values[nodeIndex]
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)
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))
OUTPUT:

The optimal value is 5


PROGRAM:(CSP)

VARIABLES = ["csc", "maths", "phy", "che", "tam", "eng",


"bio"]
DOMAIN = ["Monday", "Tuesday", "Wednesday"]
CONSTRAINTS = [
("csc", "maths"),
("csc", "phy"),
("maths", "phy"),
("maths", "che"),
("maths", "tam"),
("phy", "tam"),
("phy", "eng"),
("che", "eng"),
("tam", "eng"),
("tam", "bio"),
("eng", "bio")
]
def backtrack(assignment):
if len(assignment) == len(VARIABLES):
return assignment
var = select_unassigned_variable(assignment)
for value in DOMAIN:
if consistent(var, value, assignment):
assignment[var] = value
result = backtrack(assignment)
if result is not None:
return result
assignment[var] = None
return None
def select_unassigned_variable(assignment):
for var in VARIABLES:
if var not in assignment.keys():
return var
def consistent(var, value, assignment):
for var1, var2 in CONSTRAINTS:
if var1 == var or var2 == var:
for var3, day in assignment.items():
if (var3 == var2 or var3 == var1) and day == value:
return False
return True
solution = backtrack(dict())
print("Constraint Satisfaction Problem:")
print(solution)
OUTPUT:

C o n s tra in t S a tis fa c tio n P ro b le m :


{'c s c ':'M o n d a y ’,m a th :T u e s d a y ,’p h y ’:
'W e d n e s d a y ','c h e':'M o n d a y ',
'ta m ':'M o n d a y ', 'e n g ': 'T u es d a y', 'b io': 'W e d n e s d a y '}
PROGRAM:(Propositional model checking)

def evaluate_expression(expression, model):


if expression[0] == '-':
return not evaluate_expression(expression[1:], model)
elif expression[0] == '(':
i=0
while expression[i] != ')':
i += 1
return evaluate_expression(expression[1:i], model)
and evaluate_expression(expression[i + 2:], model)
else:
return model.get(expression, True or False)
def check_model(formula, model):
formula = formula.replace(' ', '')
return evaluate_expression(formula, model)
if __name__ == '__main__':
formula = '(A or B) or (not C)'
model = {'A': True, 'B': False, 'C': True}
result = check_model(formula, model)
print(f'The model satisfies the formula: {result}')
OUTPUT:

T h e m o d el s a tis fie s th e fo rm u la : T ru e
PROGRAM:(Forward Chaining)

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


knowbase = ["Frog", "Canary", "Green", "Yellow"]
def display():
print("\n X is \n1..Croaks \n2.Eat Flies \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='')
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):
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):
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__":
OUTPUT:

*-----Forward--Chaining-----*
X is
1..Croaks
2.Eat Flies
3.shrimps
4.Sings
Select One : 1

Chance Of Frog
X is Croaks
Color Is 1.Green 2.Yellow
Select Option : 1
yes it is Frog And Color Is Green
PROGRAM:(Backward Chaining)

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('\n select an option:'))
if k == 1 and x == 1:
print(" yes it is in ", end='')
print(color[0], end='')
print(" colour and will ", end='')
print(database[0])
elif k == 2 and x == 2:
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__":
main()
OUTPUT:

*-----Backward--Chaining-----*
X is
1.frog
2.canary
Select One : 1

Chance Of eating flies


X is Frog
1.green
2.yellow

select an option:1
yes it is in Green colour and will Croaks
PROGRAM:(Resolution Strategies)

import random
def resolution_strategy(party1, party2):
print(f"Conflict resolution between {party1} and
{party2}")
for round in range(1, 4):
print(f"Negotiation Round {round}")
offer1 = random.randint(2, 2)
offer2 = random.randint(1, 3)
print(f"{party1} offers: {offer1}")
print(f"{party2} offers: {offer2}")
if offer1 == offer2:
print("Agreement reached!")
print(f"{party1} and {party2} agree on {offer1}")
break
else:
print("No agreement reached. Continue
negotiation.")
else:
print("Negotiation unsuccessful. Consider
alternative resolution methods.")
resolution_strategy("Party A", "Party B")
OUTPUT:

Conflict resolution between Party A and Party B


Negotiation Round 1
Party A offers: 2
Party B offers: 3
No agreement reached. Continue negotiation.
Negotiation Round 2
Party A offers: 2
Party B offers: 1
No agreement reached. Continue negotiation.
Negotiation Round 3
Party A offers: 2
Party B offers: 2
Agreement reached!
Party A and Party B agree on 2
PROGRAM:(Naive Bayes Model)

from sklearn import datasets


from sklearn.metrics import confusion_matrix
from sklearn.model_selection import train_test_split
from pandas import DataFrame
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score
iris = datasets.load_iris()
X = iris.data
Y = iris.target
X_train, X_test, Y_train, Y_test = train_test_split(X, Y,
test_size=1/3)
model = GaussianNB()
model.fit(X_train, Y_train)
model_predictions = model.predict(X_test)
print("\n",model_predictions)
print("\n",Y_test)
accuracyScore = accuracy_score(Y_test,
model_predictions)
print("\naccuracyScore is",accuracyScore )
cm=confusion_matrix(Y_test,model_predictions)
print("\nconfusion matrix",cm)
OUTPUT:

[2 1 0 1 1 1 0 0 0 1 1 2 0 1 0 0 1 2 2 2 0 0 2 2 1 2 0 1 0 0 1
121112
2 0 2 0 0 0 0 0 2 1 2 1 2]

[2 1 0 1 1 1 0 0 0 1 1 2 0 1 0 0 1 2 2 2 0 0 2 2 1 2 0 1 0 0 1
121112
2 0 2 0 0 0 0 0 2 1 2 1 2]

accuracyScore is 1.0

confusion matrix [[18 0 0]


[ 0 17 0]
[ 0 0 15]]
PROGRAM:(Bayesian Networks & Perform Inferences)

import numpy as np
from sklearn import datasets
import torch
import torch.nn as nn
import torch.optim as optim
import torchbnn as bnn
import matplotlib.pyplot as plt
dataset = datasets.load_iris()
data = dataset.data
target = dataset.target
data_tensor = torch.from_numpy(data).float()
target_tensor = torch.from_numpy(target).long()
model = nn.Sequential(
bnn.BayesLinear(prior_mu=0, prior_sigma=0.1,
in_features=4, out_features=100),
nn.ReLU(),
bnn.BayesLinear(prior_mu=0, prior_sigma=0.1,
in_features=100, out_features=3),
)
cross_entropy_loss = nn.CrossEntropyLoss()
klloss = bnn.BKLLoss(reduction='mean',
last_layer_only=False)
klweight = 0.01
optimizer = optim.Adam(model.parameters(), lr=0.01)
for step in range(3000):
models = model(data_tensor)
cross_entropy = cross_entropy_loss(models,
target_tensor)
kl = klloss(model)
total_cost = cross_entropy + klweight * kl
optimizer.zero_grad()
total_cost.backward()
optimizer.step()
_, predicted = torch.max(models.data, 1)
final = target_tensor.size(0)
correct = (predicted == target_tensor).sum()
print('- Accuracy: %f %%' % (100 * float(correct) /
final))
print('- CE : %2.2f, KL : %2.2f' % (cross_entropy.item(),
kl.item()))
def draw_graph(predicted):
fig = plt.figure(figsize=(16, 8))
fig_1 = fig.add_subplot(1, 2, 1)
fig_2 = fig.add_subplot(1, 2, 2)
z1_plot = fig_1.scatter(data[:, 0], data[:, 1], c=target,
marker='v')
z2_plot = fig_2.scatter(data[:, 0], data[:, 1],
c=predicted)
plt.colorbar(z1_plot, ax=fig_1)
plt.colorbar(z2_plot, ax=fig_2)
fig_1.set_title("REAL")
fig_2.set_title("PREDICT")
plt.show()
models = model(data_tensor)
_, predicted = torch.max(models.data, 1)
draw_graph(predicted)
OUTPUT:

You might also like