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

Lab Programs

fgdvc ghfbv gdvbc sxdfc fcvx vbdc cvx
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Lab Programs

fgdvc ghfbv gdvbc sxdfc fcvx vbdc cvx
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Lab Programs

1. Write a program to solve the Water Jug Problem using Breadth Frist Search
(BFS).
from collections import deque

def bfs_water_jug(jug1_max, jug2_max, target):


visited, queue = set([(0, 0)]), deque([(0, 0)])

while queue:
jug1, jug2 = queue.popleft()
if jug1 == target or jug2 == target:
return True

next_states = [
(jug1_max, jug2), # Fill Jug 1
(jug1, jug2_max), # Fill Jug 2
(0, jug2), # Empty Jug 1
(jug1, 0), # Empty Jug 2
(jug1 - min(jug1, jug2_max - jug2), jug2 + min(jug1, jug2_max - jug2)), #
Pour Jug 1 to Jug 2
(jug1 + min(jug2, jug1_max - jug1), jug2 - min(jug2, jug1_max - jug1)) #
Pour Jug 2 to Jug 1
]

for state in next_states:


if state not in visited:
visited.add(state)
queue.append(state)

return False

# Example usage:
jug1_capacity, jug2_capacity, target_amount = 5, 10, 2
result = bfs_water_jug(jug1_capacity, jug2_capacity, target_amount)
print(f"{'Possible' if result else 'Not possible'} to measure {target_amount} liters
using the given jugs.")
2. Write a program to find the optimum path from Source to Destination using A *
search technique.
import heapq

class Node:
def __init__(self, position, parent=None, g=0, h=0):
self.position, self.parent = position, parent
self.g, self.h = g, h
self.f = g + h
def __lt__(self, other): return self.f < other.f
def heuristic(a, b): return abs(a[0] - b[0]) + abs(a[1] - b[1])

def astar_search(grid, start, end):


start_node = Node(start, None, 0, heuristic(start, end))
open_list, closed_list = [start_node], set()

while open_list:
current = heapq.heappop(open_list)
if current.position == end:
path = []
while current: path.append(current.position); current = current.parent
return path[::-1]

closed_list.add(current.position)
for dx, dy in [(0, -1), (0, 1), (-1, 0), (1, 0)]:
pos = (current.position[0] + dx, current.position[1] + dy)
if (0 <= pos[0] < len(grid) and 0 <= pos[1] < len(grid[0]) and
grid[pos[0]][pos[1]] == 0 and pos not in closed_list):
new_node = Node(pos, current, current.g + 1, heuristic(pos, end))
if not any(n.position == new_node.position and n.f <= new_node.f for n in
open_list):
heapq.heappush(open_list, new_node)
return None

# Example usage
grid = [
[0, 1, 0, 0, 0, 0],
[0, 1, 0, 1, 1, 0],
[0, 0, 0, 0, 1, 0],
[0, 1, 1, 0, 1, 0],
[0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
]

start, end = (0, 0), (5, 5)


path = astar_search(grid, start, end)
print("Path found:", path) if path else print("No path found.")
3. Write a program to solve the 4 - Queens Problem.
def is_safe(board, row, col):
return all(board[row][i] == 0 for i in range(col)) and \
all(board[i][j] == 0 for i, j in zip(range(row, -1, -1), range(col, -1, -1))) and \
all(board[i][j] == 0 for i, j in zip(range(row, len(board)), range(col, -1, -1)))

def solve_n_queens_util(board, col):


if col >= len(board): return True
for i in range(len(board)):
if is_safe(board, i, col):
board[i][col] = 1
if solve_n_queens_util(board, col + 1): return True
board[i][col] = 0
return False

def solve_n_queens(n):
board = [[0] * n for _ in range(n)]
if solve_n_queens_util(board, 0): print_board(board)
else: print("Solution does not exist")

def print_board(board):
print("\n".join(" ".join("Q" if col else "." for col in row) for row in board) + "\n")

# Solve the 4-Queens problem


solve_n_queens(4)
4. Write a program to implement Minimax search for 2 Player games.
import math

def print_board(board):
print("\n".join(" | ".join(row) for row in board) + "\n" + "-" * 9)

def check_winner(board, player):


return any(all(s == player for s in row) for row in board) or \
any(all(board[i][j] == player for i in range(3)) for j in range(3)) or \
all(board[i][i] == player for i in range(3)) or \
all(board[i][2 - i] == player for i in range(3))

def minimax(board, is_max):


if check_winner(board, 'X'): return 1
if check_winner(board, 'O'): return -1
if all(cell in ['X', 'O'] for row in board for cell in row): return 0

best_score = -math.inf if is_max else math.inf


for i in range(3):
for j in range(3):
if board[i][j] == ' ':
board[i][j] = 'X' if is_max else 'O'
score = minimax(board, not is_max)
board[i][j] = ' '
best_score = max(best_score, score) if is_max else min(best_score, score)
return best_score

def best_move(board):
best_score, move = -math.inf, None
for i in range(3):
for j in range(3):
if board[i][j] == ' ':
board[i][j] = 'X'
score = minimax(board, False)
board[i][j] = ' '
if score > best_score:
best_score, move = score, (i, j)
return move

def play_game():
board = [[' ']*3 for _ in range(3)]
print("Initial Board:")
print_board(board)

while True:
move = best_move(board)
if move:
board[move[0]][move[1]] = 'X'
print("\nAI (X) makes a move:")
print_board(board)
if check_winner(board, 'X'):
print("X wins!")
break
if all(cell in ['X', 'O'] for row in board for cell in row):
print("It's a draw!")
break

try:
row, col = map(int, input("Enter your move (row col): ").split())
if board[row][col] == ' ':
board[row][col] = 'O'
print("\nYou (O) make a move:")
print_board(board)
if check_winner(board, 'O'):
print("O wins!")
break
else:
print("Cell occupied! Try again.")
except (ValueError, IndexError):
print("Invalid input! Enter row and column as 0, 1, or 2.")

# Run the game


play_game()
5. Using OpenCV python library capture an image and perform the following image
processing operations:
a) Image Resizing
b) Blurring of Image
c) Gray scaling of image
d) Scaling and rotation
e) Edge Detection
f) Segmentation using thresholding
g) Background subtraction
h) Morphological operations
import cv2
import numpy as np
import matplotlib.pyplot as plt

def display_image(title, image, cmap=None):


plt.figure(figsize=(6, 6))
plt.title(title)
plt.axis('off')
plt.imshow(image if cmap else cv2.cvtColor(image, cv2.COLOR_BGR2RGB),
cmap=cmap)
plt.show()

# Load image
image_path = 'ntr.jpg'
image = cv2.imread(image_path)
if image is None:
print("Failed to load image.")
else:
transformations = {
"Resized Image": cv2.resize(image, (300, 300)),
"Blurred Image": cv2.GaussianBlur(image, (15, 15), 0),
"Gray Scale Image": cv2.cvtColor(image, cv2.COLOR_BGR2GRAY),
"Scaled Image": cv2.resize(image, None, fx=0.5, fy=0.5),
"Rotated Image": cv2.warpAffine(image, cv2.getRotationMatrix2D((image.shape[1]//2,
image.shape[0]//2), 45, 1.0), (image.shape[1], image.shape[0])),
"Edge Detection": cv2.Canny(image, 100, 200),
"Thresholded Image": cv2.threshold(cv2.cvtColor(image, cv2.COLOR_BGR2GRAY),
128, 255, cv2.THRESH_BINARY)[1],
"Background Subtraction": cv2.createBackgroundSubtractorMOG2().apply(image)
}

# Morphological operations on thresholded image


kernel = np.ones((5, 5), np.uint8)
threshold_image = transformations["Thresholded Image"]
transformations.update({
"Dilated Image": cv2.dilate(threshold_image, kernel, iterations=1),
"Eroded Image": cv2.erode(threshold_image, kernel, iterations=1)
})

# Display all transformations


for title, img in transformations.items():
display_image(title, img, cmap='gray' if "Gray" in title or "Edge" in title or "Threshold"
in title else None)
5. Write a program with two menu options 1) Capture Image and 2) Recognize
Image. This program should capture pictures of five students and save them.
The program should identify/recognize the student and display the student's
name.
import cv2
import numpy as np
import os
from tensorflow.keras.applications.mobilenet_v2 import MobileNetV2,
preprocess_input
from tensorflow.keras.preprocessing.image import img_to_array, load_img
from tensorflow.keras.models import Model
from sklearn.preprocessing import LabelEncoder
from sklearn.svm import SVC
import pickle
import time # For delays if needed

# Initialize the MobileNetV2 model for feature extraction


base_model = MobileNetV2(weights="imagenet", include_top=False,
input_shape=(224, 224, 3))
model = Model(inputs=base_model.input, outputs=base_model.output)

# Directory for storing captured student images


image_dir = "student_images"
if not os.path.exists(image_dir):
os.makedirs(image_dir)

# List of students
students_list = ["Aaa", "Bbb", "Ccc", "Ddd", "Eee"]

# Function to capture and save images of students


def capture_images(students_list, images_per_student=1):
for student in students_list:
for i in range(images_per_student):
cap = cv2.VideoCapture(0)
if not cap.isOpened():
print("Could not open webcam.")
return
print(f"Capturing image for {student}...")

ret, frame = cap.read()


if not ret:
print("Failed to capture image.")
break
# Save captured image
save_path = os.path.join(image_dir, f"{student}_{i + 1}.jpg")
cv2.imwrite(save_path, frame)
print(f"Saved {student}'s image at {save_path}")
# Add a small delay
time.sleep(2)
cap.release()

# Function to extract features using MobileNetV2


def extract_features(img_path):
img = load_img(img_path, target_size=(224, 224))
img_array = img_to_array(img)
img_array = np.expand_dims(img_array, axis=0)
img_array = preprocess_input(img_array)
features = model.predict(img_array)
return features.flatten()
# Function to train and save the SVM model
def train_recognizer(students_list):
features = []
labels = []
for student in students_list:
student_images = [os.path.join(image_dir, f) for f in os.listdir(image_dir) if
f.startswith(student)]
for img_path in student_images:
features.append(extract_features(img_path))
labels.append(student)
le = LabelEncoder()
labels_enc = le.fit_transform(labels)
clf = SVC(kernel="linear", probability=True)
clf.fit(features, labels_enc)
# Save the model and label encoder
with open("student_recognizer.pkl", "wb") as f:
pickle.dump((clf, le), f)
print("Model trained and saved successfully.")

# Function to recognize a student from an input image


def recognize_student():
# Load the trained SVM model and label encoder
with open("student_recognizer.pkl", "rb") as f:
clf, le = pickle.load(f)
# Capture an image for recognition
cap = cv2.VideoCapture(0)
if not cap.isOpened():
print("Could not open webcam.")
return
print("Capturing image for recognition...")
ret, frame = cap.read()
if not ret:
print("Failed to capture image.")
return
# Save the captured frame temporarily
temp_path = "temp.jpg"
cv2.imwrite(temp_path, frame)
print(f"Image for recognition saved temporarily as {temp_path}")
cap.release()
# Extract features and predict
features = extract_features(temp_path)
os.remove(temp_path) # Clean up temp file after extraction

# Predict the student’s identity


prediction = clf.predict([features])[0]
student_name = le.inverse_transform([prediction])[0]
print(f"Recognized Student: {student_name}")

# Menu options
def menu():
print("1. Capture Images of Students")
print("2. Recognize Student")
print("3. Exit")
return int(input("Choose an option: "))

# Main program
def main():
while True:
choice = menu()
if choice == 1:
capture_images(students_list)
train_recognizer(students_list)
elif choice == 2:
recognize_student()
elif choice == 3:
print("Exiting the program.")
break
else:
print("Invalid option. Please try again.")

if __name__ == "__main__":
main()
Using Keras/any standard dataset write the program for the following Machine
learning takes:
7. use the decision tree classifier to classify the dataset.
# Import required libraries
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score, classification_report

# Load the dataset


file_path = 'Cleaned_Students_Performance.csv'
df = pd.read_csv(file_path)

# Display the first few rows of the dataset


print("First few rows of the dataset:")
print(df.head())

# Check for missing values


print("\nMissing values in each column:")
print(df.isnull().sum())

# Convert categorical columns to numerical format using one-hot encoding


df_encoded = pd.get_dummies(df, drop_first=True)

# Assuming the target variable is the last column (adjust if needed)


# Separate features (X) and target (y)
X = df_encoded.iloc[:, :-1] # All columns except the last
y = df_encoded.iloc[:, -1] # Last column as target

# Split the dataset into training and testing sets


X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Initialize and train the Decision Tree Classifier


clf = DecisionTreeClassifier(random_state=42)
clf.fit(X_train, y_train)

# Make predictions on the test set


y_pred = clf.predict(X_test)

# Evaluate the model


accuracy = accuracy_score(y_test, y_pred)
report = classification_report(y_test, y_pred)

print(f"\nAccuracy: {accuracy}")
print("\nClassification Report:")
print(report)
8. Use the Naïve Bayes classifier to classify the dataset.
# Import required libraries
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score, classification_report

# Load the dataset


file_path = 'Cleaned_Students_Performance.csv'
df = pd.read_csv(file_path)

# Display the first few rows of the dataset


print("First few rows of the dataset:")
print(df.head())

# Check for missing values


print("\nMissing values in each column:")
print(df.isnull().sum())

# Convert categorical columns to numerical format using one-hot encoding


df_encoded = pd.get_dummies(df, drop_first=True)

# Assuming the target variable is the last column (adjust if needed)


# Separate features (X) and target (y)
X = df_encoded.iloc[:, :-1] # All columns except the last
y = df_encoded.iloc[:, -1] # Last column as target

# Split the dataset into training and testing sets


X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Initialize and train the Naïve Bayes Classifier


nb_classifier = GaussianNB()
nb_classifier.fit(X_train, y_train)

# Make predictions on the test set


y_pred = nb_classifier.predict(X_test)

# Evaluate the model


accuracy = accuracy_score(y_test, y_pred)
report = classification_report(y_test, y_pred)

print(f"\nAccuracy: {accuracy}")
print("\nClassification Report:")
print(report)
9. Implement K-Means clustering Algorithm.
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs

# Generate synthetic data or use your own dataset


# Replace this section with your actual dataset
file_path = 'Cleaned_Students_Performance.csv'
df = pd.read_csv(file_path)

# Initialize parameters for K-Means


k = 4 # number of clusters (change as needed)
max_iters = 100 # maximum number of iterations
def initialize_centroids(data, k):
"""Randomly initialize centroids from the dataset."""
return data[np.random.choice(data.shape[0], k, replace=False)]

def closest_centroid(data, centroids):


"""Assign each data point to the closest centroid."""
distances = np.sqrt(((data - centroids[:, np.newaxis])**2).sum(axis=2))
return np.argmin(distances, axis=0)

def move_centroids(data, labels, k):


"""Compute the new centroids as the mean of assigned points."""
return np.array([data[labels == i].mean(axis=0) for i in range(k)])

# K-Means clustering algorithm


def k_means(data, k, max_iters=100):
centroids = initialize_centroids(data, k)
for _ in range(max_iters):
labels = closest_centroid(data, centroids)
new_centroids = move_centroids(data, labels, k)
# If centroids don't change, the algorithm has converged
if np.all(centroids == new_centroids):
break
centroids = new_centroids
return labels, centroids

# Run the algorithm


labels, centroids = k_means(data, k, max_iters)

# Plot the data and centroids


plt.scatter(data[:, 0], data[:, 1], c=labels, s=40, cmap='viridis')
plt.scatter(centroids[:, 0], centroids[:, 1], c='red', s=200, alpha=0.75, marker='X')
plt.title("K-Means Clustering")
plt.xlabel("Feature 1")
plt.ylabel("Feature 2")
plt.show()
10. Using Python NLTK, perform the following Natural Language Processing (NLP)
tasks for any textual content.
a) Tokenizing
b) Filtering Stop Words
c) Stemming
d) Part of Speech tagging
e) Chunking
f) Named Entity Recognition (NER)
11. Write a program that uses Neural networks for image classification using Keras Iris
dataset.

You might also like