Deep Learning Tutorial 27: Transfer Learning with Tensorflow, Keras & Python

Posted by


In this tutorial, we will be discussing Transfer Learning in deep learning using TensorFlow, Keras, and Python. Transfer learning is a technique in machine learning where a model trained on one task is re-used as a starting point for a model on a different task. This is particularly useful when you have a small dataset for your target task, as it allows you to leverage the knowledge learned from a larger dataset on a related task.

Transfer Learning can drastically reduce the amount of time and data needed to train a model, as it allows you to take advantage of pre-trained models that have already been trained on massive datasets like ImageNet.

We will be using Keras, which is a high-level neural networks API that runs on top of TensorFlow, a popular deep learning framework developed by Google. We will also be using Python programming language for coding.

Here are the steps we will be following in this tutorial:

  1. Importing necessary libraries:

    • We will start by importing the necessary libraries like TensorFlow, Keras, and numpy.
  2. Loading and preprocessing the data:

    • Next, we will load the dataset that we will be working with. For this tutorial, we will be using the CIFAR-10 dataset, which contains 60,000 32×32 color images in 10 different classes.
    • We will preprocess the images by normalizing the pixel values and resizing the images to the required input shape of the pre-trained model.
  3. Creating the base model:

    • We will choose a pre-trained model as our base model. In this tutorial, we will be using the VGG16 model, which has been pre-trained on the ImageNet dataset.
    • We will load the model using the keras.applications module, freeze the layers of the pre-trained model, and add a few additional layers on top of it.
  4. Fine-tuning the model:

    • We will train the model on the CIFAR-10 dataset using transfer learning. We will unfreeze some of the layers in the pre-trained model and fine-tune them along with the additional layers that we added.
  5. Evaluating the model:
    • Finally, we will evaluate the performance of the model on the test dataset and visualize the results using confusion matrix and classification report.

Now, let’s get started with the code:

# Step 1: Importing necessary libraries
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import numpy as np

# Step 2: Loading and preprocessing the data
(x_train, y_train), (x_test, y_test) = keras.datasets.cifar10.load_data()
x_train = x_train.astype('float32') / 255
x_test = x_test.astype('float32') / 255

# Step 3: Creating the base model
base_model = keras.applications.VGG16(input_shape=(32, 32, 3), include_top=False, weights='imagenet')
base_model.trainable = False

model = keras.Sequential([
    base_model,
    layers.GlobalAveragePooling2D(),
    layers.Dense(128, activation='relu'),
    layers.Dense(10, activation='softmax')
])

# Step 4: Fine-tuning the model
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model.fit(x_train, y_train, epochs=10, batch_size=64, validation_data=(x_test, y_test))

# Step 5: Evaluating the model
model.evaluate(x_test, y_test)

In this code snippet, we first import the necessary libraries and load the CIFAR-10 dataset. We then create the base model using the VGG16 pre-trained model and add additional layers on top of it. We freeze the layers of the base model and train the model on the CIFAR-10 dataset. Finally, we evaluate the model on the test dataset.

Transfer learning is a powerful technique in deep learning that can help you build accurate and reliable models even with limited data. By leveraging pre-trained models and fine-tuning them on your dataset, you can achieve state-of-the-art results with minimal effort. Practice this tutorial and experiment with different pre-trained models and datasets to further enhance your understanding of transfer learning.

0 0 votes
Article Rating

Leave a Reply

20 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@codebasics
2 hours ago

Check out our premium machine learning course with 2 Industry projects: https://codebasics.io/courses/machine-learning-for-data-science-beginners-to-advanced

@zzzmd11
2 hours ago

Hi Thanks for the great explanation as always. Just wanted to know about model ensembling or stacking across different datasets. As in developing a one single model which is trained from 2 separate datasets which have their own separate set of features (which are not overlapping with each other). Is it possible and are there any examples which are already done? Can you please shed a light on this..Thank you so much in advance…

@yaswanthyalamuri8799
2 hours ago

Wow, such a great techique to train models. Thank you sir for making it easy for us

@PriyankaDarshanam
2 hours ago

For those who are getting this error

