Unzip and load the new images as an image datastore. Divide the data into training and validation data sets. Use 70% of the images for training and 30% for validation.
Load the pretrained AlexNet network. If Neural Network Toolbox™ Model for AlexNet Network is 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.
net = alexnet;
复制代码
To retrain AlexNet to classify new images, replace the last three layers of the network. Set the final fully connected layer to have the same size as the number of classes in the new data set (5, in this example). To learn faster in the new layers than in the transferred layers, increase the learning rate factors of the fully connected layer.
#Divide the data into training and validation data sets. Use 70% of the images for training and 30% for validation. splitEachLabel splits the images datastore into two new datastores.
#Display the network architecture. The network has five convolutional layers and three fully connected layers.
net.Layers
复制代码
#Transfer Layers to New Network. The last three layers of the pretrained network net are configured for 1000 classes. These three layers must be fine-tuned for the new classification problem. Extract all layers, except the last three, from the pretrained network.
#To retrain GoogLeNet to classify new images, replace the last three layers of the network. These three layers of the network, with the #names 'loss3-classifier', 'prob', and 'output', contain the information of how to combine the features that the network extracts into class #probabilities and labels. Add three new layers, a fully connected layer, a softmax layer, and a classification output layer, to the layer #graph. Set the final fully connected layer to have the same size as the number of classes in the new data set (5, in this example). To #learn faster in the new layers than in the transferred layers, increase the learning rate factors of the fully connected layer.
#Connect the last of the transferred layers remaining in the network ('pool5-drop_7x7_s1') to the new layers. To check that the new layers #are correctly connected, plot the new layer graph and zoom in on the last layers of the network.
#Extract the class labels from the training and test data.
trainingLabels = trainingImages.Labels;
testLabels = testImages.Labels;
复制代码
#Use the features extracted from the training images as predictor variables and fit a multiclass support vector machine (SVM) using #fitcecoc (Statistics and Machine Learning Toolbox).