0% found this document useful (0 votes)
15 views21 pages

Intelligent and Expert Sys Lab File

Uploaded by

kashishrajput773
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)
15 views21 pages

Intelligent and Expert Sys Lab File

Uploaded by

kashishrajput773
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/ 21

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

JIMS ENGINEERING MANAGEMENT TECHNICAL


CAMPUS, GREATER NOIDA

AFFILIATED TO

GURU GOBIND SINGH INDRAPRASTHA UNIVERSITY

ACADEMIC SESSION: 2024-2025

SEMESTER- VII

INTELLIGENT AND EXPERT SYSTEMS LAB

SUB-CODE: AI-405P

SUBMITTED BY:- SUBMITTED TO:-


NAME: Dr. SHILPI SINGH

SECTION:
ENROLLMENT NUMBER:

BRANCH:
INDEX
S.No Name of the Experiment Date Signature Remarks

1. Study of PROLOG. Write the 21-08-2024


following programs using
PROLOG/LISP.
2. Write simple facts for the following statements 28-08-2024
using PROLOG.

a. Ram likes mango.

b. Seema is a girl.
c. Bill likes Cindy.

d. Rose is red.
e. John owns gold.

3. Write predicates, one convert centigrade 04-09-2024


temperature to Fahrenheit, the other checks if
the temperature is below freezing using
PROLOG.

4. Write a program to solve 8 queen ’s problem 11-09-2024

5. Solve any problem using depth first search. 18-09-2024

6. Solve any problem using best first search. 25-09-2024

7. Solve 8-puzzle problem using best first search. 09- 10-2024

8. Solve Robot (Traversal) problem using means 16- 10-2024


end analysis.

9. Solve Travelling Salesman Problem 23- 10-2024

10. Experiment based on Knowledge 25- 10-2024


Representation.

11. Experiment based on reasoning 25- 10-2024


PROGRAM NO. - 1

OBJECTIVES: STUDY OF PROLOG

PROLOG-PROGRAMMING IN LOGIC

PROLOG stands for Programming In Logic – an idea that emerged in the early 1970’s to use
logic as programming language.The early developers of this idea included Robert Kowalski
at Edinburgh ( on the theoretical side ),Marrten van Emden at Edinburgh ( experimental
demonstration) and Alian Colmerauer at Marseilles (implementation ). David D.H. Warren’s
efficient implementation at Edinburgh in the mid - 1970’s greatly contributed to the
popularity of PROLOG.

PROLOG is a programming language centered around a small set of basic mechanisms,


Including pattern matching, tree based data structuring and automatic backtracking. This
Small set constitutes a surprisingly powerful and flexible programming framework.
PROLOG is especially well suited for problems that involve objects- in particular, structured
objects- and relations between them.

SYMBOLIC LANGUAGE

PROLOG is a programming language for symbolic, non-numeric computation. It is


Especially well suited for solving problems that involve objects and relations between objects.
For example, it is an easy exercise in prolog to express spatial relationship between objects,
such as the blue sphere is behind the green one. It is also easy to state a more general rule: if
object X is closer to the observer than object Y, and object Y is closer than Z, then X must be
closer than Z. PROLOG can reason about the spatial relationships and their consistency with
respect to the general rule. Features like this make PROLOG a powerful language for
Artificial Language(AI) and non- numerical programming.

There are well-known examples of symbolic computation whose implementation in other


standard languages took tens of pages of indigestible code. When the same algorithms
were implemented in PROLOG, the result was a crystal-clear program easily fitting on one
page.

FACTS, RULES AND QUERIES

Programming in PROLOG is accomplished by creating a database of facts and rules about


objects, their properties, and their relationships to other objects. Queries then can be
posed about the objects and valid conclusions will be determined and returned by the
program. Responses to user queries are determined through a form of inferencing control
known as resolution.

FOR EXAMPLE:
a) FACTS:

b) Properties of objects, or relationships between objects;


c) "Dr Turing lectures in course 9020", is written in Prolog as:
d) lectures(turing, 9020).
e) Notice that:
a. names of properties/relationships begin with lower case letters.
b. the relationship name appears as the first term
c. objects appear as comma-separated arguments within
parentheses. d. A period "." must end a fact.
e. objects also begin with lower case letters. They also can begin with digits
(like 9020), and can be strings of characters enclosed in quotes (as in
reads(fred,
"War and Peace")).
f) lectures(turing, 9020). is also called a predicate

Facts about a hypothetical computer science department:

% lectures(X, Y): person X lectures in course Y


lectures (Turing, 9020).
lectures (codd, 9311).
lectures (backus, 9021).
lectures(Ritchie, 9201).
lectures(minsky, 9414).
lectures(codd, 9314).

% studies(X, Y): person X studies in course Y


