AI - Practical Part 2
AI - Practical Part 2
1
Aim: -Introduction of Artificial Intelligence and its application.
Artificial Intelligence: - “The science and engineering of making intelligent machines,
especially Intelligent computer programs”. Artificial Intelligence is an approach to make a
computer, a robot, or a product to think how smart human think.AI is a study of how human brain think,
learn, decide and work, when it tries to solve problems. And finally, this study outputs intelligent
software systems. The aim of AI is to improve computer functions which are related to human
knowledge, for example, reasoning, learning, and problem-solving. The intelligence is intangible. It is
composed of
• Reasoning
• Learning
• Problem Solving
• Perception
• Linguistic Intelligence
The objectives of AI research are reasoning, knowledge representation, planning, learning,
natural language processing, realization, and ability to move and manipulate objects. There are
long-term goals in the general intelligence sector.
Approaches include statistical methods, computational intelligence, and traditional coding AI.
During the AI research related to search and mathematical optimization, artificial neural
networks and methods based on statistics, probability, and economics, we use many tools.
Computer science attracts AI in the field of science, mathematics, psychology, linguistics,
philosophy and so on.
Goals of AI:
• To Create Expert Systems − The systems which exhibit intelligent behavior,
learn, demonstrate, explain, and advice its users.
• To Implement Human Intelligence in Machines − Creating systems that understand,
think, learn ,and behave like humans.
Applications of AI :
➢ Gaming − AI plays important role for machine to think of large number of possible
positions based on deep knowledge in strategic games. for example, chess,river
crossing, N-queens problems and etc.
➢ Expert Systems − Machine or software provide explanation and advice to the users.
➢ Speech Recognition − There are some AI based speech recognition systems have
ability to hear and express as sentences and understand their meanings while a
DFS is also an important type of uniform search. DFS visits all the vertices in the graph. This
type of algorithm always chooses to go deeper into the graph. After DFS visited all the
reachable vertices from a particular sources vertices it chooses one of the remaining
undiscovered vertices and continues the search. DFS reminds the space limitation of breath
first search by always generating next a child of the deepest unexpanded nodded. The data
structure stack or (LIFO) is used for DFS. One interesting property of DFS isthat, the discover
and finish time of each vertex from a parenthesis structure. If we use one open parenthesis
when a vertex is finishedthen the result is properly nested set of parenthesis.
graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}
# Driver Code
print("Following is the Depth-First
Search") dfs(visited, graph, '5')
Output:
Step 2: Enqueue the starting node A and set its STATUS = 2 (waiting state)
Step 4: Dequeue a node N. Process it and set its STATUS = 3 (processed state).
Step 5: Enqueue all the neighbours of N that are in the ready state (whose STATUS = 1) and
Set their STATUS = 2
(waiting state )
[ END OF LOOP]
graph = {
'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['F'],
'D' : [],
'E' : ['F'],
'F' : []
}
visited = [] # List to keep track of visited nodes.
queue = [] #Initialize a queue
while queue:
s = queue.pop(0)
print (s, end = " ")
# Driver Code
print("bfs traversal is as follow:")
bfs(visited, graph, 'A')
OUTPUT:
• g(n): The actual cost of traversal from initial state to the current state.
• h(n): The estimated cost of traversal from the current state to the goal state.
• f(n): The actual cost of traversal from the initial state to the goal state.
Advantages of A* Algorithm:
• There is no other optimal algorithm guaranteed to expand fewer nodes than A*.
Disadvantages of A* Algorithm:
• This algorithm is complete if the branching factor is finite and every action has fixed
cost.
Algorithm:
// A* Search Algorithm
2. Initialize the closed list put the starting node on the open list (you can leave its f at zero)
parents to q
successor.h = distance from goal to successor (This can be done using many
Heuristics)
iii) if a node with the same position as successor is in the OPEN list which has a
iV) if a node with the same position as successor is in the CLOSED list which has
a lower f than successor, skip this successor otherwise, add the node to the open list
CODE:
Graph:
adjacency_list = {
[('D', 5)],
self.adjacency_list = adjacency_list
self.adjacency_list[v]
h(self, n):
H={
'A': 1,
'B': 1,
'C': 1,
'D': 1
return H[n]
# open_list is a list of nodes which have been visited, but who's neighbors# haven't all
open_list = set([start_node])
closed_list = set([])
g = {}
g[start_node] = 0
parents[start_node] = start_nodewhile
len(open_list) > 0:
n = None
# find a node with the lowest value of f() - evaluation functionfor v in
open_list:
if n == None:
return None
stop_node:
reconst_path = [] while
parents[n] != n:
reconst_path.append(n)
n = parents[n]
reconst_path.append(start_node)
reconst_path.reverse()
reconst_path
weight) in self.get_neighbors(n):
open_list.add(m)
B.Tech CSE 6th Semester CTIEMT Page No. 10
parents[m] = n
= g[n] + weight
parents[m] = n
if m in closed_list:
closed_list.remove(m)
open_list.add(m)
closed_list.add(n)
return None
adjacency_list = {
graph1 = Graph(adjacency_list)
graph1.a_star_algorithm('A', 'D')
OUTPUT:
Algorithm:
• Identify the base case: If there is only one disk, simply move it from the source rod to
the destination rod.
• Otherwise, recursively solve the problem for n-1 disks, moving them from the source
rod to the auxiliary rod.
• Move the largest disk from the source rod to the destination rod.
• Recursively solve the problem for n-1 disks on the auxiliary rod, moving them to the
destination rod.
CODE:
def hanoi(n, f, to, via):if n
== 1:
print("Move disk",n,"from",f,"to",to);
n=3
to = 'B' via
= 'C'
OUTPUT:
CODE:
import os
import time
board = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
player = 1
# Win Flags
Win = 1
Draw = -1
Running = 0
Stop = 1
Game = Running
Mark = 'X'
def DrawBoard():
print(" %c | %c | %c " % (board[1], board[2], board[3]))
print(" | | ")
print(" %c | %c | %c " % (board[4], board[5], board[6]))
print(" | | ")
print(" %c | %c | %c " % (board[7], board[8], board[9]))
print(" | | ")
def CheckPosition(x):
if board[x] == ' ':
return True
OUTPUT:
Statement :We are given 2 jugs, a 4 liter one and a 3- liter one. Neither has any measuring
markers on it.There is a pump that can be used to fill the jugs with water. How can we get
exactly 2 liters of water in tothe 4-liter jugs?
Solution:-
1. Start with the initial state where both jugs are empty.
o If not, add the new states to the queue for further exploration.
4. BFS ensures that you find the shortest path to the goal state, which is efficient for
solving the Water Jug Problem.
CODE:
if b == 0:
return a
else:
return gcd(b, a % b)
return False
return []
if a > b:
a, b = b, a
q2 = target // gcd_val
while q2 > 0:
q1 = (target - b * q2) // a
yield ('fill', 1)
yield ('pour', 1, 2)
yield ('empty', 2)
yield ('pour', 1, 2)
yield ('fill', 1)
yield ('pour', 1, 2)
q2 -= 1
target -= a
jug1_cap = 4
jug2_cap = 3
target = 2
else:
OUTPUT:
Theory:
A Bayesian network is a directed acyclic graph in which each edge corresponds to a conditional
dependency, and each node corresponds to a unique random variable. The Bayesian network
consists of two major parts: a directed acyclic graph and a set of conditional probability
distributions
import csv
import pandas as pd
heartDisease = pd.read_csv('heart.csv')
heartDisease = heartDisease.replace('?',np.nan)
#display the data print('Few examples from the dataset are given below')
print(heartDisease.head())
Model=BayesianModel([('age','trestbps'),('age','fbs'),
('sex','trestbps'),('exang','trestbps'),('trestbps','heartdise
ase'),('fbs','heartdisease'),('heartdisease','restecg'),
('heartdisease','thalach'),('heartdisease','chol')])
HeartDisease_infer = VariableElimination(model)
Output:
Theory- Inference over a Bayesian network can come in two forms. The first is simply
evaluating the joint probability of a particular assignment of values for each variable (or a
subset ) in the network .The second, more interesting inference task ,is to find P(x|e),or, to find
the probability of some assignment of a subset of the variables (x) given assignments of other
variables (our evidence ,e).
Code:
from pgmpy.models import BayesianNetwork
from pgmpy.factors.discrete import TabularCPD
import networkx as nx
import pylab as plt
infer = VariableElimination(model)
posterior_p = infer.query(['Host'], evidence={'Guest': 2, 'Price': 2})
print(posterior_p)
Output:
Code:
Output:
Code:
class ValueIteration:
self.mdp = mdp
self.values = values
for i in range(max_iterations):
delta = 0.0
new_values = TabularValueFunction()
qtable = QTable()
new_value = 0.0
state, action
):
new_value += probability * (
reward
+(
self.mdp.get_discount_factor()
* self.values.get_value(new_state)
B.Tech CSE 6th Semester CTIEMT Page No. 26
)
new_values.update(state, max_q)
self.values.merge(new_values)
return i
Output:
Code:
# global variables
BOARD_ROWS = 3
BOARD_COLS = 4
WIN_STATE = (0, 3)
LOSE_STATE = (1, 3)
START = (2, 0)
DETERMINISTIC = True
def giveReward(self):
if self.state == WIN_STATE:
return 1
return -1
else:
return 0
if self.determine:
if action == "up":
else:
i=0
if self.State.isEnd:
reward = self.State.giveReward()
for s in reversed(self.states):
self.state_values[s] = round(reward, 3)
self.reset()
Output: