我使用的是一个预训练的ResNet-50模型,其中最后的密度被移除,平均池层的输出被平缓。这是为了特征提取的目的。图像被调整为(300,300)后从文件夹中读取;这是RGB图像。
火炬版本: 1.8.1 & torchvision版本: 0.9.1和Python3.8。
守则如下:
model_resnet50 = torchvision.models.resnet50(pretrained = True)
# To remove last dense layer from pre-trained model, Use code-
model_resnet50_modified = torch.nn.Sequential(*list(model_resnet50.children())[:-1])
# Using 'AdaptiveAvgPool2d' layer, the predictions have shape-
model_resnet50_modified(images).shape
# torch.Size([32, 2048, 1, 1])
# Add a flatten layer after 'AdaptiveAvgPool2d(output_size=(1, 1))' layer at the end-
model_resnet50_modified.flatten = nn.Flatten()
# Sanity check- make predictions using a batch of images-
predictions = model_resnet50_modified(images)
predictions.shape
# torch.Size([32, 2048])现在,我想将成批的图像提供给这个模型,并将模型(32,2048)所做的预测垂直连接起来。
# number of images in training and validation sets-
len(dataset_train), len(dataset_val)
# (22500, 2500)总共有22500 + 2500 = 25000张图像。因此,最终的表/矩阵应该具有形状:( 25000,2048) ->图像数=25000,提取的特征数=2048年。
我尝试使用np.vstack()运行一个玩具代码,如下所示:
x = np.random.random_sample(size = (1, 3))
x.shape
# (1, 3)
x
# array([[0.52381798, 0.12345404, 0.1556422 ]])
for i in range(5):
y = np.random.random_sample(size = (1, 3))
np.vstack((x, y))
x
# array([[0.52381798, 0.12345404, 0.1556422 ]])解决方案?
谢谢!
发布于 2021-06-25 07:23:42
如果要将结果叠加在张量中:
results = torch.empty((0,2048))
results.to(device)
results = torch.cat((results, predictions), 0)https://stackoverflow.com/questions/68126473
复制相似问题