pytorch利用resnet预训练模型提取特征

可以直接使用预训练模型,但是它的最终输出不是特征,而是每个类别的得分。本文以resnet18为例。

import torchvision 
model = torchvision.models.resnet18(pretrained=True)

为了使用预训练模型提取特征,需要自己将网络复制过来,进行修改。

import torch
import torch.nn as nn
from torchvision.models.resnet import Bottleneck, BasicBlock, conv1x1, conv3x3

class MyResNet(nn.Module):
    def __init__(self, block, layers, num_classes=1000, zero_init_residual=False,
                 groups=1, width_per_group=64, replace_stride_with_dilation=None,
                 norm_layer=None):
        super(MyResNet, self).__init__()
        if norm_layer is None:
            norm_layer = nn.BatchNorm2d
        self._norm_layer = norm_layer

        self.inplanes = 64
        self.dilation = 1
        if replace_stride_with_dilation is None:
            # each element in the tuple indicates if we should replace
            # the 2x2 stride with a dilated convolution instead
            replace_stride_with_dilation = [False, False, False]
        if len(replace_stride_with_dilation) != 3:
            raise ValueError("replace_stride_with_dilation should be None "
                             "or a 3-element tuple, got {}".format(replace_stride_with_dilation))
        self.groups = groups
        self.base_width = width_per_group
        self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3,
                               bias=False)
        self.bn1 = norm_layer(self.inplanes)
        self.relu = nn.ReLU(inplace=True)
        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
        self.layer1 = self._make_layer(block, 64, layers[0])
        self.layer2 = self._make_layer(block, 128, layers[1], stride=2,
                                       dilate=replace_stride_with_dilation[0])
        self.layer3 = self._make_layer(block, 256, layers[2], stride=2,
                                       dilate=replace_stride_with_dilation[1])
        self.layer4 = self._make_layer(block, 512, layers[3], stride=2,
                                       dilate=replace_stride_with_dilation[2])
        self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
        # self.fc = nn.Linear(512 * block.expansion, num_classes)  这里将全连接层注释掉了

        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
            elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)

        # Zero-initialize the last BN in each residual branch,
        # so that the residual branch starts with zeros, and each residual block behaves like an identity.
        # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677
        if zero_init_residual:
            for m in self.modules():
                if isinstance(m, Bottleneck):
                    nn.init.constant_(m.bn3.weight, 0)
                elif isinstance(m, BasicBlock):
                    nn.init.constant_(m.bn2.weight, 0)

    def _make_layer(self, block, planes, blocks, stride=1, dilate=False):
        norm_layer = self._norm_layer
        downsample = None
        previous_dilation = self.dilation
        if dilate:
            self.dilation *= stride
            stride = 1
        if stride != 1 or self.inplanes != planes * block.expansion:
            downsample = nn.Sequential(
                conv1x1(self.inplanes, planes * block.expansion, stride),
                norm_layer(planes * block.expansion),
            )

        layers = []
        layers.append(block(self.inplanes, planes, stride, downsample, self.groups,
                            self.base_width, previous_dilation, norm_layer))
        self.inplanes = planes * block.expansion
        for _ in range(1, blocks):
            layers.append(block(self.inplanes, planes, groups=self.groups,
                                base_width=self.base_width, dilation=self.dilation,
                                norm_layer=norm_layer))

        return nn.Sequential(*layers)

    def _forward_impl(self, x):
        # See note [TorchScript super()]
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu(x)
        x = self.maxpool(x)

        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        x = self.layer4(x)

        x = self.avgpool(x)
        x = torch.flatten(x, 1)
        # x = self.fc(x) 这里注释掉了最后一个全连接层,直接输出提取的特征

        return x

    def forward(self, x):
        return self._forward_impl(x)

修改完网络后需要对网络参数进行初始化,由于修改了网络,需要逐层进行初始化。

import torchvision as tv

model = MyResNet(BasicBlock, [2, 2, 2, 2]) #这里具体的参数参考库中源代码
resnet18 = tv.models.resnet18(pretrained=True)
pretrained_dict = resnet18.state_dict()
model_dict = model.state_dict()
pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict}
model_dict.update(pretrained_dict)
model.load_state_dict(model_dict)

这样便实现了对模型的初始化,可以利用resnet18预训练模型来提取图片特征了。

  • 2
    点赞
  • 47
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
### 回答1: PyTorch 提供了许多预训练模型,如 AlexNet、VGG、ResNet、Inception 等,这些模型都在 ImageNet 数据集上进行了预训练。我们可以利用这些预训练模型提取图像特征,以便用于图像分类、目标检测等任务。 以下是一个示例代码,利用 ResNet-50 模型来提取图像特征: ```python import torch import torchvision.models as models import torchvision.transforms as transforms # 加载预训练模型 resnet = models.resnet50(pretrained=True) # 定义数据预处理 transform = transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) # 加载图像 img = Image.open('test.jpg') # 预处理图像 img_tensor = transform(img) # 增加一个维度,变成 4D 张量 img_tensor.unsqueeze_(0) # 特征提取 features = resnet(img_tensor) # 打印特征向量 print(features) ``` 其中,我们首先加载了 ResNet-50 模型,并定义了一个数据预处理方法 `transform`,然后加载了一张测试图片,并将其转化为 PyTorch Tensor 格式,并增加了一个维度,变成 4D 张量。最后,我们通过调用 `resnet` 模型来提取特征,得到一个 1x1000 的张量,我们可以将其用于图像分类等任务中。 ### 回答2: PyTorch是一个功能强大的机器学习库,其中包含许多用于预训练模型特征提取工具。 预训练模型是在大规模数据集上进行训练并保存的模型,可以用来处理各种任务。PyTorch提供了许多经过预训练的模型,如ResNet、Inception、VGG等,这些模型具有很强的特征提取能力。 使用PyTorch进行预训练模型特征提取很简单。首先,我们需要下载和加载所需的预训练模型PyTorch提供了一种方便的方式,可以直接从网上下载预训练模型并加载到我们的程序中。 加载预训练模型后,我们可以通过简单地将数据传递给该模型来提取特征。这通常涉及将输入数据通过模型的前向传播过程,并从中获取感兴趣的特定层或层的输出。 例如,如果我们想要提取图像的特征,我们可以使用ResNet模型。我们可以将图片传递给该模型,然后从所需的层中获取输出。这些特征可以用来训练其他模型,进行图像分类、目标检测等任务。 PyTorch预训练模型特征提取功能很受欢迎,因为它不需要从头开始训练模型,而是利用了已经学习到的知识。这样可以节省时间和计算资源。此外,预训练模型通常在大规模数据集上进行了训练,因此其特征提取能力很强。 总而言之,PyTorch提供了简单且强大的预训练模型特征提取工具,可以用于各种任务。通过加载预训练模型提取特征,我们可以快速构建和训练其他模型,从而提高模型性能。 ### 回答3: PyTorch 提供了许多预训练模型,它们通过在大规模数据集上进行训练,能够有效捕捉到图像或文本等数据的特征预训练模型特征提取是指利用这些模型,提取输入数据的特征表示。 在 PyTorch 中,我们可以使用 torchvision 包提供的预训练模型。这些模型包括常用的卷积神经网络(如 ResNet、VGG)和循环神经网络(如 LSTM、GRU)等,它们在 ImageNet 数据集上进行了大规模的训练。 为了使用预训练模型进行特征提取,我们可以简单地加载模型并提取输入数据的中间层输出。这些中间层的输出通常被认为是数据的有意义的特征表示。例如,对于图像分类任务,我们可以加载预训练的 ResNet 模型,并通过前向传播得到图像在最后一层卷积层的输出(也称为特征图)。这些特征图可以被视为图像的高级特征表示,可以用于后续的任务,如图像检索或分类等。 通过使用预训练模型进行特征提取,我们可以获得一些优势。首先,预训练模型经过大规模数据集的训练,能够捕捉到通用的特征表示。这样,我们无需从零开始训练模型,可以在少量的数据上进行微调或直接使用。其次,特征提取能够减少计算量和内存消耗,因为我们只需运行输入数据的前向传播,并截取中间层的输出,而无需通过后向传播进行反向更新。 总之,PyTorch 提供了方便的接口和预训练模型,使得特征提取变得简单且高效。通过使用预训练模型,我们可以获得数据的有意义的特征表示,并在后续的任务中得到更好的性能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值