6. Object detection using Transfer Learning of CNN architectures

6. Object detection using Transfer Learning of CNN architectures

a. Load in a pre-trained CNN model trained on a large dataset 

b. Freeze parameters (weights) in model’s lower convolutional layers 

c. Add custom classifier with several layers of trainable parameters to model 

d. Train classifier layers on training data available for task e. Fine-tune hyper parameters and unfreeze more layers as needed

Download Writeup Here

import tensorflow as tf
from tensorflow.keras.datasets import cifar10
from tensorflow.keras.applications import VGG16
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Flatten, Dense
from tensorflow.keras.utils import to_categorical

# Load CIFAR-10 dataset
(itrain, ltrain), (itest, ltest) = cifar10.load_data()

# Preprocess the data
itrain = itrain / 255.0
itest = itest / 255.0
ltrain = to_categorical(ltrain)
ltest = to_categorical(ltest)

# Load pre-trained VGG16 model (excluding the top fully-connected layers)
basem = VGG16(weights='imagenet', include_top=False, input_shape=(32, 32, 3))

# Freeze the pre-trained layers
for layer in basem.layers:
   layer.trainable = False

# Create a new model on top
semodel = Sequential()
semodel.add(basem)
semodel.add(Flatten())
semodel.add(Dense(256, activation='relu'))
semodel.add(Dense(10, activation='softmax'))  # CIFAR-10 has 10 classes

# Compile the model
semodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

# Train the model
semodel.fit(itrain, ltrain, epochs=10, batch_size=32, validation_data=(itest, ltest))

# Evaluate the model on test data
ltest, atest = semodel.evaluate(itest, ltest)
print("Test accuracy:", atest)



In the above example, we first loaded the CIFAR-10 dataset and preprocessed the data by normalizing the pixel values and one-hot encoding the labels. Then, we load the pre-trained VGG16 model and freeze its layers. We have created a new model on top, consisting of the base model, a flatten layer, a dense layer with ReLU activation, and a dense layer with softmax activation for classification.

Applications

Transfer learning with Convolutional Neural Networks (CNNs) has numerous applications across various computer vision tasks. It has been successfully applied in image classification, where pre-trained models can be fine-tuned for specific classes or domains. Transfer learning is also beneficial in object detection, where pre-trained CNNs can be utilized as feature extractors to identify objects in images.

Comments

Popular posts from this blog

2. Implementing Feedforward neural networks with Keras and TensorFlow