Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 16

ARTIFICIAL INTELLIGENCE AND MACHINE

LEARNING (21CS54)

PROGRAMMING ASSIGNMENT

by

Lavanya L Karoshi USN: 4SU21CS045

Under the guidance of

Dr. Thyagaraju G S
Professor and Head

Department of Computer Science and Engineering

SDM INSTITUTE OF TECHNOLOGY


UJIRE-574240
2023-24
Programs

1. Aim:-

Design a Simple Vacuum Cleaner Reflex agent using Python.

Description:-

A Simple Vacuum Cleaner Reflex agent is a type of agent that makes decisions based
on the current state of its environment without considering the past or future states. In the
context of a vacuum cleaner, the agent's goal is to clean all the dirt from a given grid. The
agent can perform actions such as moving in four directions (up, down, left, right) and
cleaning the dirt at its current location.

Algorithm:-

 Initialize the current room and cleanliness of the rooms.


 Define the perceive function: observe the cleanliness of the current room.
 Define the act function: vacuum the current room if it is dirty, and then move to the
other room.
 Define the move function: switch the current room to the other room.
 Define the simulate_environment function: simulate the agent's actions for a specified
number of steps.
 Initialize the vacuum agent and the number of steps to simulate.
 Print the initial state of the environment.
 Simulate the agent's actions for the specified number of steps.

Source Code:-
class VacuumCleaner:
def __init__(self):
self.current_room = "A" # Initial room
self.cleanliness = {"A": "Dirty", "B": "Dirty"}

def perceive(self):
return self.cleanliness[self.current_room]

def act(self, perception):


if perception == "Dirty":
print(f"Vacuum cleaner is cleaning {self.current_room}.")
self.cleanliness[self.current_room] = "Clean"
else:
print(f"{self.current_room} is already clean.")
# Move to the other room
self.move()

def move(self):
if self.current_room == "A":
self.current_room = "B"
else:
self.current_room = "A"

def simulate_environment(agent, steps):


for step in range(steps):
print(f"\nStep {step + 1}:")
perception = agent.perceive()
print(f"{agent.current_room} is {perception}.")
agent.act(perception)

if __name__ == "__main__":
vacuum_agent = VacuumCleaner()
steps_to_simulate = 5

print("Initial State:")
simulate_environment(vacuum_agent, 0)

print("\nSimulation:")
simulate_environment(vacuum_agent, steps_to_simulate)

Output:-
2. Aim:-

Design and implement a Python program to perform Breadth-First Search


on a graph.

Description:-

Breadth-First Search (BFS) is an algorithm used for traversing or searching a tree or


graph in a breadth-first manner, meaning that it explores all the nodes at the current depth
level before moving on to the nodes at the next depth level. The algorithm uses a queue data
structure to keep track of the nodes to be explored

Algorithm:-

 Start by initializing a queue and a visited list/array. The visited list/array is used to
keep track of the nodes that have already been visited during the traversal
 Add the starting node to the queue and mark it as visited in the visited list/array
 While the queue is not empty, remove the front node from the queue and check all its
adjacent nodes
 For each adjacent node, if it has not been visited yet, mark it as visited and add it to
the queue
 Repeat steps 3 and 4 until the queue is empty.

Source Code:-

from collections import defaultdict, deque

class Graph:
def __init__(self):
self.graph = defaultdict(list)

def add_edge(self, u, v):


self.graph[u].append(v)
self.graph[v].append(u) # For an undirected graph

def bfs(self, start_node):


visited = set()
queue = deque([start_node])

while queue:
current_node = queue.popleft()

if current_node not in visited:


print(current_node, end=" ")
visited.add(current_node)

for neighbor in self.graph[current_node]:


if neighbor not in visited:
queue.append(neighbor)

if __name__ == "__main__":
# Example graph
graph = Graph()
graph.add_edge(1, 2)
graph.add_edge(1, 3)
graph.add_edge(2, 4)
graph.add_edge(2, 5)
graph.add_edge(3, 6)
graph.add_edge(3, 7)

start_node = 1
print(f"\nBFS starting from node {start_node}:\n")
graph.bfs(start_node)
print("\n")

Output:-

3. Aim:-

Implement a basic regression analysis in Python using a sample dataset.


Description:-

In statistics, simple linear regression is a linear regression model with a single


