Professional Documents
Culture Documents
Final Aiml
Final Aiml
LEARNING (21CS54)
PROGRAMMING ASSIGNMENT
by
Dr. Thyagaraju G S
Professor and Head
1. Aim:-
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:-
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 move(self):
if self.current_room == "A":
self.current_room = "B"
else:
self.current_room = "A"
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:-
Description:-
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:-
class Graph:
def __init__(self):
self.graph = defaultdict(list)
while queue:
current_node = queue.popleft()
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:-
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
# Make predictions
predictions = model.predict(x)
Output:-
4. Aim:-
Description:-
Algorithm:-
Source Code:-
import heapq
class WeightedGraph:
def __init__(self):
self.graph = {}
while priority_queue:
_, current_node = heapq.heappop(priority_queue)
if current_node == goal:
print(f"Goal reached: {goal}")
return
# Example Usage:
if __name__ == "__main__":
graph = WeightedGraph()
start_node = 1
goal_node = 5
Output:-
5. Aim:-
Algorithm:-
Source Code:-
class Graph:
def __init__(self):
self.graph = {}
if depth_limit == 0:
return None
visited.add(node)
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
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.
Initialize the priority queue with the starting node and a cost of 0.
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.
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.
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 get_real_time_traffic_info():
# Use an API to get real-time traffic information
# Placeholder value
return {"route_time": 10, "traffic_level": "Moderate"}
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)
# 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)]
if __name__ == "__main__":
start_location = (0, 0)
goal_location = (3, 3)
if path:
print("Optimal path:", path)
else:
print("No path found.")
Output:-