0% found this document useful (0 votes)
12 views6 pages

AI Exp-8,9,10

Uploaded by

Samarth More
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views6 pages

AI Exp-8,9,10

Uploaded by

Samarth More
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

EXPERIMENT N0.

08
1. Forward Chaining Implementation (Python)
# Forward Chaining Algorithm in Python
# Knowledge Base: Facts and Rules
knowledge_base = {
'facts': ['Human(Socrates)'], # Known fact
'rules': ['Human(x) -> Mortal(x)'] # General rule}
# Function to check if a fact is true
def is_fact_true(fact, kb):
return fact in kb['facts']
# Function to apply forward chaining
def forward_chaining(goal, kb):
# Iterate over rules to see if they can be applied
for rule in kb['rules']:
if '->' in rule:
# Extract the condition and conclusion
condition, conclusion = rule.split(' -> ')
# Replace variable with specific instance in the knowledge base
condition = condition.replace('x', 'Socrates')
conclusion = conclusion.replace('x', 'Socrates')

# If the condition is true, derive the conclusion


if is_fact_true(condition, kb):
kb['facts'].append(conclusion)
# Check if the goal is in the derived facts
if is_fact_true(goal, kb):
print(f"Goal '{goal}' is proven by forward chaining.")
else:
print(f"Goal '{goal}' cannot be proven by forward chaining.")

# Prove the goal Mortal(Socrates)


goal = 'Mortal(Socrates)'
forward_chaining(goal, knowledge_base)

OUTPUT:
Goal 'Mortal(Socrates)' is proven by forward chaining.
2.Backward Chaining in Python

# Backward Chaining Algorithm in Python


# Knowledge Base: Facts and Rules
knowledge_base = {
'facts': ['Human(Socrates)'], # Known fact
'rules': ['Human(x) -> Mortal(x)'] # General rule}
# Function to check if a fact is true
def is_fact_true(fact, kb):
return fact in kb['facts']

# Function to apply backward chaining


def backward_chaining(goal, kb):
if is_fact_true(goal, kb):
print(f"Goal '{goal}' is already a fact.")
return True

# Check rules that can derive the goal


for rule in kb['rules']:
if '->' in rule:
condition, conclusion = rule.split(' -> ')
conclusion = conclusion.replace('x', 'Socrates')
if conclusion == goal:
# Try to prove the condition
condition = condition.replace('x', 'Socrates')
if backward_chaining(condition, kb):
kb['facts'].append(goal)
print(f"Goal '{goal}' is proven by backward chaining.")
return True
print(f"Goal '{goal}' cannot be proven by backward chaining.")
return False
# Prove the goal Mortal(Socrates)
goal = 'Mortal(Socrates)'
backward_chaining(goal, knowledge_base)

OUTPUT:
Goal 'Mortal(Socrates)' is proven by backward chaining.
3.Resolution in Prolog

Prolog code:

% Facts
human(socrates).

% Rules
mortal(X) :- human(X).

% Query the goal


% ?- mortal(socrates).

OUTPUT:
true.
EXPERIMENT NO:09
Construct the Bayesian Network in a Tool
Using Python with pgmpy
Here is how you can model and infer using Python and the pgmpy library:
Program:

# Importing necessary libraries


from pgmpy.models import BayesianNetwork
from pgmpy.factors.discrete import TabularCPD
from pgmpy.inference import VariableElimination
# Define the structure of the Bayesian Network
model = BayesianNetwork([('Human', 'Mortal')])
# Define the Conditional Probability Distributions (CPDs)
cpd_human = TabularCPD(variable='Human', variable_card=2, values=[[0.0], [1.0]]) # Socrates
is human with 100% probability
cpd_mortal = TabularCPD(variable='Mortal', variable_card=2,
values=[[0.01, 0.99], # P(Mortal=False | Human=False), P(Mortal=True |
Human=False)
[0.99, 0.01]], # P(Mortal=False | Human=True), P(Mortal=True | Human=True)
evidence=['Human'], evidence_card=[2])
# Adding CPDs to the model
model.add_cpds(cpd_human, cpd_mortal)
# Validate the model
assert model.check_model()
# Perform inference on the model
infer = VariableElimination(model)
# Query the probability that Socrates is mortal
query_result = infer.query(variables=['Mortal'], evidence={'Human': 1})
# Output the result
print(query_result)

OUTPUT:

+------------+------------+
| Mortal | phi(M) |
+------------+------------+
| Mortal(0) | 0.0100 |
| Mortal(1) | 0.9900 |
+------------+------------+
EXPERIMENT NO:10

class PlanningAgent:
def __init__(self):
self.actions = {
'Move(A, B)': {'preconditions': ['At(Room A)'], 'effects': ['At(Room B)']},
'Move(B, A)': {'preconditions': ['At(Room B)'], 'effects': ['At(Room A)']}
}
def is_goal_state(self, state, goal_state):
return state == goal_state

def applicable_actions(self, state):


applicable = []
for action, details in self.actions.items():
if all(pre in state for pre in details['preconditions']):
applicable.append(action)
return applicable

def apply_action(self, state, action):


# Apply action effects to the current state
effects = self.actions[action]['effects']
return effects

def search_plan(self, initial_state, goal_state):


# Use BFS for simple state-space search
from collections import deque

# Queue for BFS


queue = deque([(initial_state, [])])
visited = set()

while queue:
current_state, plan = queue.popleft()

# Check if we've reached the goal


if self.is_goal_state(current_state, goal_state):
return plan

# Add state to visited


visited.add(tuple(current_state))

# Get applicable actions


for action in self.applicable_actions(current_state):
new_state = self.apply_action(current_state, action)
# Add to the queue if the state has not been visited
if tuple(new_state) not in visited:
queue.append((new_state, plan + [action]))

return None # No plan found

# Define the planning agent


agent = PlanningAgent()

# Initial state: Agent is at Room A


initial_state = ['At(Room A)']

# Goal state: Agent wants to be in Room B


goal_state = ['At(Room B)']

# Search for a plan


plan = agent.search_plan(initial_state, goal_state)

# Output the plan


print("Plan:", plan)

OUTPUT:
Plan: ['Move(A, B)']

You might also like