deep-learning - ResNet-101 特征图形状

标签 deep-learning object-detection resnet conv-neural-network

我对 CNN 还很陌生,在学习它时遇到了很多麻烦。

我正在尝试使用 ResNet-101 提取 CNN 特征图,并且希望获得 2048、14*14 的形状。 为了获得特征图,我删除了 ResNet-101 模型的最后一层并调整了自适应平均池。所以我得到了 torch.Size([1, 2048, 1, 1]) 形状的输出。

但我想获取 torch.Size([1, 2048, 14, 14]) 而不是 torch.Size([1, 2048, 1, 1])

谁能帮我看看结果吗?谢谢。

#load resnet101 model and remove the last layer
model = torch.hub.load('pytorch/vision:v0.5.0', 'resnet101', pretrained=True)
model = torch.nn.Sequential(*(list(model.children())[:-1]))


#extract feature map from an image and print the size of the feature map
from PIL import Image
import matplotlib.pylab as plt
from torchvision import transforms

filename = 'KM_0000000009.jpg'
input_image = Image.open(filename)

preprocess = transforms.Compose([
    transforms.Resize((244,244)),
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])

input_tensor = preprocess(input_image)

input_tensor = input_tensor.unsqueeze(0) # create a mini-batch as expected by the model

with torch.no_grad():
    output = model(input_tensor)

print(output.size()) #torch.Size([1, 2048, 1, 1])

最佳答案

你离你想要的只有一步之遥。

首先要做的事情 - 您应该始终检查模块的源代码(ResNet 的源代码位于here)。它可能有一些功能操作(例如来自torch.nn.function模块),因此它可能无法直接转移到torch.nn.Seqential,幸运的是它是在ResNet101情况下.

其次,特征图取决于输入的大小,对于标准的类似 ImageNet 的图像大小([3, 224, 224],注意你的图像大小不同),没有带有形状 [2048, 14, 14],但 [2048, 7, 7][1024, 14, 14])。 p>

第三,没有必要为 ResNet101 使用 torch.hub ,因为它在底层使用 torchvision 模型。

考虑到所有这些:

import torch
import torchvision

# load resnet101 model and remove the last layer
model = torchvision.models.resnet101()
model = torch.nn.Sequential(*(list(model.children())[:-3]))

# image-like
image = torch.randn(1, 3, 224, 224)

with torch.no_grad():
    output = model(image)

print(output.size())  # torch.Size([1, 1024, 14, 14])

如果您想要[2048, 7, 7],请使用[:-2]而不是[:-3]。 此外,您还可以在下面注意到特征图大小如何随图像形状变化:

model = torch.nn.Sequential(*(list(model.children())[:-2]))  
# Image twice as big -> twice as big height and width of features!
image = torch.randn(1, 3, 448, 448)

with torch.no_grad():
    output = model(image)

print(output.size())  # torch.Size([1, 2048, 14, 14])

关于deep-learning - ResNet-101 特征图形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61315541/

相关文章:

python-3.x - tensorflow 没有为任何变量错误提供梯度

r - 计算 R 中二进制光栅图像中的对象

opencv - 如何在 OpenCV 中训练阶段树分类器而不是级联来进行人脸检测?

class - 具有不平衡类的 Tensorflow Resnet

python - 将图层添加到 keras 预训练模型中

theano - 使用 Theano/Lasagne 在 ImageNet 等大规模数据集上进行训练的最佳实践?

python - Tensoflow2 LSTM - 未使用的参数 input_shape?

machine-learning - 为什么在目标检测中使用带有卷积神经网络的滑动窗口?

python - 在 MxNet-Gluon 中将 ROIPooling 层与预训练的 ResNet34 模型结合使用

python - tensorflow 中的 apply_gradients() 函数不会更新权重和偏差变量