Main Content

Transfer Learning Using AlexNet

此示例显示了如何微调验证的Alexnet卷积神经网络,以在新图像集合中执行分类。

AlexNet has been trained on over a million images and can classify images into 1000 object categories (such as keyboard, coffee mug, pencil, and many animals). The network has learned rich feature representations for a wide range of images. The network takes an image as input and outputs a label for the object in the image together with the probabilities for each of the object categories.

Transfer learning is commonly used in deep learning applications. You can take a pretrained network and use it as a starting point to learn a new task. Fine-tuning a network with transfer learning is usually much faster and easier than training a network with randomly initialized weights from scratch. You can quickly transfer learned features to a new task using a smaller number of training images.

Load Data

解压缩并加载新图像作为图像数据存储。imageDatastoreautomatically labels the images based on folder names and stores the data as anImageDatastoreobject. An image datastore enables you to store large image data, including data that does not fit in memory, and efficiently read batches of images during training of a convolutional neural network.

unzip('MerchData.zip'); imds = imageDatastore('MerchData',...'IncludeSubfolders',true,...'LabelSource','foldernames');

将数据分为培训和验证数据集。使用70%的图像进行培训,30%用于验证。splitEachLabelsplits theimagesdatastore into two new datastores.

[imdsTrain,imdsValidation] = splitEachLabel(imds,0.7,'randomized');

This very small data set now contains 55 training images and 20 validation images. Display some sample images.

numTrainImages = numel(imdsTrain.Labels); idx = randperm(numTrainImages,16); figurefori = 1:16 subplot(4,4,i) I = readimage(imdsTrain,idx(i)); imshow(I)end

Load Pretrained Network

Load the pretrained AlexNet neural network. If Deep Learning Toolbox™ Modelfor AlexNet Networkis not installed, then the software provides a download link. AlexNet is trained on more than one million images and can classify images into 1000 object categories, such as keyboard, mouse, pencil, and many animals. As a result, the model has learned rich feature representations for a wide range of images.

net = alexnet;

UseanalyzeNetworkto display an interactive visualization of the network architecture and detailed information about the network layers.

analyzeNetwork(net)

The first layer, the image input layer, requires input images of size 227-by-227-by-3, where 3 is the number of color channels.

inputSize = net.Layers(1).InputSize
inputSize =1×3227 227 3

Replace Final Layers

The last three layers of the pretrained networknet为1000类配置。对于新的分类问题,这三层必须进行微调。从验证的网络中提取除最后三个层以外的所有层。

layersTransfer = net.Layers(1:end-3);

Transfer the layers to the new classification task by replacing the last three layers with a fully connected layer, a softmax layer, and a classification output layer. Specify the options of the new fully connected layer according to the new data. Set the fully connected layer to have the same size as the number of classes in the new data. To learn faster in the new layers than in the transferred layers, increase theWeightLearnRateFactorandBiasLearnRateFactorvalues of the fully connected layer.

numClasses = numel(categories(imdsTrain.Labels))
numClasses = 5
layers = [ layersTransfer fullyConnectedLayer(numClasses,'WeightLearnRateFactor',20,'BiasLearnRateFactor',20) softmaxLayer classificationLayer];

Train Network

The network requires input images of size 227-by-227-by-3, but the images in the image datastores have different sizes. Use an augmented image datastore to automatically resize the training images. Specify additional augmentation operations to perform on the training images: randomly flip the training images along the vertical axis, and randomly translate them up to 30 pixels horizontally and vertically. Data augmentation helps prevent the network from overfitting and memorizing the exact details of the training images.

pixelRange = [-30 30]; imageAugmenter = imageDataAugmenter(...'RandXReflection',true,...'RandXTranslation',pixelRange,...'RandYTranslation', pixelRange);augimdsTrain = augmentedImageDatastore(inputSize(1:2),imdsTrain,...'DataAugmentation',imageAugmenter);

To automatically resize the validation images without performing further data augmentation, use an augmented image datastore without specifying any additional preprocessing operations.

augimdsValidation = augmentedImageDatastore(inputSize(1:2),imdsValidation);

Specify the training options. For transfer learning, keep the features from the early layers of the pretrained network (the transferred layer weights). To slow down learning in the transferred layers, set the initial learning rate to a small value. In the previous step, you increased the learning rate factors for the fully connected layer to speed up learning in the new final layers. This combination of learning rate settings results in fast learning only in the new layers and slower learning in the other layers. When performing transfer learning, you do not need to train for as many epochs. An epoch is a full training cycle on the entire training data set. Specify the mini-batch size and validation data. The software validates the network everyValidationFrequencyiterations during training.

options = trainingOptions('sgdm',...'MiniBatchSize',10,...“MaxEpochs”,6,...'InitialLearnRate',1e-4,...'Shuffle','every-epoch',...'ValidationData',augimdsValidation,...'ValidationFrequency',3,...'Verbose',false,...“阴谋”,'training-progress');

Train the network that consists of the transferred and new layers. By default,trainNetworkuses a GPU if one is available, otherwise, it uses a CPU. Training on a GPU requires Parallel Computing Toolbox™ and a supported GPU device. For information on supported devices, seeGPU Support by Release(Parallel Computing Toolbox). You can also specify the execution environment by using the'ExecutionEnvironment'name-value pair argument oftrainingOptions.

netTransfer = trainNetwork(augimdsTrain,layers,options);

Classify Validation Images

Classify the validation images using the fine-tuned network.

[YPred,scores] = classify(netTransfer,augimdsValidation);

Display four sample validation images with their predicted labels.

idx = randperm(numel(imdsValidation.Files),4); figurefori = 1:4 subplot(2,2,i) I = readimage(imdsValidation,idx(i)); imshow(I) label = YPred(idx(i)); title(string(label));end

Calculate the classification accuracy on the validation set. Accuracy is the fraction of labels that the network predicts correctly.

YValidation = imdsValidation.Labels; accuracy = mean(YPred == YValidation)
accuracy = 1

For tips on improving classification accuracy, seeDeep Learning Tips and Tricks.

References

[1] Krizhevsky, Alex, Ilya Sutskever, and Geoffrey E. Hinton. "ImageNet Classification with Deep Convolutional Neural Networks."Advances in neural information processing systems. 2012.

[2]BVLC AlexNet Model. https://github.com/BVLC/caffe/tree/master/models/bvlc_alexnet

See Also

|||

Related Topics