0% found this document useful (0 votes)
67 views8 pages

AI Practical Exam

This my ai practical file

Uploaded by

sameermane7777
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
67 views8 pages

AI Practical Exam

This my ai practical file

Uploaded by

sameermane7777
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Restaurent Waiting Problem

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier, plot_tree
from sklearn.metrics import accuracy_score, classification_report,
confusion_matrix
import matplotlib.pyplot as plt

# Sample data for the restaurant waiting problem


data = {
'Customer': ['Few', 'Full', 'Full', 'Few', 'Full', 'Full', 'Few'],
'Reservation': ['Yes', 'No', 'Yes', 'No', 'No', 'Yes', 'No'],
'WaitEstimate': ['Short', 'Long', 'None', 'Medium', 'Short',
'Medium', 'Long'],
'Weather': ['Sunny', 'Rainy', 'Sunny', 'Rainy', 'Sunny', 'Rainy',
'Sunny'],
'RestaurantType': ['Casual', 'Fine Dining', 'Casual', 'Fine
Dining', 'Casual', 'Fine Dining', 'Casual'],
'WillWait': ['Yes', 'No', 'Yes', 'No', 'Yes', 'Yes', 'No']
}

# Convert to DataFrame and preprocess data


df = pd.get_dummies(pd.DataFrame(data).drop('WillWait', axis=1))
y = pd.Series([1 if w == 'Yes' else 0 for w in data['WillWait']])

# Split data, train, and evaluate the model


X_train, X_test, y_train, y_test = train_test_split(df, y,
test_size=0.3, random_state=42)
clf = DecisionTreeClassifier().fit(X_train, y_train)
y_pred = clf.predict(X_test)

# Output accuracy and classification results


print(f"Accuracy: {accuracy_score(y_test, y_pred)}")
print(classification_report(y_test, y_pred))
print(confusion_matrix(y_test, y_pred))

# Visualize decision tree


plt.figure(figsize=(10, 8))
plot_tree(clf, feature_names=df.columns, class_names=['No', 'Yes'],
filled=True)
plt.show()
Romanian Map Problem - Recursive BFS

from collections import deque

graph = {
'A': ['B', 'C'],
'B': ['D', 'C'],
'C': ['D'],
'D': []
}

def recursive_bfs(queue, visited, goal):


if not queue:
return None

path = queue.popleft()
city = path[-1]

if city == goal:
return path

if city not in visited:


visited.add(city)
for neighbor in graph[city]:
queue.append(path + [neighbor])

return recursive_bfs(queue, visited, goal)

def bfs(graph, start, goal):


queue = deque([[start]])
visited = set()
return recursive_bfs(queue, visited, goal)

path = bfs(graph, 'A', 'D')


if path:
print(f"Path from A to D: {' -> '.join(path)}")
else:
print("No path found.")
Romanion Map Problem - Iterative Deep DFS

graph = {
'A': ['B', 'C'],
'B': ['D', 'C'],
'C': ['D'],
'D': []
}

def depth_limited_search(graph, start, goal, depth):


stack = [[start]]
visited = set()

while stack:
path = stack.pop()
city = path[-1]

if city == goal:
return path

if city not in visited and len(path) - 1 < depth:


visited.add(city)
for neighbor in graph[city]:
stack.append(path + [neighbor])

return None

def iddfs(graph, start, goal, max_depth):


for depth in range(max_depth + 1):
result = depth_limited_search(graph, start, goal, depth)
if result is not None:
return result
return None

path = iddfs(graph, 'A', 'D', max_depth=3)


if path:
print(f"Path from A to D: {' -> '.join(path)}")
else:
print("No path found.")
Romanion Map Problem – BFS

from collections import deque

graph = {
'A': ['B', 'C'],
'B': ['D', 'C'],
'C': ['D'],
'D': []
}

def bfs(graph, start, goal):


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

while queue:
path = queue.popleft()
city = path[-1]

if city == goal:
return path

if city not in visited:


visited.add(city)
for neighbor in graph[city]:
queue.append(path + [neighbor])

return None

path = bfs(graph, 'A', 'D')


if path:
print(f"Path from A to D: {' -> '.join(path)}")
else:
print("No path found.")
Romanian Map Problem - A* Search Algorithm

from collections import deque


import heapq

graph = {
'Arad': [('Sibiu', 140), ('Timisoara', 118)],
'Sibiu': [('Arad', 140), ('Fagaras', 99), ('Oradea', 151)],
'Timisoara': [('Arad', 118), ('Lugoj', 111)],
'Lugoj': [('Timisoara', 111), ('Mehadia', 70)],
'Mehadia': [('Lugoj', 70), ('Drobeta', 75)],
'Drobeta': [('Mehadia', 75), ('Craiova', 120)],
'Craiova': [('Drobeta', 120), ('Rimnicu Vilcea', 146)],
'Rimnicu Vilcea': [('Craiova', 146), ('Sibiu', 80), ('Pitesti',
97)],
'Fagaras': [('Sibiu', 99), ('Bucharest', 211)],
'Oradea': [('Sibiu', 151), ('Zerind', 71)],
'Zerind': [('Oradea', 71), ('Arad', 75)],
'Pitesti': [('Rimnicu Vilcea', 97), ('Bucharest', 101)],
'Bucharest': [('Fagaras', 211), ('Pitesti', 101), ('Giurgiu',
90)],
}

heuristics = {
'Arad': 366, 'Sibiu': 253, 'Timisoara': 329, 'Lugoj': 244,
'Mehadia': 241, 'Drobeta': 242, 'Craiova': 160, 'Rimnicu
Vilcea': 193,
'Fagaras': 176, 'Oradea': 380, 'Zerind': 374, 'Pitesti': 100,
'Bucharest': 0, 'Giurgiu': 77,
}

def a_star_search(graph, start, goal):


open_set = [(0, [start])]
visited = set()

while open_set:
f_cost, path = heapq.heappop(open_set)
city = path[-1]
if city == goal:
return path
if city not in visited:
visited.add(city)
for neighbor, cost in graph[city]:
g_cost = len(path)
f_neighbor = g_cost + 1 + heuristics[neighbor]
heapq.heappush(open_set, (f_neighbor, path +
[neighbor]))
return None

path = a_star_search(graph, 'Arad', 'Bucharest')


print(f"Path from Arad to Bucharest: {' -> '.join(path)}" if path
else "No path found.")
Restaurent Waiting Problem - Feed Forward Back Propagation Neural
Network

import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, classification_report

data = {
'Patrons': ['Few', 'Full', 'Full', 'Few', 'Full', 'Full', 'Few'],
'Reservation': ['Yes', 'No', 'Yes', 'No', 'No', 'Yes', 'No'],
'WaitEstimate': ['Short', 'Long', 'None', 'Medium', 'Short',
'Medium', 'Long'],
'Weather': ['Sunny', 'Rainy', 'Sunny', 'Rainy', 'Sunny', 'Rainy',
'Sunny'],
'WillWait': ['Yes', 'No', 'Yes', 'No', 'Yes', 'Yes', 'No']
}

df = pd.get_dummies(pd.DataFrame(data).drop('WillWait', axis=1))
y = (pd.DataFrame(data)['WillWait'] == 'Yes').astype(int).values
X_train, X_test, y_train, y_test = train_test_split(df.values, y,
test_size=0.3, random_state=42)

class NeuralNetwork:
def __init__(self, input_size, hidden_size, learning_rate=0.1):
self.learning_rate = learning_rate
self.weights_input_hidden = np.random.rand(input_size,
hidden_size)
self.weights_hidden_output = np.random.rand(hidden_size, 1)

def sigmoid(self, x):


return 1 / (1 + np.exp(-x))

def forward(self, X):


self.hidden = self.sigmoid(X @ self.weights_input_hidden)
return self.sigmoid(self.hidden @ self.weights_hidden_output)

def backward(self, X, y, output):


output_delta = (y.reshape(-1, 1) - output) * output * (1 -
output)
hidden_delta = output_delta @ self.weights_hidden_output.T *
self.hidden * (1 - self.hidden)
self.weights_hidden_output += self.hidden.T @ output_delta *
self.learning_rate
self.weights_input_hidden += X.T @ hidden_delta *
self.learning_rate
def train(self, X, y, epochs=1000):
for _ in range(epochs):
output = self.forward(X)
self.backward(X, y, output)

def predict(self, X):


return np.round(self.forward(X))

nn = NeuralNetwork(X_train.shape[1], 5)
nn.train(X_train, y_train)
y_pred = nn.predict(X_test)
print("Accuracy:", accuracy_score(y_test, y_pred))
print("\nClassification Report:\n", classification_report(y_test,
y_pred))

You might also like