III_AI-DS_AD3311_AI_Lab Manual
III_AI-DS_AD3311_AI_Lab Manual
SCIENCE
II Year/III Semester
Lab Manual
Prepared By,
AD3311_AI Lab
4931_Grace College of Engineering,Thoothukudi
COURSE OBJECTIVES:
LIST OF EXPERIMENTS:
COURSE OUTCOMES:
AD3311_AI Lab
4931_Grace College of Engineering,Thoothukudi
Aim:
3.Create Frontier:
6.Expand Node:
For each valid action, generate a new state by applying the action.
Create a new node for the new state.
Calculate the cost and heuristic for the new node.
Add the new node to the frontier if it's not in the explored set.
8.Return Failure:
If the frontier is empty and the goal state is not reached, return failure (no solution).
If the goal state is reached, return the solution path from the initial state to the goal state.
PROGRAM:
AD3311_AI Lab
4931_Grace College of Engineering,Thoothukudi
import heapq
import copy
class PuzzleNode:
self.state = state
self.parent = parent
self.action = action
self.cost = cost
self.heuristic = self.calculate_heuristic()
def calculate_heuristic(self):
heuristic = 0
for i in range(3):
for j in range(3):
if self.state[i][j] != 0:
return heuristic
def get_blank_position(state):
for i in range(3):
for j in range(3):
if state[i][j] == 0:
return i, j
def get_neighbors(node):
i, j = get_blank_position(node.state)
neighbors = []
AD3311_AI Lab
4931_Grace College of Engineering,Thoothukudi
for action in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
new_state = copy.deepcopy(node.state)
return neighbors
def a_star(initial_state):
start_node = PuzzleNode(initial_state)
frontier = [start_node]
explored = set()
while frontier:
node = heapq.heappop(frontier)
return get_solution_path(node)
explored.add(tuple(map(tuple, node.state)))
heapq.heappush(frontier, neighbor)
return None
def get_solution_path(node):
path = []
while node.parent:
path.append((node.state, node.action))
node = node.parent
path.append((node.state, node.action))
path.reverse()
return path
def print_solution_path(path):
AD3311_AI Lab
4931_Grace College of Engineering,Thoothukudi
print(f"Step {i + 1}:")
print_state(state)
if action:
def action_direction(action):
return "right"
return "left"
return "down"
return "up"
def print_state(state):
print(row)
print()
if __name__ == "__main__":
print("Initial State:")
print_state(initial_state)
solution_path = a_star(initial_state)
if solution_path:
print("Solution Path:")
print_solution_path(solution_path)
else:
OUTPUT:
AD3311_AI Lab
4931_Grace College of Engineering,Thoothukudi
Initial State:
[1, 2, 3]
[4, 0, 5]
[7, 8, 6]
Solution Path:
Step 1:
[1, 2, 3]
[4, 0, 5]
[7, 8, 6]
Step 2:
[1, 2, 3]
[4, 5, 0]
[7, 8, 6]
Step 3:
[1, 2, 3]
[4, 5, 6]
[7, 8, 0]
>>>
RESULT:
Aim:
Define the search space representing all possible configurations of queens on the chessboard.
AD3311_AI Lab
4931_Grace College of Engineering,Thoothukudi
Specify the conditions for a solution, i.e., a state where eight queens are placed without any
conflicts.
5.Select a Search Algorithm:
Implement the selected search algorithm to explore the state space and find a valid solution.
7.Check Constraints:
During the search, ensure that each state adheres to the constraints of the problem (no conflicts).
8.Backtrack if Necessary:
If a conflict is detected, backtrack to the previous state and try alternative moves.
9.Return Solution:
Once a state is found where eight queens are placed without conflicts, return it as the solution.
PROGRAM:
class EightQueensProblem:
def __init__(self, size=8):
self.size = size
self.solution = [None] * size
if prev_col == col or \
prev_col - prev_row == col - row or \
prev_col + prev_row == col + row:
return False
return True
AD3311_AI Lab
4931_Grace College of Engineering,Thoothukudi
self.solution[row] = None
return False
def print_solution(self):
for row in range(self.size):
line = ""
for col in range(self.size):
if col == self.solution[row]:
line += "Q "
else:
line += ". "
print(line.strip())
if __name__ == "__main__":
queens_problem = EightQueensProblem()
if queens_problem.solve_queens(0):
print("Solution Found:")
queens_problem.print_solution()
else:
print("No solution exists.")
OUTPUT:
Solution Found:
Q.......
....Q...
.......Q
.....Q..
..Q.....
......Q.
.Q......
...Q....
>
RESULT:
Aim:
Identify the given cryptarithmetic problem, including the arithmetic expression and any
constraints.
AD3311_AI Lab
4931_Grace College of Engineering,Thoothukudi
Define the search space representing all possible digit assignments to letters.
4.Define State Transition Operators:
Define operators that represent valid changes to the current state, such as assigning a digit to a
letter.
5.Define Goal State:
Specify the conditions for a solution, i.e., a state where the arithmetic expression is satisfied with
valid digit assignments.
6.Select a Search Algorithm:
Choose a search algorithm suitable for exploring the state space efficiently. Backtracking is
commonly used for Cryptarithmetic problems.
7.Implement the Search Algorithm:
Implement the chosen search algorithm to explore the state space and find a valid solution.
8.Check Constraints:
During the search, ensure that each state adheres to the constraints of the cryptarithmetic problem
(unique digit assignments).
9.Backtrack if Necessary:
If a conflict is detected or if a partial assignment cannot lead to a valid solution, backtrack to the
previous state and try alternative assignments.
10.Return Solution:
Once a valid digit assignment is found that satisfies the cryptarithmetic problem, return it as the
solution.
PROGRAM:
def solve_cryptarithmetic(puzzle):
letters = set("".join(puzzle))
if len(letters) > 10:
print("Invalid puzzle. Too many unique letters.")
return None
letter = list(letters)[index]
AD3311_AI Lab
4931_Grace College of Engineering,Thoothukudi
mapping[letter] = None
return False
if __name__ == "__main__":
puzzle = ["SEND", "MORE", "MONEY"]
print("Cryptarithmetic Puzzle:")
for word in puzzle:
print(word, end=" ")
print()
solution = solve_cryptarithmetic(puzzle)
if solution:
print("\nSolution:")
print_solution(solution, puzzle)
else:
print("\nNo solution found.")
OUTPUT:
Cryptarithmetic Puzzle:
SEND MORE MONEY
RESULT:
Thus the above program was implemented and executed successfully.
AD3311_AI Lab
4931_Grace College of Engineering,Thoothukudi
EX Implement A* algorithms
NO:2a
Aim:
Pop the node with the lowest total cost (actual cost + heuristic) from the open set.
If the popped node is the goal, reconstruct and return the solution path.
4.Generate Successors:
If the open set is empty and the goal has not been reached, return failure (no solution).
PROGRAM:
import heapq
g_score = {start: 0}
f_score = {start: heuristic(start, goal)}
AD3311_AI Lab
4931_Grace College of Engineering,Thoothukudi
while open_set:
current_f, current = heapq.heappop(open_set)
if current == goal:
path = reconstruct_path(came_from, current)
return path
closed_set.add(current)
tentative_g = g_score[current] + 1
return None
if __name__ == "__main__":
# Example usage
graph = {
(0, 0): [(1, 0), (0, 1)],
(1, 0): [(0, 0), (2, 0)],
(0, 1): [(0, 0), (1, 1), (0, 2)],
(1, 1): [(0, 1), (2, 1)],
(0, 2): [(0, 1), (1, 2)],
(2, 0): [(1, 0), (2, 1)],
(2, 1): [(1, 1), (2, 0), (2, 2)],
(1, 2): [(0, 2), (2, 2)],
(2, 2): [(1, 2), (2, 1)]
}
start_node = (0, 0)
goal_node = (2, 2)
if result:
print(f"Shortest Path from {start_node} to {goal_node}: {result}")
AD3311_AI Lab
4931_Grace College of Engineering,Thoothukudi
else:
print("No path found.")
OUTPUT:
Shortest Path from (0, 0) to (2, 2): [(0, 0), (0, 1), (0, 2), (1, 2), (2, 2)]
>
RESULT:
Thus the above program was implemented and executed successfully.
Aim:
Pop the node with the lowest total cost (actual cost + heuristic) from the open set.
If the popped node is the goal, reconstruct and return the solution path.
4.Generate Successors:
If the open set is empty and the goal has not been reached, return failure (no solution).
PROGRAM:
import heapq
AD3311_AI Lab
4931_Grace College of Engineering,Thoothukudi
g_score = {start: 0}
f_score = {start: heuristic(start, goal)}
while open_set:
current_f, current = heapq.heappop(open_set)
if current == goal:
path = reconstruct_path(came_from, current)
return path
closed_set.add(current)
tentative_g = g_score[current] + 1
return None
if __name__ == "__main__":
# Example usage
graph = {
(0, 0): [(1, 0), (0, 1)],
(1, 0): [(0, 0), (2, 0)],
(0, 1): [(0, 0), (1, 1), (0, 2)],
(1, 1): [(0, 1), (2, 1)],
AD3311_AI Lab
4931_Grace College of Engineering,Thoothukudi
start_node = (0, 0)
goal_node = (2, 2)
memory_limit = 5 # Set the memory limit
if result:
print(f"Shortest Path from {start_node} to {goal_node}: {result}")
else:
print("No path found.")
OUTPUT:
Shortest Path from (0, 0) to (2, 2): [(0, 0), (0, 1), (0, 2), (1, 2), (2, 2)]
>
RESULT:
Thus the above program was implemented and executed successfully.
Aim:
Algorithm:
If maximizingPlayer is true:
alpha = max(alpha, v)
AD3311_AI Lab
4931_Grace College of Engineering,Thoothukudi
Return v.
If maximizingPlayer is false:
beta = min(beta, v)
Return v.
PROGRAM:
def evaluate(board):
# Check rows, columns, and diagonals for a win
for row in board:
if all(cell == 'X' for cell in row):
return 1 # Player X wins
elif all(cell == 'O' for cell in row):
return -1 # Player O wins
def is_terminal(board):
return evaluate(board) is not None
AD3311_AI Lab
4931_Grace College of Engineering,Thoothukudi
if maximizingPlayer:
maxEval = float('-inf')
for i in range(3):
for j in range(3):
if board[i][j] == ' ':
board[i][j] = 'X'
eval = minimax(board, depth - 1, False)
board[i][j] = ' ' # Undo the move
maxEval = max(maxEval, eval)
return maxEval
else:
minEval = float('inf')
for i in range(3):
for j in range(3):
if board[i][j] == ' ':
board[i][j] = 'O'
eval = minimax(board, depth - 1, True)
board[i][j] = ' ' # Undo the move
minEval = min(minEval, eval)
return minEval
def best_move(board):
bestVal = float('-inf')
bestMove = None
for i in range(3):
for j in range(3):
if board[i][j] == ' ':
board[i][j] = 'X'
moveVal = minimax(board, 9, False) # Depth is set to 9 for Tic-Tac-Toe
board[i][j] = ' ' # Undo the move
return bestMove
def print_board(board):
for row in board:
print(" ".join(row))
if __name__ == "__main__":
# Example usage for Tic-Tac-Toe
initial_board = [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]
AD3311_AI Lab
4931_Grace College of Engineering,Thoothukudi
if is_terminal(initial_board):
break
print_board(initial_board)
ai_move = best_move(initial_board)
print(f"AI's move: {ai_move}")
initial_board[ai_move[0]][ai_move[1]] = 'X'
result = evaluate(initial_board)
print_board(initial_board)
if result == 1:
print("Player X wins!")
elif result == -1:
print("Player O wins!")
else:
print("It's a draw!")
OUTPUT:
Enter your move (row and column): 1
RESULT:
Thus the above program was implemented and executed successfully.
Aim:
Procedure:
CONSTRAINT
In this example, we have three variables (A, B, and C) that need to be assigned values from the set [1, 2,
..., 9]. The goal is to find assignments that satisfy a specific constraint, in this case, the sum of A, B, and
C should be equal to 15, and the values of A, B, and C should be distinct.
PROGRAM:
def is_valid_assignment(assignment):
a, b, c = assignment
AD3311_AI Lab
4931_Grace College of Engineering,Thoothukudi
def print_solution(assignments):
print()
def solve_csp():
variables = [1, 2, 3, 4, 5, 6, 7, 8, 9]
all_assignments = list(product(*domains))
print_solution(valid_assignments)
if __name__ == "__main__":
solve_csp()
OUTPUT:
A: 1, B: 5, C: 9
A: 1, B: 6, C: 8
A: 1, B: 8, C: 6
A: 1, B: 9, C: 5
A: 2, B: 4, C: 9
AD3311_AI Lab
4931_Grace College of Engineering,Thoothukudi
A: 2, B: 5, C: 8
A: 2, B: 6, C: 7
A: 2, B: 7, C: 6
A: 2, B: 8, C: 5
A: 2, B: 9, C: 4
A: 3, B: 4, C: 8
A: 3, B: 5, C: 7
A: 3, B: 7, C: 5
A: 3, B: 8, C: 4
A: 4, B: 2, C: 9
A: 4, B: 3, C: 8
A: 4, B: 5, C: 6
A: 4, B: 6, C: 5
A: 4, B: 8, C: 3
A: 4, B: 9, C: 2
A: 5, B: 1, C: 9
A: 5, B: 2, C: 8
A: 5, B: 3, C: 7
A: 5, B: 4, C: 6
A: 5, B: 6, C: 4
A: 5, B: 7, C: 3
A: 5, B: 8, C: 2
A: 5, B: 9, C: 1
A: 6, B: 1, C: 8
A: 6, B: 2, C: 7
A: 6, B: 4, C: 5
A: 6, B: 5, C: 4
A: 6, B: 7, C: 2
A: 6, B: 8, C: 1
AD3311_AI Lab
4931_Grace College of Engineering,Thoothukudi
A: 7, B: 2, C: 6
A: 7, B: 3, C: 5
A: 7, B: 5, C: 3
A: 7, B: 6, C: 2
A: 8, B: 1, C: 6
A: 8, B: 2, C: 5
A: 8, B: 3, C: 4
A: 8, B: 4, C: 3
A: 8, B: 5, C: 2
A: 8, B: 6, C: 1
A: 9, B: 1, C: 5
A: 9, B: 2, C: 4
A: 9, B: 4, C: 2
A: 9, B: 5, C: 1
>
RESULT:
Thus the above program was implemented and executed successfully.
Aim:
ALGORITHM:
Input:
Procedure:
AD3311_AI Lab
4931_Grace College of Engineering,Thoothukudi
If formula is a variable, return the value assigned to that variable in the model.
If formula is a negation, recursively evaluate the negated formula and return the negation of the result.
If formula is a conjunction, recursively evaluate both sub-formulas and return the conjunction of the
results.
If formula is a disjunction, recursively evaluate both sub-formulas and return the disjunction of the
results.
If formula is an implication, recursively evaluate both sub-formulas and return the implication result.
Output:
PROGRAM:
if formula[0] == 'Var':
AD3311_AI Lab
4931_Grace College of Engineering,Thoothukudi
else:
if __name__ == "__main__":
# Example usage
propositional_formula = ('Or', ('And', ('Var', 'A'), ('Var', 'B')), ('Not', ('Var', 'C')))
print(f"Does the formula hold in the model? {'Yes' if result else 'No'}")
OUTPUT:
>
RESULT:
Thus the above program was implemented and executed successfully.
Aim:
Input:
AD3311_AI Lab
4931_Grace College of Engineering,Thoothukudi
Procedure:
Add all conclusions of rules with the fact in their premises to the agenda.
Output:
Input:
Procedure:
Return failure.
Output:
AD3311_AI Lab
4931_Grace College of Engineering,Thoothukudi
Resolution Algorithm:
Input:
Procedure:
Initialize clauses with the knowledge base and the negation of the query.
Output:
PROGRAM:
agenda = list(knowledge_base['facts'])
inferred = set()
while agenda:
current_fact = agenda.pop(0)
if current_fact == goal:
inferred.add(current_fact)
AD3311_AI Lab
4931_Grace College of Engineering,Thoothukudi
if explored is None:
explored = set()
if goal in knowledge_base['facts']:
explored.add(goal)
if premises_satisfied:
return True
new = set()
while True:
for ci in clauses:
for cj in clauses:
if ci != cj:
if not resolvents:
new.update(resolvents)
if new.issubset(clauses):
clauses.update(new)
AD3311_AI Lab
4931_Grace College of Engineering,Thoothukudi
resolvents = set()
if frozenset([-literal]) in cj:
if not resolvent:
resolvents.add(frozenset(resolvent))
return resolvents
if __name__ == "__main__":
knowledge_base_forward = {
'rules': [
goal_forward = 'D'
knowledge_base_backward = {
'facts': {'D'},
'rules': [
AD3311_AI Lab
4931_Grace College of Engineering,Thoothukudi
goal_backward = 'A'
knowledge_base_resolution = {
query_resolution = -1
OUTPUT:
>
RESULT:
Aim:
AD3311_AI Lab
4931_Grace College of Engineering,Thoothukudi
Training:
Input:
Procedure:
Calculate the likelihood probabilities for each class given the feature.
Prediction:
Input:
Test example.
Procedure:
Calculate the product of prior probability and likelihood probabilities for each feature.
Assign the class with the highest probability to the test example.
PROGRAM:
# Example data
corpus = [
AD3311_AI Lab
4931_Grace College of Engineering,Thoothukudi
vectorizer = CountVectorizer()
X_train_vectorized = vectorizer.fit_transform(X_train)
X_test_vectorized = vectorizer.transform(X_test)
naive_bayes_classifier = MultinomialNB()
naive_bayes_classifier.fit(X_train_vectorized, y_train)
predictions = naive_bayes_classifier.predict(X_test_vectorized)
print(f"Accuracy: {accuracy:.2f}")
print("Classification Report:")
print(classification_report(y_test, predictions))
AD3311_AI Lab
4931_Grace College of Engineering,Thoothukudi
OUTPUT:
Accuracy: 0.00
Classification Report:
precision recall f1-score support
negative 0.00 0.00 0.00 1.0
positive 0.00 0.00 0.00 0.0
accuracy 0.00 1.0
macro avg 0.00 0.00 0.00 1.0
weighted avg 0.00 0.00 0.00 1.0
Predictions for the test set:
Text: negative sentiment here, True Label: negative, Predicted Label: positive
RESULT:
Aim:
ALGORITHM:
Define the Bayesian Network structure: Specify the nodes and edges in the network.
Estimate Conditional Probability Distributions (CPDs): Use the ParameterEstimator to estimate CPDs
based on your data.
Assign CPDs to the model: Add the estimated CPDs to the Bayesian network.
Check model structure and CPDs: Print the structure and CPDs to verify correctness.
Perform inference using VariableElimination: Use the VariableElimination method for inference.
PROGRAM:
AD3311_AI Lab
4931_Grace College of Engineering,Thoothukudi
cpd_a = ParameterEstimator(model).estimate_cpd('A')
cpd_b = ParameterEstimator(model).estimate_cpd('B')
model.add_cpds(cpd_a, cpd_b)
print("Model Structure:")
print(model.edges())
print(model.get_cpds('A'))
print(model.get_cpds('B'))
inference = VariableElimination(model)
print("\nInference Result:")
print(query)
OUTPUT:
Collecting pgmpy
Downloading pgmpy-0.1.24-py3-none-any.whl (2.0 MB)
Requirement already satisfied: scipy in c:\users\a\anaconda3\lib\site-packages (from pgmpy) (1.7.3)
Requirement already satisfied: numpy in c:\users\a\anaconda3\lib\site-packages (from pgmpy) (1.21.5)
Requirement already satisfied: pandas in c:\users\a\anaconda3\lib\site-packages (from pgmpy) (1.4.2)
Requirement already satisfied: statsmodels in c:\users\a\anaconda3\lib\site-packages (from pgmpy) (0.13.2)
Requirement already satisfied: joblib in c:\users\a\anaconda3\lib\site-packages (from pgmpy) (1.1.0)
Requirement already satisfied: pyparsing in c:\users\a\anaconda3\lib\site-packages (from pgmpy) (3.0.4)
Requirement already satisfied: tqdm in c:\users\a\anaconda3\lib\site-packages (from pgmpy) (4.64.0)
Downloading pgmpy-0.1.23-py3-none-any.whl (1.9 MB)
Downloading pgmpy-0.1.22-py3-none-any.whl (1.9 MB)
Downloading pgmpy-0.1.21-py3-none-any.whl (1.9 MB)
Downloading pgmpy-0.1.20-py3-none-any.whl (1.9 MB)
Downloading pgmpy-0.1.19-py3-none-any.whl (1.9 MB)
Downloading pgmpy-0.1.18-py3-none-any.whl (1.9 MB)
AD3311_AI Lab
4931_Grace College of Engineering,Thoothukudi
RESULT:
Thus, the program to implement Bayesian Networks and perform inferences is implemented and executed
successfully.
AD3311_AI Lab