Artificial Intelligence Lab Record
Artificial Intelligence Lab Record
while queue:
node = queue.popleft()
print(node, end=' ')
# Example usage:
print("BFS traversal starting from node 'A':")
bfs(graph, 'A')
OUTPUT:
visited.add(start)
print(start, end=' ')
# Example usage:
print("DFS traversal starting from node 'A':")
dfs(graph, 'A')
OUTPUT:
if current == goal:
break
return came_from
# Example usage:
start_node = 'A'
goal_node = 'F'
came_from = greedy_best_first_search(graph, start_node, goal_node)
path = reconstruct_path(came_from, start_node, goal_node)
print("Greedy Best-First Search path from", start_node, "to", goal_node, ":", path)
OUTPUT:
[‘A’,’C’,’F’]
import heapq
# Define the graph as an adjacency list with heuristic values
graph = {
'A': {'B': 3, 'C': 7},
'B': {'D': 2, 'E': 5},
'C': {'F': 4},
'D': {},
'E': {'F': 1},
'F': {}
}
while frontier:
current_cost, current_node = heapq.heappop(frontier)
if current_node == goal:
break
# Example usage:
start_node = 'A'
goal_node = 'F'
came_from, cost_so_far = astar_search(graph, start_node, goal_node)
path = reconstruct_path(came_from, start_node, goal_node)
print("A* Search path from", start_node, "to", goal_node, ":", path)
print("Cost of the path:", cost_so_far[goal_node])
OUTPUT:
class Graph:
def __init__(self):
self.graph = {}
def add_edge(self, u, v, cost):
if u not in self.graph:
self.graph[u] = []
self.graph[u].append((v, cost))
def ao_star_search(self, start, goal):
open_list = [(0, start)]
closed_set = set()
g_values = {start: 0}
parents = {start: None} # To store parent nodes for path reconstruction
while open_list:
_, current_node = min(open_list)
open_list.remove((_, current_node))
closed_set.add(current_node)
if current_node == goal:
# Reconstruct path
path = []
while current_node is not None:
path.append(current_node)
current_node = parents[current_node]
path.reverse()
return path
for neighbor, weight in self.graph.get(current_node, []):
if neighbor not in closed_set:
g = g_values[current_node] + weight
h = self.heuristic(neighbor, goal)
f=g+h
if neighbor not in g_values or g < g_values[neighbor]:
g_values[neighbor] = g
parents[neighbor] = current_node # Update parent node
open_list.append((f, neighbor))
return None # No path found
def heuristic(self, node, goal):
# Example heuristic: Euclidean distance
return ((node[0] - goal[0]) ** 2 + (node[1] - goal[1]) ** 2) ** 0.5
# Example usage
if __name__ == "__main__":
g = Graph()
g.add_edge((0, 0), (1, 0), 1)
g.add_edge((0, 0), (0, 1), 4)
g.add_edge((1, 0), (1, 1), 3)
g.add_edge((0, 1), (1, 1), 1)
g.add_edge((1, 1), (2, 1), 2)
start_node = (0, 0)
goal_node = (2 , 1)
#goal_node = (3, 3) # Set an unreachable goal for demonstration
path = g.ao_star_search(start_node, goal_node)
if path:
print("Path found:", path)
print("Goal Reached.")
else:
print("Unable to find path")
print("Goal is unreachable.")
OUTPUT:
Path found: [(0, 0), (1, 0), (1, 1), (2, 1)]
Goal Reached.
OUTPUT:
7. Python program to predict the price of the car using decision tree.
OUTPUT:
Output:
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
import seaborn as sns
import matplotlib.pyplot as plt
# Load the dataset
data = pd.read_csv("startup_data.csv")
# Summary statistics of the data
print(data.describe())
# Correlation between features
data_no_state = data.drop('State', axis=1)
sns.heatmap(data_no_state.corr(), annot=True)
plt.show()
# Prepare the data for the model
X = data[["R&D Spend", "Administration cost", "Marketing cost"]]
y = data["Profit"]
# Train the linear regression model
model = LinearRegression()
model.fit(X, y)
# Predict the profit
def predict_profit(rnd_spend, admin_cost, marketing_cost):
X_new = np.array([[rnd_spend, admin_cost, marketing_cost]])
return model.predict(X_new)[0]
# Example usage
rnd_spend = 100000
admin_cost = 50000
marketing_cost = 200000
predicted_profit = predict_profit(rnd_spend, admin_cost, marketing_cost)
print(f"Predicted profit: ${predicted_profit:.2f}")
OUTPUT:
SPEND Marketing
R&D ADMINISTRATION
cost Profit
cost
count 35 35 35 35
OUTPUT:
OUTPUT:
12. Python program that demonstrates how to use a basic Artificial Neural
Network (ANN) to classify students based on their height and weight.
# Import necessary libraries
import numpy as np
from sklearn.neural_network import MLPClassifier
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
# Sample dataset
heights = [155, 160, 165, 170, 175, 180, 185, 190, 195, 200]
weights = [50, 55, 60, 65, 70, 75, 80, 85, 90, 95]
labels = [0, 0, 0, 0, 1, 1, 1, 1, 1, 1] # 0: underweight, 1: normal weight
# Combine data into a single array
data = np.column_stack((heights, weights))
# Split data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(data, labels, test_size=0.2,
random_state=42)
# Create and train an ANN classifier
ann = MLPClassifier(hidden_layer_sizes=(5,), max_iter=1000)
ann.fit(X_train, y_train)
# Evaluate the ANN classifier
accuracy = ann.score(X_test, y_test)
print(f"Accuracy: {accuracy:.2f}")
# Use the ANN classifier to make predictions
predictions = ann.predict(X_test)
# Plot the data and predictions
plt.scatter(X_test[:, 0], X_test[:, 1], c=predictions)
plt.xlabel("Height (cm)")
OUTPUT:
OUTPUT:
def speech_to_text():
r=sr.Recognizer()
with sr.Microphone() as source:
print("Please say something:")
audio=r.listen(source)
try:
voice_data=""
voice_data=r.recognize_google(audio)
print(voice_data)
except sr.UnknownValueError:
print("Could not understand audio")
except sr.RequestError as e:
print("Could not request results from Google Speech Recognition service;
{0}".format(e))
OUTPUT:
15. Python program using the PIL (Pillow) library to illustrate basic image
processing operations like opening an image, resizing it, applying a filter,
and saving the processed image.
OUTPUT: