0% found this document useful (0 votes)
13 views20 pages

Intel AI Mini Project

The document contains multiple Python programs that implement various algorithms including Hill Climbing for the N-Queens problem and function maximization, Simulated Annealing for the Traveling Salesman Problem and global maximum finding, and a decision tree for decision-making under uncertainty. It also includes a Genetic Algorithm for optimizing neural network weights and a Support Vector Machine for classifying emails as spam. Each section provides code snippets and explanations for the respective algorithms and their applications.

Uploaded by

Haseeb Pasha
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)
13 views20 pages

Intel AI Mini Project

The document contains multiple Python programs that implement various algorithms including Hill Climbing for the N-Queens problem and function maximization, Simulated Annealing for the Traveling Salesman Problem and global maximum finding, and a decision tree for decision-making under uncertainty. It also includes a Genetic Algorithm for optimizing neural network weights and a Support Vector Machine for classifying emails as spam. Each section provides code snippets and explanations for the respective algorithms and their applications.

Uploaded by

Haseeb Pasha
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/ 20

Name: HASEEB PASHA

Register Number: 23BTCE221


Section: ‘B’ Section
Subject: Intel AI

2025
1. Write a Python program to solve the N-Queens problem using the Hill Climbing
algorithm
Sol:
import random

# Function to calculate the number of conflicts (attacking pairs of queens)


def calculate_conflicts(board):
conflicts = 0
n = len(board)

for i in range(n):
for j in range(i + 1, n):
# Check if queens are in the same column or diagonal
if board[i] == board[j] or abs(board[i] - board[j]) == j - i:
conflicts += 1
return conflicts

# Function to perform the Hill Climbing search


def hill_climbing(n, max_restarts=1000):
for _ in range(max_restarts):
# Random initial configuration (each queen in a different column)
board = [random.randint(0, n-1) for _ in range(n)]

while True:
conflicts = calculate_conflicts(board)

# If there are no conflicts, return the solution


if conflicts == 0:
return board

# List of possible next configurations


neighbors = []

for i in range(n):
for j in range(n):
if j != board[i]: # Don't move the queen to the same row
neighbor = board[:]
neighbor[i] = j
neighbors.append(neighbor)
# Evaluate neighbors by their conflict count
best_neighbor = None
min_conflicts = float('inf')

for neighbor in neighbors:


neighbor_conflicts = calculate_conflicts(neighbor)
if neighbor_conflicts < min_conflicts:
best_neighbor = neighbor
min_conflicts = neighbor_conflicts

# If no improvement is found, terminate the loop (local maximum)


if min_conflicts >= conflicts:
break

# Move to the best neighbor


board = best_neighbor

return None # Return None if no solution is found after max_restarts

# Function to print the solution board


def print_solution(board):
n = len(board)
for i in range(n):
row = ['Q' if board[i] == j else '.' for j in range(n)]
print(" ".join(row))
print("\n")

# Main function to solve the N-Queens problem using Hill Climbing


def solve_n_queens(n):
solution = hill_climbing(n)

if solution is None:
print(f"No solution found for N={n}")
else:
print(f"Solution for N={n}:")
print_solution(solution)

# Example usage
n = 8 # Change N as needed
solve_n_queens(n)

Output:

2. Write a Python program to find the maximum of the function f(x) = -x² + 4x
using Hill Climbing.
Sol:
import random

# Define the function


def f(x):
return -x**2 + 4*x

# Hill Climbing Algorithm


def hill_climb(start_x, step_size=0.01, max_iterations=1000):
current_x = start_x
current_value = f(current_x)

for _ in range(max_iterations):
# Generate neighbors
next_x1 = current_x + step_size
next_x2 = current_x - step_size

# Evaluate neighbors
value1 = f(next_x1)
value2 = f(next_x2)
# Choose the best neighbor
if value1 > current_value:
current_x = next_x1
current_value = value1
elif value2 > current_value:
current_x = next_x2
current_value = value2
else:
# No better neighbor found
break