Only instances of keras.Layer can be added to a Sequential model. Received: <tensorflow_hub.keras_layer.KerasLayer object at 0x7de8fc820ee0> (of type <class 'tensorflow_hub.keras_layer.KerasLayer'>)

try this,

import tf_keras

and replace every 'tf.keras' with 'tf_keras'

@adamassrkfan
2 hours ago

24:00

@aliksmshaik-x8t
2 hours ago

Amazing explanation, very easy to understand

@karatugba
2 hours ago

What if I want to classify 1005 classes with freezing, what do I need to do?

@CertifiedAuthur
2 hours ago

this is the params that i have been getting from the model

Model: "sequential_1"

┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┓

┃ Layer (type) ┃ Output Shape ┃ Param # ┃

┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━┩

│ lambda_1 (Lambda) │ (None, 1280) │ 0 │

├─────────────────────────────────┼────────────────────────┼───────────────┤

│ dense (Dense) │ (None, 5) │ 6,405 │

└─────────────────────────────────┴────────────────────────┴───────────────┘

Total params: 6,405 (25.02 KB)

Trainable params: 6,405 (25.02 KB)

Non-trainable params: 0 (0.00 B)

@Piyush-yp2po
2 hours ago

Tensorflow hib is not compatible with latest tf versions

@mangaldasgaonkar568
2 hours ago

import tf_keras

IMAGE_SHAPE = (224, 224)
classifier = tf_keras.Sequential([
hub.KerasLayer(model_link, input_shape=IMAGE_SHAPE+(3,))
])

First install tf_keras by pip install tf_keras then,

import it by import tf_keras

And use it
classifier = tf_keras.Sequential([…])

For me it is working

Replace tf.keras to tf_keras everywhere

@wcottee
2 hours ago

So let me see if I understand…we froze all the weights/biases/filters for all the layers except the final one. So when we say we are "training" the model with our flower data set, we are only optimizing the weights and biases of the final layer (i.e. the input to the softmax function)?????

@uswakhan3050
2 hours ago

can anyone help me in resolving this error …. ValueError: Only instances of `keras.Layer` can be added to a Sequential model. Received: <tensorflow_hub.keras_layer.KerasLayer object at 0x000001EC1B571AD0> (of type <class 'tensorflow_hub.keras_layer.KerasLayer'>)

@shaiksameer6625
2 hours ago

while executing this part of code
————————————————————————————————————————————————————————————————————————
IMAGE_SHAPE = (224, 224)

classifier = tf.keras.Sequential([

hub.KerasLayer("https://tfhub.dev/google/tf2-preview/mobilenet_v2/classification/4&quot;, input_shape=IMAGE_SHAPE+(3,))

])
————————————————————————————————————————————————————————————————————————
I get this error. (I have installed tensorflow_hub too)
ValueError: Only instances of `keras.Layer` can be added to a Sequential model. Received: <tensorflow_hub.keras_layer.KerasLayer object at 0x000001F10F866AA0> (of type <class 'tensorflow_hub.keras_layer.KerasLayer'>)

Please solve this issue

@kunalll24
2 hours ago

Having error while using the pretrained model,
error : ValueError: Only instances of `keras.Layer` can be added to a Sequential model. Received: <tensorflow_hub.keras_layer.KerasLayer object at 0x00000121E029D890> (of type <class 'tensorflow_hub.keras_layer.KerasLayer'>)
please help.

@navneetkumar5517
2 hours ago

thank you so much bhaiya

@studentmitra5372
2 hours ago

Can you please analyse HAM10000 dataset. Because this dataset is highly imbalanced and it also contain meta data in csv file. So I am bit confused.

@Suriyabegum22PHD053
2 hours ago

sir, how to search TensorFlow hub training models give me the same as you have used.

@nastaran1010
2 hours ago

the model perfomance with useing 'feature vector' is increased. but when i tried to predict ([X[0],X[1], X[2]]), it perfomes so bad. why?

@nastaran1010
2 hours ago

what is the version od tensorflow, hub?

@sanooosai
2 hours ago

thank you sir

20
0
Would love your thoughts, please comment.x
()
x