0% found this document useful (0 votes)
227 views26 pages

Aim L Record

The document describes four experiments related to artificial intelligence algorithms: 1. Implementation of depth-first search for the water jug problem to find a path from the initial empty state to a target state. 2. Implementation of breadth-first search for tic-tac-toe to evaluate board positions and find a winning state. 3. Implementation of the traveling salesman problem using a heuristic approach to find the shortest route visiting each city once. 4. Implementation of hill climbing to solve the 8-puzzle problem by incrementally moving tiles to arrange them in order.

Uploaded by

Abhilash Abhi
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)
227 views26 pages

Aim L Record

The document describes four experiments related to artificial intelligence algorithms: 1. Implementation of depth-first search for the water jug problem to find a path from the initial empty state to a target state. 2. Implementation of breadth-first search for tic-tac-toe to evaluate board positions and find a winning state. 3. Implementation of the traveling salesman problem using a heuristic approach to find the shortest route visiting each city once. 4. Implementation of hill climbing to solve the 8-puzzle problem by incrementally moving tiles to arrange them in order.

Uploaded by

Abhilash Abhi
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/ 26

Date:

Experiment-1:
1.Implementation of DFS for water jug problem.

Aim:To Implementation of DFS for water jug problem.


Description:
You are given an m liter jug and a n liter jug. Both the jugs are initially empty. The jugs don’t have
markings to allow measuring smaller quantities. You have to use the jugs to measure d liters of water
where d is less than n.
(X, Y) corresponds to a state where X refers to the amount of water in Jug1 and Y refers to the
amount of water in Jug2
Determine the path from the initial state (xi, yi) to the final state (xf, yf), where (xi, yi) is (0, 0) which
indicates both Jugs are initially empty and (xf, yf) indicates a state which could be (0, d) or (d, 0).
The operations you can perform are:
1.Empty a Jug, (X, Y)->(0, Y) Empty Jug 1
2.Fill a Jug, (0, 0)->(X, 0) Fill Jug 1
3.Pour water from one jug to the other until one of the jugs is either empty or full, (X, Y) -> (X-d,
Y+d)
Program:
def pour_water(juga,jugb):
max1,max2,fill=3,4,2
print("%d\t%d"%(juga,jugb))
if jugb==fill:
return
elif jugb==max2:
pour_water(0,juga)
elif juga!=0 and jugb==0:
pour_water(0,juga)
elif juga==fill:
pour_water(juga,0)
elif juga<max1:
pour_water(max1,jugb)
elif juga<(max2-jugb):
pour_water(0,(juga+jugb))
else:

1|Page
RollNo: 2 1 A 9 1 A 6 1 0 7
Date:

pour_water(juga-(max2-jugb),(max2-jugb)+jugb)
print("JUGA \t JUGB")
pour_water(0,0)

Output:

2|Page
RollNo: 2 1 A 9 1 A 6 1 0 7
Date:

Experiment-2:
2. Implementation of BFS for tic-tac-toe problem.
Aim: To Implementation of BFS for tic-tac-toe problem.
Description:
Breadth-First Search algorithm is a graph traversing algorithm, where you select a random initial node
(source or root node) and starts traversing the graph from root node and explores all the
neighboring nodes first.Then, it selects the nearest node and explore all the unexplored nodes.
Basically BFS traverse a graph layer-wise in such a way that all the nodes and their respective
children nodes are visited and explored.

Program:
import numpy as np
import random
from time import sleep

# Creates an empty board