return current_x, current_value

# Start from a random point in range [0, 4]


start = random.uniform(0, 4)

# Run hill climbing


max_x, max_value = hill_climb(start)

# Print the result


print(f"Maximum occurs at x = {max_x:.4f}, f(x) = {max_value:.4f}")

Output:

3. Write a Python program to solve the Traveling Salesman Problem using


Simulated Annealing.
Sol:
import math
import random

# Distance between two cities


def distance(a, b):
return math.sqrt((a[0] - b[0])**2 + (a[1] - b[1])**2)

# Total path length


def total_distance(tour, cities):
return sum(distance(cities[tour[i]], cities[tour[(i + 1) % len(tour)]]) for i in range(len(tour)))

# Simulated Annealing for TSP


def simulated_annealing(cities, temp=10000, cooling_rate=0.995, stop_temp=1e-8):
# Initial tour (0, 1, 2, ..., n-1)
current_tour = list(range(len(cities)))
random.shuffle(current_tour)
current_cost = total_distance(current_tour, cities)

best_tour = current_tour[:]
best_cost = current_cost

while temp > stop_temp:


# Generate a new neighbor by swapping two cities
i, j = random.sample(range(len(cities)), 2)
new_tour = current_tour[:]
new_tour[i], new_tour[j] = new_tour[j], new_tour[i]
new_cost = total_distance(new_tour, cities)

# Accept new tour with probability


if new_cost < current_cost or random.random() < math.exp((current_cost - new_cost) / temp):
current_tour = new_tour
current_cost = new_cost

# Update best tour


if new_cost < best_cost:
best_tour = new_tour
best_cost = new_cost

# Cool down
temp *= cooling_rate

return best_tour, best_cost

# Example: list of cities (x, y)


cities = [
(0, 0), (1, 5), (5, 2), (6, 6), (8, 3),
(3, 7), (7, 1), (2, 9), (4, 4), (9, 5)
]

# Solve TSP
best_path, best_distance = simulated_annealing(cities)

# Print result
print("Best tour:", best_path)
print("Shortest distance:", round(best_distance, 2))

Output:

4. Write a Python program to find the global maximum of a complex mathematical


function using Simulated Annealing.
Sol:
import math
import random

# Define the complex function


def f(x):
return x * math.sin(10 * math.pi * x) + 1.0

# Simulated Annealing algorithm


def simulated_annealing(f, lower_bound, upper_bound, temp=1000, cooling_rate=0.98, stop_temp=1e-8):
# Start with a random solution
current_x = random.uniform(lower_bound, upper_bound)
current_f = f(current_x)

best_x = current_x
best_f = current_f

while temp > stop_temp:


# Generate new candidate in neighborhood
new_x = current_x + random.uniform(-1, 1) * temp / 100
new_x = max(min(new_x, upper_bound), lower_bound) # Stay within bounds
new_f = f(new_x)
# Accept new candidate with a probability
if new_f > current_f or random.random() < math.exp((new_f - current_f) / temp):
current_x = new_x
current_f = new_f

# Update best
if new_f > best_f:
best_x = new_x
best_f = new_f

# Cool down
temp *= cooling_rate

return best_x, best_f

# Run the algorithm


best_x, best_value = simulated_annealing(f, lower_bound=0, upper_bound=1)

# Show result
print(f"Global maximum found at x = {best_x:.6f}")
print(f"Maximum value f(x) = {best_value:.6f}")

Output:

5. Write a Python program to predict the probability of tomorrow’s weather using


historical data and probabilistic models.
Sol:
import random
from collections import defaultdict

# Sample historical data (can be expanded)


historical_weather = [
"Sunny", "Sunny", "Cloudy", "Rainy", "Sunny", "Sunny", "Cloudy", "Rainy",
"Sunny", "Cloudy", "Cloudy", "Rainy", "Sunny", "Rainy", "Rainy", "Sunny"
]

# Step 1: Build transition probabilities


def build_transition_matrix(data):
transition_counts = defaultdict(lambda: defaultdict(int))

for i in range(len(data) - 1):


current = data[i]
next_day = data[i + 1]
transition_counts[current][next_day] += 1

# Convert counts to probabilities


transition_probs = {}
for current_state, next_states in transition_counts.items():
total = sum(next_states.values())
transition_probs[current_state] = {
state: count / total for state, count in next_states.items()
}

return transition_probs

# Step 2: Predict next day using probabilities


def predict_weather(today, transition_probs):
if today not in transition_probs:
print("No data available for current state.")
return None

next_states = list(transition_probs[today].keys())
probabilities = list(transition_probs[today].values())

# Randomly choose based on learned probabilities


predicted = random.choices(next_states, probabilities)[0]
return predicted

# Build model
transition_probs = build_transition_matrix(historical_weather)

# Example usage
today_weather = input("Enter today's weather (Sunny, Cloudy, Rainy): ").capitalize()

predicted = predict_weather(today_weather, transition_probs)


if predicted:
print(f"Based on historical data, tomorrow is likely to be: {predicted}")

Output:

6. Write a Python program to simulate a decision tree for making choices under
uncertainty using Decision Theory
Sol:
# Decision Tree Simulation using Decision Theory (Expected Value)

# Each decision has a list of outcomes with associated probability and reward

decisions = {
"Launch New Product": [
{"outcome": "High Market Demand", "probability": 0.3, "value": 100000},
{"outcome": "Moderate Market Demand", "probability": 0.5, "value": 40000},
{"outcome": "Low Market Demand", "probability": 0.2, "value": -20000}
],
"Improve Existing Product": [
{"outcome": "Increased Sales", "probability": 0.6, "value": 30000},
{"outcome": "No Significant Change", "probability": 0.4, "value": 5000}
]
}

def expected_value(outcomes):
"""Calculate expected value for a list of outcomes."""
return sum(o["probability"] * o["value"] for o in outcomes)

# Evaluate each decision


results = {}
for decision, outcomes in decisions.items():
ev = expected_value(outcomes)
results[decision] = ev
print(f"Expected Value for '{decision}': ₹{ev:,.2f}")

# Recommend the best option


best_decision = max(results, key=results.get)
print(f"\n ✅ Best Decision based on Expected Value: '{best_decision}'")

Output:

7. Write a Python program to optimize the weights of a neural network using a


Genetic Algorithm.
Sol:
import numpy as np
import random

# XOR input and output


X = np.array([
[0, 0],
[0, 1],
[1, 0],
[1, 1]
])
y = np.array([0, 1, 1, 0]) # XOR output

# Neural network structure


INPUT_SIZE = 2
HIDDEN_SIZE = 2
OUTPUT_SIZE = 1
CHROMOSOME_LENGTH = (INPUT_SIZE * HIDDEN_SIZE) + (HIDDEN_SIZE * OUTPUT_SIZE) +
HIDDEN_SIZE + OUTPUT_SIZE

POP_SIZE = 50
GENS = 1000
MUTATION_RATE = 0.1

# Activation
def sigmoid(x):
return 1 / (1 + np.exp(-x))

# Decode a chromosome into weights and biases


def decode_chromosome(chrom):
i_h = np.array(chrom[0:4]).reshape((INPUT_SIZE, HIDDEN_SIZE))
h_o = np.array(chrom[4:6]).reshape((HIDDEN_SIZE, OUTPUT_SIZE))
b_h = np.array(chrom[6:8])
b_o = np.array(chrom[8])
return i_h, h_o, b_h, b_o

# Forward pass using decoded weights


def forward(x, i_h, h_o, b_h, b_o):
hidden = sigmoid(np.dot(x, i_h) + b_h)
output = sigmoid(np.dot(hidden, h_o) + b_o)
return output

# Fitness: Mean squared error (lower is better)


def fitness(chrom):
i_h, h_o, b_h, b_o = decode_chromosome(chrom)
predictions = np.array([forward(x, i_h, h_o, b_h, b_o)[0] for x in X])
return np.mean((predictions - y) ** 2)

# Generate random chromosome


def create_chromosome():
return [random.uniform(-1, 1) for _ in range(CHROMOSOME_LENGTH)]

# Crossover (single point)


def crossover(parent1, parent2):
point = random.randint(1, CHROMOSOME_LENGTH - 1)
return parent1[:point] + parent2[point:]

# Mutation
def mutate(chrom):
for i in range(CHROMOSOME_LENGTH):
if random.random() < MUTATION_RATE:
chrom[i] += random.uniform(-0.5, 0.5)
return chrom

# Genetic Algorithm
def genetic_algorithm():
population = [create_chromosome() for _ in range(POP_SIZE)]
for gen in range(GENS):
population = sorted(population, key=lambda chrom: fitness(chrom))
best_fit = fitness(population[0])

if gen % 100 == 0:
print(f"Generation {gen}, Best MSE: {best_fit:.5f}")
if best_fit < 0.01:
print(f"\nSolution found at generation {gen} with MSE: {best_fit:.5f}")
return population[0]

new_pop = population[:10] # Elitism


while len(new_pop) < POP_SIZE:
parent1, parent2 = random.sample(population[:25], 2)
child = crossover(parent1, parent2)
new_pop.append(mutate(child))

population = new_pop

print("\nNo perfect solution found.")


return population[0]

# Run GA and display results


best_chromosome = genetic_algorithm()
i_h, h_o, b_h, b_o = decode_chromosome(best_chromosome)

print("\nFinal predictions on XOR inputs:")


for x_val in X:
out = forward(x_val, i_h, h_o, b_h, b_o)[0]
print(f"Input: {x_val}, Predicted: {out:.4f}")

Output:
8. Write a Python program to classify emails as spam or not spam using Support
Vector Machines (SVM).
Sol:
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score, classification_report

# Sample dataset: emails and labels (1=spam, 0=not spam)


emails = [
"Congratulations, you've won a lottery! Claim your prize now.",
"Dear friend, I need your assistance in transferring funds.",
"Meeting scheduled for tomorrow at 10am. Please confirm attendance.",
"Lowest prices on medications, buy now!",
"Can we reschedule our appointment to next week?",
"Get cheap loans without credit checks!",
"Project deadline extended to next Friday.",
"You have been selected for a free vacation to Bahamas!",
"Lunch at 1pm today?",
"Earn money fast working from home, no experience needed."
]

labels = [1, 1, 0, 1, 0, 1, 0, 1, 0, 1] # 1=spam, 0=not spam

# Split dataset into training and test sets


X_train, X_test, y_train, y_test = train_test_split(emails, labels, test_size=0.3, random_state=42)
# Convert emails to TF-IDF feature vectors
vectorizer = TfidfVectorizer(stop_words='english')
X_train_vectors = vectorizer.fit_transform(X_train)
X_test_vectors = vectorizer.transform(X_test)

# Train SVM classifier


svm = SVC(kernel='linear', probability=True)
svm.fit(X_train_vectors, y_train)

# Predict on test set


y_pred = svm.predict(X_test_vectors)

# Evaluate the model


print("Accuracy:", accuracy_score(y_test, y_pred))
print("\nClassification Report:")
print(classification_report(y_test, y_pred, target_names=["Not Spam", "Spam"]))

# Example: Predict new email


new_email = ["Exclusive offer! Get your free trial today."]
new_vector = vectorizer.transform(new_email)
prediction = svm.predict(new_vector)
print(f"\nNew email prediction: {'Spam' if prediction[0] == 1 else 'Not Spam'}")

Output:
9. Write a Python program to train a robot using Q-learning to reach a goal in a
grid world environment.
Sol:
import numpy as np
import random

# Define the environment


GRID_SIZE = 5
START = (0, 0)
GOAL = (4, 4)

# Actions: up, down, left, right


actions = ['up', 'down', 'left', 'right']

# Q-table: state (row, col) x actions


Q = np.zeros((GRID_SIZE, GRID_SIZE, len(actions)))

# Parameters
alpha = 0.8 # Learning rate
gamma = 0.95 # Discount factor
epsilon = 0.1 # Exploration rate
episodes = 2000
max_steps = 50

def is_valid_pos(pos):
r, c = pos
return 0 <= r < GRID_SIZE and 0 <= c < GRID_SIZE
def get_next_state(state, action):
r, c = state
if action == 'up':
r -= 1
elif action == 'down':
r += 1
elif action == 'left':
c -= 1
elif action == 'right':
c += 1
return (r, c) if is_valid_pos((r, c)) else state

def get_reward(state):
if state == GOAL:
return 100 # Reward for reaching the goal
else:
return -1 # Small penalty for each move to encourage shortest path

for episode in range(episodes):


state = START
for _ in range(max_steps):
r, c = state

# Choose action (epsilon-greedy)


if random.uniform(0,1) < epsilon:
action_idx = random.randint(0, len(actions) - 1) # explore
else:
action_idx = np.argmax(Q[r, c]) # exploit

action = actions[action_idx]
next_state = get_next_state(state, action)
reward = get_reward(next_state)
nr, nc = next_state

# Update Q-value using the Q-learning formula


old_value = Q[r, c, action_idx]
next_max = np.max(Q[nr, nc])
Q[r, c, action_idx] = old_value + alpha * (reward + gamma * next_max - old_value)
state = next_state

if state == GOAL:
break

# Test learned policy


state = START
path = [state]
for _ in range(max_steps):
r, c = state
action_idx = np.argmax(Q[r, c])
state = get_next_state(state, actions[action_idx])
path.append(state)
if state == GOAL:
break

print("Learned path from start to goal:")


print(path)

Output:

10. Write a Python program to simulate LIDAR sensor data for obstacle detection
in a 2D map.
Sol:
import math
import numpy as np
import matplotlib.pyplot as plt

# 2D Map size and obstacle setup (1 = obstacle, 0 = free)


MAP_SIZE = 20
map_grid = np.zeros((MAP_SIZE, MAP_SIZE))

# Place some obstacles


obstacles = [(5, 5), (10, 10), (15, 7), (7, 14), (12, 16)]
for (x, y) in obstacles:
map_grid[y, x] = 1

# LIDAR parameters
lidar_pos = (10, 5) # (x, y)
max_range = 15
num_rays = 360 # 1-degree resolution

def cast_ray(map_grid, origin, angle_deg, max_range):


angle_rad = math.radians(angle_deg)
x0, y0 = origin
for r in range(max_range):
x = int(round(x0 + r * math.cos(angle_rad)))
y = int(round(y0 + r * math.sin(angle_rad)))
if x < 0 or x >= MAP_SIZE or y < 0 or y >= MAP_SIZE:
return r # reached map boundary
if map_grid[y, x] == 1: # obstacle found
return r
return max_range

# Collect LIDAR distances


distances = []
angles = list(range(0, 360, 360 // num_rays))
for angle in angles:
dist = cast_ray(map_grid, lidar_pos, angle, max_range)
distances.append(dist)

# Convert polar to cartesian for visualization


points_x = [lidar_pos[0] + d * math.cos(math.radians(a)) for d, a in zip(distances, angles)]
points_y = [lidar_pos[1] + d * math.sin(math.radians(a)) for d, a in zip(distances, angles)]

# Plot map, obstacles, LIDAR origin, and detected points


plt.figure(figsize=(8,8))
plt.imshow(map_grid, cmap='Greys', origin='lower')

plt.scatter(lidar_pos[0], lidar_pos[1], color='blue', label='LIDAR')


plt.scatter(points_x, points_y, color='red', s=5, label='LIDAR Points')

plt.title("2D LIDAR Simulation")


plt.legend()
plt.grid(True)
plt.show()

Output:

You might also like