Experiment 6
Experiment 6
Neural Network (CNN) for Simple Image Classification (Dogs and Cats)**, including the
title, aim, objectives, step-by-step explanation with code, expected output, and
conclusion.
---
### Title
Design and implement a CNN-based image classifier for distinguishing between dogs
and cats using a dataset.
### Aim
To build a Convolutional Neural Network (CNN) that classifies images of dogs and cats
using TensorFlow and Keras.
### Objectives
---
```python
import tensorflow as tf
import os
```
**Explanation**:
- `tensorflow` and `keras` provide the framework for building and training the CNN.
---
```python
dataset_url =
"https://storage.googleapis.com/mledu-datasets/cats_and_dogs_filtered.zip"
```
**Explanation**:
- Downloads the Dogs vs. Cats dataset from TensorFlow’s online repository.
---
```python
val_datagen = ImageDataGenerator(rescale=1.0/255.0)
validation_generator = val_datagen.flow_from_directory(validation_dir,
target_size=(150, 150), batch_size=32, class_mode="binary")
```
**Explanation**:
---
```python
model = keras.Sequential([
])
```
**Explanation**:
- **Conv Layer 1**: Uses 32 filters (3x3) with ReLU activation to extract basic features
from RGB images (150x150x3).
- **Conv Layer 2**: Uses 64 filters (3x3) to capture more complex features.
- **Conv Layer 3**: Uses 128 filters (3x3) for deeper feature extraction.
- **Dense Layer**: 512 neurons with ReLU activation to learn high-level patterns.
- **Output Layer**: 1 neuron with sigmoid activation for binary classification (dog or
cat).
---
```python
```
**Explanation**:
- **Optimizer**: `adam` adjusts the learning rate dynamically for efficient training.
---
```python
```
**Explanation**:
- Trains the model for 10 epochs using the training data (`train_generator`).
---
```python
```
**Explanation**:
- Evaluates the model on the validation set to measure performance on unseen data.
---
```python
import numpy as np
prediction = model.predict(img_array)
```
**Explanation**:
- Loads a test image and resizes it to 150x150 pixels.
- Converts it to a NumPy array, normalizes pixel values, and adds a batch dimension.
- Uses the trained model to predict the class (dog or cat) based on the sigmoid output
(threshold: 0.5).
---
## Expected Output
```
Epoch 1/10
...
Epoch 10/10
```
- **Evaluation Output**:
```
```
```
```
---
## Conclusion
- We successfully built and trained a CNN model to classify images of dogs and cats
using TensorFlow and Keras.
- The model, with three convolutional layers, max pooling, and dense layers, achieved
a test accuracy of around 85-90%.
- This experiment showcases the power of CNNs for binary image classification tasks.
---
**Note**: To run this code, ensure you have TensorFlow, Matplotlib, and NumPy
installed in your Python environment. Replace `"path_to_test_image.jpg"` with the
actual path to a dog or cat image for prediction.