def create_board():
return(np.array([[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]))

# Check for empty places on board


def possibilities(board):
l = []

for i in range(len(board)):
for j in range(len(board)):

if board[i][j] == 0:
l.append((i, j))
return(l)

# Select a random place for the player

3|Page
RollNo: 2 1 A 9 1 A 6 1 0 7
Date:

def random_place(board, player):


selection = possibilities(board)
current_loc = random.choice(selection)
board[current_loc] = player
return(board)

# Checks whether the player has three


# of their marks in a horizontal row
def row_win(board, player):
for x in range(len(board)):
win = True

for y in range(len(board)):
if board[x, y] != player:
win = False
continue

if win == True:
return(win)
return(win)

# Checks whether the player has three


# of their marks in a vertical row
def col_win(board, player):
for x in range(len(board)):
win = True

for y in range(len(board)):
if board[y][x] != player:
win = False
continue

4|Page
RollNo: 2 1 A 9 1 A 6 1 0 7
Date:

if win == True:
return(win)
return(win)
# Checks whether the player has three
# of their marks in a diagonal row
def diag_win(board, player):
win = True
y=0
for x in range(len(board)):
if board[x, x] != player:
win = False
if win:
return win
win = True
if win:
for x in range(len(board)):
y = len(board) - 1 - x
if board[x, y] != player:
win = False
return win
# Evaluates whether there is
# a winner or a tie
def evaluate(board):
winner = 0

for player in [1, 2]:


if (row_win(board, player) or
col_win(board,player) or
diag_win(board,player)):

winner = player

5|Page
RollNo: 2 1 A 9 1 A 6 1 0 7
Date:

if np.all(board != 0) and winner == 0:


winner = -1
return winner

# Main function to start the game


def play_game():
board, winner, counter = create_board(), 0, 1
print(board)
sleep(2)

while winner == 0:
for player in [1, 2]:
board = random_place(board, player)
print("Board after " + str(counter) + " move")
print(board)
sleep(2)
counter += 1
winner = evaluate(board)
if winner != 0:
break
return(winner)

# Driver Code
print("Winner is: " + str(play_game()))

6|Page
RollNo: 2 1 A 9 1 A 6 1 0 7
Date:

Output:

7|Page
RollNo: 2 1 A 9 1 A 6 1 0 7
Date:

Experiment-3:
3. Implementation of TSP using heuristic approach.
Aim: To Implement TSP using heuristic approach.

Description:
(TSP) The travelling salesman problem, the problem is to find the shortest possible route that
visit every city exactly once and returns to the starting point.

The traveling salesman problem (TSP) is to find the shortest hamiltonian cycle in a graph. This
problem is NP-hard and thus interesting. There are a number of algorithms used to find optimal tours,
but none are feasible for large instances since they all grow exponentially

Program:
from sys import maxsize
from itertools import permutations
V=4

# implementation of traveling Salesman Problem


def travellingSalesmanProblem(graph, s):

# store all vertex apart from source vertex


vertex = []
for i in range(V):
if i != s:
vertex.append(i)

# store minimum weight Hamiltonian Cycle


min_path = maxsize
next_permutation=permutations(vertex)
for i in next_permutation:

# store current Path weight(cost)


current_pathweight = 0

# compute current path weight


8|Page
RollNo: 2 1 A 9 1 A 6 1 0 7
Date:

k=s
for j in i:
current_pathweight += graph[k][j]
k=j
current_pathweight += graph[k][s]

# update minimum
min_path = min(min_path, curren t_pathweight)

return min_path

# Driver Code
if __name__ == "__main__":

# matrix representation of graph


graph = [[0, 10, 15, 20], [10, 0, 35, 25],
[15, 35, 0, 30], [20, 25, 30, 0]]
s=0
print(travellingSalesmanProblem(graph, s))

Output:
80

9|Page
RollNo: 2 1 A 9 1 A 6 1 0 7
Date:

Experiment-4:
4. Implementation of Hill-climbing to solve 8- Puzzle Problem.
Aim: To implementation of Hill-climbing to solve 8- Puzzle Problem.
Description:
A set of eight numbered tiles are arranged in order on a puzzle slate with an empty tile placed at
last. Here, In this problem, need to arrange the tiles which are unorderd , using the hill climbing
searching strategy as in the goal state
Hill Climbing is a heuristic search used for mathematical optimization problems in the field of
Artificial Intelligence. It is an iterative algorithm that starts with an arbitrary solution to a problem,
then attempts to find a better solution by making an incremental change to the solution.
So, given a large set of inputs and a good heuristic function, the algorithm tries to find the best
possible solution to the problem in the most reasonable time period.
Solution is not necessary, a optimal solution (Global Optimal Maxima) but it is consider to be good
solution according to time period.
Mathematical optimization problems: Implies that hill-climbing solves the problems where we need to
maximize or minimize a given real function by choosing values from the given inputs.
Program:

Syntax-
Syntax-
import sys
import numpy as np

class Node:
def __init__(self, state, parent, action):
self.state = state
self.parent = parent
self.action = action

class StackFrontier:
def __init__(self):
self.frontier = []

def add(self, node):


self.frontier.append(node)

def contains_state(self, state):


return any((node.state[0] == state[0]).all() for node in self.frontier)

def empty(self):
return len(self.frontier) == 0

def remove(self):
if self.empty():

10 | P a g e
RollNo: 2 1 A 9 1 A 6 1 0 7
Date:

raise Exception("Empty Frontier")


else:
node = self.frontier[-1]
self.frontier = self.frontier[:-1]
return node

class QueueFrontier(StackFrontier):
def remove(self):
if self.empty():
raise Exception("Empty Frontier")
else:
node = self.frontier[0]
self.frontier = self.frontier[1:]
return node

class Puzzle:
def __init__(self, start, startIndex, goal, goalIndex):
self.start = [start, startIndex]
self.goal = [goal, goalIndex]
self.solution = None

def neighbors(self, state):


mat, (row, col) = state
results = []

if row > 0:
mat1 = np.copy(mat)
mat1[row][col] = mat1[row - 1][col]
mat1[row - 1][col] = 0
results.append(('up', [mat1, (row - 1, col)]))
if col > 0:
mat1 = np.copy(mat)
mat1[row][col] = mat1[row][col - 1]
mat1[row][col - 1] = 0
results.append(('left', [mat1, (row, col - 1)]))
if row < 2:
mat1 = np.copy(mat)
mat1[row][col] = mat1[row + 1][col]
mat1[row + 1][col] = 0
results.append(('down', [mat1, (row + 1, col)]))
if col < 2:
mat1 = np.copy(mat)
mat1[row][col] = mat1[row][col + 1]
mat1[row][col + 1] = 0
results.append(('right', [mat1, (row, col + 1)]))

return results

def print(self):
11 | P a g e
RollNo: 2 1 A 9 1 A 6 1 0 7
Date:

solution = self.solution if self.solution is not None else None


print("Start State:\n", self.start[0], "\n")
print("Goal State:\n", self.goal[0], "\n")
print("\nStates Explored: ", self.num_explored, "\n")
print("Solution:\n ")
for action, cell in zip(solution[0], solution[1]):
print("action: ", action, "\n", cell[0], "\n")
print("Goal Reached!!")

def does_not_contain_state(self, state):


for st in self.explored:
if (st[0] == state[0]).all():
return False
return True

def solve(self):
self.num_explored = 0

start = Node(state=self.start, parent=None, action=None)


frontier = QueueFrontier()
frontier.add(start)

self.explored = []

while True:
if frontier.empty():
raise Exception("No solution")

node = frontier.remove()
self.num_explored += 1

if (node.state[0] == self.goal[0]).all():
actions = []
cells = []
while node.parent is not None:
actions.append(node.action)
cells.append(node.state)
node = node.parent
actions.reverse()
cells.reverse()
self.solution = (actions, cells)
return

self.explored.append(node.state)

for action, state in self.neighbors(node.state):


if not frontier.contains_state(state) and self.does_not_contain_state(state):
child = Node(state=state, parent=node, action=action)
frontier.add(child)
12 | P a g e
RollNo: 2 1 A 9 1 A 6 1 0 7
Date:

start = np.array([[1, 2, 3], [8, 0, 4], [7, 6, 5]])


goal = np.array([[2, 8, 1], [0, 4, 3], [7, 6, 5]])

startIndex = (1, 1)
goalIndex = (1, 0)

p = Puzzle(start, startIndex, goal, goalIndex)


p.solve()
p.print()

13 | P a g e
RollNo: 2 1 A 9 1 A 6 1 0 7
Date:

Output:

14 | P a g e
RollNo: 2 1 A 9 1 A 6 1 0 7
Date:

15 | P a g e
RollNo: 2 1 A 9 1 A 6 1 0 7
Date:

Experiment-5:
5. Implement and demonstrate FIND-S algorithm for finding the most specific hypothesis based
on a given set of training data samples. Read the training data from a .csv file.

Aim: To implement and demonstrate FIND-S algorithm for finding the most specific hypothesis
based on a given set of training data samples. Read the training data from a .csv file.

Description:
The find-S algorithm is a basic concept learning algorithm in machine learning. The find-S algorithm
finds the most specific hypothesis that fits all the positive examples. We have to note here that the
algorithm considers only those positive training example.

DataSet:

Example Sky Air temperature Humidity Wind Water Forecast Enjoy-sport


1 Sunny Warm Normal Strong Warm Same Yes
2 Sunny Warm High Strong Warm Same Yes
3 Rainy Cold High Strong Warm Change No
4 Sunny Warm High Strong Cool Change Yes

Program:
import pandas as pd
import numpy as np
import csv
filename=(r"C:\Users\LENOVO\Downloads\Find.csv")
df=pd.read_csv(filename)
df.info()
df.head()
a=np.array(df)[::-1]
print(a)
target=np.array(df)[::-1]
print(target)
def func(concept,target):
for i,val in enumurate(target):
if val=="yes":

16 | P a g e
RollNo: 2 1 A 9 1 A 6 1 0 7
Date:

for x in range(len(specific_hypothesis)):
if val[x]!=specific_hypothesis[x]:
specific_hypothesis[x]='?'
return specific_hypothesis
print("The final hypothesis is:",func(a,target))

output:
<class 'pandas.core.frame.DataFrame'>

RangeIndex: 4 entries, 0 to 3

Data columns (total 8 columns):

# Column Non-Null Count Dtype


--- ------ -------------- -----

0 Example 4 non-null int64


1 Sky 4 non-null object
2 Air temperature 4 non-null object
3 Humidity 4 non-null object
4 Wind 4 non-null object
5 Water 4 non-null object
6 Forecast 4 non-null object
7 Enjoy-sport 4 non-null object

dtypes: int64(1), object(7)

memory usage: 384.0+ bytes

[[4 'Sunny' 'Warm' 'High' 'Strong' 'Cool' 'Change' 'Yes']


[3 'Rainy' 'Cold' 'High' 'Strong' 'Warm' 'Change' 'No']
[2 'Sunny' 'Warm' 'High' 'Strong' 'Warm' 'Same' 'Yes']
[1 'Sunny' 'Warm' 'Normal' 'Strong' 'Warm' 'Same' 'Yes']]
[[4 'Sunny' 'Warm' 'High' 'Strong' 'Cool' 'Change' 'Yes']
[3 'Rainy' 'Cold' 'High' 'Strong' 'Warm' 'Change' 'No']
[2 'Sunny' 'Warm' 'High' 'Strong' 'Warm' 'Same' 'Yes']
[1 'Sunny' 'Warm' 'Normal' 'Strong' 'Warm' 'Same' 'Yes']]

17 | P a g e
RollNo: 2 1 A 9 1 A 6 1 0 7
Date:

Experiment-6:
6. For a given set of training data examples stored in a .csv file, implement and demonstrate the
candidate elimination algorithm to output a description of the set of all hypotheses consistent
with the training examples

Aim: To For a given set of training data examples stored in a .csv file, implement and demonstrate
the candidate elimination algorithm to output a description of the set of all hypotheses consistent with
the training examples

Description:
Candidate Elimination Algorithm is used to find the set of consistent hypothesis, that is
Version spsce.
The candidate Elimination algorithm finds all hypotheses that match all the given training
examples. Unlike in Find-S algorithm and List-then-Eliminate algorithm, it goes through both
negative and positive examples, eliminating any inconsistent hypothesis.Candidate generation
is the first stage of recommendation. Given a query, the system generates a set of relevant
candidates. The following table shows two common candidate generation approaches: Type.
Definition.
DataSet:
Humidity Enjoy-
Example
Sky Air temperature Wind Water Forecast sport
1 Sunny Warm Normal Strong Warm Same Yes
2 Sunny Warm High Strong Warm Same Yes
3 Rainy Cold High Strong Warm Change No
4 Sunny Warm High Strong Cool Change Yes

Program:
import csv
filename=(r"C:\Users\LENOVO\Downloads\Find.csv")
df=pd.read_csv(filename)
df.info()
df.head()
concepts.np.array(df.iloc[:,0:-1])
print(concepts)
18 | P a g e
RollNo: 2 1 A 9 1 A 6 1 0 7
Date:

target=np.array(df.loc[:,-1])
print(target)
def learn(concepts, target):
specific_h-concepts[0].copy()
print("Initialization of specific_h and general=h")
print("specific_h:",specific_h)
general_h=[["?" for i in range(len(specific ))] for i in range(len(specific_))]
print("general_h:",general_h)
print("concepts:",concepts)
for i,h in enumerate(concepts):
if target[i]=="yes":
for x in range(len(specifi_h)):
#print("h[x]",h[x])
if h[x]!=specific_h[x]:
specific_h[x]='?'
general_h[x][x]='?'
if target[i]=="no":
for x in range(len(specific_h)):
if h[x]!=specific_h[x]:
general_h[x][x]=specific_h[x]
else:
general_h[x][x]='?'
print("\n steps of candidate elimation algorithm:",[])
print("specific_h:",i-1)
print(specific_h,"\n")
print("general_h:",i+1)
print(general_h)
indicates=[i for i,val in enumurate(general_h)if val==['?','?','?','?','?','?']]
print("\n indicates",indices)
for i in indices:
19 | P a g e
RollNo: 2 1 A 9 1 A 6 1 0 7
Date:

general_h.remove(['?','?','?','?','?','?'])
return specific_h,general_h
s_final,g_final=learn(concepts,target)
print("\n final specific_h:",s_final,sep="\n")
print("final general_h:",g_final,sep="\n")

Output:
<class 'pandas.core.frame.DataFrame'>

RangeIndex: 4 entries, 0 to 3

Data columns (total 8 columns):

# Column Non-Null Count Dtype


--- ------ -------------- -----
0 Example 4 non-null int64
1 Sky 4 non-null object
2 Air temperature 4 non-null object
3 Humidity 4 non-null object
4 Wind 4 non-null object
5 Water 4 non-null object
6 Forecast 4 non-null object
7 Enjoy-sport 4 non-null object

dtypes: int64(1), object(7)

memory usage: 384.0+ bytes

[[1 'Sunny' 'Warm' 'Normal' 'Strong' 'Warm' 'Same']


[2 'Sunny' 'Warm' 'High' 'Strong' 'Warm' 'Same']
[3 'Rainy' 'Cold' 'High' 'Strong' 'Warm' 'Change']
[4 'Sunny' 'Warm' 'High' 'Strong' 'Cool' 'Change']]
['Yes' 'Yes' 'No' 'Yes']

20 | P a g e
RollNo: 2 1 A 9 1 A 6 1 0 7
Date:

Experiment-7:
7. Write a program to demonstrate the working of the decision tree classifier. Use appropriate
dataset for building the decision tree and apply this knowledge to classify a new sample.

Aim: To Write a program to demonstrate the working of the decision tree classifier. Use appropriate
dataset for building the decision tree and apply this knowledge to classify a new sample.

Description:
Decision tree is one of the most poweful and popular algorithm decision tree algorithm
falls under the company of supersied learning algorithm,it works for both continuous as well
as categorical output variable.
Program:
import pandas as pd
df=pd.read_csv(r"C:\Users\LENOVO\Downloads\company.csv")
df.head()
inputs=df.drop('salary more than 100k',axis='columns')
inputs
target=df['salary more than 100k']
target
from sklearn.preprocessing import LabelEncoder
le_company=LabelEncoder()
le_job=LabelEncoder()
le_degree=LabelEncoder()
inputs['company_n']=le_company.fit_transform(inputs['company'])
inputs['job_n']=le_job.fit_transform(inputs['job'])
inputs['degree_n']=le_job.fit_transform(inputs['degree'])
inputs
inputs_n=inputs.drop(['company','job','degree'],axis='columns')
inputs_n
target

21 | P a g e
RollNo: 2 1 A 9 1 A 6 1 0 7
Date:

Output:
0 0
1 0
2 1
3 1
4 0
5 1
6 0
7 0
8 1
9 1
10 1
11 1
12 1
13 1
14 1
15 1
Name: salary more than 100k, dtype: int64

22 | P a g e
RollNo: 2 1 A 9 1 A 6 1 0 7
Date:

23 | P a g e
RollNo: 2 1 A 9 1 A 6 1 0 7
Date:

24 | P a g e
RollNo: 2 1 A 9 1 A 6 1 0 7
Date:

25 | P a g e
RollNo: 2 1 A 9 1 A 6 1 0 7
Date:

26 | P a g e
RollNo: 2 1 A 9 1 A 6 1 0 7

You might also like