View image files
Task 1
Import an image
img1 = imread('file01.jpg')
Task 2
View image
imshow(img1)
Classify images
Task 1
Load pretrained network
deepnet = alexnet
file01.jpg.
img1 = imread('file01.jpg');
imshow(img1)
Task 2
Classify an image
pred1 = classify(deepnet,img1)
Examine Network Layers
This code imports AlexNet.
deepnet = alexnet;
Task 1
变量deepnet表示一个深卷积网络。您可以通过使用变量引用变量的layers属性来检查网络的各个层。属性索引:
Save layers
ly = deepnet.Layers
Task 2
变量ly是网络层的数组。你可以检查一个单独的层索引到ly与常规MATLAB数组索引:
Extract first layer
inlayer = ly(1)
Task 3
网络的每一层都具有与该类型的层相关的属性。输入层的一个重要属性是InputSize,它是网络期望作为输入的图像的大小(维度)。
Extract input size
insz = inlayer.InputSize
Task 4
Extract last layer
outlayer = ly(end)
Task 5
输出层的Classes属性给出网络训练用来预测的类别的名称。
Extract class names
categorynames = outlayer.Classes
Investigate Predictions
This code loads in an image and imports AlexNet.
img = imread('file01.jpg');
imshow(img)
net = alexnet;
categorynames = net.Layers(end).ClassNames;
Task 1
该classify函数给出了网络分配最高分的类。您可以通过请求第二个输出来获得所有类的预测分数classify。
使用classify预训练的AlexNet网络功能net来预测存储在变量中的图像的主题img。将网络的预测存储在一个被调用的变量中,pred并将所有预测分数存储在一个名为的变量中scores。
Classify an image
[pred,scores] = classify(net,img)
Task 2
您可以使用预测分数向量来研究网络的分类。
创建预测分数的条形图。
请注意,此条形图将难以阅读,因为有1000个预测分数。您将在完成此任务后创建一个聚焦条形图。
Display scores
bar(scores)
Task 3
创建逻辑阵列highscores,其具有值1( true)无论scores是大于0.01。
Threshold scores
highscores = scores > 0.01
Task 4
使用逻辑索引创建高于阈值的预测值的条形图0.01
Display thresholded scores
bar(scores(highscores))
Task 5
使用逻辑索引和xticklabels函数使用适当的预测类名标记条形图。完整的类名列表存储在变量中categorynames。
Add tick labels
xticklabels(categorynames(highscores))
Create a Datastore
This code displays the images in the current folder and imports AlexNet.
ls *.jpg
net = alexnet;
Task 1
您可以使用该imageDatastore函数在MATLAB中创建数据存储区,指定文件夹或文件名作为输入。您可以使用通配符等*指定多个文件。
ds = imageDatastore ('foo * .png' )
这将为当前文件夹中名称以foo。开头的所有PNG文件创建数据存储。
创建一个名为的数据存储区imds,该数据存储区引用名为file01.jpgthrough 的当前文件夹中的图像文件file12.jpg。(请注意,这些是此文件夹中唯一具有表单名称的图像文件。)filenn.jpg
Create datastore
imds = imageDatastore('file*.jpg')
Task 2
数据存储的属性包含有关数据文件的元信息
使用Files数据存储区的属性imds提取图像的文件名。将结果存储在一个名为的变量中fname
Extract file names
fname = imds.Files
Task 3
您可以手动从数据存储使用导入数据read,readimage以及readall功能- read进口图像一次一个,以便; readimage导入单个特定图像; readall将所有图像导入单个单元格阵列(每个图像位于单独的单元格中)。
I = readimage (ds ,n)
这会将数据存储区的第n 个映像ds导入到一个名为的数组中I。
使用此readimage功能导入图像file07.jpg(数据存储区中的第 7 个文件)。将导入的图像存储在名为的变量中img。
Read an image
img = readimage(imds,7);
Task 4
您可以使用图像数据存储区代替CNN功能中的单个图像,例如classify。
preds = classify (net ,ds )
结果将是一组预测类,一个用于数据存储区中的每个图像。
使用AlexNet(作为变量加载net)对数据集中所有图像的内容进行分类。将结果存储在一个名为的变量中preds。
请注意,该classify功能将通过AlexNet运行12张图像。执行可能需要几秒钟。
Classify images
preds = classify(net,imds)
Process Images for Classification
This code imports and displays the image from the file
img = imread('file01.jpg');
imshow(img)
Task 1
使用此size功能可以查看图像的大小img。将结果保存到变量sz。
View image size
sz = size(img)
Task 2
网络的输入层指定网络所需的图像大小。
expectedSize = inputlayer .InputSize
导入AlexNet。提取InputSize网络第一层的属性。将结果存储在一个名为的变量中insz。
Load network and view input size
net = alexnet;
inlayer = net.Layers(1)
insz = inlayer.InputSize
Task 3
您可以使用此 imresize 功能调整图像大小以匹配预期的输入大小。
imgresz = imresize (img ,[ numrows numcols ]);
这个大小调整 img 为 numrows-by- numcols。也就是说, imgresz 具有numcols 像素宽度和 像素高度 numrows 。
使用此 imresize 功能可将存储在变量中的图像的大小调整 img 为227 x 227。将结果存储回变量中 img。
然后显示调整大小的图像 imshow。
Resize image and display
img = imresize(img,[227 227]);
imshow(img)
Resize Images in a Datastore
This code displays the images in the current folder and imports AlexNet.
ls *.jpg
net = alexnet
Task 1
回想一下,您可以使用该 imageDatastore 功能来创建数据存储区。您可以使用通配符等 * 指定多个文件。
ds = imageDatastore('*.jpg')
创建一个名为的图像数据存储区 imds ,引用当前文件夹中具有扩展名的图像文件。.jpg
Create datastore
imds = imageDatastore('*.jpg')
Task 2
增强图像数据存储可以对整个集合图像执行简单的预处理。要创建此数据存储,请使用augmentedImageDatastore网络图像输入大小作为输入的功能。
auds = augmentedImageDatastore([],ds)
从中创建增强图像数据存储区 imds,将图像大小调整为227 x 227。命名新数据存储区auds
Create augmentedImageDatastore
auds = augmentedImageDatastore([227,227],imds)
Task 3
您可以使用增强图像数据存储区作为classify函数的输入 。在对每个图像进行分类之前,将使用您在创建数据存储区时指定的方法对其进行预处理。
使用存储在变量中的网络auds使用 classify函数对图像进行分类 net。将预测存储在变量中 preds。
Classify datastore
preds = classify(net,auds)
Preprocess Color Using a Datastore
This code displays the images in the current folder and imports AlexNet.
ls *.jpg
net = alexnet
This code creates an image datastore of these images.
imds = imageDatastore('file*.jpg')
Task 1
您将在此交互中使用的图像是灰度图像。您可以使用该montage功能显示所有图像。
使用此功能 montage可在数据存储中显示图像 imds。
Display images in imds
montage(imds)
Task 2
通过ColorPreprocessing在创建扩充图像数据存储区时设置选项,可以将这些图像转换为3-D阵列。
auds = augmentedImageDatastore([ n m ],imds,‘ColorPreprocessing’,‘gray2rgb’)
这将复制灰度图像三次以创建三维阵列。如果 imgray 是表示灰度图像的矩阵,则处理后的图像将是表示颜色(RGB)图像的3-D阵列。
从映像数据存储区创建扩充映像数据存储区 imds。预处理图像为227×227×3。
命名扩充图像数据存储auds。
Create augmentedImageDatastore
auds = augmentedImageDatastore([227,227],imds,'colorpreprocessing','gray2rgb')
Task 3
使用分类功能对auds中的图像进行分类。 AlexNet存储在变量net中。将预测存储在变量preds中。
Classify datastore
preds = classify(net,auds)
Create a Datastore Using Subfolders
This code imports AlexNet
net = alexnet;
Task 1
默认情况下,imageDatastore在给定文件夹中查找图像文件。您可以使用“IncludeSubfolders”选项在给定文件夹的子文件夹中查找图像。
ds = imageDatastore('folder','IncludeSubfolders',true)
为Flowers文件夹的子文件夹中的所有图像创建数据存储区flwrds。
Create datastore
flwrds = imageDatastore('Flowers','IncludeSubfolders',true)
Task 2
使用AlexNet(作为变量网加载)对数据集中所有图像的内容进行分类。将结果存储在名为preds的变量中。
请注意,分类功能将通过AlexNet运行15个图像。执行可能需要几秒钟。
Classify images
preds = classify(net,flwrds)
Label Images in a Datastore
This code creates a datastore of 960 flower images.
load pathToImages
flwrds = imageDatastore(pathToImages,'IncludeSubfolders',true);
flowernames = flwrds.Labels
Task 1
训练所需的标签可以存储在图像数据存储区的Labels属性中。默认情况下,Labels属性为空。
您可以通过指定“LabelSource”选项让数据存储区自动确定文件夹名称中的标签。
ds = imageDatastore(folder,...
'IncludeSubfolders',true,...
'LabelSource','foldernames')
将数据存储区flwrds重新创建到存储在变量pathToImages中的文件夹路径的子文件夹中的所有图像,这次使用文件夹名称作为图像标签。 pathToImages已存在于工作区中。
Create datastore with labels使用标签创建数据存储
flwrds = imageDatastore(pathToImages,'IncludeSubfolders',true,'LabelSource','foldernames')
Task 2
将flwrds的Labels属性提取到名为flowernames的变量中。
Extract new labels提取新标签
flowernames = flwrds.Labels
Split Data for Training and Testing
This code creates a datastore of 960 flower images.
load pathToImages
flwrds = imageDatastore(pathToImages,'IncludeSubfolders',true,'LabelSource','foldernames')
Task 1
您可以使用splitEachLabel函数将数据存储区中的图像划分为两个单独的数据存储区
[ds1,ds2] = splitEachLabel(imds,p)
比例p(从0到1的值)表示每个标签的图像与ds1中应包含的imds的比例。其余文件分配给ds2。
Split the datastore flwrds into two datastores flwrTrain and flwrTest, such that 60% of the files in each category are in flwrTrain.
中文(简体)
将数据存储区flwrds拆分为两个数据存储区flwrTrain和flwrTest,这样每个类别中60%的文件都在flwrTrain中。
Split datastore
[flwrTrain,flwrTest] = splitEachLabel(flwrds,0.6)
Task 2
默认情况下,splitEachLabel会按顺序保留文件。您可以通过添加可选的“随机化”标志随机随机播放文件。
[ds1,ds2] = splitEachLabel(imds,p,'randomized')
将数据存储区flwrds拆分为两个数据存储区flwrTrain和flwrTest,以便随机选择每个类别中80%的文件位于flwrTrain中。
Split datastore randomly
[flwrTrain,flwrTest] = splitEachLabel(flwrds,0.8,'randomized')
Task 3
当p是0到1之间的值时,它被解释为一个比例。然后分割图像,以便按比例分割每个标签。您还可以指定要从每个标签中获取的确切数量的文件以分配给ds1。
[ds1,ds2] = splitEachLabel(imds,n)
这可确保ds1中的每个标签都有n个图像,即使这些类别并非都包含相同数量的图像。
将数据存储区flwrds拆分为两个数据存储区flwrTrain和flwrTest,这样每个类别中的50个文件都在flwrTrain中。
Split datastore by number of images
[flwrTrain,flwrTest] = splitEachLabel(flwrds,50)
您还可以使用“验证”集来监控培训期间网络的性能。在这种情况下,您可以将数据拆分为三组一个用于培训,一个用于培训期间的验证,一个用于单独测试最终结果。尝试使用splitEachLabel将Flowers图像分成多个集合将p或n的多个值作为输入,并要求将适当数量的数据存储作为输出。
Modify Network Layers
This code imports AlexNet and extracts its layers.
anet = alexnet;
layers = anet.Layers
Task 1
fullyConnectedLayer函数创建一个新的完全连接的层,具有给定数量的神经元。
fclayer = fullyConnectedLayer(n)
创建一个名为fc的新的完全连接层,包含12个神经元(适用于12种类型的花)。
Create new layer
fc = fullyConnectedLayer(12)
Task 2
您可以使用标准数组索引来修改图层数组的各个元素。
mylayers(n) = mynewlayer
将阵列图层表示的网络的最后一个完全连接的图层(第23层)替换为刚刚创建的新图层fc
Replace 23rd layer
layers(23) = fc
Task 3
您可以使用classificationLayer函数为图像分类网络创建新的输出图层。
cl = classificationLayer
您可以在单个命令中创建新图层并使用新图层覆盖现有图层:
mylayers(n) = classificationLayer
用新的分类层替换由数组层表示的网络的最终(输出)层
Replace last layer
layers(end) = classificationLayer
Set Training Options
Task 1
您可以设置哪些选项来控制网络培训?您可以使用trainingOptions函数查看所选训练算法的可用选项。
opts = trainingOptions('sgdm')
这将创建一个变量opts,其中包含训练算法“带动量的随机梯度下降”的默认选项。
使用SGDM优化器的默认训练算法选项创建一个名为opts的变量。在行尾不要使用分号来显示结果。
Set default options
opts = trainingOptions('sgdm')
Task 2
您可以在trainingOptions函数中将任意数量的设置指定为可选的名称 - 值对。
opts = trainingOptions('sgdm','Name',value)
使用SGDM优化器的默认训练算法选项创建名为opts的变量,但InitialLearnRate选项除外,该选项应设置为0.001。
Set initial learning rate
opts = trainingOptions('sgdm','InitialLearnRate',0.001)
您创建了一个包含默认训练算法设置的变量,初始学习率除外,该值设置为0.001而不是0.01。
有其他训练算法可用。尝试为Adam优化器创建培训选项。
%得到训练图像
flower_ds = imageDatastore('Flowers','IncludeSubfolders',true,'LabelSource','foldernames');
[trainImgs,testImgs] = splitEachLabel(flower_ds,0.6);
numClasses = numel(categories(flower_ds.Labels));
%通过修改AlexNet创建网络
net = alexnet;
layers = net.Layers;
layers(end-2) = fullyConnectedLayer(numClasses);
layers(end) = classificationLayer;
%设置训练算法选项
options = trainingOptions('sgdm','InitialLearnRate', 0.001);
%执行培训
[flowernet,info] = trainNetwork(trainImgs, layers, options);
%使用训练好的网络对测试图像进行分类
[flowernet,info] = trainNetwork(trainImgs, layers, options);
Evaluate Performance
This code loads the training information of flowernet.
load pathToImages
load trainedFlowerNetwork flowernet info
Task 1
变量信息是包含有关培训信息的结构。 TrainingLoss和TrainingAccuracy字段包含每次迭代时网络在训练数据上的性能记录。
绘制训练损失,存储在TrainingLoss信息字段中。
Plot training loss
plot(info.TrainingLoss)
This code creates a datastore of the flower images.
dsflowers = imageDatastore(pathToImages,'IncludeSubfolders',true,'LabelSource','foldernames');
[trainImgs,testImgs] = splitEachLabel(dsflowers,0.98);
Task 2
使用classify函数获取数据存储区testImgs中图像的分类flowernet预测。将结果存储在名为flwrPreds的变量中。
请注意,分类功能将通过flowernet运行24个图像。执行可能需要几秒钟。
Classify images
flwrPreds = classify(flowernet,testImgs)
Investigate test performance
This code sets up the Workspace for this activity.
load pathToImages.mat
pathToImages
flwrds = imageDatastore(pathToImages,‘IncludeSubfolders’,true,‘LabelSource’,‘foldernames’);
[trainImgs,testImgs] = splitEachLabel(flwrds,0.98);
load trainedFlowerNetwork flwrPreds
Task 1
您可以通过将预测分类与已知分类进行比较来确定网络正确分类的测试图像的数量。已知的分类存储在数据存储区的Labels属性中。
通过提取testImgs数据存储区的Labels属性,将已知的测试图像分类存储在名为flwrActual的变量中。
Extract labels
flwrActual = testImgs.Labels
Task 2
您可以使用逻辑比较和nnz函数来确定匹配的两个数组的元素数:
numequal = nnz(a == b)
使用nnz函数和等于运算符(==)来计算有多少预测分类(flwrPreds)与正确的分类(flwrActual)匹配。将结果存储在名为numCorrect的变量中。
Count correct
numCorrect = nnz(flwrPreds == flwrActual)
Task 3
通过将numCorrect除以测试图像的数量来计算正确分类的测试图像的分数。将结果存储在名为fracCorrect的变量中。
Calculate fraction correct
fracCorrect = numCorrect/numel(flwrPreds)
Task 4
混淆图函数计算并显示预测分类的混淆矩阵。 confusionchart(knownclass,predictedclass)
混淆矩阵的(j,k)元素是网络预测在类k中来自类j的多少图像的计数。因此,对角线元素代表正确的分类;非对角线元素表示错误分类。
显示花卉测试数据的混淆矩阵。预测的分类存储在分类数组flwrPreds中。已知的分类存储在数据存储区testImgs的Labels属性中。
Display confusion matrix
confusionchart(testImgs.Labels,flwrPreds)
您已经确定了flowernet网络对测试数据的准确率为92%(22/24)。你可以看到这两个错误的分类都被预测为风信子,而实际上它们是番红花和鸢尾。您可以使用标准MATLAB数据分析技术进一步研究这些错误分类的图像。一种典型的方法是查找哪些文件包含错误分类的图像,然后导入并查看这些图像(或其中的一个子集),以查看是否有任何特征导致网络出现问题。
注意,这个示例使用的训练图像与测试图像的比例比您在实际中通常使用的要高得多。这样做是为了减少在这些交互中对测试图像进行分类所需的时间。如果可能的话,在实践中您应该保留足够的测试图像,这样测试结果就可以作为一般使用的网络行为的代表。
Transfer Learning Function Summary
创建一个网络
Function Description
alexnet Load pretrained network “AlexNet”
supported networks View list of available pretrained networks
fullyConnectedLayer Create new fully connected network layer
classificationLayer Create new output layer for a classification network
得到训练图像
Function Description
imageDatastore Create datastore reference to image files
augmentedImageDatastore Preprocess a collection of image files
splitEachLabel Divide datastore into multiple datastores
设置训练算法选项
Function Description
trainingOptions Create variable containing training algorithm options
执行培训
Function Description
trainNetwork Perform training
使用训练过的网络进行分类
Function Description
classify Obtain trained network’s classifications of input images
评估培训网络
Function Description
nnz Count non-zero elements in an array
confusionchart Calculate confusion matrix
heatmap Visualize confusion matrix as a heatmap
本教程介绍了如何使用Matlab进行深度学习,包括查看图像文件、分类图像、检查网络层、调查预测、创建和处理图像数据存储。通过任务化的步骤,学习如何使用AlexNet对图像进行预处理和分类,并评估网络性能。

372

被折叠的 条评论
为什么被折叠?



