Advertisement

【pytorch】预训练模型的使用

阅读量:

PyTorch提供了torchvision.models模块来加载预训练模型,默认支持图像分类等任务。例如可以使用torchvision.models.densenet169(pretrained=True)调用预训练的DenseNet169模型。该模块涵盖多种模型架构,包括图像分类、像素级语义分割、目标检测等多种任务。对于修改分类数目,可以通过替换最后一层或重写模型类来实现。此外还可以通过调整中间层或自定义网络结构来实现特定需求。

pytorch内置了一些较为复杂的高级功能[模型],这些资源可通过访问 torchvision.models 网址获取。例如torchvision.models.densenet169(pretrained=True)即可获取预训练版本。

了解该模块包含的各种模型类型:访问https://pytorch.org/vision/stable/models.html查看详细信息。

注意

大多数预训练模型源自ImageNet数据集。
可以从自该网站(链接)下载一个JSON文件。
接下来,请参考以下代码段提取0至999每个数字对应的文本分类标签:

复制代码
    # ImageNet class index to label 
    ## ref: https://discuss.pytorch.org/t/imagenet-classes/4923/2
    idx_to_label = json.load(open('imagenet_class_index.json'))
    idx_to_label = {int(key):value[1] for key, value in idx_to_label.items()}
    print(idx_to_label)

out:

在这里插入图片描述

TORCHVISION.MODELS
The subpackage dedicated to providing model definitions offers a comprehensive collection of models designed to address various tasks. Such as: image classification tasks, pixelwise semantic segmentation approaches, object detection models, instance segmentation systems, person keypoint detection methods, and video classification techniques.

Classification
The models subpackage includes a variety of model architecture definitions specifically designed for image classification tasks. These architecture definitions encompass a comprehensive range of models tailored to handle diverse image classification challenges.

复制代码
    AlexNet
    VGG
    ResNet
    SqueezeNet
    DenseNet
    Inception v3
    GoogLeNet
    ShuffleNet v2
    MobileNetV2
    MobileNetV3
    ResNeXt
    Wide ResNet
    MNASNet

具有代表性的图像分类模型包括Alex网(VGG)的具体实例如 Alex_net Vgg res_net dense_net 和 res_next 等

1 查看网络结构

例如,调用densenet169模型:

复制代码
    from torchvision import models
    model = models.densenet169()
    # 查看网络结构
    print(model)

out:

在这里插入图片描述

内容较为复杂,在展示时选择了截取关键部分。通过分析得知该模型具有1,000个分类单元,并其分类能力达到1,

2 修改模型(分类数目)

2.1 方法一

根据上一章的内容可知该模型涉及1000个分类任务。若希望构建一个仅包含两个分类任务的模型,则需要如何进行调整?

可以看出,在深度学习模型中,默认情况下最后一层的名称会被系统自动生成一个默认值。这是因为系统会在构建模型时自动识别出这一特征提取环节的重要性,并将其命名为classifier以便后续处理和优化。

复制代码
    #提取最后一层层中的输入神经元数目 
    in_features = model.classifier.in_features 
    #修改类别为2
    model.classifier = nn.Linear(in_features, 2)
    print(model)

就好了:

在这里插入图片描述

可以看到最后一层输出单元数变成2了。

类似地, 如果我想对中间某一层进行修改, 只要我知道它的名称, 就可以完成相应的修改操作.

2.2 方法2(重写类)

复制代码
    import torchvision.models as models
    
    class DenseNet121(nn.Module):
     """Model modified.
     The architecture of our model is the same as standard DenseNet121
     except the classifier layer which has an additional sigmoid function.
     """
     def __init__(self, out_size):
         super(DenseNet121, self).__init__()
         self.densenet121 = torchvision.models.densenet121(pretrained=True)
         # 首先最好print一下这个模型 检查最后一层的名称是否叫做 “classifier”
         num_ftrs = self.densenet121.classifier.in_features
         # 修改最后一层
         self.densenet121.classifier = nn.Sequential(
             nn.Linear(num_ftrs, out_size),
             nn.Sigmoid()
         )
    
     def forward(self, x):
         x = self.densenet121(x)
         return x
      
    N_CLASSES = 2
    DenseNet121_model = DenseNet121(N_CLASSES)

3 读取模型参数

和正常模型一样,用 model.state_dict() 读取所有参数。

复制代码
    model.state_dict()

out:

在这里插入图片描述

需要注意的是,在他所用的词典中,key 值采用了独特的命名策略;为了查看第2章最后一层的 bias 属性,请按照以下步骤操作:

在这里插入图片描述

4 保存模型

保存pytorch模型

5 查看模型某一层输出

在开始之前, 必须使用print[函数]获取其标识符, 然后调用该函数

复制代码
    import torch
    from torchvision import models
    from torch import nn
    
    
    model = models.VGG(10)
    # 查看网络结构
    print(model)
    
    # 我想要avgpool层的输出
    model2 = models.VGG(10).avgpool
    
    input1 = torch.rand(1,1,224,224)
    output1 = model2(input1)

该研究探讨了基于深度学习的图像识别算法设计与实现,并通过大量实验数据验证了其有效性。
该研究阐述了基于卷积神经网络的自然语言处理模型构建方法及其在实际应用中的可行性。
该研究分析了分布式计算框架在大数据处理系统中的性能优化策略及其潜在应用前景。

全部评论 (0)

还没有任何评论哟~