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

Graph Algorithms and AI Techniques

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)
3 views14 pages

Graph Algorithms and AI Techniques

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

1.

bfs

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

output:-

ABCDEF

[Link]

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)
[Link](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):
[Link] = []

def push(self, k):


heappush([Link], k)

def pop(self):
return heappop([Link])

def empty(self):
if not [Link]:
return True
else:
return False

class node:
def __init__(self, parent, mat, empty_tile_pos,
cost, level):
[Link] = parent
[Link] = mat
self.empty_tile_pos = empty_tile_pos
[Link] = cost
[Link] = level

def __lt__(self, nxt):


return [Link] < [Link]

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 = [Link](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([Link])
printMatrix([Link])
print()

def solve(initial, empty_tile_pos, final):


pq = priorityQueue()

cost = calculateCost(initial, final)


root = node(None, initial,
empty_tile_pos, cost, 0)
[Link](root)
while not [Link]():
minimum = [Link]()
if [Link] == 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([Link],
minimum.empty_tile_pos,
new_tile_pos,
[Link] + 1,
minimum, final, )
[Link](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]]

[Link]-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

[Link]-chaining

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


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

[Link] Flies

[Link]

[Link]

Select One 1

Chance Of Frog

X is Croaks

Color Is [Link] [Link]

Select Option 1

yes it is Frog And Color Is Green

[Link]-chaining

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


knowbase = ["Frog", "Canary"]
color=["Green","Yellow"]
def display():
print("\n X is \[Link] \[Link]", 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 [Link] [Link]", 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

[Link]

[Link]

Select One 2
Chance of shrimpig

X is Eat Flies

Color Is [Link] 2.Yellow2

yes it is Yellow Color I and will Eat Flies

[Link]

import pandas as pd
from [Link] import accuracy_score
from sklearn.model_selection import train_test_split
from [Link] import KNeighborsClassifier
from [Link] 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 = [Link](X_test)

knn=KNeighborsClassifier(n_neighbors=3)
[Link](X_train,y_train)

y_pred = [Link](X_test)

accuracy = accuracy_score(y_test, y_pred)


print("Accuracy:", accuracy)

output:-

Accuracy: 0.9866666666666667

[Link]-regression

import numpy as np
import [Link] as plt
from sklearn.linear_model import LinearRegression

[Link](0)
X = 2 * [Link](100, 1)
y = 4 + 3 * X + [Link](100, 1)
model = LinearRegression()
[Link](X, y)
X_new = [Link]([[0], [2]])
y_pred =[Link](X_new)
[Link](X, y, color='blue')
[Link](X_new, y_pred, color='red')
[Link]('X')
[Link]('y')
[Link]('Linear Regression')
[Link]()

output:-

[Link]

import pandas as pd
from sklearn.model_selection import train_test_split
from [Link] import StandardScaler
from sklearn.naive_bayes import GaussianNB
from [Link] 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 = [Link](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

[Link]

import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from [Link] import StandardScaler
from [Link] import SVC
from [Link] import accuracy_score, confusion_matrix
from [Link] 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 = [Link](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]]

[Link]

import tensorflow as tf
from [Link] import Flatten, Dense
from [Link] import Sequential
from [Link] import ImageDataGenerator
train_dir = "C:\\Users\\com13\\Downloads\\[Link]\\training_set"
validation_dir = "C:\\Users\\com13\\Downloads\\[Link]\\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')
])
[Link](optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

history = [Link](
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