0% found this document useful (0 votes)
29 views14 pages

Py Lab Programs

The document discusses 10 different machine learning algorithms: 1) Breadth-first search (BFS) on graphs, 2) Depth-first search (DFS) on graphs, 3) Solving the 8-puzzle problem using A* search, 4) Solving the N-queens problem, 5) Minimax algorithm for game trees, 6) Forward chaining in rule-based expert systems, 7) Backward chaining in rule-based expert systems, 8) K-nearest neighbors (KNN) classification algorithm, 9) Linear regression, 10) Naive Bayes classification.

Uploaded by

balakrishna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views14 pages

Py Lab Programs

The document discusses 10 different machine learning algorithms: 1) Breadth-first search (BFS) on graphs, 2) Depth-first search (DFS) on graphs, 3) Solving the 8-puzzle problem using A* search, 4) Solving the N-queens problem, 5) Minimax algorithm for game trees, 6) Forward chaining in rule-based expert systems, 7) Backward chaining in rule-based expert systems, 8) K-nearest neighbors (KNN) classification algorithm, 9) Linear regression, 10) Naive Bayes classification.

Uploaded by

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

1.

bfs

graph={
'A':['B','C'],
'B':['D','E'],
'C':['F'],
'D':[],
'E':['F'],
'F':[]
}
visited=[]
queue=[]
def bfs(visted,graph,node):
visted.append(node)
queue.append(node)
while queue:
S=queue.pop(0)
print(S,end=" ")
for neighbour in graph[S]:
if neighbour not in visted:
visted.append(neighbour)
queue.append(neighbour)
bfs(visited,graph,'A')

output:-

ABCDEF

2.dfs

graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
}
visited = set()

def dfs(visted, graph, node):


if node not in visted:
print(node)
visted.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)
dfs(visited, graph, 'A')

output:-

3.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):
if not self.heap:
return True
else:
return False

class node:
def __init__(self, parent, mat, empty_tile_pos,
cost, level):
self.parent = parent
self.mat = mat
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) -> int:


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,


level, parent, final) -> node:
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(parent, new_mat, 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 0 <= y < n

def printPath(root):
if root is None:
return

printPath(root.parent)
printMatrix(root.mat)
print()

def solve(initial, empty_tile_pos, final):


pq = priorityQueue()

cost = calculateCost(initial, final)


root = node(None, initial,
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.level + 1,
minimum, 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:-

1 2 3

5 6 0

7 8 4

1 2 3

5 0 6

7 8 4

1 2 3

5 8 6

7 0 4

1 2 3

5 8 6

0 7 4

4.n-queens

N = 8 # (size of the chessboard)

def solveNQueens(board, col):


if col == N:
print(board)
return True
for i in range(N):
if isSafe(board, i, col):
board[i][col] = 1
if solveNQueens(board, col + 1):
return True
board[i][col] = 0
return False
def isSafe(board, row, col):
for x in range(col):
if board[row][x] == 1:
return False
for x, y in zip(range(row, -1, -1), range(col, -1, -1)):
if board[x][y] == 1:
return False
for x, y in zip(range(row, N, 1), range(col, -1, -1)):
if board[x][y] == 1:
return False
return True

board = [[0 for x in range(N)] for y in range(N)]


if not solveNQueens(board, 0):
print("No solution found")

output:-

[[1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1], [0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1,
0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0]]

5.alpha-beta

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

6.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): # 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()

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

7.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 shrimpig", end='')
else:
print("\n-------In Valid Option Select --------", end='')
if x >= 1 and x <= 2:
print("\n X is ", end='')
print(database[x-1], end='')
print("\n Color Is 1.Green 2.Yellow", end='')
k = int(input())
if k == 1 and x == 1: # frog0 and green1
print(" yes it is ", end='')
print(color[0], end='')
print("Color and will", end='')
print(database[0], end='')
elif k == 2 and x == 2: # canary1 and yellow3
print(" yes it is ", end='')
print(color[1], end='')
print(" Color I and will ", end='')
print(database[1], end='')
else:
print("\n---InValid Knowledge Database", end='')
if __name__ == "__main__":
main()

output:-

*-----Backward--Chaining-----*

X is

1.frog

2.Canary

Select One 2
Chance of shrimpig

X is Eat Flies

Color Is 1.Green 2.Yellow2

yes it is Yellow Color I and will Eat Flies

8.knn

import pandas as pd
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.preprocessing import StandardScaler

file_path = "C:\\Users\\mcom13\\Downloads\\Iris (1).csv"

iris_data = pd.read_csv(file_path)

X = iris_data.iloc[:, :-1].values # Features


y = iris_data.iloc[:, -1].values # Target variable

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, random_state=49)

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)

accuracy = accuracy_score(y_test, y_pred)


print("Accuracy:", accuracy)

output:-

Accuracy: 0.9866666666666667

9.linear-regression

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.rand(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()

output:-

10.NB

import pandas as pd
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,classification_report
file_path = "C:\\Users\\mcom13\\Downloads\\Iris (1).csv"
iris_data = pd.read_csv("C:\\Users\\mcom13\\Downloads\\Iris (1).csv")
X = iris_data.iloc[:, :-1].values
y = iris_data.iloc[:, -1].values
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
print(len(y_train))
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
naive_bayes = GaussianNB()
naive_bayes.fit(X_train, y_train)
y_pred = naive_bayes.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
conf_matrix = confusion_matrix(y_test, y_pred)
print("Confusion Matrix:")
print(conf_matrix)
print(classification_report(y_test,y_pred))

output:-

120

Accuracy: 1.0

Confusion Matrix:

[[10 0 0]

[ 0 9 0]

[ 0 0 11]]

precision recall f1-score support

Iris-setosa 1.00 1.00 1.00 10

Iris-versicolor 1.00 1.00 1.00 9

Iris-virginica 1.00 1.00 1.00 11

accuracy 1.00 30

macro avg 1.00 1.00 1.00 30

weighted avg 1.00 1.00 1.00 30

11.SVM

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

file_path = "C:\\Users\\mcom13\\Downloads\\Iris (1).csv"

iris_data = pd.read_csv("C:\\Users\\mcom13\\Downloads\\Iris (1).csv")

X = iris_data.iloc[:, :-1].values # Features


y = iris_data.iloc[:, -1].values # Target variable

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.9, 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) # Using a linear kernel

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:")
print(conf_matrix)

output:-

Accuracy: 0.9777777777777777

Confusion Matrix:

[[48 0 0]

[ 0 41 3]

[ 0 0 43]]

12.classification

import tensorflow as tf
from tensorflow.keras.layers import Flatten, Dense
from tensorflow.keras.models import Sequential
from tensorflow.keras.preprocessing.image import ImageDataGenerator
train_dir = "C:\\Users\\com13\\Downloads\\archive.zip\\training_set"
validation_dir = "C:\\Users\\com13\\Downloads\\archive.zip\\test_set"
batch_size = 32
img_height = 150
img_width = 150
epochs = 10
train_datagen = ImageDataGenerator(rescale=1. / 255)
validation_datagen = ImageDataGenerator(rescale=1. / 255)
train_generator = train_datagen.flow_from_directory(
train_dir,
target_size=(img_height, img_width),
batch_size=batch_size,
class_mode='binary'
)
validation_generator = validation_datagen.flow_from_directory(
validation_dir,
target_size=(img_height, img_width),
batch_size=batch_size,
class_mode='binary'
)
model = Sequential([
Flatten(input_shape=(img_height, img_width, 3)),
Dense(128, activation='relu'),
Dense(1, activation='sigmoid')
])
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

history = model.fit(
train_generator,
steps_per_epoch=train_generator.samples // batch_size,
epochs=epochs,
validation_data=validation_generator,
validation_steps=validation_generator.samples // batch_size
)

You might also like