DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
Experiment-3.3
Student Name: Kunal Shaw UID: 21BCS2144
Branch: BE-CSE
Subject Name: Computer Vision
AIM
To develop a simple computer vision application using a Convolutional Neural
Network (CNN) for image classification.
Code:
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import matplotlib.pyplot as plt
# Prepare image data
train_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory('data/train', target_size=(150,
150), batch_size=32, class_mode='binary')
# Define the CNN model
model = Sequential([
Conv2D(32, (3, 3), activation='relu', input_shape=(150, 150, 3)),
MaxPooling2D(pool_size=(2, 2)),
Conv2D(64, (3, 3), activation='relu'),
MaxPooling2D(pool_size=(2, 2)),
Flatten(),
Dense(128, activation='relu'),
Dense(1, activation='sigmoid')
])
# Compile and train the model
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
model.fit(train_generator, epochs=5)
# Evaluate the model and plot results
loss, accuracy = model.evaluate(train_generator)
print(f"Model Accuracy: {accuracy * 100}%")
# Plotting training accuracy
plt.plot(model.history.history['accuracy'])
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
plt.title('Model Accuracy')
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.show()
Expected Output:
- The CNN model is trained on the images in the 'data/train' directory.
- Printed model accuracy after training.
- A plot showing the training accuracy over the epochs.
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
Learning Outcomes:
• - Understand the basic structure of a Convolutional Neural Network (CNN).
• - Learn how to preprocess image data and train a CNN for image classification.
• - Visualize the training process and accuracy of a CNN model.