AIML Final Programs
AIML Final Programs
import random
GRID_SIZE = 3
DIRTY, CLEAN, VACUUM = 'D', 'C', 'V'
def main():
grid = create_grid(GRID_SIZE)
pos = (0, 0)
print("\n=== Initial Grid ===")
print_grid(grid, pos)
while pos:
x, y = pos
if grid[x][y] == DIRTY:
print(f"→ Cleaning cell ({x}, {y})")
grid[x][y] = CLEAN
else:
print(f"→ Cell ({x}, {y}) already clean")
print_grid(grid, pos)
pos = (x, y + 1) if y < GRID_SIZE - 1 else (x + 1, 0) if x < GRID_SIZE - 1 else
None
if __name__ == "__main__":
main()
#Best First Search
import heapq
h_dist = {'A': 10, 'B': 5, 'C': 2, 'D': 0}
graph = {'A': [('C', 4), ('B', 1)], 'B': [('A', 1), ('D', 1)],
'C': [('D', 2), ('A', 4)], 'D': [('B', 1), ('C', 2)]}
def best_first_search(graph, start, goal):
pq = [(h_dist[start], start)]
visited, parent = set([start]), {start: None}
while pq:
_, node = heapq.heappop(pq)
if node == goal:
path = []
while node: path.append(node); node = parent[node]
return path[::-1]
for nbr, _ in graph[node]:
if nbr not in visited:
visited.add(nbr)
parent[nbr] = node
heapq.heappush(pq, (h_dist[nbr], nbr))
return None
path = best_first_search(graph, 'A', 'D')
print(path if path else "No path found")
#A* Search
import heapq
h = {'A': 10, 'B': 8, 'C': 5, 'D': 0, 'E': 3, 'F': 6, 'G': 5, 'H': 12, 'I': 2, 'J': 0}
graph = {
'A': [('B', 6), ('F', 3)], 'B': [('C', 3), ('D', 2)], 'C': [('D', 1), ('E', 5)],
'D': [('C', 1), ('E', 8)], 'E': [('I', 5), ('J', 5)], 'F': [('G', 1), ('H', 7)],
'G': [('I', 3)], 'H': [('I', 2)], 'I': [('E', 5), ('J', 3)], 'J': []
}
def a_star(graph, start, goal):
pq = [(h[start], 0, start)] # (f = h + g, g, node)
parent, g_cost = {start: None}, {start: 0}
visited = set()
while pq:
f, g, node = heapq.heappop(pq)
if node == goal:
path = []
while node: path.append(node); node = parent[node]
return path[::-1]
if node in visited: continue
visited.add(node)
for nbr, w in graph[node]:
new_g = g + w
if nbr not in g_cost or new_g < g_cost[nbr]:
g_cost[nbr] = new_g
parent[nbr] = node
heapq.heappush(pq, (new_g + h[nbr], new_g, nbr))
return None
path = a_star(graph, 'A', 'J')
print(path if path else "No path found")
#Candidate Elimination Algorithm
import numpy as np
import pandas as pd
data = pd.DataFrame({
'sky': ['sunny', 'sunny', 'rainy', 'sunny'],
'airtemp': ['warm', 'warm', 'cold', 'warm'],
'humidity': ['normal', 'high', 'high', 'high'],
'wind': ['strong'] * 4,
'water': ['warm', 'warm', 'warm', 'cool'],
'forecast': ['same', 'same', 'change', 'change'],
'enjoysport': ['yes', 'yes', 'no', 'yes']
})
S, G = candidate_elimination(concepts, target)
print("Final Specific Hypothesis:\n", S)
print("Final General Hypothesis:\n", G)
# Constraint Satisfaction Problem (CSP)
from itertools import permutations
def solve_cryptarithm(equation):
letters = sorted(set(filter(str.isalpha, equation)))
if len(letters) > 10:
return None
for perm in permutations(range(10), len(letters)):
assign = dict(zip(letters, perm))
expr = equation
for l, d in assign.items():
expr = expr.replace(l, str(d))
try:
left, right = expr.split('=')
if eval(left) == eval(right):
return assign
except:
continue
return None
eps = np.finfo(float).eps
def entropy(df):
p = df.iloc[:,-1].value_counts()/len(df)
return -np.sum(p*np.log2(p+eps))
def best_attr(df):
ent=entropy(df)
return max(df.columns[:-1], key=lambda a: ent -
sum((df[a]==v).mean()*entropy(df[df[a]==v]) for v in df[a].unique()))
def build(df):
if len(df.iloc[:,-1].unique())==1: return df.iloc[0,-1]
attr=best_attr(df)
return {attr:{v:build(df[df[attr]==v].drop(columns=[attr])) for v in
df[attr].unique()}}
df = pd.read_csv("D:\\AIML-LAB\\PlayTennis.csv")
print("Dataset:\n",df)
tree = build(df)
print("\nDecision Tree:\n")
pprint(tree)
sample = {'Outlook':'Rain','Temperature':'Mild','Humidity':'Normal','Wind':'Strong'}
print("\nPrediction:",predict(tree,sample))
# Q Learning
import numpy as np, random
n = 3
Q = np.zeros((n, n, 4)) # Q-table: (row, col, action)
actions = [(-1, 0), (0, 1), (1, 0), (0, -1)] # up, right, down, left
# Activation functions
sigmoid = lambda x: 1/(1+np.exp(-x))
dsigmoid = lambda x: x*(1-x)
# Initialize variables
epoch, lr = 5000, 0.1
wh, bh = np.random.rand(2,3), np.random.rand(1,3)
wout, bout = np.random.rand(3,1), np.random.rand(1,1)
# Training loop
for _ in range(epoch):
hlayer = sigmoid(np.dot(X, wh) + bh)
output = sigmoid(np.dot(hlayer, wout) + bout)
wout += hlayer.T.dot(d_output) * lr
wh += X.T.dot(d_hidden) * lr
# Results
print("Input:\n", X)
print("Actual Output:\n", y)
print("Predicted Output:\n", output)
#EM Algorithm
import numpy as np, matplotlib.pyplot as plt
from sklearn.mixture import GaussianMixture
np.random.seed(0)
X = np.vstack([np.random.normal(-2,1,(300,2)), np.random.normal(2,1,(300,2))])
# Inference
infer = VariableElimination(model)
res = infer.query(variables=['target'],
evidence={'age':1,'sex':1,'cp':3,'chol':1,'thalach':2})
# Output
print("\nProbability of Heart Disease:\n", res)
# Evaluate
print(f'Accuracy: {accuracy_score(y_test, y_pred) * 100:.2f}%')
print(classification_report(y_test, y_pred))
print("Confusion Matrix:\n", confusion_matrix(y_test, y_pred))