Skip to main content

Command Palette

Search for a command to run...

GenerativeAI

GenAI

Published
•8 min read•View as Markdown
# Sigmoid function
import matplotlib.pyplot as plt
import numpy as np
def sigmoid(x):
    s=1/(1+np.exp(-x))  
    ds=s*(1-s)         
    return s,ds
x=np.arange(-8,8,0.01)
sigmoid(x)
fig, ax = plt.subplots(figsize=(9,5))
ax.spines['left'].set_position('center')
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.plot(x,sigmoid(x)[0], color="Blue", linewidth=3, label="sigmoid")
ax.plot(x,sigmoid(x)[1], color="#9621E2", linewidth=3, label="derivative")
ax.legend(loc="upper right", frameon=False)
fig.show()

# Tanh function
import matplotlib.pyplot as plt
import numpy as np
def tanh(x):
    t=(np.exp(x)-np.exp(-x))/(np.exp(x)+np.exp(-x))
    dt=1-t**2
    return t,dt
z=np.arange(-6,6,0.01)
tanh(z)[0].size, tanh(z)[1].size
fig, ax = plt.subplots(figsize=(9,5))
ax.spines['left'].set_position('center')
ax.spines['bottom'].set_position('center')
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.plot(z,tanh(z)[0], color="#307EC7", linewidth=3, label="tanh")
ax.plot(z,tanh(z)[1], color="#9621E2", linewidth=3, label="derivative")
ax.legend(loc="upper right", frameon=False)
fig.show()

# ReLU Activation and its derivative
import matplotlib.pyplot as plt
import numpy as np
def relu(x):
    r = np.maximum(0, x)
    dr = np.where(x <= 0, 0, 1)
    return r,dr
x=np.arange(-6,6,0.01)  # Range for the x-axis
relu_values, relu_derivatives = relu(x)   # Compute ReLU and its derivative
fig, ax = plt.subplots(figsize=(9,5))
ax.spines['left'].set_position('center')
ax.spines['bottom'].set_position(('data', 0))   # Set the x-axis at y=0
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
# Plotting the ReLU and its derivative
ax.plot(x,relu_values, color="#307EC7", linewidth=3, label="ReLU")
ax.plot(x,relu_derivatives, color="#9621E2", linewidth=3, label="derivative")
ax.legend(loc="upper left", frameon=False)
fig.show()

# Leaky Rectified Linear Unit (Leaky ReLU)
import matplotlib.pyplot as plt
import numpy as np
# Define the Leaky ReLU function and its derivative
def leaky_relu(x, alpha=0.01):
    r = np.maximum(alpha * x, x)
    dr = np.where(x <= 0, alpha, 1)
    return r,dr
#Generate x values
x=np.arange(-6,6,0.01)  # Range for the x-axis
leaky_relu_values, leaky_relu_derivatives = leaky_relu(x)
# Create the plot
fig, ax = plt.subplots(figsize=(9,5))
ax.spines['left'].set_position('center')
ax.spines['bottom'].set_position(('data', 0))   # Set the x-axis at y=0
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
# Plotting the Leaky ReLU and its derivative
ax.plot(x,leaky_relu_values, color="#307EC7", linewidth=1, label="Leaky ReLU")
ax.plot(x,leaky_relu_derivatives, color="#9621E2", linewidth=1, label="Derivative")
ax.legend(loc="upper left", frameon=False)
fig.show()

# Parametric Rectified Linear Unit (PReLU)
import matplotlib.pyplot as plt
import numpy as np
# Define the Leaky ReLU function and its derivative
def prelu(x, alpha=0.25):
    r = np.maximum(alpha * x, x)
    dr = np.where(x <= 0, alpha, 1)
    return r,dr
#Generate x values
x=np.arange(-6,6,0.01)  # Range for the x-axis
prelu_values, prelu_derivatives = prelu(x)
# Create the plot
fig, ax = plt.subplots(figsize=(9,5))
ax.spines['left'].set_position('center')
ax.spines['bottom'].set_position(('data', 0))   # Set the x-axis at y=0
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
# Plotting the Leaky ReLU and its derivative
ax.plot(x,prelu_values, color="#307EC7", linewidth=3, label="PReLU")
ax.plot(x,prelu_derivatives, color="#9621E2", linewidth=3, label="Derivative")
ax.legend(loc="upper left", frameon=False)
plt.show()

# Exponential Linear Unit (ELU)
import matplotlib.pyplot as plt
import numpy as np
# Define the Leaky ReLU function and its derivative
def elu(x, alpha=1.0):
    r = np.where(x >=0, x, alpha * (np.exp(x) - 1))
    dr = np.where(x >= 0, 1, alpha * np.exp(x))
    return r,dr
#Generate x values
x=np.arange(-6,6,0.01)  # Range for the x-axis
elu_values, elu_derivatives = elu(x)
# Create the plot
fig, ax = plt.subplots(figsize=(9,5))
ax.spines['left'].set_position('center')
ax.spines['bottom'].set_position(('data', 0))   # Set the x-axis at y=0
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
# Plotting the ELU and its derivative
ax.plot(x,elu_values, color="#307EC7", linewidth=3, label="ELU")
ax.plot(x,elu_derivatives, color="#9621E2", linewidth=3, label="Derivative")
ax.legend(loc="upper left", frameon=False)
plt.show()

# Softplus
import matplotlib.pyplot as plt
import numpy as np
# Define the Leaky ReLU function and its derivative
def softplus(x):
    r = np.log(1 + np.exp(x))
    dr = 1 / (1 + np.exp(-x))
    return r,dr
#Generate x values
x = np.arange(-6, 6, 0.01)  # Range for the x-axis
softplus_values, softplus_derivatives = softplus(x)
# Create the plot
fig, ax = plt.subplots(figsize=(9,5))
ax.spines['left'].set_position('center')
ax.spines['bottom'].set_position(('data', 0))   # Set the x-axis at y=0
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
# Plotting the Softplus and its derivative
ax.plot(x,softplus_values, color="#307EC7", linewidth=3, label="Softplus")
ax.plot(x,softplus_derivatives, color="#9621E2", linewidth=3, label="Derivative")
ax.legend(loc="upper left", frameon=False)
plt.show()

###########PRAC 2####################
#For Iris Dataset
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import Adam
from sklearn.metrics import classification_report, confusion_matrix

# Load the Iris dataset
iris = load_iris()
X = iris.data  # shape: (150, 4)
y = iris.target  # shape: (150,)
# Normalize the dataset
scaler = StandardScaler()
X = scaler.fit_transform(X)
# One hot encode the labels
y = to_categorical(y, num_classes=3)
# Split into train and test
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# Build MLP model function
def build_mlp(activation='relu', layer_config=[64, 32]):
    model = Sequential()
    model.add(Dense(layer_config[0], input_shape=(4,), activation=activation))
    for units in layer_config[1:]:
        model.add(Dense(units, activation=activation))
    model.add(Dense(3, activation='softmax'))  # 3 classes for Iris
    model.compile(optimizer=Adam(learning_rate=0.001), loss='categorical_crossentropy', metrics=['accuracy'])
    return model

# Experiment with different configurations
activations = ['relu', 'tanh', 'sigmoid']
layer_configs = [[64, 32], [128, 64, 32], [256, 128, 64, 32]]
results = {}
for activation in activations:
    for config in layer_configs:
        model = build_mlp(activation=activation, layer_config=config)
        history = model.fit(X_train, y_train, epochs=50, batch_size=8, validation_split=0.2, verbose=0)
        _, accuracy = model.evaluate(X_test, y_test, verbose=0)
        results[(activation, tuple(config))] = accuracy
        print(f'Activation: {activation}, Layer Config: {config}, Accuracy: {accuracy:.4f}')

###############PRAC 3####################
# Import required libraries
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from tensorflow import keras
from tensorflow.keras import layers, models
from sklearn.metrics import classification_report, confusion_matrix

# 1. Dataset Preparation
# ----------------------

