Build your first CNN model: Convolutional Neural Network for Image Recognition
Sibasish Chowdhury PgDip,MIT,PMP?ITIL?PCSM,PC AgilePM,Certified CSM
Strategic Technology Leader | Technology Innovation | Proponent of AI as new stakeholder l Project /Product/Service Delivery in Application and Cloud | Digital Transformation | Public Speaker | 13K+ Followers
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
2. Load and Preprocess the Data
python
4. Compile the Model
5. Train the Model
python
6. Evaluate the Model
领英推荐
7. Fine-Tuning and Hyperparameter Tuning
8. Generate Reports
9. Document the Final Results
This structured approach ensures that you handle data preprocessing, model design, and evaluation effectively.
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()
Sr Consultant COE @ Microsoft | AI | Azure | Power Platform | Solution Design & Delivery Lead | ScrumMaster
5 个月Insightful