我对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])发布于 2020-04-20 11:29:15
你离你想要的只有一步之遥。
首先,您应该始终检查模块的源代码(位于这里 for ResNet)。它可能有一些功能操作(例如来自torch.nn.functional模块),因此它可能不能直接传输到torch.nn.Seqential,幸运的是,在ResNet101情况下是这样的。
其次,特征映射取决于输入的大小,对于标准的ImageNet类图像大小([3, 224, 224],注意您的图像大小不同)没有[2048, 14, 14]形状的层,只有[2048, 7, 7]或[1024, 14, 14]。
第三,没有必要使用torch.hub for ResNet101,因为它无论如何都使用隐藏的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])https://stackoverflow.com/questions/61315541
复制相似问题