2.2修改预训练网络的图层
用fullyConnectedLayer函数创建一个新的全连接层,具有给定数量的神经元:
fclayer = fullyConnectedLayer(n);
如创建一个带有12个神经元的(代表12种花)新的全连接层 fc:
fc = fullyConnectedLayer(12);
可以使用标准数组索引来修改图层数组的各个元素:
mylayers(n) = mynewlayer;
通过layers(数组),将刚创建的全连接层 fc替换到最后的全连接层(第23层):
layers(23) = fc;
您可以使用该classificationLayer功能为图像分类网络创建新的输出图层:
cl = classificationLayer ;
您可以使用单个命令创建新图层并使用新图层覆盖现有图层:
mylayers (n)= classificationLayer ;
改变layers(通过数组下标)的输出层为用classificationLayer新创建的输出层:
layers(25) = classificationLayer;
您可以为训练算法设置哪些选项?您可以使用该trainingOptions功能查看可用选项。
opts = trainingOptions ('sgdm' ) ;
这将创建一个变量opts,其中包含训练算法的默认选项“带动量的随机梯度下降”。
您可以在trainingOptions函数中指定任意数量的设置作为可选的名称 - 值对。
opts = trainingOptions ('sgdm' ,' name ' ,value);
将初始学习速率(InitialLearnRate)设置为0.001 :
opts = trainingoptions('sgdm' , 'InitialLearnRate' , 0.001);
What is a "mini-batch"?
At each iteration, a subset of the training images, known as a mini-batch, is used to update the weights. Each iteration uses a different mini-batch. Once the whole training set has been used, that's known as an epoch.
The maximum number of epochs (MaxEpochs) and the size of the mini-batches (MiniBatchSize) are parameters you can set in the training algorithm options.
Note that the loss and accuracy reported during training are for the mini-batch being used in the current iteration.
By default, the images are shuffled once prior to being divided into mini-batches. You can control this behavior with the Shuffle option.
2.3评估绩效
变量info是包含培训信息的结构。字段TrainingLoss和TrainingAccuracy包含在每次迭代训练数据网络的性能的记录。
使用plot可以绘制训练损失:
plot(info.TrianingLoss);
网络在训练数据上似乎表现良好,但真正的测试是它在测试数据上表现如何。flowernet是训练好的网络,testImgs是测试集,使用 classify来进行预测:
flwrPreds = classify(flowernet , testImgs);
通过属性Labels来提取测试集的标签:
flwrActual = testImgs.Labels;
使用nnz函数和“==”来查看预测标签和实际标签匹配度:
numCorrect = nnz(flwPreds == flwrActual);
为计算预测正确的百分比,可以使用numel函数确定flwrPreds的元素数量:
fracCorrect = numCorrect/numel(flwrPreds);
confusionmat函数是计算预测分类的混淆矩阵:
cmat = confusionmat(knownclass,predictedclass);
混淆矩阵的(j,k)元素cmat是网络预测在类k中来自类j的图像的数量。因此,对角元素代表正确的分类; 非对角元素代表错误分类。
要解释混淆矩阵,有助于获得类标签列表。您可以从中获取标签作为第二个输confusionmat。计算flwrconf花朵测试数据的混淆矩阵,并获取关联的类别标签。将标签存储在一个名为的变量中flwrnames:
[flwrconf , flwrnames] = confusionmat(testImgs.Labels , flwrPreds);
通过可视化来理解混淆矩阵通常更容易理解。您可以使用该heatmap功能将混淆矩阵可视化为“heatmap”。
heatmap(xlabels, ylabels, matrix);
对于混淆矩阵,x和y标签是相同的(类名称)。
将混淆矩阵flwrconf可视化,使用类标签flwrnames来标记轴:
heatmap (flwrnames , flwrnames , flwrconf);
迁移学习总结