pytorch预测运行出现 raise RuntimeError(‘Error(s) in loading state_dict for {}:\n\t{}‘.format( RuntimeError

运行出现以下情况,

using cpu device.
Traceback (most recent call last):
File “E:\桌面\pytorch项目练习\predict.py”, line 64, in
main()
File “E:\桌面\pytorch项目练习\predict.py”, line 45, in main
model.load_state_dict(torch.load(weights_path))
File “C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\torch\nn\modules\module.py”, line 1497, in load_state_dict
raise RuntimeError(‘Error(s) in loading state_dict for {}:\n\t{}’.format(
RuntimeError: Error(s) in loading state_dict for AlexNet/VGG16:
size mismatch for classifier.6.weight: copying a param with shape torch.Size([2, 2048]) from checkpoint, the shape in current model is torch.Size([3, 2048]).
size mismatch for classifier.6.bias: copying a param with shape torch.Size([2]) from checkpoint, the shape in current model is torch.Size([3]).
在这里插入图片描述

我们在train.py文件里num_classes值没有改成我们对应需要训练类数;或者是predict.py里num_classes值改成我们这次预测类数

解决办法:修改值重新训练,重新运行

net = AlexNet(num_classes=2, init_weights=True)

model = AlexNet(num_classes=2).to(device)
using cpu device.
Traceback (most recent call last):
  File "E:\桌面\pytorch项目练习\carb实战\Test2_alexnet\predict.py", line 64, in <module>
    main()
  File "E:\桌面\pytorch项目练习\carb实战\Test2_alexnet\predict.py", line 45, in main
    model.load_state_dict(torch.load(weights_path))
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\torch\nn\modules\module.py", line 1497, in load_state_dict
    raise RuntimeError('Error(s) in loading state_dict for {
    
    }:\n\t{
    
    }'.format(
RuntimeError: Error(s) in loading state_dict for AlexNet:
	size mismatch for classifier.6.weight: copying a param with shape torch.Size([2, 2048]) from checkpoint, the shape in current model is torch.Size([3, 2048]).
	size mismatch for classifier.6.bias: copying a param with shape torch.Size([2]) from checkpoint, the shape in current model is torch.Size([3]).

猜你喜欢

转载自blog.csdn.net/qq_55433305/article/details/129439611