Aim L Record
Aim L Record
Experiment-1:
1.Implementation of DFS for water jug problem.
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
for i in range(len(board)):
for j in range(len(board)):
if board[i][j] == 0:
l.append((i, j))
return(l)
3|Page
RollNo: 2 1 A 9 1 A 6 1 0 7
Date:
for y in range(len(board)):
if board[x, y] != player:
win = False
continue
if win == True:
return(win)
return(win)
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
winner = player
5|Page
RollNo: 2 1 A 9 1 A 6 1 0 7
Date:
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
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__":
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 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:
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
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:
def solve(self):
self.num_explored = 0
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)
startIndex = (1, 1)
goalIndex = (1, 0)
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:
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
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
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