What is transfer learning? (with tensorflow code implementation)


1、 The concept of transfer learning

What is transfer learning? Transfer learning can be represented by the following diagram:



The leftmost part of this graph shows the transfer learning, that is, the trained model and weight are directly incorporated into the new dataset for training, but we only change the classifier of the previous model (full connection layer and softmax / sigmoid), so that we can save the training time to a new training model!

But why is it possible to do so?

2、 Why can transfer learning be used?

Generally, in the problem of image classification, the front layer of the convolutional neural network is used to identify the most basic features of the image, such as the outline, color, texture, etc., while the latter layer is the key to extract the abstract features of the image. Therefore, the best way is that we only need to retain the weight of the bottom layer in the convolutional neural network, and train the top-level and new classifiers 。 So how do we use transfer learning in image classification? In general, the steps of using transfer learning, that is, pre training neural network, are as follows;

1. Freeze the convolution layer weight of the pre training network

2. Replace the old full connection layer with a new full connection layer and classifier

3. Thaw the convolution layer at the top of the part and keep the weight of the bottom convolution neural network

4. At the same time, the top layer of the convolution layer and the full connection layer are trained jointly to obtain the new network weight

Now that we know the basic characteristics of transfer learning, why not give it a try?

3、 Code implementation of transfer learning

We use the method of migration learning to classify and recognize the images of cats and dogs. The images of cats and cats are in my folder as shown in the following figure:



Then guide the package:

import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as plt
import numpy as np
import glob
import os

Get the path of the picture, label, and make batch data. The path of the picture is stored in the train folder under disk F, and the path is: F: / / university study / AI / dataset / CatDog / train /.

The code is as follows:

#Get all the labels of the picture
train_image_label=[int(p.split("\")[1]=='cat') for p in train_image_path ]

#Now our JPG file is decoded and becomes a three-dimensional matrix
def load_preprosess_image(path,label):
    #Read path
    image= tf.image.decode_ JPEG (image, channels = 3) ා color image has 3 channels
    #Change the image to the same size, using crop or twist, where twist is applied
    #Random cropping image
    #Flip images randomly up and down
    #Random flip up and down
    #Randomly change the brightness of the image
    #Change the contrast randomly
    #Change data type
    #The image was normalized
    #Now we need to process the label. Now we are the list [1,2,3],
    #Need to become [[1]. [2]. [3]]
    return image,label

AUTOTUNE= tf.data.experimental . autotune ා adjust the operation speed according to the performance of the computer
#Train now_ image_ DS will be read in, and now the order and batch size will be specified
#Now set batch and out of order
train_ image_ ds=train_ image_ ds.prefetch Preprocessing part of the process, ready to read

imags,labels=iter(train_ image_ Put the data in the next () separately

The cat image in the batch data is displayed


Build the network architecture, introduce the classical image classification model vgg16, and call the weight of vgg16 pre training network. Finally, the last three layers of the coiling layer are adjusted to be trainable, that is, the convolution neural network at the top level can be combined with the full link classifier.

#If weights is set to Imagenet, it means the weight trained by imagebnet. If you fill in false, it means no weight is used
#Network architecture only, include_ Top indicates whether to use the full connectivity layer for classification
#We can add full connection layer and output layer to the convolution layer

conv_ base.trainable=True# There are 19 floors
for layer in conv_base.layers[:-3]:
#From the first layer to the last third layer, it is not trainable. Now the top layer of convolution has been thawed and joint training is started

#Compile this network


The results of training only one epoch are as follows;

Train for 62 steps
62/62 [==============================] - 469s 8s/step - loss: 0.6323 - acc: 0.6159

The accuracy of one iteration has reached 60%. How about it? Do you have a certain feeling about transfer learning now?