Write a Python Program using Perceptron Neural Network to recognise even and odd
numbers. Given numbers are in ASCII form 0 to 9
import numpy as np
print("Write a Python Program using Perceptron Neural Network to recognise even and odd
numbers.")
print("Given numbers are in ASCII form 0 to 9\n")
# ASCII-like binary representation of digits 0–9
ascii_digits = {
0: [0,0,1,1,0,1,1,1,1,1],
1: [0,0,0,1,0,0,1,0,0,1],
2: [0,1,1,1,1,1,1,1,1,1],
3: [0,1,1,1,1,0,1,1,1,1],
4: [0,1,0,1,0,0,1,0,0,1],
5: [0,1,1,0,1,0,1,1,1,1],
6: [0,1,1,0,1,1,1,1,1,1],
7: [0,0,1,1,0,0,1,0,0,1],
8: [0,1,1,1,1,1,1,1,1,1],
9: [0,1,1,1,1,0,1,1,1,1],
}
labels = {
0: 1, 1: 0, 2: 1, 3: 0, 4: 1,
5: 0, 6: 0, 7: 0, 8: 1, 9: 0
}
X = np.array([ascii_digits[i] for i in range(10)])
y = np.array([labels[i] for i in range(10)])
def train(X, y, epochs=10, lr=0.1):
w = np.random.rand(X.shape[1])
b = np.random.rand()
for _ in range(epochs):
for xi, target in zip(X, y):
z = np.dot(xi, w) + b
pred = 1 if z >= 0 else 0
error = target - pred
w += lr * error * xi
b += lr * error
return w, b
weights, bias = train(X, y)
digit = int(input("Enter a digit (0-9): "))
if 0 <= digit <= 9:
x_input = np.array(ascii_digits[digit])
output = 1 if np.dot(x_input, weights) + bias >= 0 else 0
print(f" The digit {digit} is {'Even' if output else 'Odd'}")
else:
print(" Please enter a digit between 0 and 9 only.")
OUTPUT:
Write Python program to implement CNN object detection. Discuss numerous
performance evaluation metrics for evaluating the object detecting algorithms'
performance.
from ultralytics import YOLO
import cv2
model = YOLO("yolov5s.pt")
img_path = "C:/Users/Hp/Desktop/flower.jpg" # change this to your image
img = cv2.imread(img_path)
if img is None:
print(f"[ERROR] Could not read image: {img_path}")
exit()
results = model(img)
boxes = results[0].boxes
bird_detected = False
if boxes is not None and len(boxes) > 0:
for box in boxes:
cls_id = int(box.cls[0])
class_name = model.names[cls_id]
confidence = float(box.conf[0])
if class_name.lower() == "bird":
bird_detected = True
x1, y1, x2, y2 = map(int, box.xyxy[0])
label = f"{class_name} {confidence:.2f}"
cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.putText(img, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 0,
0), 2)
if bird_detected:
print(" Bird detected in the image.")
else:
print(" Bird NOT detected in the image.")
else:
print(" No objects detected at all.")
cv2.imshow("YOLO Detection", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
OUTPUT:
MINI PROJECT
import os
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
# Path to training image directory
train_dir = r"C:\Users\Hp\Desktop\data"
# Image size and batch configuration
img_size = (224, 224)
batch_size = 32
# Data generator with rescaling and validation split
train_datagen = ImageDataGenerator(rescale=1./255, validation_split=0.2)
# Training data generator
train_gen = train_datagen.flow_from_directory(
train_dir,
target_size=img_size,
batch_size=batch_size,
class_mode='categorical',
subset='training',
shuffle=True
)
# Validation data generator
val_gen = train_datagen.flow_from_directory(
train_dir,
target_size=img_size,
batch_size=batch_size,
class_mode='categorical',
subset='validation',
shuffle=False
)
# Load ResNet50 base model
base_model = tf.keras.applications.ResNet50(
weights='imagenet',
include_top=False,
input_shape=(224, 224, 3)
)
base_model.trainable = False # Freeze base model layers
# Build model
model = tf.keras.Sequential([
base_model,
tf.keras.layers.GlobalAveragePooling2D(),
tf.keras.layers.Dense(256, activation='relu'),
tf.keras.layers.Dropout(0.3),
tf.keras.layers.Dense(train_gen.num_classes, activation='softmax')
])
# Optimizers to test
optimizers = {
"adam": tf.keras.optimizers.Adam(),
"sgd": tf.keras.optimizers.SGD(),
"rmsprop": tf.keras.optimizers.RMSprop()
}
# Dictionary to store results
results = {}
# Train and evaluate with each optimizer
for name, opt in optimizers.items():
model.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy'])
print(f"\nTraining with {name} optimizer:")
history = model.fit(train_gen, validation_data=val_gen, epochs=5)
results[name] = history.history
OUTPUT: