0% found this document useful (0 votes)
4 views

AIML Final Programs

The document contains various algorithms and implementations related to artificial intelligence and machine learning, including a Simple Reflex Agent for grid cleaning, Best First Search, A* Search, Candidate Elimination Algorithm, and more. Each section provides code examples demonstrating the functionality of the respective algorithms. Additionally, it covers applications such as decision trees, Q-learning, EM algorithm, Bayesian networks, and Gaussian Naive Bayes classification.

Uploaded by

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

AIML Final Programs

The document contains various algorithms and implementations related to artificial intelligence and machine learning, including a Simple Reflex Agent for grid cleaning, Best First Search, A* Search, Candidate Elimination Algorithm, and more. Each section provides code examples demonstrating the functionality of the respective algorithms. Additionally, it covers applications such as decision trees, Q-learning, EM algorithm, Bayesian networks, and Gaussian Naive Bayes classification.

Uploaded by

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

#Simple Reflex Agent

import random

GRID_SIZE = 3
DIRTY, CLEAN, VACUUM = 'D', 'C', 'V'

def create_grid(size): return [[random.choice([DIRTY, CLEAN]) for _ in range(size)] for _


in range(size)]

def print_grid(grid, pos):


print("-" * (GRID_SIZE * 4))
for i in range(GRID_SIZE):
print(' '.join(f'[{VACUUM}]' if (i, j) == pos else f' {grid[i][j]} ' for j in
range(GRID_SIZE)))
print("-" * (GRID_SIZE * 4), "\n")

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

print("All cells are clean!")

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']
})

concepts = data.iloc[:, :-1].values


target = data.iloc[:, -1].values

def candidate_elimination(concepts, target):


S = concepts[0].copy()
G = [['?'] * len(S) for _ in S]

for i, row in enumerate(concepts):


if target[i] == 'yes':
S = ['?' if S[j] != row[j] else S[j] for j in range(len(S))]
else:
for j in range(len(S)):
if row[j] != S[j]:
G[j][j] = S[j]
else:
G[j][j] = '?'

G = [g for g in G if g != ['?'] * len(S)]


return S, G

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

eq = input("Enter equation: ")


sol = solve_cryptarithm(eq)
if sol:
print("Solution:", *[f"{k}={v}" for k, v in sol.items()])
else:
print("No valid solution found")
# ID3 Decision Tree Algorithm
import pandas as pd, numpy as np
from pprint import pprint

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()}}

def predict(tree, sample):


if not isinstance(tree,dict): return tree
attr=list(tree.keys())[0]
return predict(tree[attr].get(sample[attr], None), sample)

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

def move(state, action):


r, c = state
dr, dc = actions[action]
r, c = np.clip(r + dr, 0, n - 1), np.clip(c + dc, 0, n - 1)
next_state = (r, c)
reward = 99 if next_state == (n - 1, n - 1) else -1
return next_state, reward

for episode in range(500):


state = (0, 0)
epsilon = max(0.1, 0.99 ** episode)
while state != (n - 1, n - 1):
if random.random() < epsilon:
action = random.randint(0, 3)
else:
action = Q[state].argmax()
next_state, reward = move(state, action)
Q[state][action] += 0.1 * (reward + 0.9 * Q[next_state].max() - Q[state][action])
state = next_state

print("Q-values:\n", np.round(Q, 1))


print("Policy:\n", Q.argmax(2)) # best action per state

# Print learned path


state = (0, 0); print("Path:")
while state != (n - 1, n - 1):
print(state, end=" -> ")
state, _ = move(state, Q[state].argmax())
print(state)
#Backpropagation
import numpy as np

# Input and normalization


X = np.array([[2,9],[1,5],[3,6]], dtype=float)
y = np.array([[92],[86],[89]], dtype=float) / 100
X /= X.max(axis=0)

# 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)

d_output = (y - output) * dsigmoid(output)


d_hidden = d_output.dot(wout.T) * dsigmoid(hlayer)

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))])

gmm = GaussianMixture(n_components = 2).fit(X)


labels = gmm.predict(X)

plt.scatter(X[:,0], X[:,1], c=labels, cmap='viridis', s=30)


plt.scatter(*gmm.means_.T, c='red', marker='x', s=200)
plt.title("GMM Clustering (EM Algorithm)")
plt.show()
# Bayesian Network
import pandas as pd
from pgmpy.models import DiscreteBayesianNetwork as BN
from pgmpy.estimators import MaximumLikelihoodEstimator
from pgmpy.inference import VariableElimination

# Load and preprocess


df = pd.read_csv("D:\\AIML-LAB\\heart.csv")

df["target"] = (df["target"] > 0).astype(int)


df = df[["age", "sex", "cp", "chol", "thalach", "target"]]
df['age'] = pd.cut(df['age'], [28,40,55,77], labels=[0,1,2]).astype(int)
df['chol'] = pd.cut(df['chol'], [120,200,300,600], labels=[0,1,2]).astype(int)
df['thalach'] = pd.cut(df['thalach'], [70,120,160,210], labels=[0,1,2]).astype(int)

# Build and train model


model =
BN([('age','target'),('sex','target'),('cp','target'),('chol','target'),('thalach','target
')])
model.fit(df, estimator=MaximumLikelihoodEstimator)

# 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)

#Bayesian Belief Network


import pandas as pd
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix

# Load dataset and split


X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

# Train and predict


model = GaussianNB().fit(X_train, y_train)
y_pred = model.predict(X_test)

# 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))

# Predict new samples


new_samples = [[5.0, 3.5, 1.5, 0.2], [6.5, 3.0, 5.5, 2.0]]
print('Predictions:', load_iris().target_names[model.predict(new_samples)])

You might also like