explanatory variable. In simple linear regression, we predict scores on one variable based on
results on another. The criteria variable Y is the variable we are predicting. Predictor variable
X is the variable using which we are making our predictions. The prediction approach is
known as simple regression as there is only one predictor variable. As a result, a linear
function that predicts the values of the dependent variable as a function of the independent
variable is discovered for two-dimensional sample points with one independent variable and
one dependent variable.
Algorithm:-

 Import Libraries: Import the required libraries, including numpy, matplotlib.pyplot, and
LinearRegression from sklearn.linear_model.
 Create Sample Dataset: Define a sample dataset with independent variable x and dependent
variable y.
 Linear Regression Model: Create a linear regression model using LinearRegression() from
scikit-learn.
 Fit Model: Fit the linear regression model using the fit method with the sample dataset.
 Make Predictions: Use the fitted model to make predictions on the independent variable x.
 Visualization: i. Plot the actual data points using plt.scatter.. ii. Plot the linear regression line
using plt.plot. iii. Display the plot with appropriate labels and a title using plt.xlabel,
plt.ylabel, plt.title, and plt.legend.
 Display Regression Parameters: Print the regression coefficient (slope) and intercept using
model.coef_[0] and model.intercept_.
 End: The program execution ends.

Source Code:-
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression

# Sample dataset
x = np.array([1, 2, 3, 4, 5]).reshape(-1, 1) # Independent variable
y = np.array([2, 4, 5, 4, 5]) # Dependent variable

# Create and fit the linear regression model


model = LinearRegression()
model.fit(x, y)

# Make predictions
predictions = model.predict(x)

# Visualize the data and regression line


plt.scatter(x, y, label='Actual Data')
plt.plot(x, predictions, color='red', label='Linear Regression Line')
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Linear Regression Analysis')
plt.legend()
plt.show()

# Display regression parameters


print("Regression Coefficient (slope):", model.coef_[0])
print("Intercept:", model.intercept_)

Output:-

4. Aim:-

Design a Python program to perform Greedy Best-First Search on a


weighted graph.

Description:-

Greedy Best-First Search is an uninformed search algorithm that prioritizes


exploration based on heuristic information. It belongs to the family of heuristic search
algorithms that use an evaluation function to decide which adjacent node to explore next.
Unlike traditional best-first search algorithms, Greedy Best-First Search selects the node that
appears to be the most promising based solely on the heuristic value, without considering the
cost of reaching that node.

Algorithm:-

 Initialization: Create an empty priority queue to store nodes.


Initialize the priority queue with the initial node (start node) and its heuristic value.
Create a set to keep track of visited nodes.
 Main Loop: While the priority queue is not empty: Dequeue the node with the highest
priority (lowest heuristic value). Check if the current node is the goal node:
If yes, the search is successful, and the goal is reached. Otherwise: Mark the current
node as visited. Enqueue all unvisited neighbors of the current node along with their
heuristic values. Repeat the loop.
 Termination: If the priority queue becomes empty and the goal node is not reached,
declare that there is no path to the goal.

Source Code:-
import heapq

class WeightedGraph:
def __init__(self):
self.graph = {}

def add_edge(self, u, v, weight):


if u not in self.graph:
self.graph[u] = []
self.graph[u].append((v, weight))
def greedy_best_first_search(self, start, goal):
visited = set()
priority_queue = [(0, start)]

while priority_queue:
_, current_node = heapq.heappop(priority_queue)

if current_node == goal:
print(f"Goal reached: {goal}")
return

if current_node not in visited:


print(f"Visiting node: {current_node}")
visited.add(current_node)

neighbors = self.graph.get(current_node, [])


for neighbor, weight in neighbors:
if neighbor not in visited:
heapq.heappush(priority_queue,
(self.heuristic(neighbor, goal), neighbor))

print(f"No path found to reach the goal: {goal}")

def heuristic(self, node, goal):


return abs(node - goal)

# Example Usage:
if __name__ == "__main__":
graph = WeightedGraph()

# Adding edges with weights


graph.add_edge(1, 2, 5)
graph.add_edge(1, 3, 2)
graph.add_edge(2, 4, 1)
graph.add_edge(2, 5, 4)
graph.add_edge(3, 6, 3)
graph.add_edge(3, 7, 6)

start_node = 1
goal_node = 5

