RuntimeError: Error(s) in loading state_dict for VGG:
size mismatch for classifier.0.weight: copying a param with shape torch.Size([4096, 25088]) from checkpoint, the shape in current model is torch.Size([4096, 512, 7, 7]).
size mismatch for classifier.3.weight: copying a param with shape torch.Size([4096, 4096]) from checkpoint, the shape in current model is torch.Size([4096, 4096, 1, 1]).
size mismatch for classifier.6.weight: copying a param with shape torch.Size([5, 4096]) from checkpoint, the shape in current model is torch.Size([5, 4096, 1, 1]).
weights_path = r"vgg11Net.pth"
state_dict = torch.load(weights_path)
model.load_state_dict(state_dict)
model.load_state_dict(state_dict)
加载模型时,全连接层训练的模型权重torch.size
和卷积层的torch.size
维度是不同的。
我们要将训练好的模型的权重进行升维的操作,才能与卷积层的torch.size
匹配起来。
self.classifier = nn.Sequential(
# nn.Linear(512*7*7, 4096), # classifier.0
# nn.ReLU(True),
# nn.Dropout(p=0.5),
# nn.Linear(4096, 4096), # classifier.3
# nn.ReLU(True),
# nn.Dropout(p=0.5),
# nn.Linear(4096, num_classes) # classifier.6
# 全连接层与卷积层要对应起来,可不使用dropout,可以使用池化层将两者对应起来
nn.Conv2d(in_channels=512, out_channels=4096, kernel_size=7, stride=1), # classifier.0
nn.ReLU(True),
nn.Dropout(p=0.5),
nn.Conv2d(in_channels=4096, out_channels=4096, kernel_size=1, stride=1), # classifier.3
nn.ReLU(True),
nn.Dropout(p=0.5),
nn.Conv2d(in_channels=4096, out_channels=num_classes, kernel_size=1, stride=1), # classifier.6
)
在加载模型state_dict = torch.load(weights_path)
后面添加以下代码,使用reshape()
来改变加载训练模型权重的维度,与卷积层所需要的维度一样。
state_dict = torch.load(weights_path)
for k, v in state_dict.items():
if "classifier.0.weight" == k:
state_dict[k] = v.reshape(4096, 512, 7, 7)
if "classifier.3.weight" == k:
state_dict[k] = v.reshape(4096, 4096, 1, 1)
if "classifier.6.weight" == k:
state_dict[k] = v.reshape(num_classes, 4096, 1, 1)
model.load_state_dict(state_dict)
修改之后,就可以用全卷积进行测试了。
例如:输入图片大小为256*256,最后输出的为2*2*num_classes大小的输出(num_classes
为测试分类数量),全卷积测试时图片大小变化及最后输出权重的形状如下。
with torch.no_grad():
output = torch.squeeze(model(img.to(device))).cpu()
predict = torch.softmax(output, dim=0)
'''判断输出的权重为几维的 '''
if len(predict.shape) == 3:
three_dim = np.array(predict) # 将tensor数据转换为三维的numpy数组
two_dim = np.sum(three_dim, -1) # 按每个feature map进行行求和,降为二维的numpy数组
one_dim = two_dim.sum(axis=1) # axis=0 按列求和, axis=1 按行求和
predict = torch.tensor(one_dim) # 将numpy数组转换为tensor
if len(predict.shape) == 2:
two_dim = np.array(predict)
one_dim = two_dim.sum(axis=1)
predict = torch.tensor(one_dim)
'''以上为需要添加的代码'''
predict_cla = torch.argmax(predict).numpy() # 获取最大权重分类的下标
分析原因:这也是我自己的理解,使用全连接层对图片进行了Resize()
缩放,把原有的图片压扁了。而使用全卷积图片没有进行缩放,可能提取的特征更加明显,而且全卷积得到的权重向量为多维的,获取得到的权重参数更多,从而使测试时精确度更高。