# Load the MNIST dataset (28x28 grayscale images of handwritten digits)
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
# Normalize the image data to range [0, 1]
x_train = x_train.astype("float32") / 255.0
x_test = x_test.astype("float32") / 255.0
# Reshape to include channel dimension (28, 28, 1)
x_train = x_train[..., np.newaxis]
x_test = x_test[..., np.newaxis]
# Convert labels to one-hot encoded format
num_classes = 10
y_train_cat = keras.utils.to_categorical(y_train, num_classes)
y_test_cat = keras.utils.to_categorical(y_test, num_classes)
# Split training data into train and validation sets
from sklearn.model_selection import train_test_split
x_train, x_val, y_train_cat, y_val_cat = train_test_split(x_train, y_train_cat, test_size=0.1, random_state=42)

# 2. Define CNN Model Architecture
model = models.Sequential()
# Convolutional Layer 1: Extract Low-Level features
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)))
model.add(layers.MaxPooling2D((2,2)))   # Reduce spatial dimensions
# Convolutional Layer 2
model.add(layers.Conv2D(64, (3, 3), activation='relu'))   # 64 means you're extracting high level features
model.add(layers.MaxPooling2D((2, 2)))
# Flatten the output and feed into Fully Connected Layers
model.add(layers.Flatten())
model.add(layers.Dense(128, activation='relu'))   # Fully connected layer
model.add(layers.Dropout(0.5))  # Dropout for regularization
# Output layer with Softmax for multi-class classification
model.add(layers.Dense(num_classes, activation='softmax'))
# Display the model summary
model.summary()

#############PRAC 4################
import torch
import torchvision
from torchvision import transforms
import matplotlib.pyplot as plt
from PIL import Image

# Load pre-trained models for segmentation and detection
fcn_model = torchvision.models.segmentation.fcn_resnet50(pretrained=True)
fcn_model.eval()
faster_rcnn_model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True)
faster_rcnn_model.eval()

# Function to process and show images with FCN segmentation and Faster-RCNN detection
def process_image(image, model_fcn, model_frcnn):
  transform = transforms.Compose([
      transforms.ToTensor(),   # Convert the image to a PyTorch tensor
  ])
  image_tensor = transform(image)
  # FCN Semantic Segmentation
  with torch.no_grad():
    output_fcn = model_fcn(image_tensor.unsqueeze(0))  # Add batch dimension
    output_fcn_predictions = output_fcn['out'].argmax(1).squeeze().cpu().numpy()
  # Faster R-CNN Object Detection
  with torch.no_grad():
    output_frcnn = model_frcnn([image_tensor])
  # Extract boxes and labe;s from Faster R-CNN output
  boxes = output_frcnn[0]['boxes'].cpu().numpy()
  labels = output_frcnn[0]['labels'].cpu().numpy()
  # Plot the original image, FCN segmentation output, and Faster R-CNN detections
  fig, ax = plt.subplots(1, 3, figsize=(15, 5))
  # Original Image
  ax[0].imshow(image)
  ax[0].set_title('Original Image')
  ax[0].axis('off')
  # FCN Segmentation Output
  ax[1].imshow(output_fcn_predictions)
  ax[1].set_title('FCN Segmentation Output')
  ax[1].axis('off')
  # Faster R-CNN Object Detection
  ax[2].imshow(image)
  for box in boxes:
    x_min, y_min, x_max, y_max = box
    rect = plt.Rectangle((x_min, y_min), x_max - x_min, y_max - y_min, fill=False, color='red', linewidth=2)
    ax[2].add_patch(rect)
  ax[2].set_title('Faster R-CNN Object Detection')
  ax[2].axis('off')
  plt.tight_layout()
  plt.show()

# Load your images
room_image = Image.open('/road.jpg')
road1_image = Image.open('/road1.jpg')
road2_image = Image.open('/room.jpeg')

# Process each image with the models
process_image(room_image, fcn_model, faster_rcnn_model)
process_image(road1_image, fcn_model, faster_rcnn_model)
process_image(road2_image, fcn_model, faster_rcnn_model)

#######PRAC 5###################
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import os
import zipfile
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.applications import VGG16

#Download and extract dataset
url = "https://storage.googleapis.com/mledu-datasets/cats_and_dogs_filtered.zip"
filename = "cats_and_dogs_filtered.zip"
tf.keras.utils.get_file(filename, url)
with zipfile.ZipFile("cats_and_dogs_filtered.zip", "r") as zip_ref:
    zip_ref.extractall()

#Define data generators
base_dir = "cats_and_dogs_filtered"
train_dir = os.path.join(base_dir, "train")
validation_dir = os.path.join(base_dir, "validation")
train_datagen = ImageDataGenerator(rescale = 1./255,
                                  rotation_range = 20,
                                  width_shift_range = 0.2,
                                  height_shift_range = 0.2,
                                  shear_range = 0.2,
                                  zoom_range = 0.2,
                                  horizontal_flip = True)
validation_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(validation_dir,
                                                        target_size=(150, 150),
                                                        batch_size = 20,
                                                        class_mode = "binary")
validation_generator = validation_datagen.flow_from_directory(validation_dir,
                                                        target_size=(150, 150),
                                                        batch_size = 20,
                                                        class_mode = "binary")

#Load pre_trained VGG16 model
conv_base = VGG16(weights = "imagenet",
                 include_top = False,
                 input_shape=(150, 150, 3))
#Freeze convolutional base layers
conv_base.trainable = False

#Build model on top of the convolution base
model = tf.keras.models.Sequential()
model.add(conv_base)
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(256, activation = "relu"))
model.add(tf.keras.layers.Dropout(0.5))
model.add(tf.keras.layers.Dense(1, activation="sigmoid"))

#Compile Model
model.compile(loss = "binary_crossentropy",
             optimizer = tf.keras.optimizers.RMSprop(learning_rate=2e-5),
             metrics = ["accuracy"])
history = model.fit(train_generator,
                    steps_per_epoch=100,
                    epochs=30,
                    validation_data=validation_generator,
                    validation_steps=50)

# Show sample input and its predicted class
x, y_true = next(validation_generator)
y_pred = model.predict(x)
class_names = ['cat', 'dog' ]
for i in range(len(x)):
    plt.imshow(x[i])
    plt.title(f'Predicted class: {class_names[int(round(y_pred[i][0])) ]}, True class: {class_names[int(y_true[i]) ]}')
    plt.show()
# PLot accuracy and Loss over time
acc = history. history["accuracy"]
val_acc = history.history["val_accuracy"]
loss = history. history["loss"]
val_loss = history.history["val_loss"]
epochs = range(1, len(acc) + 1)
plt.plot(epochs, acc, "bo", label="Training acc")
plt.pllt(epochs, val_acc, "b", label="Validation acc")
plt.title("Trainig and Validation Loss")
plt.legend()
plt.show()

#############PRAC 6####################
!pip install opencv-python ultralytics ipython

import cv2
from ultralytics import YOLO
from IPython.display import display, Image
import time

model = YOLO('yolov8n.pt')

# --- Initialize Webcam ---
try:
    # Open a connection to the default camera (camera index 0)
    cap = cv2.VideoCapture(0)
    if not cap.isOpened():
        raise IOError("Cannot open webcam. Please check if it is connected and not in use by another application.")
except Exception as e:
    print(f"Error: {e}")
    exit()

# Set camera resolution (optional)
cap.set(3, 640)  # Width
cap.set(4, 480)  # Height

# A set to store all unique object classes detected during the session
all_detected_objects = set()
print("Starting live detection... Press 'q' in the display window to quit.")
# --- Main Loop for Detection ---
while True:
    # Read a frame from the camera
    success, frame = cap.read()

    if not success:
        print("Failed to grab a frame. Exiting...")
        break
# Perform object detection on the current frame
    results = model(frame)
    # Iterate over the detected objects in the current frame
    for result in results:
        boxes = result.boxes
        for box in boxes:
            # Get class ID and name
            class_id = int(box.cls[0])
            class_name = model.names[class_id]
# Add the detected class name to our master set
            all_detected_objects.add(class_name)
            # --- Visualization ---
            # Get confidence score and coordinates
            confidence = float(box.conf[0])
            x1, y1, x2, y2 = map(int, box.xyxy[0])
# Draw the bounding box on the frame
            cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
            # Create the label text
            label = f'{class_name} {confidence:.2f}'
            # Put the label on the bounding box
            cv2.putText(frame, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2)
# Display the resulting frame in a window named 'Live Object Detection'
    cv2.imshow('Live Object Detection', frame)
    # Check if the 'q' key is pressed. If yes, break the loop.
    # cv2.waitKey(1) waits 1ms for a key event. & 0xFF is a standard mask.
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break