AI LAB – EXECUTABLE PYTHON PROGRAMS
Corrected and arranged from the uploaded AI Lab Manual
13 programs arranged in the same numbered sequence as the manual, with Python syntax/indentation corrected
for execution.
1. Breadth-First Search (BFS)
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F', 'G'],
'D': [], 'E': [], 'F': [], 'G': []
}
visited = []
queue = []
def bfs(visited, graph, node):
[Link](node)
[Link](node)
while queue:
s = [Link](0)
print(s, end=" ")
for neighbour in graph[s]:
if neighbour not in visited:
[Link](neighbour)
[Link](neighbour)
bfs(visited, graph, 'A')
2. Depth-First Search (DFS)
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F', 'G'],
'D': [], 'E': [], 'F': [], 'G': []
}
goal = 'F'
visited = set()
def dfs(visited, graph, node):
if node not in visited:
print(node)
[Link](node)
if node == goal:
return True
for neighbour in graph[node]:
if dfs(visited, graph, neighbour):
return True
return False
dfs(visited, graph, 'A')
3. Greedy Best-First Search
graph = {
'A': [('B', 12), ('C', 4)],
'B': [('D', 7), ('E', 3)],
'C': [('F', 8), ('G', 2)],
'D': [],
'E': [('H', 0)],
'F': [('H', 0)],
'G': [('H', 0)],
'H': []
}
def greedy_best_first(start, target, graph):
queue = [(start, 0)]
visited = set()
while queue:
node, _ = [Link](0)
if node in visited:
continue
print(node)
[Link](node)
if node == target:
return
for neighbour, heuristic in graph[node]:
if neighbour not in visited:
[Link]((neighbour, heuristic))
[Link](key=lambda x: x[1])
greedy_best_first('A', 'H', graph)
4. A* Search
graph = [
['A', 'B', 1, 3],
['A', 'C', 2, 4],
['A', 'H', 7, 0],
['B', 'D', 4, 2],
['B', 'E', 6, 6],
['C', 'F', 3, 3],
['C', 'G', 2, 1],
['D', 'E', 7, 6],
['D', 'H', 5, 0],
['F', 'H', 1, 0],
['G', 'H', 2, 0]
]
nodes = set()
for edge in graph:
[Link](edge[0])
[Link](edge[1])
def a_star(graph, start, goal):
g_cost = {node: float('inf') for node in nodes}
parent = {node: None for node in nodes}
g_cost[start] = 0
open_list = [(0, start)]
while open_list:
_, current = min(open_list)
open_list.remove((_, current))
if current == goal:
path = []
while current is not None:
[Link](current)
current = parent[current]
return path[::-1], g_cost[goal]
for source, dest, cost, heuristic in graph:
if source == current:
new_g = g_cost[current] + cost
if new_g < g_cost[dest]:
g_cost[dest] = new_g
parent[dest] = current
f = new_g + heuristic
open_list.append((f, dest))
return None, float('inf')
start = input("Enter the Start Node: ").strip().upper()
goal = input("Enter the Goal Node: ").strip().upper()
path, cost = a_star(graph, start, goal)
if path:
print("Path with least cost is:", " -> ".join(path))
print("Cost:", cost)
else:
print("No path found.")
5. AO* Search / AND-OR Path
def cost(H, condition, weight=1):
result = {}
if 'AND' in condition:
nodes = condition['AND']
path = ' AND '.join(nodes)
result[path] = sum(H[node] + weight for node in nodes)
if 'OR' in condition:
nodes = condition['OR']
path = ' OR '.join(nodes)
result[path] = min(H[node] + weight for node in nodes)
return result
def update_cost(H, conditions, weight=1):
updated = {}
for key in reversed(list([Link]())):
result = cost(H, conditions[key], weight)
print(key, ':', conditions[key], '>>>', result)
H[key] = min([Link]())
updated[key] = result
return updated
def shortest_path(start, updated_cost, H):
path = start
if start in updated_cost:
values = updated_cost[start]
minimum = min([Link]())
keys = list([Link]())
key = keys[list([Link]()).index(minimum)]
next_nodes = [Link]()
if len(next_nodes) == 1:
path += '<--' + shortest_path(next_nodes[0], updated_cost, H)
else:
path += '<--(' + key + ') ['
path += shortest_path(next_nodes[0], updated_cost, H)
path += ' + '
path += shortest_path(next_nodes[-1], updated_cost, H)
path += ']'
return path
H = {
'A': -1, 'B': 5, 'C': 2, 'D': 4,
'E': 7, 'F': 9, 'G': 3, 'H': 0, 'I': 0, 'J': 0
}
conditions = {
'A': {'OR': ['B'], 'AND': ['C', 'D']},
'B': {'OR': ['E', 'F']},
'C': {'OR': ['G'], 'AND': ['H', 'I']},
'D': {'OR': ['J']}
}
print('Updated Cost:')
updated_cost = update_cost(H, conditions)
print('*' * 75)
print('Shortest Path:')
print(shortest_path('A', updated_cost, H))
6. Supervised Machine Learning – Linear Regression
import numpy as np
from sklearn.linear_model import LinearRegression
X_train = [Link]([[1, 1], [1, 2], [2, 2], [2, 3]])
y_train = [Link](X_train, [Link]([1, 2])) + 3
model = LinearRegression()
[Link](X_train, y_train)
X_test = [Link]([[3, 5]])
y_pred = [Link](X_test)
print("Training data:")
print("X values:", X_train)
print("y values:", y_train)
print("Coefficients:", model.coef_)
print("Intercept:", model.intercept_)
print("X test values:", X_test)
print("Predicted value of y:", y_pred)
7. Car Price Prediction – Decision Tree
import pandas as pd
from sklearn.model_selection import train_test_split
from [Link] import DecisionTreeRegressor
data = {
'Mileage': [15000, 30000, 45000, 60000, 75000, 90000],
'Age': [1, 2, 3, 4, 5, 6],
'Horsepower': [150, 200, 250, 300, 350, 400],
'Price': [200000, 180000, 160000, 140000, 120000, 100000]
}
df = [Link](data)
X = df[['Mileage', 'Age', 'Horsepower']]
y = df['Price']
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
model = DecisionTreeRegressor(random_state=42)
[Link](X_train, y_train)
new_car = [Link]({
'Mileage': [50000],
'Age': [3],
'Horsepower': [275]
})
predicted_price = [Link](new_car)
print(f"Predicted Price for the new car: Rs.{predicted_price[0]:.2f}")
8. Weather / Rain Prediction – Decision Tree
import pandas as pd
from sklearn.model_selection import train_test_split
from [Link] import DecisionTreeClassifier
from [Link] import accuracy_score
data = {
'temperature': [30, 22, 25, 27, 28, 32, 35, 40, 22, 24],
'humidity': [80, 60, 75, 70, 65, 55, 45, 40, 85, 80],
'pressure': [1012, 1008, 1010, 1013, 1011, 1014, 1015, 1016, 1009, 1013],
'rain': [1, 0, 1, 0, 0, 0, 0, 0, 1, 1]
}
df = [Link](data)
X = df[['temperature', 'humidity', 'pressure']]
y = df['rain']
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
clf = DecisionTreeClassifier(random_state=42)
[Link](X_train, y_train)
y_pred = [Link](X_test)
accuracy = accuracy_score(y_test, y_pred)
print(f"Model accuracy: {accuracy * 100:.2f}%")
def predict_rain(temperature, humidity, pressure):
input_data = [Link](
[[temperature, humidity, pressure]],
columns=['temperature', 'humidity', 'pressure']
)
prediction = [Link](input_data)
return "Rain" if prediction[0] == 1 else "No Rain"
print("Prediction:",
predict_rain(36, 40, 1010))
9. Profit Prediction – Linear Regression
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
data = {
'SalesVolume': [1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500, 5000, 5500],
'ProductionCost': [2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 11000],
'AdvertisingBudget': [500, 700, 800, 1000, 1200, 1400, 1600, 1800, 2000, 2200],
'Profit': [700, 1200, 1500, 2100, 2600, 3100, 3500, 4000, 4500, 4900]
}
df = [Link](data)
X = df[['SalesVolume', 'ProductionCost', 'AdvertisingBudget']]
y = df['Profit']
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
model = LinearRegression()
[Link](X_train, y_train)
new_data = [Link]({
'SalesVolume': [6000],
'ProductionCost': [12000],
'AdvertisingBudget': [2500]
})
predicted_profit = [Link](new_data)
print(f"Predicted Profit: {predicted_profit[0]:.2f}")
10. Email Spam Classification – Naive Bayes
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import MultinomialNB
data = {
'EmailText': [
'Free money now!!!',
'Hi Bob, how about a game of golf tomorrow?',
'Limited time offer, buy one get one free!',
'Your invoice for the month is attached',
'Congratulations, you won a lottery! Claim now.',
'Can we reschedule our meeting to next week?',
'Earn cash by working from home!',
'Your package has been shipped',
'Important information about your account',
'Win a free vacation to the Bahamas!'
],
'Label': [
'spam', 'not spam', 'spam', 'not spam', 'spam',
'not spam', 'spam', 'not spam', 'not spam', 'spam'
]
}
df = [Link](data)
X = df['EmailText']
y = df['Label']
vectorizer = TfidfVectorizer()
X_tfidf = vectorizer.fit_transform(X)
X_train, X_test, y_train, y_test = train_test_split(
X_tfidf, y, test_size=0.2, random_state=42
)
model = MultinomialNB()
[Link](X_train, y_train)
new_emails = [
"Hi John, just wanted to check if you're free for a meeting next Tuesday.",
"Dear customer, your order has been shipped and is on its way.",
"Please find attached the monthly report for your review."
]
predictions = [Link]([Link](new_emails))
for email, prediction in zip(new_emails, predictions):
print(f'Email: "{email}" is classified as: {prediction}')
11. Flower Classification – SVM
from sklearn.model_selection import train_test_split
from [Link] import SVC
X_custom = [
[5.1, 3.5, 1.4, 0.2],
[6.2, 2.9, 4.3, 1.3],
[7.3, 2.9, 6.3, 1.8],
[5.0, 3.4, 1.5, 0.2],
[6.4, 3.0, 4.5, 1.5],
[7.0, 3.0, 6.0, 1.8]
]
y_custom = [0, 1, 2, 0, 1, 2]
X_train, X_test, y_train, y_test = train_test_split(
X_custom, y_custom, test_size=0.2, random_state=42
)
model = SVC(kernel='linear', C=1.0)
[Link](X_train, y_train)
new_flowers = [
[5.5, 3.0, 4.5, 1.5],
[6.0, 3.2, 5.0, 1.8]
]
predictions = [Link](new_flowers)
for flower, prediction in zip(new_flowers, predictions):
print(f"Flower: {flower} is classified as: {prediction}")
12. Student Classification – Artificial Neural Network
(ANN)
import numpy as np
from sklearn.model_selection import train_test_split
from [Link] import StandardScaler
import tensorflow as tf
from [Link] import Sequential
from [Link] import Dense
data = [Link]([
[150, 45, 1],
[160, 55, 1],
[170, 65, 1],
[180, 75, 1],
[160, 50, 0],
[170, 60, 0],
[180, 70, 0],
[190, 80, 0]
])
X = data[:, :-1]
y = data[:, -1]
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
X_train, X_test, y_train, y_test = train_test_split(
X_scaled, y, test_size=0.2, random_state=42
)
model = Sequential([
Dense(4, activation='relu', input_shape=(2,)),
Dense(4, activation='relu'),
Dense(1, activation='sigmoid')
])
[Link](
optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy']
)
[Link](X_train, y_train, epochs=50, batch_size=1, verbose=0)
new_students = [Link]([
[155, 50],
[185, 70]
])
new_students_scaled = [Link](new_students)
predictions = [Link](new_students_scaled, verbose=0)
predicted_classes = (predictions > 0.5).astype(int).flatten()
for i, pred in enumerate(predicted_classes):
print(f"New student {i+1} is predicted to be in Class {pred}")
13. Text Classification – Naive Bayes
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import MultinomialNB
data = {
'text': [
'I love this movie',
'This movie is terrible',
'I really enjoyed this film',
'This film is bad',
'Amazing movie',
'I hate this film',
'Great movie',
'Awful movie'
],
'label': [
'positive', 'negative', 'positive', 'negative',
'positive', 'negative', 'positive', 'negative'
]
}
df = [Link](data)
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(df['text'])
X_train, X_test, y_train, y_test = train_test_split(
X, df['label'], test_size=0.2, random_state=42
)
model = MultinomialNB()
[Link](X_train, y_train)
new_texts = [
'I like this movie',
'This film is not good'
]
new_texts_transformed = [Link](new_texts)
predicted_labels = [Link](new_texts_transformed)
for text, label in zip(new_texts, predicted_labels):
print(f"Text: '{text}' is classified as '{label}'")