studies(fred, 9020).
studies(jack, 9311).
studies(jill, 9314).
studies(jill, 9414).
studies(henry, 9414).
studies(henry, 9314).

%year(X, Y): person X is in year Y


year(fred, 1).
year(jack, 2).
year(jill, 2).
year(henry, 4).

Some facts about family relationships could be written as :

sister(sue,bill)

parent(ann,sam)

male(jo)

female(riya)

b ) RULES:
To represent the general rule for grandfather, we write:

grandfather(X,Z)

parent(X,Y)

parent(Y,Z)

male(X)

c) QUERIES:

. Once we have a database of facts (and, soon, rules) we can ask questions
about the stored information.
. Suppose we want to know if Turing lectures in course 9020. We can ask:

% prolog -s facts03
(multi-line welcome message) facts03 loaded into Prolog
?- lectures(turing, 9020). "?-" is Prolog's prompt
true. output from Prolog
?- <control-D> hold down control & press D
% to leave Prolog

. Notice that:
o In SWI Prolog, queries are terminated by a full stop.
o To answer this query, Prolog consults its database to see if this is a known fact.
o In example dialogues with Prolog, the text in green italics is what the user
types.

Another example query

?- lectures(codd, 9020).
false.

. if answer is true., the query succeeded


. if answer is false., the query failed. Note: many early versions of Prolog,
including early versions of SWI-Prolog, say No instead of false. See the article on
negation in the Prolog dictionary to find out why No. is a more accurate
descrectures(xyzzy, 9020).
though a person inspecting the database can see that fred is a student, not a lecturer,
and that xyzzy is neither student nor lecturer.

Given a database of facts and rules such as that above, we may make queries by typing
after a query a symbol ‘?
’ statements such as: ?
_ Parent(X,sam) X=ann ?

_grandfather(X,Y)

X=jo, Y=sam

Backtracking in Prolog

. Who does Codd teach?


. ?- lectures(codd, Course), studies(Student, Course).
. Course = 9311
. Student = jack ;
.
. Course = 9314
. Student = jill ;
.
. Course = 9314
. Student = henry ;
. Prolog solves this problem by proceeding left to right and then backtracking.
. When given the initial query, Prolog starts by trying to solve
. lectures(codd, Course)
. There are six lectures clauses, but only two have codd as their first argument.
. Prolog uses the first clause that refers to codd: lectures(codd, 9311).
. With Course = 9311, it tries to satisfy the next goal, studies(Student, 9311).
. It finds the fact studies(jack, 9311). and hence the first solution: (Course =
9311, Student = jack)

Backtracking in Prolog 2

. After the first solution is found, Prolog retraces its steps up the tree and looks
for alternative solutions.
. First it looks for other students studying 9311 (but finds none).
. Then it
o backs up
o rebinds Course to 9314,
o goes down the lectures(codd, 9314) branch
o tries studies(Student, 9314),
o finds the other two solutions:
(Course = 9314, Student = jill)
and ( Course = 9 3 1 4 , Student = henry) .
Backtracking in Prolog 3

To picture what happens when Prolog tries to find a solution and backtracks, we draw a
" proof tree":

PROLOG IN DESIGINING EXPERT SYSTEMS

An expert system is a set of programs that manipulates encoded knowledge to solve


problems in a specialized domain that normally requires human expertise. An expert
system’s knowledge is obtained from expert sources such as texts, journal articles,
databases etc. and encoded in a form suitable for the system to use in its inference or
reasoning processes. Once a sufficient body of expert knowledge has been acquired, it must
be encoded in some form, loaded into knowledge base, then tested, and refined
continually throughout the life of the system.

PROLOG serves as a powerful language in designing expert systems because of its


following features:

• Use of knowledge rather than data

• Modification of the knowledge base without recompilation of the control programs.

• Capable of explaining conclusion.

• Symbolic computations resembling manipulations of natural language.

• Reason with meta-knowledge.

META PROGRAMMING
A meta program is a program that takes other programs as data. Interpreters and compilers
are examples of meta-programs. Meta-interpreter is a particular kind of metaprogram: an
interpreter for a language written in that language. So a PROLOG meteinterpreter is an
interpreter for PROLOG, itself written in PROLOG.

Due to its symbol- manipulation capabilities, PROLOG is a powerful language for


metaprogramming. Therefore, it is often used as an implementation language for other
languages. PROLOG is particularly suitable as a language for rapid prototyping where we are
interested in implementing new ideas quickly. New ideas are rapidly implemented and
experimented with

Applications of Prolog

Some applications of Prolog are:

. intelligent data base retrieval


. natural language understanding
. expert systems
. specification language
. machine learning
. robot planning
. automated reasoning
. problem solving
PROGRAM NO. - 2

Write simple fact for the statements using Python:

a. Ram likes mango.


b. Seema is a girl.
c. Bill likes Cindy.
d. Rose is red.
e. John owns gold.

Code:
# Facts as simple relations
facts = {
'Ram': 'likes mango',
'Seema': 'is a girl',
'Bill': 'likes Cindy',
'Rose': 'is red',
'John': 'owns gold'
}

# Display all facts


for person, fact in facts.items():
print(f" {person} {fact}.")

OUTPUT:
PROGRAM NO .- 3

Write predicates, one converts centigrade temperatures to Fahrenheit, the other checks
if a temperature is below freezing using Python.

Code:
def celsius_to_fahrenheit(celsius):
return (celsius * 9/5) + 32

def is_below_freezing(celsius):
return celsius < 0

temp = 29.84
fahrenheit = celsius to fahrenheit(temp)
print(f"Temperature in Fahrenheit: {fahrenheit}")

if is_below_freezing(temp):
print("The temperature is below freezing.")
else:
print("The temperature is above freezing.")

OUTPUT:
PROGRAM NO- 4

Write a program to solve 8 queens’ problem

Code:
def is_safe(board, row, col):
for i in range(col):
if board[row][i] == 1:
return False
Code:
def is_safe(board, row, col):
for i in range(col):
if board[row][i] == 1:
return False
for i, j in zip(range(row, - 1, - 1), range(col, - 1, - 1)):
if board[i][j] == 1:
return False
for i, j in zip(range(row, len(board), 1), range(col, - 1, - 1)):
if board[i][j] == 1:
return False
return True

def solve n queens(board, col):


if col >= len(board):
return True
for i in range(len(board)):
if is_safe(board, i, col):
board[i][col] = 1
if solve n queens(board, col + 1):
return True
board[i][col] = 0
return False

def print board(board)_:


for row in board:
print(" ".join("Q" if col else "." for col in row))

def solve 8 queens():


n=8
board = [[0] * n for _ in range(n)]
if solve n queens(board, 0):
print_board(board)
else:
print("Solution does not exist")

solve 8 queens()
OUTPUT:
PROGRAM NO:-5

Solve any problem using depth first search

Code:
defdfs(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
print(start, end=" ")
for neighbor in graph[start]:
if neighbor not in visited:
dfs(graph, neighbor, visited)

graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': ['F'],
'F': []
}

dfs(graph, 'A')

OUTPUT:
PROGRAM NO:- 6

Solve any problem using best first search.

Code:
import heapq

def best_first_search(graph, start, goal, h):


pq = []
heapq.heappush(pq, (h[start], start))
visited = set()

while pq:
cost, node = heapq.heappop(pq)
if node = = goal:
print(f"Goal {goal} found!")
return
visited.add(node)
print(f"Visiting node {node}")
for neighbor, weight in graph[node]:
if neighbor not in visited:
heapq.heappush(pq, (h[neighbor], neighbor))

graph = {
'A': [('B', 1), ('C', 3)],
'B': [('D', 5), ('E', 6)],
'C': [('F', 7)],
'D': [],
'E': [('F', 4)],
'F': []
}

heuristic = {
'A': 10,
'B': 8,
'C': 5,
'D': 7,
'E': 3,
'F': 0
}

best_first_search(graph, 'A', 'F', heuristic)

OUTPUT:
PROGRAM NO:- 7

Solve 8‐puzzle problem using best first search

Code:
from collections import deque

def is_solvable(state):
inversions = 0
flat_state = [num for row in state for num in row if num != 0]
for i in range(len(flat state_)):
for j in range(i + 1, len(flat state_)):
if flat_state[i] > flat_state[j]:
inversions += 1
return inversions % 2 = = 0

def bfs(start, goal):


queue = deque([start])
visited = set()
visited.add(tuple(map(tuple, start)))

while queue:
current = queue.popleft()
if current = = goal:
print("Solution found!")
return
# Implement movement logic here (left, right, up, down)
# Expand the state and add new states to the queue
# Check if the state is already visited
print("No solution exists.")

initial_state = [[1, 2, 3], [4, 0, 5], [6, 7, 8]]


goal_state = [[1, 2, 3], [4, 5, 6], [7, 8, 0]]

if is_solvable(initial_state):
bfs(initial_state, goal_state)
else:
print("This puzzle is not solvable.")

OUTPUT:
PROGRAM NO:-8

Solve Robot (traversal) problem using means End Analysis

Code:
# Example of robot navigation
def robot_navigation(start, goal):
print(f"Robot starts at {start}")
while start != goal:
if start[0] < goal[0]:
start = (start[0] + 1, start[1])
elif start[0] > goal[0]:
start = (start[0] - 1, start[1])
if start[1] < goal[1]:
start = (start[0], start[1] + 1)
elif start[1] > goal[1]:
start = (start[0], start[1] - 1)
print(f"Robot moves to {start}")
print("Robot reached the goal.")

robot navigation_((0, 0), (3, 3))

OUTPUT:
PROGRAM NO:-9

Solve traveling salesman problem

Code:
from itertools import permutations

def tsp_bruteforce(graph, start):


vertices = list(graph.keys())
vertices.remove(start)
min_path = float('inf')
for perm in permutations(vertices):
current_cost = 0
k = start
for j in perm:
current_ cost + = graph[ k ] [ j ]
k=j
current_cost += graph[k][start]
min_path = min(min_path, current cost)_
return min_path

graph = {
'A': {'B': 10, 'C': 15, 'D': 20},
'B': {'A': 10, 'C': 35, 'D': 25},
'C': {'A': 15, 'B': 35, 'D': 30},
'D': {'A': 20, 'B': 25, 'C': 30}
}

print("Minimum TSP cost:", tsp_bruteforce(graph, 'A'))

OUTPUT:
PROGRAM NO:-10

Experiment based on knowledge representation.

Code:
class KnowledgeBase:
def__init (self):
# Initialize an empty set for facts and an empty list for rules
self.facts = set()
self.rules = []

def add_fact(self, fact):


"""
Adds a fact to the knowledge base.
:param fact: String representing the fact
"""
self.facts.add(fact)
print(f"Added fact: {fact}")

def add_rule(self, rule):


"""
Adds a rule to the knowledge base.
:param rule: String representing the rule
"""
self.rules.append(rule)
print(f"Added rule: {rule}")

def check_fact(self, fact):


"""
Checks if a fact is in the knowledge base.
:param fact: String representing the fact
:return: Boolean (True if fact is in the knowledge base, False otherwise)
"""
return fact in self.facts

def print_facts(self):
"""
Prints all the facts currently in the knowledge base.
"""
print("\nCurrent Facts in Knowledge Base:")
for fact in self.facts:
print(fact)

def print_rules(self):
"""
Prints all the rules currently in the knowledge base.
"""
print("\nCurrent Rules in Knowledge Base:")
for rule in self.rules:
print(rule)

# Example usage:
if __name__ == "__main__":
# Create an instance of the KnowledgeBase
kb = KnowledgeBase()

# Add some facts to the knowledge base


kb.add_fact("Cats are mammals")
kb.add_fact("Birds can fly")
kb.add_fact("Fish live in water")

# Add some rules to the knowledge base


kb.add_rule("If it has feathers, it is a bird")
kb.add_rule("If it has scales, it is a fish")

# Check if a fact exists in the knowledge base


print("\nChecking if the fact 'Fish live in water' exists:")
print(kb.check_fact("Fish live in water"))

# Print all facts in the knowledge base


kb.print_facts()

# Print all rules in the knowledge base


kb.print_rules()

OUTPUT:
Program No:- 11

Experiment based on Reasoning

Code:
class KnowledgeBase:
def__init (self):
self.facts = set() # A set to store known facts
self.rules = [] # A list to store inference rules

def add_fact(self, fact):


self.facts.add(fact)
print(f"Added fact: {fact}")

def add_rule(self, rule):


self.rules.append(rule)
print(f"Added rule: {rule}")

def infer(self):
inferred = True
while inferred:
inferred = False
for rule in self.rules:
if rule():
inferred = True

def check_fact(self, fact):


return fact in self.facts

# Create an instance of the knowledge base


kb = KnowledgeBase()

# Function to define rules


def rule_animal_is_mammal():
if "has_hair" in kb.facts and "gives_birth" in kb.facts:
if "is_mammal" not in kb.facts:
kb.add_fact("is_mammal")
return True
return False

def rule_animal_is_bird():
if "has_feathers" in kb.facts and "lays_eggs" in kb.facts:
if "is_bird" not in kb.facts:
kb.add_fact("is_bird")
return True
return False

def rule_is_warm_blooded():
if "is_mammal" in kb.facts or "is_bird" in kb.facts:
if "is_warm_blooded" not in kb.facts:
kb.add_fact("is_warm_blooded")
return True
return False
# Add rules to the knowledge base
kb.add_rule(rule_animal_is_mammal)
kb.add_rule(rule_animal_is_bird)
kb.add_rule(rule_is_warm_blooded)

# Add initial facts to the knowledge base


kb.add_fact("has_hair")
kb.add_fact("gives_birth")

# Perform reasoning (inference)


print("\nStarting inference process:")
kb.infer()

# Check and print the final facts


print("\nFinal Facts in the Knowledge Base:")
for fact in kb.facts:
print(fact)

OUTPUT:

You might also like