主要内容

本页翻译不是最新的。点击此处可查看最新英文版本。

imagePretrainedNetwork

适用于图像的预训练神经网络

自 R2024a 起

    说明

    imagePretrainedNetwork 函数加载预训练的神经网络,并可以选择调整神经网络架构以进行迁移学习和微调。

    [net,classNames] = imagePretrainedNetwork 返回预训练的 SqueezeNet 神经网络和网络类名称。此网络是基于 ImageNet 数据集针对 1000 个类训练的。

    示例

    [net,classNames] = imagePretrainedNetwork(name) 返回指定的预训练神经网络及其类名称。

    除使用上述语法中输入参量的任意组合外,[net,classNames] = imagePretrainedNetwork(___,Name=Value) 还使用一个或多个名称-值参量来指定选项。例如,Weights="none" 指定返回未初始化的神经网络,不带预训练的权重。

    示例

    全部折叠

    将预训练的 SqueezeNet 神经网络和网络类名称加载到工作区中。

    [net,classNames] = imagePretrainedNetwork;

    查看网络属性。

    net
    net = 
      dlnetwork with properties:
    
             Layers: [68×1 nnet.cnn.layer.Layer]
        Connections: [75×2 table]
         Learnables: [52×3 table]
              State: [0×3 table]
         InputNames: {'data'}
        OutputNames: {'prob_flatten'}
        Initialized: 1
    
      View summary with summary.
    
    

    查看前几个类名称。

    head(classNames)
        "tench"
        "goldfish"
        "great white shark"
        "tiger shark"
        "hammerhead"
        "electric ray"
        "stingray"
        "cock"
    

    将预训练的 SqueezeNet 神经网络加载到工作区中。

    [net,classNames] = imagePretrainedNetwork;

    从 PNG 文件中读取图像并对其进行分类。要对图像进行分类,请先将其数据类型转换为 single

    im = imread("peppers.png");
    figure
    imshow(im)

    Figure contains an axes object. The hidden axes object contains an object of type image.

    X = single(im);
    scores = predict(net,X);
    [label,score] = scores2label(scores,classNames);

    显示具有预测标签和对应分数的图像。

    figure
    imshow(im)
    title(string(label) + " (Score: " + score + ")")

    Figure contains an axes object. The hidden axes object with title bell pepper (Score: 0.89394) contains an object of type image.

    通过调整神经网络以匹配新任务,并使用其学习到的权重作为起点,您可以针对新数据集重新训练预训练的网络。为了使网络适应新数据,请替换最后几层(称为网络头),使其针对新任务输出每个类的预测分数。

    加载训练数据

    提取 MathWorks™ Merch 数据集。这是一个包含 75 个 MathWorks 商品图像的小型数据集,这些商品分属五个不同的类。数据的排列使得图像位于对应于这五个类的子文件夹中。

    folderName = "MerchData";
    unzip("MerchData.zip",folderName);

    创建一个图像数据存储。图像数据存储可用于存储大量的图像数据,包括无法放入内存的数据,并在训练神经网络时高效地分批读取图像。指定包含提取图像的文件夹,并指示子文件夹名称与图像标签对应。

    imds = imageDatastore(folderName, ...
        IncludeSubfolders=true, ...
        LabelSource="foldernames");

    显示一些示例图像。

    numImages = numel(imds.Labels);
    idx = randperm(numImages,16);
    I = imtile(imds,Frames=idx);
    figure
    imshow(I)

    查看类名称和类数。

    classNames = categories(imds.Labels)
    classNames = 5×1 cell
        {'MathWorks Cap'          }
        {'MathWorks Cube'         }
        {'MathWorks Playing Cards'}
        {'MathWorks Screwdriver'  }
        {'MathWorks Torch'        }
    
    
    numClasses = numel(classNames)
    numClasses = 
    5
    

    将数据划分为训练数据集和验证数据集。将 70% 的图像用于训练,15% 的图像用于验证,15% 的图像用于测试。splitEachLabel 函数将图像数据存储拆分为两个新数据存储。

    [imdsTrain,imdsValidation,imdsTest] = splitEachLabel(imds,0.7,0.15,"randomized");

    加载预训练网络

    将预训练的 SqueezeNet 神经网络加载到工作区中。要返回准备好针对新数据重新训练的神经网络,请指定类数。

    net = imagePretrainedNetwork(NumClasses=numClasses)
    net = 
      dlnetwork with properties:
    
             Layers: [68×1 nnet.cnn.layer.Layer]
        Connections: [75×2 table]
         Learnables: [52×3 table]
              State: [0×3 table]
         InputNames: {'data'}
        OutputNames: {'prob_flatten'}
        Initialized: 1
    
      View summary with summary.
    
    

    从输入层中获取神经网络输入大小。

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

    网络头中的可学习层(具有可学习参数的最后一个层)需要重新训练。该层通常是一个全连接层或卷积层,其输出大小与类数相匹配。

    要提高对此层的更新级别并加快收敛速度,可以使用 setLearnRateFactor 函数增大其可学习参数的学习率因子。将可学习参数的学习率因子设置为 10

    net = setLearnRateFactor(net,"conv10/Weights",10);
    net = setLearnRateFactor(net,"conv10/Bias",10);

    准备要训练的数据

    数据存储中图像的大小可以不同。要自动调整训练图像的大小,请使用增强的图像数据存储。数据增强还有助于防止网络过拟合和记忆训练图像的具体细节。指定要对训练图像额外执行的这些增强操作:沿垂直轴随机翻转训练图像,以及在水平和垂直方向上随机平移训练图像最多 30 个像素。

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

    要在不执行进一步数据增强的情况下自动调整验证和测试图像的大小,请使用增强的图像数据存储,而不指定任何其他预处理操作。

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

    指定训练选项

    指定训练选项。在选项中进行选择需要经验分析。要通过运行试验探索不同训练选项配置,您可以使用Experiment Manager

    对于此示例,请使用以下选项:

    • 使用 Adam 优化器进行训练。

    • 要降低预训练的权重的更新级别,请使用较小的学习率。将学习率设置为 0.0001

    • 每迭代五次使用验证数据对网络进行一次验证。对于较大的数据集,为了防止验证拖慢训练速度,请增大此值。

    • 在图中显示训练进度,并监控准确度度量。

    • 禁用详尽输出。

    options = trainingOptions("adam", ...
        InitialLearnRate=0.0001, ...
        ValidationData=augimdsValidation, ...
        ValidationFrequency=5, ...
        Plots="training-progress", ...
        Metrics="accuracy", ...
        Verbose=false);

    训练神经网络

    使用 trainnet 函数训练神经网络。对于分类,使用交叉熵损失。默认情况下,trainnet 函数使用 GPU(如果有)。使用 GPU 需要 Parallel Computing Toolbox™ 许可证和受支持的 GPU 设备。有关受支持设备的信息,请参阅GPU 计算要求 (Parallel Computing Toolbox)。否则,trainnet 函数使用 CPU。要指定执行环境,请使用 ExecutionEnvironment 训练选项。

    net = trainnet(augimdsTrain,net,"crossentropy",options);

    测试神经网络

    使用 testnet 函数测试神经网络。对于单标签分类,需评估准确度。准确度是指正确预测的百分比。默认情况下,testnet 函数使用 GPU(如果有)。要手动选择执行环境,请使用 testnet 函数的 ExecutionEnvironment 参量。

    accuracy = testnet(net,augimdsTest,"accuracy")
    accuracy = 
    100
    

    进行预测

    读取并显示测试图像。

    im = imread("MerchDataTest.jpg");
    figure
    imshow(im)

    使用神经网络进行预测。要使用单个图像进行预测,请将该图像转换为数据类型 single 并使用 predict 函数。如果有 GPU 可用,若要使用它,请先将数据转换为 gpuArray。要使用多个图像进行预测,请使用 minibatchpredict 函数。

    X = single(im);
    
    if canUseGPU
        X = gpuArray(X);
    end
    
    scores = predict(net,X);
    label = scores2label(scores,classNames);

    显示图像和预测。

    figure
    imshow(im)
    title("Prediction: " + string(label))

    输入参数

    全部折叠

    预训练的神经网络的名称,指定为下列值之一:

    imagePretrainedNetwork 模型名称参量神经网络名称深度参数内存参数(单位为百万)图像输入大小输入值范围输入层归一化所需的支持包
    "squeezenet"SqueezeNet [2] 18

    4.7 MB

    1.24

    227×227

    [0, 255]"zerocenter"
    "googlenet"GoogLeNet [3][4]22

    27 MB

    7.0

    224×224

    [0, 255]"zerocenter"

    Deep Learning Toolbox™ Model for GoogLeNet Network

    "googlenet-places365"[0, 255]"zerocenter"
    "inceptionv3"Inception-v3 [5]48

    91 MB

    23.9

    299×299

    [0, 255]"rescale-symmetric"Deep Learning Toolbox Model for Inception-v3 Network
    "densenet201"DenseNet-201 [6]201

    77 MB

    20.0

    224×224

    [0, 255]"zscore"Deep Learning Toolbox Model for DenseNet-201 Network
    "mobilenetv2"MobileNet-v2 [7]53

    14 MB

    3.5

    224×224

    [0, 255]"zscore"Deep Learning Toolbox Model for MobileNet-v2 Network
    "resnet18"ResNet-18 [8]18

    45 MB

    11.7

    224×224

    [0, 255]"zscore"Deep Learning Toolbox Model for ResNet-18 Network
    "resnet50"ResNet-50 [8]50

    98 MB

    25.6

    224×224

    [0, 255]"zscore"Deep Learning Toolbox Model for ResNet-50 Network
    "resnet101"ResNet-101 [8]101

    171 MB

    44.6

    224×224

    [0, 255]"zerocenter"Deep Learning Toolbox Model for ResNet-101 Network
    "xception"Xception [9]71

    88 MB

    22.9299×299[0, 255]"rescale-symmetric"Deep Learning Toolbox Model for Xception Network
    "inceptionresnetv2"Inception-ResNet-v2 [10]164

    213 MB

    55.9

    299×299

    [0, 255]"rescale-symmetric"Deep Learning Toolbox Model for Inception-ResNet-v2 Network
    "shufflenet"ShuffleNet [11]505.5 MB1.4224×224[0, 255]"zscore"Deep Learning Toolbox Model for ShuffleNet Network
    "nasnetmobile"NASNet-Mobile [12]*20 MB 5.3224×224[0, 255]"rescale-symmetric"Deep Learning Toolbox Model for NASNet-Mobile Network
    "nasnetlarge"NASNet-Large [12]*340 MB88.9331×331[0, 255]"rescale-symmetric"Deep Learning Toolbox Model for NASNet-Large Network
    "darknet19"DarkNet-19 [13]1980 MB20.8256×256[0, 255]"rescale-zero-one"Deep Learning Toolbox Model for DarkNet-19 Network
    "darknet53"DarkNet-53 [13]53159 MB41.6256×256[0, 255]"rescale-zero-one"Deep Learning Toolbox Model for DarkNet-53 Network
    "efficientnetb0"EfficientNet-b0 [14]8220 MB5.3

    224×224

    [0, 255]"zscore"Deep Learning Toolbox Model for EfficientNet-b0 Network
    "alexnet"AlexNet [15]8

    233 MB

    61.0

    227×227

    [0, 255]"zerocenter"Deep Learning Toolbox Model for AlexNet Network
    "vgg16"VGG-16 [16]16

    528 MB

    138

    224×224

    [0, 255]"zerocenter"Deep Learning Toolbox Model for VGG-16 Network
    "vgg19"VGG-19 [16]19

    548 MB

    144

    224×224

    [0, 255]"zerocenter"Deep Learning Toolbox Model for VGG-19 Network

    注意

    如果您将 Weights 选项设置为 "none",则对大多数模型而言,不需要下载支持包。

    名称-值参数

    全部折叠

    Name1=Value1,...,NameN=ValueN 的形式指定可选参量对组,其中 Name 是参量名称,Value 是对应的值。名称-值参量必须出现在其他参量之后,但对各个参量对组的顺序没有要求。

    示例: net = imagePretrainedNetwork("googlenet",NumClasses=10) 返回一个预训练的 GoogleNet 神经网络,该神经网络已准备好针对一个 10 类分类任务进行重新训练。

    分类任务的类数,指定为正整数或 []

    如果 NumClasses 是一个整数,则 imagePretrainedNetwork 函数通过替换网络的分类头中的可学习层,使预训练的神经网络适应具有指定类数的分类任务。

    如果您指定 NumClasses 选项,则 NumResponses 必须是 [],并且函数不得输出 classNames 参量。

    数据类型: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

    回归任务的响应数,指定为正整数或 []

    如果 NumResponses 是一个整数,则 imagePretrainedNetwork 函数通过将网络的分类头替换为回归任务的头,使预训练的神经网络适应具有指定响应数的回归任务。

    如果您指定 NumResponses 选项,则 NumClasses 必须是 [],并且函数不得输出 classNames 参量。

    数据类型: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64

    神经网络权重,指定为下列值之一:

    • "pretrained" - 返回神经网络及其预训练权重。

    • "none" - 仅返回未初始化的神经网络架构。在这种情况下,大多数网络不要求您下载支持包。

    类名称类型,指定为下列值之一:

    • "string" - 以字符串数组形式返回类名称。

    • "cell" - 以字符向量元胞数组形式返回类名称。使用此选项生成代码。

    输出参量

    全部折叠

    神经网络,以 dlnetwork 对象形式返回。

    类名称,以字符串数组或字符向量元胞数组形式返回。

    仅当 NumClassesNumResponses 值都是 [] 时,此函数才返回类名称。classNames 的数据类型取决于 ClassNamesTypes 参量。

    数据类型: string | cell

    提示

    参考

    [1] ImageNet. http://www.image-net.org.

    [2] Iandola, Forrest N., Song Han, Matthew W. Moskewicz, Khalid Ashraf, William J. Dally, and Kurt Keutzer. “SqueezeNet: AlexNet-Level Accuracy with 50x Fewer Parameters and <0.5MB Model Size.” Preprint, submitted November 4, 2016. https://arxiv.org/abs/1602.07360.

    [3] Szegedy, Christian, Wei Liu, Yangqing Jia, Pierre Sermanet, Scott Reed, Dragomir Anguelov, Dumitru Erhan, Vincent Vanhoucke, and Andrew Rabinovich. “Going Deeper with Convolutions.” In 2015 IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 1–9. Boston, MA, USA: IEEE, 2015. https://doi.org/10.1109/CVPR.2015.7298594.

    [4] Places. http://places2.csail.mit.edu/

    [5] Szegedy, Christian, Vincent Vanhoucke, Sergey Ioffe, Jon Shlens, and Zbigniew Wojna. “Rethinking the Inception Architecture for Computer Vision.” In 2016 IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2818–26. Las Vegas, NV, USA: IEEE, 2016. https://doi.org/10.1109/CVPR.2016.308.

    [6] Huang, Gao, Zhuang Liu, Laurens Van Der Maaten, and Kilian Q. Weinberger. “Densely Connected Convolutional Networks.” In 2017 IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 2261–69. Honolulu, HI: IEEE, 2017. https://doi.org/10.1109/CVPR.2017.243.

    [7] Sandler, Mark, Andrew Howard, Menglong Zhu, Andrey Zhmoginov, and Liang-Chieh Chen. “MobileNetV2: Inverted Residuals and Linear Bottlenecks.” In 2018 IEEE/CVF Conference on Computer Vision and Pattern Recognition, 4510–20. Salt Lake City, UT: IEEE, 2018. https://doi.org/10.1109/CVPR.2018.00474.

    [8] He, Kaiming, Xiangyu Zhang, Shaoqing Ren, and Jian Sun. “Deep Residual Learning for Image Recognition.” In 2016 IEEE Conference on Computer Vision and Pattern Recognition (CVPR), 770–78. Las Vegas, NV, USA: IEEE, 2016. https://doi.org/10.1109/CVPR.2016.90.

    [9] Chollet, François. “Xception: Deep Learning with Depthwise Separable Convolutions.” Preprint, submitted in 2016. https://doi.org/10.48550/ARXIV.1610.02357.

    [10] Szegedy, Christian, Sergey Ioffe, Vincent Vanhoucke, and Alexander Alemi. “Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning.” Proceedings of the AAAI Conference on Artificial Intelligence 31, no. 1 (February 12, 2017). https://doi.org/10.1609/aaai.v31i1.11231.

    [11] Zhang, Xiangyu, Xinyu Zhou, Mengxiao Lin, and Jian Sun. “ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile Devices.” Preprint, submitted July 4, 2017. http://arxiv.org/abs/1707.01083.

    [12] Zoph, Barret, Vijay Vasudevan, Jonathon Shlens, and Quoc V. Le. “Learning Transferable Architectures for Scalable Image Recognition.” Preprint, submitted in 2017. https://doi.org/10.48550/ARXIV.1707.07012.

    [13] Redmon, Joseph. “Darknet: Open Source Neural Networks in C.” https://pjreddie.com/darknet.

    [14] Tan, Mingxing, and Quoc V. Le. “EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks.” Preprint, submitted in 2019. https://doi.org/10.48550/ARXIV.1905.11946.

    [15] Krizhevsky, Alex, Ilya Sutskever, and Geoffrey E. Hinton. "ImageNet Classification with Deep Convolutional Neural Networks." Communications of the ACM 60, no. 6 (May 24, 2017): 84–90. https://doi.org/10.1145/3065386.

    [16] Simonyan, Karen, and Andrew Zisserman. “Very Deep Convolutional Networks for Large-Scale Image Recognition.” Preprint, submitted in 2014. https://doi.org/10.48550/ARXIV.1409.1556.

    扩展功能

    全部展开

    版本历史记录

    在 R2024a 中推出