programing_of_ai
programing_of_ai
Submitted by
M.Huzaifa(2022-cs-438)
Bachelor of Technology
import os # Provides functions to interact with the operating system (like reading file directories)import
matplotlib.pyplot as plt # Library for creating visualizations and plots
# Set the style for all plots to a dark background for better contrast
plt.style.use('dark_background')
# ----------------------------
plt.figure(figsize=(12,12)) # Create a new figure with a width and height of 12 inches each
for i in range(1, 10): # Loop over image indices from 1 to 9 (assuming indexing starts at 0; adjust as
needed)
plt.subplot(3, 3, i) # Create a subplot in a 3x3 grid and select the i-th subplot for plotting the image
# Construct the path for the i-th healthy spiral image by combining the directory path and the list of file
names
img = load_img(
"../input/parkinsons-drawings/spiral/training/healthy/" +
os.listdir("../input/parkinsons-drawings/spiral/training/healthy")[i]
plt.show() # Render and display the entire figure with all 9 images
# ----------------------------
# ----------------------------
plt.subplot(3, 3, i) # Create a subplot grid of 3 rows and 3 columns, positioning each image
accordingly
# Construct the path for the i-th Parkinson spiral image from the appropriate folder
img = load_img(
"../input/parkinsons-drawings/spiral/training/parkinson/" +
os.listdir("../input/parkinsons-drawings/spiral/training/parkinson")[i]
# ----------------------------
# ----------------------------
for i in range(1, 10): # Loop through indices 1 to 9 for healthy wave images
# Create the file path for each healthy wave image by concatenating the base directory and the specific
file name
img = load_img(
"../input/parkinsons-drawings/wave/training/healthy/" +
os.listdir("../input/parkinsons-drawings/wave/training/healthy")[i]
# ----------------------------
# ----------------------------
for i in range(1, 10): # Loop over the first 9 images from the Parkinson wave folder
# Build the full file path for the image from the Parkinson wave training directory
img = load_img(
"../input/parkinsons-drawings/wave/training/parkinson/" +
os.listdir("../input/parkinsons-drawings/wave/training/parkinson")[i]
# ----------------------------
# ----------------------------
from keras.models import Sequential # Import the Sequential model type for stacking layers linearly
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense # Import various layers: Conv2D for
convolutions, MaxPooling2D for pooling, Flatten to convert image to vector, Dense for fully connected
layers
# ----------------------------
# ----------------------------
# Add the first convolutional layer with 32 filters, a 3x3 kernel, and ReLU activation function; specify the
input shape
# Add a max pooling layer with a pool size of 2x2 to reduce spatial dimensions
classifier.add(MaxPooling2D(pool_size=(2,2)))
# Add a second convolutional layer with 32 filters and a 3x3 kernel; use ReLU activation
classifier.add(MaxPooling2D(pool_size=(2,2)))
# Flatten the 2D features from the convolutional layers into a 1D feature vector
classifier.add(Flatten())
# Add a fully connected (dense) layer with 128 units and ReLU activation
classifier.add(Dense(activation='relu', units=128))
# Add the output layer with 1 unit (for binary classification) using a sigmoid activation function
classifier.add(Dense(activation='sigmoid', units=1))
# ----------------------------
# Preparing Image Data Generation for Training and Testing
# ----------------------------
# Create an ImageDataGenerator for training that rescales pixel values and applies data augmentation
transformations
train_datagen = ImageDataGenerator(
test_datagen = ImageDataGenerator(rescale=1./255)
spiral_train_generator = train_datagen.flow_from_directory(
target_size=(128,128),
batch_size=32,
class_mode='binary'
wave_train_generator = train_datagen.flow_from_directory(
target_size=(128,128),
batch_size=32,
class_mode='binary'
wave_test_generator = test_datagen.flow_from_directory(
target_size=(128,128),
batch_size=32,
class_mode='binary'
# ----------------------------
# Fitting the Model using the Training Data
# ----------------------------
from keras.callbacks import EarlyStopping, ReduceLROnPlateau # Import callbacks for early stopping
and learning rate reduction
# Create an EarlyStopping callback to halt training when validation loss stops improving
early_stopping = EarlyStopping(
patience=3, # Number of epochs with no improvement after which training will be stopped
restore_best_weights=True # Restore model weights from the epoch with the best value of the
monitored quantity
# Create a ReduceLROnPlateau callback to reduce the learning rate when a metric has stopped improving
reduce_learningrate = ReduceLROnPlateau(
factor=0.2, # Factor by which the learning rate will be reduced (new_lr = lr * factor)
patience=3, # Number of epochs with no improvement before reducing the learning rate
min_delta=0.0001 # Threshold for measuring the new optimum, to only focus on significant changes
)
# Group callbacks into a list to pass them together
epochs = 48
# Compile the classifier with binary cross-entropy loss and Adam optimizer
classifier.compile(
# Fit the model using the spiral training images, validating with spiral testing images
history = classifier.fit_generator(
# ----------------------------
# Plotting the Training Accuracy and Loss Curves
# ----------------------------
Task 2(github):
# Output layer with 2 neurons (since we have 2 classes) and softmax activation
model.add(Dense(2, activation='softmax'))
# Compiling the model with loss function, optimizer, and evaluation metric
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
# Author: Huzaiifa
# Description: This script handles DICOM to PNG conversion, normalization, resizing, and augmentation
for MRI image datasets.
import os
import pydicom
import numpy as np
import random
if not os.path.exists(png_dir):
os.makedirs(png_dir)
if filename.lower().endswith(".dcm"):
dicom_image = pydicom.dcmread(dicom_path)
image_array = dicom_image.pixel_array.astype(float)
image_uint8 = normalized_image.astype(np.uint8)
image = Image.fromarray(image_uint8)
image.save(output_path)
def normalize_images(image_dir):
image = Image.open(path).convert("L")
image.save(path)
image = Image.open(path).convert("L")
image = image.resize(output_size)
image.save(path)
if not os.path.exists(output_dir):
os.makedirs(output_dir)
image = Image.open(img_path).convert("L")
for i in range(num_augmented):
aug_img = image.copy()
# Random rotation
angle = random.randint(
-augmentations.get("rotation_angle", 30),
augmentations.get("rotation_angle", 30)
)
aug_img = aug_img.rotate(angle)
aug_img = aug_img.transpose(Image.FLIP_LEFT_RIGHT)
aug_img = aug_img.transpose(Image.FLIP_TOP_BOTTOM)
w, h = aug_img.size
aug_img.save(os.path.join(output_dir, f"aug_{i}_{filename}"))
# Example usage:
# normalize_images("PNG_PD")
# resize_images("PNG_PD")
# augment_images(
# input_dir="PNG_PD",
# output_dir="Augmented_PD",
# augmentations={
# "rotation_probability": 0.7,
# "rotation_angle": 20,
# "flip_probability": 0.5,
# "zoom_probability": 0.3,
# "zoom_factor": 1.1
# },
# num_augmented=5
Output Images: