[ WARN:0@7.644] global C:\b\abs_d8ltn27ay8\croot\opencv-suite_1676452046667\work\modules\videoio\src\cap_gstreamer.cpp (862) cv::GStreamerCapture::isPipelinePlaying OpenCV | GStreamer warning: GStreamer: pipeline have not been created Traceback (most recent call last): File "D:\projectfiles\PycharmProj\wheal-condition-identify\src\predict.py", line 8, in <module> model.load_state_dict(torch.load("../models/0.9664634466171265.pth")) File "C:\Users\NLER\.conda\envs\pytorch-Demo2\lib\site-packages\torch\nn\modules\module.py", line 2041, in load_state_dict raise RuntimeError('Error(s) in loading state_dict for {}:\n\t{}'.format( RuntimeError: Error(s) in loading state_dict for ResNet: size mismatch for fc.weight: copying a param with shape torch.Size([20, 2048]) from checkpoint, the shape in current model is torch.Size([1000, 2048]). size mismatch for fc.bias: copying a param with shape torch.Size([20]) from checkpoint, the shape in current model is torch.Size([1000]).
时间: 2023-07-21 17:39:46 浏览: 220
opencv_world451.dll
根据错误提示,您的模型中的fc层的结构与加载的预训练模型的fc层结构不一致,导致无法加载预训练模型的参数。在这种情况下,需要修改您的模型的fc层结构,使其与预训练模型的fc层结构一致,或者重新训练一个与预训练模型fc层结构一致的模型。
具体来说,预训练模型的fc层的权重矩阵的形状是`[1000, 2048]`,偏置向量的形状是`[1000]`,而您的模型中fc层的权重矩阵的形状是`[20, 2048]`,偏置向量的形状是`[20]`。因此,您需要将您的模型中的fc层的结构修改为与预训练模型的fc层结构一致,即权重矩阵的形状为`[1000, 2048]`,偏置向量的形状为`[1000]`。
修改方式可以参考以下代码:
```python
import torch.nn as nn
import torch.nn.functional as F
class MyModel(nn.Module):
def __init__(self, num_classes):
super(MyModel, self).__init__()
self.features = nn.Sequential(
# ... 略
)
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
self.fc = nn.Linear(2048, num_classes) # 修改fc层结构
def forward(self, x):
x = self.features(x)
x = self.avgpool(x)
x = x.view(x.size(0), -1)
x = self.fc(x)
return F.softmax(x, dim=1)
```
您需要根据自己的情况修改模型的其他部分。修改后,将预训练模型的参数加载到新模型中应该就不会出现形状不匹配的问题了。
阅读全文