Build your first CNN model: Convolutional Neural Network for Image Recognition

Build your first CNN model: Convolutional Neural Network for Image Recognition

Build a CNN model that classifies the given pet images correctly into dog and cat images.? The project scope document specifies the requirements for the project “Pet Classification Model Using CNN.” Apart from specifying the functional and non-functional requirements for the project, it also serves as an input for project scoping.?

Plan of Attack:

1. Set Up the Environment

  • Install the necessary libraries: tensorflow, keras, numpy, matplotlib, and pandas if not already installed.
  • Use PyCharm

2. Load and Preprocess the Data

  • Load the Dataset: Start by loading the images of cats and dogs.
  • Resize Images: Since the input images are of varying sizes, resize them to a consistent size (e.g., 128x128 pixels).
  • Normalize Pixel Values: Scale pixel values between 0 and 1 by dividing by 255.
  • Split Dataset: Split the dataset into training and testing sets. Usually, 80% for training and 20% for testing works well.3. Define the CNN Model Architecture

  • Input Layer: Use the resized images as input.
  • Convolutional Layer 1: Add a Conv2D layer with 32 filters of kernel size (5,5).
  • Pooling Layer 1: Add a MaxPooling2D layer with pool size (2,2) and stride 2.
  • Convolutional Layer 2: Add another Conv2D layer with 64 filters of kernel size (5,5).
  • Pooling Layer 2: Add another MaxPooling2D layer with pool size (2,2) and stride 2.
  • Flatten the Output: Flatten the feature maps for the fully connected layer.
  • Dense Layer: Add a dense layer with 32 units (fc_size).
  • Dropout Layer: Add a dropout layer with a probability of 0.4 to reduce overfitting.
  • Output Layer: Apply a softmax function to classify the images into two classes (cat/dog).

python        

4. Compile the Model

  • Define the loss function using binary_crossentropy (since there are two classes).
  • Use the Adam optimizer and track accuracy as a performance metric.

5. Train the Model

  • Train the model on the training data, running for 100, 200, and 300 iterations (epochs).
  • Use the validation data for evaluating the performance after each epoch.

python        

6. Evaluate the Model

  • After training, evaluate the model's accuracy and loss on the test data.

7. Fine-Tuning and Hyperparameter Tuning

  • Adjust the number of filters, learning rate, and dropout rate if necessary to improve accuracy.
  • Run for 200 and 300 iterations to compare results and choose the best model.

8. Generate Reports

  • Plot training/validation loss and accuracy across iterations using matplotlib.
  • Summarize the final performance metrics.

9. Document the Final Results

  • Report the final accuracy and loss after 100, 200, and 300 iterations.
  • Present insights on how the model performed with different iterations and any observed patterns.

This structured approach ensures that you handle data preprocessing, model design, and evaluation effectively.


Schematics: Feature Detection in Convolutional Neural Network

Schematic: Max Pooling


Schematic: Image Recognition

Code Base:

import os
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import matplotlib.pyplot as plt
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense

# Set image dimensions and batch size
img_width, img_height = 128, 128
batch_size = 32

# Specify the correct path to your dataset folder
dataset_dir = r'C:\Users\sib_p\OneDrive\Desktop\JhinukDataClean\Deeplearning\data'  # Update with your dataset path

# Define training and validation data generators
train_datagen = ImageDataGenerator(rescale=1./255, validation_split=0.2)

# Load training data
train_generator = train_datagen.flow_from_directory(
    dataset_dir,  # Make sure this is the correct path to your dataset
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode='binary',
    subset='training'
)

# Load validation data
validation_generator = train_datagen.flow_from_directory(
    dataset_dir,  # Make sure this is the correct path to your dataset
    target_size=(img_width, img_height),
    batch_size=batch_size,
    class_mode='binary',
    subset='validation'
)

# Define the CNN Model Architecture
model = Sequential()

# Input and first Conv layer
model.add(Conv2D(32, kernel_size=(5,5), activation='relu', input_shape=(img_width, img_height, 3)))
model.add(MaxPooling2D(pool_size=(2,2), strides=2))

# Second Conv layer
model.add(Conv2D(64, kernel_size=(5,5), activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2), strides=2))

# Flatten and Dense layers
model.add(Flatten())
model.add(Dense(32, activation='relu'))
model.add(Dropout(0.4))

# Output layer
model.add(Dense(1, activation='sigmoid'))

# Compile the Model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

# Train the Model
history = model.fit(
    train_generator,
    steps_per_epoch=train_generator.samples // batch_size,
    epochs=45,  # Change to 200, 300 for additional runs
    validation_data=validation_generator,
    validation_steps=validation_generator.samples // batch_size
)

# Evaluate the Model
score = model.evaluate(validation_generator, verbose=0)
print(f"Test loss: {score[0]}")
print(f"Test accuracy: {score[1]}")

# Plotting Accuracy and Loss
# Plot training & validation accuracy values
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('Model Accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Train', 'Validation'], loc='upper left')
plt.show()

# Plot training & validation loss values
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('Model Loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Train', 'Validation'], loc='upper left')
plt.show()        


Abhishek Dhoriya

Sr Consultant COE @ Microsoft | AI | Azure | Power Platform | Solution Design & Delivery Lead | ScrumMaster

5 个月

Insightful

要查看或添加评论,请登录

Sibasish Chowdhury PgDip,MIT,PMP?ITIL?PCSM,PC AgilePM,Certified CSM的更多文章

社区洞察

其他会员也浏览了