You are on page 1of 29

SUSEC 1916810

SUS ENGINEERING COLLEGE

AI LAB FILE
SIXTH SEMESTER

SUBMITTED TO:- SUBMITTED BY:


ER. Deepinder Kaur NAME:- Anand Kumar
COURSE: - B. Tech 6th Sem(CSE) Roll no: 1916810
Subject Code: BTCS602-18

PAGE N0. 1
SUSEC 1916810

INDEX
S.NO EXPERIMENTS DATE OF SUB.

1.

2.

3.

4.

5.

6.

7.

PAGE N0. 2
SUSEC 1916810

ARTIFICIAL INTELLIGENCE LAB MANNUAL

EXPERIMENT :- 1

Introduction to Artificial Intelligence

“The science and engineering of making intelligent machines, especially


intelligent computer programs”. -John McCarthy-

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

PAGE N0. 3
SUSEC 1916810

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.

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.

· Natural Language Processing − Interact with the computer that


understands natural language spoken by humans.

· Expert Systems − Machine or software provide explanation and advice to


the users.

· Vision Systems − Systems understand, explain, and describe visual input


on the computer.

· Speech Recognition − There are some AI based speech recognition


systems have ability to hear and express as sentences and understand
their meanings while a person talks to it. For example Siri and Google
assistant.

PAGE N0. 4
SUSEC 1916810

· Handwriting Recognition − The handwriting recognition software reads the


text written on paper and recognize the shapes of the letters and convert it
into editable text.

· Intelligent Robots − Robots are able to perform the instructions given by a


human.

Major Goals

 Knowledge reasoning

 Planning

 Machine Learning

 Natural Language Processing

 Computer Vision

Robotics

EXPERIMENT :- 2

Introduction of Facts and Rules

PAGE N0. 5
SUSEC 1916810

Facts:-
A fact s a predicate expression that makes a declarative statement about the problem domain. Whenever
a variable occurs in a Prolog expression, it is assumed to be universally quantified. Note that all Prolog
sentences must end with a period.
likes(john, susie). /* John likes Susie */
likes(X, susie). /* Everyone likes Susie */
likes(john, Y). /* John likes everybody */
likes(john, Y), likes(Y, john). /* John likes everybody and everybody likes John */
likes(john, susie); likes(john,mary). /* John likes Susie or John likes Mary */
not(likes(john,pizza)). /* John does not like pizza */
likes(john,susie) :- likes(john,mary)./* John likes Susie if John likes Mary.

Rules:-
A rule is a predicate expression that uses logical implication (:-) to describe a relationship among facts.
Thus a Prolog rule takes the form
left_hand_side :- right_hand_side .

This sentence is interpreted as: eft_hand_side fright_hand_side. The left_hand_side is restricted to a


single, positive, literal, which means it must consist of a positive atomic expression. It cannot be
negated and it cannot contain logical connectives.

This notation is known as a Horn clause. In Horn clause logic, the left hand side of the clause is the
conclusion, and must be a single positive literal. The right hand side contains the premises. The Horn
clause calculus is equivalent to the first-order predicate calculus.

Examples of valid rules:

friends(X,Y) :- likes(X,Y),likes(Y,X). /* X and Y are friends if they like each other */


hates(X,Y) :- not(likes(X,Y)). /* X hates Y if X does not like Y. */
enemies(X,Y) :- not(likes(X,Y)),not(likes(Y,X)). /* X and Y are enemies if they don't like each other */

Examples of invalid rules:

left_of(X,Y) :- right_of(Y,X) /* Missing a period */


likes(X,Y),likes(Y,X) :- friends(X,Y). /* LHS is not a single literal */
not(likes(X,Y)) :- hates(X,Y). /* LHS cannot be negated */

ashish is a boy.

PAGE N0. 6
SUSEC 1916810

Ashish and ashmani are brother.

PAGE N0. 7
SUSEC 1916810

EXPERIMENT :- 3

A.) Write a programme to conduct “BREDTH FIRST SEARCH” .

FROM COLLECTIONS IMPORT DEFAULTDICT


class Graph:
def __init__(self):

self.graph = defaultdict(list)

def addEdge(self,u,v):
self.graph[u].append(v)

# Function to print a BFS of graph


def BFS(self, s):

# Mark all the vertices as not visited


visited = [False] * (max(self.graph) + 1)

# Create a queue for BFS


queue = []

# visited and enqueue it


queue.append(s)
visited[s] = True

while queue:

# Dequeue a vertex from

PAGE N0. 8
SUSEC 1916810

# queue and print it


s = queue.pop(0)
print (s, end = " ")

for i in self.graph[s]:
if visited[i] == False:
queue.append(i)
visited[i] = True

OUTPUT & DRIVER CODE :-

PAGE N0. 9
SUSEC 1916810

B). Write a programme to conduct “DEPTH FIRST SEARCH” .

from collections import defaultdict


lass Graph:

# Constructor
def __init__(self):

# default dictionary to store graph


self.graph = defaultdict(list)

# function to add an edge to graph


def addEdge(self, u, v):
self.graph[u].append(v)

# A function used by DFS


def DFSUtil(self, v, visited):

# Mark the current node as visited


# and print it
visited.add(v)
print(v, end=' ')

# Recur for all the vertices


for neighbour in self.graph[v]:
if neighbour not in visited:
self.DFSUtil(neighbour, visited)

PAGE N0. 10
SUSEC 1916810

# The function to do DFS traversal. It uses


# recursive DFSUtil()
def DFS(self, v):

visited = set()
self.DFSUtil(v, visited)

OUTPUT & DRIVER CODE :-

PAGE N0. 11
SUSEC 1916810

C). Write a programme to conduct “A* ALGORITHM” .


from collections import deque
class Graph:

def __init__(self, adjacency_list):


self.adjacency_list = adjacency_list
def get_neighbors(self, v):
return self.adjacency_list[v]
def h(self, n):
H={
'A': 1,
'B': 1,
'C': 1,
'D': 1
}

return H[n]
def a_star_algorithm(self, start_node, stop_node):

open_list = set([start_node])
closed_list = set([])
g = {}
g[start_node] = 0
parents = {}
parents[start_node] = start_node

while len(open_list) > 0:


n = None

PAGE N0. 12
SUSEC 1916810

for v in open_list:
if n == None or g[v] + self.h(v) < g[n] + self.h(n):
n = v;

if n == None:
print('Path does not exist!')
return None
if n == stop_node:
reconst_path = []

while parents[n] != n:
reconst_path.append(n)
n = parents[n]

reconst_path.append(start_node)
reconst_path.reverse()

print('Path found: {}'.format(reconst_path))


return reconst_path

for (m, weight) in self.get_neighbors(n):

if m not in open_list and m not in closed_list:


open_list.add(m)
parents[m] = n
g[m] = g[n] + weight
else:
if g[m] > g[n] + weight:
g[m] = g[n] + weight

PAGE N0. 13
SUSEC 1916810

parents[m] = n

if m in closed_list:
closed_list.remove(m)

open_list.add(m)
open_list.remove(n)
closed_list.add(n)

print('Path does not exist!')


return None

OUTPUT & DRIVER CODE:-

PAGE N0. 14
SUSEC 1916810

D).Write a program to conduct”BEST FIRST SEARCH”.

from queue import PriorityQueue


v = 14
graph = [[] for i in range(v)]

def best_first_search(source, target, n):


visited = [False] * n
visited = True
pq = PriorityQueue()
pq.put((0, source))
while pq.empty() == False:
u = pq.get()[1]
print(u, end=" ")
if u == target:
break

for v, c in graph[u]:
if visited[v] == False:
visited[v] = True
pq.put((c, v))
print()

def addedge(x, y, cost):


graph[x].append((y, cost))
graph[y].append((x, cost))

addedge(0, 1, 3)
addedge(0, 2, 6)
addedge(0, 3, 5)

PAGE N0. 15
SUSEC 1916810

addedge(1, 4, 9)
addedge(1, 5, 8)
addedge(2, 6, 12)
addedge(2, 7, 14)
addedge(3, 8, 7)
addedge(8, 9, 5)
addedge(8, 10, 6)
addedge(9, 11, 1)
addedge(9, 12, 10)
addedge(9, 13, 2)

source = 0
target = 9
best_first_search(source, target, v)

PAGE N0. 16
SUSEC 1916810

EXPERIMENT :- 4
Write a programme to conduct game search

#include <iostream>
#include <iomanip>
#include <array> using namespace std;
void printarray(int num[3][3])
{
for(int i = 0;i < 3; i++)
{
for(int j = 0; j< 3; j++)
{
cout << num[i][j] << " ";
}
cout << "\n";
}
}

void swapValues(int (&array)[3][3], int i1,int j1,int i2,int j2)


{
int temp = array[i1]
[j1]; array[i1][j1] =
array[i2][j2]; array[i2]
[j2] = temp;
}

void moveleft(int (&array)[3][3], int i, int j)


{
if(i==1&&j==1)
{
swapValues(array, i, j, i-
1, j); swapValues(array,
i, j, i+1, j);

PAGE N0. 17
SUSEC 1916810

}
else if(i==1&&j==2)
{
swapValues(array, i, j, i,
j-1); swapValues(array,
i, j, i, j-2);
}
else if(i==0&&j==0)
{
swapValues(array, i, j+2,
i, j); swapValues(array,
i, j+1, i, j);
}
else if(i==0&&j==2)
{
swapValues(array, i, j, i, j);
}
else
swapValues(array, i, j, i-
1, j); swapValues(array,
i, j, i+1, j);
}

void movedown(int (&array)[3][3], int i, int j)


{
if(i==0&&j==0)
{
swapValues(array, i, j,
i+1, j);
swapValues(array, i, j,
i+2, j);
}
else if(i==1&&j==1)
{

PAGE N0. 18
SUSEC 1916810

swapValues(array, i+1, j,
i, j); swapValues(array,
i-1, j, i, j);
}
else if(i==0&&j==2)
{
swapValues(array, i, j, i+1, j);
}
else
swapValues(array, i, j, i-
1, j); swapValues(array,
i, j, i+1, j);
}

void moveright(int (&array)[3][3], int i, int j)


{
if(i==0&&j==0)
{
swapValues(array, i, j+1,
i, j); swapValues(array,
i, j+2, i, j);
}
else if(i==1&&j==1)
{
swapValues(array, i, j+1,
i, j); swapValues(array,
i, j-1, i, j);
}
else if(i==1&&j==2)
{
swapValues(array, i, j-2,
i, j); swapValues(array,
i, j-1, i, j);
}
PAGE N0. 19
SUSEC 1916810

else
swapValues(array, i, j, i-
1, j); swapValues(array,
i, j, i+1, j);
}

void moveup(int (&array)[3][3], int i, int j)


{
if(i==0&&j==0)
{
swapValues(array, i, j,
i+2, j);
swapValues(array, i, j,
i+1, j);
}
else if(i==1&&j==1)
{
swapValues(array, i, j, i-
1, j); swapValues(array,
i, j, i+1, j);
}
else if(i==0&&j==2)
{
swapValues(array, i, j,
i+1, j);
swapValues(array, i, j,
i+2, j);
swapValues(array, i, j,
i+1, j);
}
else

PAGE N0. 20
SUSEC 1916810

swapValues(array, i, j, i-
1, j); swapValues(array,
i, j, i+2, j);
//int coord1d = j * 3 + i;
}
class Puzzle
{
public:
Puzzle();
void swapValues(int num[3][3], int i1, int
j1, int i2, int j2); //void moveleft(int[3][3],
int start1, int start2); void moveup(int
(&array)[3][3], int i, int j);
void moveright(int (&array)[3][3],
int i, int j); void moveleft(int
(&array)[3][3], int i, int j); void
movedown(int (&array)[3][3], int i,
int j); void printarray(int[3][3]);
};

int main()
{
int state1[3][3] = {{2, 8, 3}, {1, 6, 4}, {7, 0, 5}};
int state2[3][3] = {{2, 8, 1}, {4, 6, 3}, {0, 7, 5}};
int gstate[3][3] = {{1, 2, 3}, {8, 0, 4}, {7, 6, 5}};
cout << "this is state 1"
<< endl;
printarray(state1);
cout << "\n\n";
cout << "now this is state 2"
<< endl; printarray(state2);
cout << "\n\n";
cout << "now this is the goal state"
<< endl;; printarray(gstate);
int start1, start2;

PAGE N0. 21
SUSEC 1916810

cout << endl << endl << "please enter your starting point in the states
listed above going up or down" << endl;
cin >> start1;
cout << "now enter the point going left
to right" << endl; cin >> start2;
//moveleft(state1, start1, start2);
cout << "this is moving coordinate (1, 1)
upwards" << endl; moveup(state1, start1,
start2);
printarray(state
1); cout <<
endl;
cout << "this is moving coordinate (1, 1) to
the left" << endl; moveleft(state1, start1,
start2);
printarray(state
1); cout <<
endl;
cout << "this is moving coordinate (1, 1)
downwards" << endl; movedown(state1,
start1, start2);
printarray(state
1); cout <<
endl;
cout << "this is moving coordinate (1, 1) to the
right" << endl; moveright(state1, start1, start2);
printarray(state
1); cout <<
endl; cin.get();
cin.get();
return 0;
}

PAGE N0. 22
SUSEC 1916810

PAGE N0. 23
SUSEC 1916810

EXPERIMENT :- 5

Write a programme to construct a Bayesian network from given data.


import numpy as np
import pandas as pd
import csv
from pgmpy.estimators import MaximumLikelihoodEstimator
from pgmpy.models import BayesianModel
from pgmpy.inference import VariableElimination

heartDisease = pd.read_csv('heart.csv')
heartDisease = heartDisease.replace('?',np.nan)

print('Sample instances from the dataset are given below')


print(heartDisease.head())

print('\n Attributes and datatypes')


print(heartDisease.dtypes)

model= BayesianModel([('age','heartdisease'),('sex','heartdisease'),
('exang','heartdisease'),('cp','heartdisease'),('heartdisease','restecg'),
('heartdisease','chol')])
print('\nLearning CPD using Maximum likelihood estimators')
model.fit(heartDisease,estimator=MaximumLikelihoodEstimator)

print('\n Inferencing with Bayesian Network:')


HeartDiseasetest_infer = VariableElimination(model)

print('\n 1. Probability of HeartDisease given evidence= restecg')


q1=HeartDiseasetest_infer.query(variables=['heartdisease'],evidence={'restec
g':1})
print(q1)

PAGE N0. 24
SUSEC 1916810

print('\n 2. Probability of HeartDisease given evidence= cp ')


q2=HeartDiseasetest_infer.query(variables=['heartdisease'],evidence={'cp':2}
)
print(q2)

OUTPUT:-

PAGE N0. 25
SUSEC 1916810

EXPERIMENT :- 6

.Write a programme to run value and policy iteration in a grid


world.
def play_episodes(environment, n_episodes, policy):
def play_episodes(environment, n_episodes, policy):
wins = 0
total_reward = 0
for episode in range(n_episodes):
terminated = False
state = environment.reset()
while not terminated:
# Select best action to perform in a current state
action = np.argmax(policy[state])
# Perform an action an observe how environment
acted in response
next_state, reward, terminated, info =
environment.step(action)
# Summarize total reward
total_reward += reward
# Update current state
state = next_state
# Calculate number of wins over episodes
if terminated and reward == 1.0:
wins += 1
average_reward = total_reward / n_episodes
return wins, total_reward, average_reward

# Number of episodes to play


n_episodes = 10000
# Functions to find best policy

PAGE N0. 26
SUSEC 1916810

solvers = [('Policy Iteration', policy_iteration),


('Value Iteration', value_iteration)]
for iteration_name, iteration_func in solvers:
# Load a Frozen Lake environment
environment = gym.make('FrozenLake-v0')
# Search for an optimal policy using policy iteration
policy, V = iteration_func(environment.env)
# Apply best policy to the real environment
wins, total_reward, average_reward = play_episodes(environment,
n_episodes, policy)
print(f'{iteration_name} :: number of wins over {n_episodes}
episodes = {wins}')
print(f'{iteration_name} :: average reward over {n_episodes}
episodes = {average_reward} \n\n')

PAGE N0. 27
SUSEC 1916810

EXPERIMENT :- 7

Write a programme to do reinforcement learning in a grid world


def play(self, rounds=10):
i=0
while i < rounds:
# to the end of game back propagate reward
if self.State.isEnd:
# back propagate
reward = self.State.giveReward()
# explicitly assign end state to reward values
self.state_values[self.State.state] = reward # this is optional
print("Game End Reward", reward)
for s in reversed(self.states):
reward = self.state_values[s] + self.lr * (reward -
self.state_values[s])
self.state_values[s] = round(reward, 3)
self.reset()
i += 1
else:
action = self.chooseAction()
# append trace
self.states.append(self.State.nxtPosition(action))
print("current position {} action {}".format(self.State.state, action))
# by taking the action, it reaches the next state
self.State = self.takeAction(action)
# mark is end
self.State.isEndFunc()
print("nxt state", self.State.state)
print("---------------------")
def chooseAction(self):
# choose action with most expected value
mx_nxt_reward = 0

PAGE N0. 28
SUSEC 1916810

action = ""

if np.random.uniform(0, 1) <= self.exp_rate:


action = np.random.choice(self.actions)
else:
# greedy action
for a in self.actions:
# if the action is deterministic
nxt_reward = self.state_values[self.State.nxtPosition(a)]
if nxt_reward >= mx_nxt_reward:
action = a
mx_nxt_reward = nxt_reward
return action

OUTPUT:-

PAGE N0. 29

You might also like