0% found this document useful (0 votes)
17 views9 pages

Image Classification with CNN in Python

Uploaded by

Dhawal Soni
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views9 pages

Image Classification with CNN in Python

Uploaded by

Dhawal Soni
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Import libraries:

os: For interacting with the operating system (though not used in this snippet).
matplotlib.pyplot as plt: For plotting images.
numpy as np: For numerical operations (though not used in this snippet).
tensorflow.keras.preprocessing.image import ImageDataGenerator: For
generating batches of image data with real-time data augmentation.

Define the dataset path:

Create ImageDataGenerator Instances:

ImageDataGenerator: This class provides a range of data augmentation and preprocessing


options.
rescale=1./255: Rescales the pixel values from [0, 255] to [0, 1].
validation_split=0.2: Specifies that 20% of the data will be used for validation.

Load Training and Validation Data:


flow_from_directory: This method loads images from the specified directory and applies
the defined preprocessing steps.
data_dir: Directory where the dataset is stored.
target_size=(224, 224): Resizes all images to 224x224 pixels.
batch_size=32: Loads images in batches of 32.
class_mode='binary': Specifies that the labels are binary (male or female).
subset='training' and subset='validation': Split the data into training and validation
sets based on the validation_split specified earlier.

Define Function to Display Images:

● show_images: Function to display a specified number of images for a given class label.
● generator: The data generator (either train_generator or
validation_generator).
● class_label: The class label to display images for ('male' or 'female').
● num_images=5: Number of images to display.
● class_indices: Dictionary mapping class labels to indices.
● label_index: Index of the specified class label.
● for batch_images, batch_labels in generator: Iterate over batches of
images and labels.
● for img, label in zip(batch_images, batch_labels): Iterate over images
and their corresponding labels in the batch.
● if label == label_index: Check if the image belongs to the specified class.
● plt.imshow(img): Display the image.
● plt.title(class_label): Set the title of the plot to the class label.
plt.show(): Show the plot.
counter += 1: Increment the counter.
if counter >= num_images: Stop displaying images after reaching the specified number.

Displaying Images:

● print("Displaying male images:"): Print a message indicating that male


images will be displayed.
● show_images(train_generator, 'male'): Call the show_images function to
display images of males.
● print("Displaying female images:"): Print a message indicating that female
images will be displayed.
● show_images(train_generator, 'female'): Call the show_images function to
display images of females.

Obtain Class Indices and Labels:

● class_indices: Dictionary mapping class labels to indices (e.g.,


{'male': 0, 'female': 1}).
● class_labels: Reverses the class_indices dictionary to map indices to
class labels (e.g., {0: 'male', 1: 'female'}).

Count Samples per Class:


● train_generator.classes: Array of class indices for each sample in the
training set.
● np.bincount(class_counts): Counts the number of occurrences of each
class index, resulting in an array where the value at each index represents the
count of samples for that class.

Print and Plot Class Distribution:

● print(f"Class distribution: {class_counts}"): Prints the count of


samples for each class.
● plt.bar(class_labels.values(), class_counts): Creates a bar chart
with class labels on the x-axis and sample counts on the y-axis.
● plt.title('Class Distribution'): Sets the title of the plot.
● plt.xlabel('Class'): Labels the x-axis as 'Class'.
● plt.ylabel('Count'): Labels the y-axis as 'Count'.
● plt.show(): Displays the plot.

Define the CNN Model:


● tf.keras.Sequential: Sequential model where layers are stacked linearly.
● tf.keras.layers.Conv2D(32, (3, 3), activation='relu',
input_shape=(224, 224, 3)): 2D convolution layer with 32 filters, kernel size of
3x3, ReLU activation, and input shape of 224x224x3 (color images).
● tf.keras.layers.MaxPooling2D((2, 2)): Max pooling layer with pool size of
2x2.
● tf.keras.layers.Conv2D(64, (3, 3), activation='relu'): 2D convolution
layer with 64 filters and kernel size of 3x3.
● tf.keras.layers.MaxPooling2D((2, 2)): Max pooling layer with pool size of
2x2.
● tf.keras.layers.Conv2D(128, (3, 3), activation='relu'): 2D
convolution layer with 128 filters and kernel size of 3x3.
● tf.keras.layers.MaxPooling2D((2, 2)): Max pooling layer with pool size of
2x2.
● tf.keras.layers.Flatten(): Flattens the 3D output to 1D.
● tf.keras.layers.Dense(128, activation='relu'): Fully connected (dense)
layer with 128 units and ReLU activation.
● tf.keras.layers.Dense(1, activation='sigmoid'): Output layer with 1 unit
and sigmoid activation for binary classification.

Compile the Model:


● optimizer='adam': Adam optimizer for training.
● loss='binary_crossentropy': Binary cross-entropy loss function for binary
classification.
● metrics=['accuracy']: Metric to evaluate during training and testing.

Train the Model:

● model.fit: Trains the model for a fixed number of epochs.


● train_generator: Training data generator.
● epochs=10: Number of epochs to train the model.
● validation_data=validation_generator: Validation data generator for
evaluating the model during training.

Initialize Lists for Labels and Predictions:

● val_labels: List to store true labels of validation samples.


● val_predictions: List to store predicted labels of validation samples.

Iterate Through the Validation Data:


● for i in range(len(validation_generator)): Loop through the validation
data batches.
● x_val, y_val = validation_generator[i]: Get the input images and true
labels for the current batch.
● y_pred = model.predict(x_val): Predict the labels for the input images.
● val_labels.extend(y_val): Append true labels to the val_labels list.
● val_predictions.extend(np.round(y_pred).astype(int).flatten()):
Append predicted labels (rounded to 0 or 1) to the val_predictions list.

Convert Lists to NumPy Arrays:

● Convert val_labels and val_predictions lists to NumPy arrays for easier


manipulation.

Calculate Accuracy for Each Class:


● male_indices = np.where(val_labels == 0)[0]: Get the indices of male
samples.
● female_indices = np.where(val_labels == 1)[0]: Get the indices of female
samples.
● male_accuracy = np.mean(val_predictions[male_indices] ==
val_labels[male_indices]): Calculate accuracy for male samples.
● female_accuracy = np.mean(val_predictions[female_indices] ==
val_labels[female_indices]): Calculate accuracy for female samples.
● print(f'Male Accuracy: {male_accuracy}'): Print male accuracy.
● print(f'Female Accuracy: {female_accuracy}'): Print female accuracy.

Show Misclassified Images:

● class_labels = {v: k for k, v in


validation_generator.class_indices.items()}: Reverse the
class_indices dictionary to map indices to class labels.
● misclassified_indices = np.where(val_predictions !=
val_labels)[0]: Get the indices of misclassified samples.
● for i in misclassified_indices[:5]: Loop through the first 5
misclassified samples.
● batch_index = i // validation_generator.batch_size: Calculate
the batch index for the misclassified sample.
● image_index = i % validation_generator.batch_size: Calculate the
image index within the batch.
● x_val, y_val = validation_generator[batch_index]: Get the
images and labels for the batch.
● img = x_val[image_index]: Get the misclassified image.
● true_label = class_labels[int(val_labels[i])]: Get the true label
for the image.
● predicted_label = class_labels[int(val_predictions[i])]: Get
the predicted label for the image.
● plt.imshow(img): Display the image.
● plt.title(f'True: {true_label}, Pred: {predicted_label}'):
Set the title of the plot to show true and predicted labels.
● plt.show(): Display the plot.

You might also like