0% found this document useful (0 votes)
2 views

Experiment 7

This document outlines Experiment 7, which demonstrates the use of the pre-trained VGG16 Convolutional Neural Network for image classification. It details the aim, objectives, step-by-step implementation with code, and expected outcomes, emphasizing the model's ability to classify images accurately and its adaptability for custom tasks. The conclusion highlights the effectiveness of transfer learning in reducing training time and enhancing performance on new datasets.

Uploaded by

gnanesh847
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Experiment 7

This document outlines Experiment 7, which demonstrates the use of the pre-trained VGG16 Convolutional Neural Network for image classification. It details the aim, objectives, step-by-step implementation with code, and expected outcomes, emphasizing the model's ability to classify images accurately and its adaptability for custom tasks. The conclusion highlights the effectiveness of transfer learning in reducing training time and enhancing performance on new datasets.

Uploaded by

gnanesh847
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Below is a complete response to your query for **Experiment 7: Use a Pre-Trained

Convolutional Neural Network (VGG16) for Image Classification**. It includes the title,
aim, objectives, step-by-step explanation with code, example output, and conclusion,
all formatted for clarity using markdown.

---

## Experiment 7: Use a Pre-Trained Convolutional Neural Network (VGG16) for Image


Classification

### Title

Implementation of VGG16, a pre-trained Convolutional Neural Network (CNN), for


image classification.

### Aim

To utilize the VGG16 deep learning model for classifying images into different
categories.

### Objectives

- Load the VGG16 model pre-trained on ImageNet.

- Process an input image to match the model’s expected format.

- Use the pre-trained model for feature extraction or classification.

- Interpret the model’s predictions.

---

## Step-by-Step Explanation of the Program

### Step 1: Import Necessary Libraries

```python

import tensorflow as tf

from tensorflow.keras.applications import VGG16

from tensorflow.keras.preprocessing import image

from tensorflow.keras.applications.vgg16 import preprocess_input, decode_predictions


import numpy as np

import matplotlib.pyplot as plt

```

**Explanation**:

- `tensorflow` and `VGG16` provide access to the pre-trained VGG16 model.

- `image` is used to load and preprocess input images.

- `preprocess_input` normalizes the image data, and `decode_predictions` converts


model outputs into readable labels.

- `numpy` handles array operations, and `matplotlib.pyplot` displays the image.

---

### Step 2: Load the Pre-Trained VGG16 Model

```python

model = VGG16(weights="imagenet")

```

**Explanation**:

- Loads the VGG16 model pre-trained on the ImageNet dataset, which includes 1,000
object categories (e.g., dogs, cats, cars).

- The pre-trained weights enable immediate classification without additional training.

---

### Step 3: Load and Display an Input Image

```python

img_path = "path_to_your_image.jpg" # Replace with your image file path

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

plt.imshow(img)

plt.axis("off")

plt.show()

```

**Explanation**:
- Loads an image from the specified path and resizes it to 224x224 pixels, the input
size required by VGG16.

- Displays the image using Matplotlib to visually confirm the input.

---

### Step 4: Convert Image into an Array and Preprocess

```python

img_array = image.img_to_array(img)

img_array = np.expand_dims(img_array, axis=0) # Add batch dimension

img_array = preprocess_input(img_array) # Normalize the image

```

**Explanation**:

- Converts the image into a numerical array for processing.

- Adds a batch dimension to match VGG16’s expected input shape: `(1, 224, 224, 3)`.

- Normalizes the image by subtracting mean RGB values, as required by VGG16.

---

### Step 5: Predict the Class of the Image

```python

predictions = model.predict(img_array)

decoded_preds = decode_predictions(predictions, top=3)[0]

for i, (imagenet_id, label, score) in enumerate(decoded_preds):

print(f"{i+1}. {label}: {score:.2f}")

```

**Explanation**:

- Uses the VGG16 model to predict the image’s class probabilities.

- Decodes the predictions into human-readable labels and confidence scores.

- Prints the top 3 predictions for easy interpretation.

---
### Example Output

If the input image is of a dog, the output might look like this:

```

1. Labrador retriever: 0.85

2. Golden retriever: 0.12

3. Beagle: 0.03

```

**Explanation**:

- The model identifies the image as a "Labrador retriever" with 85% confidence,
followed by less likely options like "Golden retriever" and "Beagle."

---

## Modifying VGG16 for Custom Classification

For specific tasks, VGG16 can be adapted for feature extraction and paired with
custom classification layers.

### Step 6: Load VGG16 Without the Top Classification Layer

```python

base_model = VGG16(weights="imagenet", include_top=False, input_shape=(224,


224, 3))

for layer in base_model.layers:

layer.trainable = False

```

**Explanation**:

- Loads VGG16 without its final classification layers (`include_top=False`).

- Freezes the pre-trained layers to preserve ImageNet-learned features and avoid


retraining them.

---

### Step 7: Add Custom Classification Layers


```python

from tensorflow.keras import models, layers

model = models.Sequential([

base_model,

layers.Flatten(),

layers.Dense(256, activation="relu"),

layers.Dropout(0.5),

layers.Dense(10, activation="softmax") # Adjust the number of classes as needed

])

```

**Explanation**:

- Flattens the VGG16 feature maps into a 1D vector.

- Adds a dense layer with 256 neurons and ReLU activation for custom feature
learning.

- Applies dropout (50%) to reduce overfitting.

- Adds an output layer with softmax activation for multi-class classification (e.g., 10
classes).

---

### Step 8: Compile the Model

```python

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

```

**Explanation**:

- Uses the Adam optimizer for efficient gradient descent.

- Applies `categorical_crossentropy` as the loss function for multi-class tasks.

- Tracks accuracy to evaluate performance.

---
### Step 9: Train the Model

```python

# Assuming train_generator and validation_generator are defined (e.g., via


ImageDataGenerator)

model.fit(train_generator, epochs=10, validation_data=validation_generator)

```

**Explanation**:

- Trains the model on a custom dataset using transfer learning.

- Leverages VGG16’s pre-trained features for faster and more effective training.

---

## Expected Outcome

- **Direct VGG16 Predictions**: Accurate classification of common objects (e.g.,


animals, vehicles) from the ImageNet dataset.

- **Fine-Tuned VGG16 Model**: High accuracy on custom datasets by adapting pre-


trained features to new classes.

---

## Conclusion

- VGG16 is a robust pre-trained CNN that excels at image classification out-of-the-box


using ImageNet weights.

- It can be directly applied for quick predictions or fine-tuned with custom layers for
specialized tasks.

- This experiment highlights the power of transfer learning, reducing training time and
improving performance on new datasets.

---

This solution provides everything you need to implement and understand VGG16 for
image classification. To test it, install TensorFlow and Matplotlib, replace
`"path_to_your_image.jpg"` with an actual image path, and run the code in a Python
environment.

You might also like