print(f"Starting Greedy Best-First Search from {start_node} to


{goal_node}:\n")
graph.greedy_best_first_search(start_node, goal_node)

Output:-

5. Aim:-

Implement Iterative Deepening Depth-First Search in Python for graph


traversal.
Description:-

Iterative Deepening Depth-First Search (IDDFS) is a combination of depth-first


search and breadth-first search. It gradually increases the depth limit until the goal is found.
This code defines a simple graph and implements Iterative Deepening Depth-First Search
(IDDFS). The add_edge method is used to add edges to the graph. The iddfs method performs
IDDFS, and the _dls method is a helper function for depth-limited search.

Algorithm:-

 Initialize the Graph Class: Initialize the Graph Class:


Create a class Graph to represent the graph and define methods within it.
 Add Edges to the Graph:
Implement a method add_edge to add edges to the graph.
 Implement IDDFS:
Create a method iddfs to perform Iterative Deepening Depth-First Search.
Use a while loop to gradually increase the depth limit until the goal is found.
 Implement Depth-Limited Search (DLS):
Create a helper method dls for depth-limited search.
If the goal is found at the current depth, return the path.
If the depth limit is reached, return None.
Perform recursive depth-limited search on unvisited neighbors.

Source Code:-
class Graph:
def __init__(self):
self.graph = {}

def add_edge(self, u, v):


if u not in self.graph:
self.graph[u] = []
self.graph[u].append(v)

def iddfs(self, start, goal):


depth_limit = 0
while True:
visited = set()
result = self._dls(start, goal, depth_limit, visited)
if result is not None:
return result
depth_limit += 1

def _dls(self, node, goal, depth_limit, visited):


if node == goal:
return [node]

if depth_limit == 0:
return None

visited.add(node)

for neighbor in self.graph.get(node, []):


if neighbor not in visited:
path = self._dls(neighbor, goal, depth_limit - 1,
visited.copy())
if path is not None:
return [node] + path

return None

# Example Usage:
if __name__ == "__main__":
graph = Graph()

# Adding edges
graph.add_edge(1, 2)
graph.add_edge(1, 3)
graph.add_edge(2, 4)
graph.add_edge(2, 5)
graph.add_edge(3, 6)
graph.add_edge(3, 7)

start_node = 1
goal_node = 6

path = graph.iddfs(start_node, goal_node)

if path:
print(f"\nPath from {start_node} to {goal_node}: {path}")
else:
print(f"No path found from {start_node} to {goal_node}.")

Output:-

Projects

1. Aim:-
Design a model-based agent that predicts the temperature for the next day
based on historical data and uses a mathematical equation as a model. The
agent’s goal is to decide whether to bring an umbrella depending on the
predicted temperature.

Description of Algorithm:-

 Prepare historical temperature data and load the historical temperature data from a
CSV file.
 Prepare the data for the linear regression model using the 'Date' column as the feature
(x) and the 'Temperature' column as the target (y) for the linear regression model.
 The linear regression model is trained using the training data. The model learns the
relationship between the date and temperature, allowing it to predict the temperature
for future dates.
 The algorithm defines a function called should_bring_umbrella(model,
next_date) that takes the trained linear regression model and a future date as input.
The function predicts the temperature for the next day using the model and compares
it to a threshold temperature. If the predicted temperature is below the threshold, the
function returns False, indicating that an umbrella is not needed. Otherwise, the
function returns True, indicating that an umbrella is needed.
 The algorithm tests the should_bring_umbrella function with a future date, which is
created by adding one day to the maximum date in the historical data. The function
prints the decision returned by the should_bring_umbrella function, indicating
whether an umbrella is needed or not.
Source Code:
class TemperaturePredictor:
def __init__(self, historical_data):
self.historical_data = historical_data
def build_temperature_model(self):
# Build a simple model (e.g., linear regression) based on
historical data
# This is a simplified example; in practice, more sophisticated
models may be used
# For simplicity, let's assume a linear model: temperature = m *
day + b
days = list(range(1, len(self.historical_data) + 1))
temperatures = self.historical_data
m, b = self.simple_linear_regression(days, temperatures)
return m, b
def simple_linear_regression(self, x, y):
n = len(x)
sum_x = sum(x)
sum_y = sum(y)
sum_x_squared = sum(x_i ** 2 for x_i in x)
sum_xy = sum(x_i * y_i for x_i, y_i in zip(x, y))
m = (n * sum_xy - sum_x * sum_y) / (n * sum_x_squared - sum_x ** 2)
b = (sum_y - m * sum_x) / n
return m, b
def predict_temperature(self, day, model):
# Use the model to predict the temperature for the next day
m, b = model
predicted_temperature = m * day + b
return predicted_temperature
class UmbrellaDecisionAgent:
def __init__(self, threshold):
self.threshold = threshold
def make_decision(self, predicted_temperature):
# Decide whether to bring an umbrella based on the predicted
temperature
return predicted_temperature > self.threshold
# Example Usage
historical_temperature_data = [25, 28, 30, 24, 22, 26, 29, 32, 31, 27]
predictor = TemperaturePredictor(historical_temperature_data)
temperature_model = predictor.build_temperature_model()
# Assuming the next day is the 11th day
predicted_temp = predictor.predict_temperature(11, temperature_model)
umbrella_agent = UmbrellaDecisionAgent(threshold=28)
decision = umbrella_agent.make_decision(predicted_temp)
print(f"\nPredicted Temperature for the next day: {predicted_temp}°C")
print(f"Decision: {'Bring an Umbrella' if decision else 'No Umbrella
needed'}")

Output:-

2. Aim:-
Create a Python application that uses heuristic functions and A* search for
smart route planning, considering real-time traffic conditions and user
preferences.

Description of Algorithm:-

The application will use the A* search algorithm, which is an informed search algorithm that
uses a heuristic function to guide the search towards the goal. The heuristic function estimates
the cost from the current node to the goal node. In this case, the heuristic function will
consider real-time traffic conditions and user preferences. The traffic conditions can be
obtained from APIs like Google Maps or HERE Maps, and user preferences can include
factors like avoiding tolls, highways, or preferring scenic routes.

 Prepare the map data and Obtain real-time traffic conditions.


 Implement the heuristic function and the A* search algorithm.

 Initialize the priority queue with the starting node and a cost of 0.

 While the priority queue is not empty.

 Pop the node with the lowest f-value (estimated total cost) from the priority queue.

 If the popped node is the goal node, return the path from the starting node to the goal
node.

 Otherwise, for each neighbor of the popped node:

 Calculate the tentative g-value (actual cost) and h-value (heuristic cost) for the
neighbor.

 If the neighbor is not in the explored set or the new path to the neighbor has a lower f-
value, update the neighbor's cost and add it to the priority queue.

 Post process the solution.

 Convert the path from nodes to a sequence of road segments.

 Display the path on a map or provide turn-by-turn directions.

Source Code:
import heapq

class Node:
def __init__(self, state, parent=None, cost=0, heuristic=0):
self.state = state
self.parent = parent
self.cost = cost
self.heuristic = heuristic

def __lt__(self, other):


return (self.cost + self.heuristic) < (other.cost +
other.heuristic)
def calculate_heuristic(current_location, destination):
# Implement a heuristic function based on distance or other factors
return 0 # Placeholder value

def get_real_time_traffic_info():
# Use an API to get real-time traffic information
# Placeholder value
return {"route_time": 10, "traffic_level": "Moderate"}

def A_star_search(start, goal):


open_set = [Node(start, None, 0, calculate_heuristic(start, goal))]
closed_set = set()

while open_set:
current_node = heapq.heappop(open_set)

if current_node.state == goal:
# Goal reached, reconstruct and return the path
path = []
while current_node:
path.insert(0, current_node.state)
current_node = current_node.parent
return path

closed_set.add(current_node.state)

for neighbor in get_neighbors(current_node.state):


if neighbor in closed_set:
continue

cost = current_node.cost + calculate_cost(current_node.state,


neighbor)
heuristic = calculate_heuristic(neighbor, goal)
new_node = Node(neighbor, current_node, cost, heuristic)

if new_node not in open_set:


heapq.heappush(open_set, new_node)

# No path found
return None

def get_neighbors(location):
# Implement a function to get neighboring locations
# Placeholder value
return [(location[0] + 1, location[1]), (location[0], location[1] + 1)]

def calculate_cost(current_location, next_location):


# Implement a function to calculate the cost between two locations
# Placeholder value
return 1

if __name__ == "__main__":
start_location = (0, 0)
goal_location = (3, 3)

path = A_star_search(start_location, goal_location)

if path:
print("Optimal path:", path)
else:
print("No path found.")

# Output snapshot example


traffic_info = get_real_time_traffic_info()
print("Estimated time with current traffic:",
traffic_info["route_time"])
print("Traffic level:", traffic_info["traffic_level"])

Output:-

You might also like