0% found this document useful (0 votes)
10 views

AI Record Final

AL lab record for university exam

Uploaded by

sri2krishna123
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)
10 views

AI Record Final

AL lab record for university exam

Uploaded by

sri2krishna123
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/ 37

EX.NO:1.

a IMPLEMENTATION OF 8-PUZZLE PROBLEM

DATE:

AIM:

The aim of this project is to solve the 8-puzzle problem. The goal is to find the shortest
sequence of moves to arrange the tiles from a given starting position to the target configuration.

ALGORITHM:

1. Start with the puzzle's initial state and the goal state.
2. Create a list to keep track of states to explore.
3. Repeat:

● Pick the state that looks closest to the solution (based on how far the tiles are from
their correct positions).
● If it’s the goal state, stop.
● Otherwise, move the blank tile in all possible directions to create new states.
● Add these new states to the list to explore later.

4. Stop when you find the goal or when there are no more states to explore.

PROGRAM:

from heapq import heappop, heappush

import itertools

class PuzzleState:

def __init__(self, board, moves=0, prev=None):

self.board = board

self.moves = moves

self.prev = prev

self.blank_pos = board.index(0)

def __lt__(self, other):

return (self.moves + self.heuristic()) < (other.moves + other.heuristic())


def heuristic(self):

"""Calculate the Manhattan distance heuristic."""

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

return sum(abs((val % 3) - (goal.index(val) % 3)) + abs((val // 3) - (goal.index(val) // 3))


for val in self.board if val != 0)

def get_neighbors(self):

"""Generate all valid neighbor states by moving tiles."""

neighbors = []

moves = [(-1, 0), (1, 0), (0, -1), (0, 1)] # Up, Down, Left, Right

x, y = self.blank_pos % 3, self.blank_pos // 3

for move in moves:

nx, ny = x + move[0], y + move[1]

if 0 <= nx < 3 and 0 <= ny < 3:

new_blank_pos = ny * 3 + nx

new_board = list(self.board)

new_board[self.blank_pos], new_board[new_blank_pos] =
new_board[new_blank_pos], new_board[self.blank_pos]

neighbors.append(PuzzleState(new_board, self.moves + 1, self))

return neighbors

def a_star(start_board):

"""Solve the 8-puzzle problem using A* algorithm."""

start_state = PuzzleState(start_board)

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

open_list = []

closed_set = set()

heappush(open_list, start_state)

while open_list:
current_state = heappop(open_list)

if current_state.board == goal_state.board:

return current_state

closed_set.add(tuple(current_state.board))

for neighbor in current_state.get_neighbors():

if tuple(neighbor.board) in closed_set:

continue

heappush(open_list, neighbor)

return None

def print_solution(state):

"""Print the solution path."""

path = []

while state:

path.append(state.board)

state = state.prev

for board in reversed(path):

print_board(board)

print()

def print_board(board):

"""Prints the board in a readable format."""

for i in range(0, len(board), 3):

print(" ".join(str(x) if x != 0 else "." for x in board[i:i+3]))

print()

def main():

# Example starting board (you can change this to any solvable configuration)

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

solution = a_star(start_board)
if solution:

print("Solution found!")

print_solution(solution)

else:

print("No solution exists")

if __name__ == "__main__":

main()

OUTPUT:

Solution found!

123

456

78.

RESULT:

Thus the output for implementation of 8 queens problem is executed and verified.
EX.NO:1.b IMPLEMENTATION OF 8-QUEENS PROBLEM

DATE:

AIM:

The aim of this program is to place N queens on an N x N chessboard so that no two


queens threaten each other. It uses a backtracking algorithm to find a valid configuration. The
program outputs the solution when found.

ALGORITHM:

1 Initialize the Board:

● Create an N x N board with all cells set to False (no queens placed).

2 Start with the First Column:

● Begin placing queens in column 0.

3 Place Queens:

● For each row in the current column:

● Check if placing a queen is safe (no other queens in the same row, column, or
diagonals).
● If safe, place the queen and move to the next column (call the function
recursively).

4 Check for Solutions:

● If all queens are placed, print the board.


● If a row doesn't work, backtrack (remove the queen and try the next row).

5 Repeat:

● Continue until all columns are processed or no solution exists.

6 Output:

● If a solution is found, display the board; if not, indicate that no solution exists.
PROGRAM:

def print_board(board):

"""Prints the chessboard with queens."""

for row in board:

print(" ".join("Q" if cell else "." for cell in row))

print()

def is_safe(board, row, col):

"""Checks if it's safe to place a queen at (row, col)."""

# Check this column on the left side

for i in range(col):

if board[row][i]:

return False

# Check upper diagonal on the left side

for i, j in zip(range(row, -1, -1), range(col, -1, -1)):

if board[i][j]:

return False

# Check lower diagonal on the left side

for i, j in zip(range(row, len(board), 1), range(col, -1, -1)):

if board[i][j]:

return False

return True

def solve_queens(board, col):

"""Solves the 8-Queens problem using backtracking."""

if col >= len(board):

return True

for i in range(len(board)):
if is_safe(board, i, col):

board[i][col] = True

if solve_queens(board, col + 1):

return True

board[i][col] = False

return False

def main():

N=8

board = [[False for _ in range(N)] for _ in range(N)]

if solve_queens(board, 0):

print_board(board)

else:

print("No solution exists")

if __name__ == "__main__":

main()

OUTPUT:

Q.......
......Q.
....Q...
.......Q
.Q......
...Q....
.....Q..
..Q.....

RESULT:

Thus the output for implementation of 8 queens problem is executed and verified.
EX.NO:1.c IMPLEMENTATION OF CRYPTARITHMETIC PROBLEM

DATE:

AIM:

The aim of this program is to solve cryptarithmetic puzzles by substituting letters with
digits to form valid equations. It uses permutations to explore all possible digit assignments
and checks for valid solutions. The program outputs the mapping of letters to digits if a solution
is found.

ALGORITHM:

1. Parse the puzzle to get the LHS and RHS of the equation.
2. Collect unique letters from both sides and ensure there are 10 or fewer.
3. Generate digit combinations for the letters using permutations.
4. Replace letters with digits and check if the equation holds true.
5. Return the solution if found, or indicate no solution exists.

PROGRAM:

from itertools import permutations

def solve_cryptarithmetic(puzzle):

# Extract letters and equation from the puzzle

puzzle = puzzle.replace(' ', '')

parts = puzzle.split('=')

if len(parts) != 2:

raise ValueError("Puzzle must have exactly one '='.")

lhs = parts[0].split('+')

rhs = parts[1]

letters = set(''.join(lhs) + rhs)

if len(letters) > 10:

raise ValueError("Too many unique letters for a single digit solution.")


# Generate all possible digit assignments

for perm in permutations(range(10), len(letters)):

letter_to_digit = dict(zip(letters, perm))

# Replace letters with digits in the puzzle parts

lhs_digits = [replace_letters(part, letter_to_digit) for part in lhs]

rhs_digit = replace_letters(rhs, letter_to_digit)

# Check if the equation is valid

try:

if sum(int(part) for part in lhs_digits) == int(rhs_digit):

return letter_to_digit

except ValueError:

continue # Skip cases with invalid numbers

return None

def replace_letters(expression, letter_to_digit):

return ''.join(str(letter_to_digit[char]) if char in letter_to_digit else char for char in


expression)

# Example puzzle: SEND + MORE = MONEY

puzzle = 'SEND + MORE = MONEY'

solution = solve_cryptarithmetic(puzzle)

if solution:

print("Solution found:")

for letter, digit in solution.items():

print(f"{letter} = {digit}")

else:

print("No solution found.")


OUTPUT:

Solution found:
O=0
R=8
N=6
E=5
M=1
D=7
Y=2
S=9

RESULT:

Thus the output for implementation of cryptarithmetic problem is executed and verified.
EX.NO:2 IMPLEMENTATION OF A* AND MEMORY BOUND A*

DATE:

AIM:

The A* and memory-bounded A* algorithms aim to find the shortest path in a graph
from a starting point to a goal. They use a priority queue to explore paths while balancing cost
and estimated distance to the goal. The memory-bounded version limits memory usage during
the search.

ALGORITHM:

A* Search Algorithm

1. Initialize: Create the graph and add the starting vertex to a priority queue.
2. Search:
o While the queue is not empty:
▪ Dequeue the lowest-cost vertex.
▪ If it’s the goal, reconstruct and return the path.
▪ For each neighbor, calculate the cost and update if it's lower.
3. Return Path: If the goal is reached, trace back the path.

Memory-Bounded A* Search Algorithm

1. Initialize: Create the graph and add the starting vertex to a priority queue.
2. Search:
o While the queue is not empty:
▪ Dequeue the lowest-cost vertex.
▪ If it’s the goal, reconstruct and return the path.
▪ For each neighbor, calculate the cost and update if it's lower.
▪ If the memory limit is exceeded, return "Memory limit exceeded."
3. Return Path: If the goal is reached, trace back the path.

PROGRAM:

import heapq

class Graph:

def __init__(self):
self.vertices = {}

def add_vertex(self, id):

self.vertices[id] = Vertex(id)

def add_edge(self, from_id, to_id, cost):

self.vertices[from_id].add_neighbor(to_id, cost)

class Vertex:

def __init__(self, id):

self.id = id

self.neighbors = {}

def add_neighbor(self, neighbor_id, cost):

self.neighbors[neighbor_id] = cost

def heuristic(self, goal_id):

return abs(ord(self.id) - ord(goal_id))

def a_star_search(graph, start_id, goal_id):

frontier = [(0, start_id)]

came_from = {start_id: None}

cost_so_far = {start_id: 0}

while frontier:

current_cost, current_id = heapq.heappop(frontier)

if current_id == goal_id:
break

for neighbor_id, cost in graph.vertices[current_id].neighbors.items():

new_cost = cost_so_far[current_id] + cost

if neighbor_id not in cost_so_far or new_cost < cost_so_far[neighbor_id]:

cost_so_far[neighbor_id] = new_cost

priority = new_cost + graph.vertices[current_id].heuristic(goal_id)

heapq.heappush(frontier, (priority, neighbor_id))

came_from[neighbor_id] = current_id

return reconstruct_path(came_from, start_id, goal_id)

def reconstruct_path(came_from, start_id, goal_id):

path, current_id = [], goal_id

while current_id != start_id:

path.append(current_id)

current_id = came_from[current_id]

path.append(start_id)

return path[::-1] # Reverse the path

def memory_bounded_a_star_search(graph, start_id, goal_id, memory_limit):

frontier = [(0, start_id)]

came_from = {start_id: None}

cost_so_far = {start_id: 0}

while frontier:

current_cost, current_id = heapq.heappop(frontier)

if current_id == goal_id:

break

for neighbor_id, cost in graph.vertices[current_id].neighbors.items():

new_cost = cost_so_far[current_id] + cost

if neighbor_id not in cost_so_far or new_cost < cost_so_far[neighbor_id]:


cost_so_far[neighbor_id] = new_cost

priority = new_cost + graph.vertices[current_id].heuristic(goal_id)

heapq.heappush(frontier, (priority, neighbor_id))

came_from[neighbor_id] = current_id

if len(frontier) > memory_limit:

return "Memory limit exceeded", None

return reconstruct_path(came_from, start_id, goal_id)

# Example usage

graph = Graph()

vertices = ["A", "B", "C", "D", "E", "F", "G"]

for vertex_id in vertices:

graph.add_vertex(vertex_id)

edges = [("A", "B", 5), ("A", "C", 3), ("B", "D", 4), ("C", "D", 2),

("C", "E", 6), ("D", "F", 7), ("E", "F", 4), ("E", "G", 5),

("F", "G", 3)]

for edge in edges:

graph.add_edge(*edge)

# Run A* search

start_id = "A"

goal_id = "G"

path_a_star = a_star_search(graph, start_id, goal_id)

print("A* Path:", path_a_star)

# Run Memory-Bounded A* search

memory_limit = 1000

path_ma_star = memory_bounded_a_star_search(graph, start_id, goal_id, memory_limit)

print("MA* Path:", path_ma_star)


OUTPUT:

A* Path: ['A', 'C', 'E', 'G']


MA* Path: ['A', 'C', 'E', 'G']

RESULT:

Thus the output for implementation of A* and memory bound A* executed and
verified.
EX.NO:3 IMPLEMENTATION OF MIN-MAX ALGORITHM

DATE:

AIM:

The aim of this program is to create a simple Rock-Paper-Scissors game where a player
can compete against a randomly choosing AI opponent. The program allows for repeated
rounds of play until the player decides to exit. It determines and announces the winner based
on the standard rules of the game.

ALGORITHM:

1. Start Game:
2. Print a welcome message.
3. Define Moves:
4. List possible moves: ['rock', 'paper', 'scissors'].
5. Game Loop:
6. While true:
a. Prompt player for their move or "quit" to exit.
b. If "quit", exit the loop.
c. If input is invalid, print an error and repeat.
7. AI Move:
8. Randomly select an AI move from the list.
9. Determine Winner:
10. Compare player and AI moves:
a. If same, declare a draw.
b. If player wins, print "You win!".
c. If AI wins, print "AI wins!".
11. Repeat:
12. Go back to step 3 for the next round.

PROGRAM:

import random

def determine_winner(player_move, ai_move):

if player_move == ai_move:

return "It's a draw!"

elif (player_move == 'rock' and ai_move == 'scissors') or \

(player_move == 'paper' and ai_move == 'rock') or \


(player_move == 'scissors' and ai_move == 'paper'):

return "You win!"

else:

return "AI wins!"

def play_game():

print("Welcome to Rock-Paper-Scissors!")

moves = ['rock', 'paper', 'scissors']

while True:

player_move = input("Enter rock, paper, or scissors (or 'quit' to exit): ").lower()

if player_move == 'quit':

break

if player_move not in moves:

print("Invalid input! Please try again.")

continue

ai_move = random.choice(moves)

print(f"AI chose: {ai_move}")

result = determine_winner(player_move, ai_move)

print(result)

play_game()
OUTPUT:

Welcome to Rock-Paper-Scissors!
Enter rock, paper, or scissors (or 'quit' to exit): rock
AI chose: paper
AI wins!
Enter rock, paper, or scissors (or 'quit' to exit): paper
AI chose: paper
It's a draw!
Enter rock, paper, or scissors (or 'quit' to exit): scissor
Invalid input! Please try again.
Enter rock, paper, or scissors (or 'quit' to exit): scissors
AI chose: paper
You win!

RESULT:

Thus the output for implementattion of min-max algorithm for game theory is
executed and verified
EX.NO:4 IMPLEMENTATION OF CONSTRAINT SATISFACTION
PROBLEMS
DATE:

AIM:

The aim of this program is to solve the map coloring problem by ensuring that no
adjacent regions have the same color. It uses a backtracking algorithm to explore different color
assignments. The program outputs a valid coloring solution or states if none exists.

ALGORITHM:

1. Initialize Variables:

● Define regions and their adjacency relationships.


● Create a list to hold the color assigned to each region (initialize with no color).

2. Define a Function is_safe(region, color):

● Check if assigning color to region is safe by verifying that no adjacent regions have
the same color.

3.Define a Recursive Function map_coloring(index):

● If all regions are colored, return success.


● For each color:
o If it’s safe to color the region:
▪ Assign the color.
▪ Recursively attempt to color the next region.
▪ If successful, return success.
▪ If not, backtrack by removing the color assignment.

4. Call map_coloring(0):

● Start coloring from the first region.

5.Output the Result:

● Print the color assignments or indicate if no solution exists.


PROGRAM:

def is_safe(region, color, colors, adjacency):

""" Check if it's safe to assign the color to the region. """

for neighbor in adjacency[region]:

if colors[neighbor] == color:

return False

return True

def map_coloring_util(regions, colors, adjacency, index, num_colors):

""" Utility function to solve the map coloring problem using backtracking. """

if index == len(regions):

return True # All regions are colored

region = regions[index]

for color in range(num_colors):

if is_safe(region, color, colors, adjacency):

colors[region] = color # Assign color

if map_coloring_util(regions, colors, adjacency, index + 1, num_colors):

return True

colors[region] = -1 # Backtrack

return False # No color could be assigned

def map_coloring(regions, adjacency, num_colors):

""" Main function to solve the map coloring problem. """

colors = {region: -1 for region in regions} # Initialize all regions with no color
if map_coloring_util(regions, colors, adjacency, 0, num_colors):

return colors

else:

return None

# Define regions and adjacency list

regions = ['A', 'B', 'C', 'D']

adjacency = {

'A': ['B', 'C'],

'B': ['A', 'D'],

'C': ['A', 'D'],

'D': ['B', 'C']

# Number of colors

num_colors = 3

# Solve the map coloring problem

solution = map_coloring(regions, adjacency, num_colors)

# Output the solution

if solution:

color_names = ['Red', 'Green', 'Blue']

colored_solution = {region: color_names[solution[region]] for region in regions}

print('Solution:', colored_solution)

else:
print('No solution found.')

OUTPUT:

Solution: {'A': 'Red', 'B': 'Green', 'C': 'Green', 'D': 'Red'}

RESULT:

Thus the output for implementation of Constraint Satisfication problem is executed and
verified.
EX.NO:5 IMPLEMENTATION OF PROPOSITIONAL MODEL
CHECKING ALGORITHMS
DATE:

AIM:

The aim of the program is to implement a simple propositional model checking


algorithm that explores a state space using depth-first search. It evaluates whether a specified
property holds true for the states reachable from an initial state.

ALGORITHM:

1.Initialize:

● Create a visited set to keep track of visited states.


● Start from the initial_state.

2. Depth-First Search (DFS):

● If the current state is already in visited, return False (cycle detected).


● Add the current state to visited.
● If the property function returns True for the current state, return True.
● For each transition from the current state:
o Recursively call DFS on the next state.
o If any recursive call returns True, return True.

3.Backtrack:

● Remove the current state from visited before returning False (to allow for other
paths).

4.Return Result:

● If no states satisfy the property, return False.

PROGRAM:

class State:

def __init__(self, name):

self.name = name

self.transitions = {}
def add_transition(self, action, next_state):

self.transitions[action] = next_state

class ModelChecker:

def __init__(self, initial_state):

self.initial_state = initial_state

def check_property(self, property_func):

visited = set()

return self._dfs(self.initial_state, visited, property_func)

def _dfs(self, state, visited, property_func):

if state in visited:

return False

visited.add(state)

if property_func(state):

return True

for action, next_state in state.transitions.items():

if self._dfs(next_state, visited, property_func):

return True

visited.remove(state)

return False
# Define states

s0 = State("s0")

s1 = State("s1")

s2 = State("s2")

# Define transitions

s0.add_transition("a", s1)

s1.add_transition("b", s2)

s2.add_transition("c", s0)

# Define the initial state

initial_state = s0

# Create the model checker

checker = ModelChecker(initial_state)

# Define a property function

def property_function(state):

return state.name == "s2" # Check if we reach state s2

# Check the property

result = checker.check_property(property_function)

print("Property holds:", result)


OUTPUT:

Property holds: True

RESULT:

Thus the output for implementation of Propositional Model Checking Algorithms


is executed and verified.
EX.NO:6 IMPLEMENTATION OF FORWARD CHAINING,
BACKWARD CHAINING, AND RESOLUTION
DATE: STRATEGIES

AIM:

The aim of the program is to implement three logic-based reasoning strategies: forward
chaining, backward chaining, and resolution. It allows users to infer conclusions from given
rules and facts, demonstrating how each method derives knowledge.

ALGORITHM:

Forward Chaining Algorithm

1. Input: Rules and facts.


2. Initialize: Start with the given facts.
3. While new facts can be inferred:
o For each rule, if its conditions are met by the current facts:
▪ Add the rule's conclusion to the facts.
4. Output: The final set of facts.

2. Backward Chaining Algorithm

1. Input: Rules, facts, and a goal.


2. If the goal is in the facts:
o Return true.
3. For each rule:
o If the conclusion matches the goal, check if all conditions can be satisfied.
4. Output: True if the goal is proven, else false.

3. Resolution Algorithm

1. Input: Clauses and a goal.


2. Negate the goal and add it to the clauses.
3. While new clauses can be generated:
o For each pair of clauses, apply resolution to find new clauses.
o Check for an empty clause (contradiction).
4. Output: True if an empty clause is found, else false.

PROGRAM:

class ForwardChaining:
def __init__(self, rules, facts):

self.rules = rules

self.facts = set(facts)

def infer(self):

new_facts = True

while new_facts:

new_facts = False

for rule in self.rules:

if rule['condition'].issubset(self.facts) and rule['conclusion'] not in self.facts:

self.facts.add(rule['conclusion'])

new_facts = True

print(f"Inferred (Forward Chaining): {rule['conclusion']}")

return self.facts

class BackwardChaining:

def __init__(self, rules, facts):

self.rules = rules

self.facts = set(facts)

def can_prove(self, goal):

if goal in self.facts:

return True

for rule in self.rules:

if rule['conclusion'] == goal and all(self.can_prove(cond) for cond in rule['condition']):

return True

return False
class Resolution:

def __init__(self, clauses):

self.clauses = clauses

def resolve(self, clause1, clause2):

resolvents = []

for literal in clause1:

if -literal in clause2:

new_clause = (clause1 - {literal}) | (clause2 - {-literal})

resolvents.append(new_clause)

return resolvents

def prove(self, goal):

negated_goal = {-goal}

clauses = self.clauses + [negated_goal]

new_resolvents = clauses[:]

while True:

pairs = [(c1, c2) for i, c1 in enumerate(new_resolvents) for c2 in new_resolvents[i +


1:]]

new_clauses = {frozenset(self.resolve(c1, c2)) for c1, c2 in pairs}

if frozenset() in new_clauses:

return True

if new_clauses.issubset(set(new_resolvents)):

return False

new_resolvents.extend(new_clauses)

# Sample Data for Testing


def main():

# Forward Chaining

print("----- Forward Chaining -----")

rules = [

{'condition': {'A'}, 'conclusion': 'B'},

{'condition': {'B'}, 'conclusion': 'C'}

facts = ['A']

fc = ForwardChaining(rules, facts)

fc.infer()

print("Final Facts (Forward Chaining):", fc.facts)

# Backward Chaining

print("\n----- Backward Chaining -----")

rules_bc = [

{'condition': {'A'}, 'conclusion': 'B'},

{'condition': {'B'}, 'conclusion': 'C'}

facts_bc = ['A']

bc = BackwardChaining(rules_bc, facts_bc)

goal = 'C'

print(f"Can prove {goal} (Backward Chaining): {bc.can_prove(goal)}")

# Resolution

print("\n----- Resolution -----")

clauses = [
frozenset({1, 2}), # P or Q

frozenset({-1, 3}) # Not P or R

resolution = Resolution(clauses)

goal_res = 3 # R

print(f"Can prove {goal_res} (Resolution): {resolution.prove(goal_res)}")

if __name__ == "__main__":

main()

OUTPUT:

---- Forward Chaining -----


Inferred (Forward Chaining): B
Inferred (Forward Chaining): C
Final Facts (Forward Chaining): {'C', 'B', 'A'}

----- Backward Chaining -----


Can prove C (Backward Chaining): True

----- Resolution -----


Can prove 3 (Resolution): True

RESULT:

Thus the output for implementation of forward chaining, backward chaining and
resolution strategies is executed and verified.
EX.NO:7 IMPLEMENTATION OF NAÏVE BAYES MODELS

DATE:

AIM:

The aim of the Naïve Bayes classifier implementation is to demonstrate a simple and
effective probabilistic classification method based on Bayes' theorem.

ALGORITHM:

1.Input: Dataset with features and labels.

2. Preprocess:

● Split into training and testing sets.

3.Calculate Probabilities:

● For each class, compute:


o Prior probability (how often the class occurs).
o Likelihood (probability of features given the class).

4.Predict:

● For each test instance, compute the class with the highest probability using:
P(Class∣Features)∝P(Class)×P(Features∣Class)P(Class | Features) \propto P(Class)
\times P(Features | Class)P(Class∣Features)∝P(Class)×P(Features∣Class)

5.Output: Show accuracy and performance metrics.

PROGRAM:

import pandas as pd

from sklearn.model_selection import train_test_split

from sklearn.naive_bayes import GaussianNB

from sklearn.metrics import accuracy_score, classification_report

# Sample Data

data = {
'Feature1': [1, 2, 1, 2, 1, 2, 1, 2],

'Feature2': [0, 0, 1, 1, 0, 1, 1, 0],

'Label': ['A', 'A', 'B', 'B', 'A', 'B', 'A', 'B']

# Create DataFrame

df = pd.DataFrame(data)

# Features and Labels

X = df[['Feature1', 'Feature2']]

y = df['Label']

# Split the dataset

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)

# Train and evaluate the model

model = GaussianNB().fit(X_train, y_train)

y_pred = model.predict(X_test)

# Output results

print(f"Accuracy: {accuracy_score(y_test, y_pred):.2f}")

print("Classification Report:\n", classification_report(y_test, y_pred))


OUTPUT:

Accuracy: 0.50
Classification Report:
precision recall f1-score support

A 0.00 0.00 0.00 1


B 0.50 1.00 0.67 1

accuracy 0.50 2
macro avg 0.25 0.50 0.33 2
weighted avg 0.25 0.50 0.33 2

RESULT :

Thus the output for implementation of naïve’s bayes model is executed and verified.
EX.NO:8 IMPLEMENTATION OF BAYESIAN NETWORKS AND PERFORM
INFERENCES
DATE:

AIM:

The aim of the Bayesian network program is to model the probabilistic relationships
between variables using a structured graphical representation. It allows for efficient inference,
enabling users to compute the likelihood of certain outcomes given specific evidence.

ALGORITHM:

1.Define Structure:

● Create a Bayesian network model by specifying nodes (variables) and their


dependencies (edges).

2.Define Probabilities:

● For each node, create Conditional Probability Tables (CPTs) that represent the
probabilities of the node given its parents.

3.Add CPDs to Model:

● Incorporate the defined CPTs into the Bayesian network.

4.Verify Model:

● Check if the model is correctly specified.

5.Perform Inference:

● Use inference algorithms (e.g., Variable Elimination) to query the model for
probabilities given specific evidence.

6.Output Results:

● Display the calculated probabilities for the queries.

PROGRAM:

from pgmpy.models import BayesianModel


from pgmpy.inference import VariableElimination

from pgmpy.factors.discrete import TabularCPD

# Define the Bayesian Network structure

model = BayesianModel([('Rain', 'Traffic'), ('Accident', 'Traffic'), ('Traffic', 'Arrival')])

# Define the Conditional Probability Tables (CPTs)

cpt_rain = TabularCPD(variable='Rain', variable_card=2, values=[[0.8], [0.2]]) # P(Rain)

cpt_accident = TabularCPD(variable='Accident', variable_card=2, values=[[0.9], [0.1]]) #


P(Accident)

cpt_traffic = TabularCPD(variable='Traffic', variable_card=2,

values=[[0.7, 0.2, 0.4, 0.1], # P(Traffic | Rain, Accident)

[0.3, 0.8, 0.6, 0.9]],

evidence=['Rain', 'Accident'],

evidence_card=[2, 2])

cpt_arrival = TabularCPD(variable='Arrival', variable_card=2,

values=[[0.9, 0.7], # P(Arrival | Traffic)

[0.1, 0.3]],

evidence=['Traffic'],

evidence_card=[2])

# Add CPDs to the model

model.add_cpds(cpt_rain, cpt_accident, cpt_traffic, cpt_arrival)

# Verify the model

assert model.check_model()

# Perform inference
infer = VariableElimination(model)

# Example queries

result_arrival = infer.query(variables=['Arrival'], evidence={'Rain': 1, 'Accident': 0})

result_traffic = infer.query(variables=['Traffic'], evidence={'Arrival': 1})

# Output results

print("P(Arrival | Rain=True, Accident=False):")

print(result_arrival)

print("\nP(Traffic | Arrival=True):")

print(result_traffic)

OUTPUT:

P(Arrival | Rain=True, Accident=False):


+------------+----------------+
| Arrival | phi(Arrival) |
+============+================+
| Arrival(0) | 0.7800 |
+------------+----------------+
| Arrival(1) | 0.2200 |
+------------+----------------+

P(Traffic | Arrival=True):
+------------+----------------+
| Traffic | phi(Traffic) |
+============+================+
| Traffic(0) | 0.3278 |
+------------+----------------+
| Traffic(1) | 0.6722 |
+------------+----------------+

RESULT:
Thus the output is verified for implementation of bayesian networks and perform
inference is executed and verified.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy