解決pytorch 損失函數(shù)中輸入輸出不匹配的問題
一、pytorch 損失函數(shù)中輸入輸出不匹配問題
File "C:\Users\Rain\AppData\Local\Programs\Python\Anaconda.3.5.1\envs\python35\python35\lib\site-packages\torch\nn\modules\module.py", line 491, in __call__ result = self.forward(*input, **kwargs)
File "C:\Users\Rain\AppData\Local\Programs\Python\Anaconda.3.5.1\envs\python35\python35\lib\site-packages\torch\nn\modules\loss.py", line 500, in forward reduce=self.reduce)
File "C:\Users\Rain\AppData\Local\Programs\Python\Anaconda.3.5.1\envs\python35\python35\lib\site-packages\torch\nn\functional.py", line 1514, in binary_cross_entropy_with_logits
raise ValueError("Target size ({}) must be the same as input size ({})".format(target.size(), input.size()))
ValueError: Target size (torch.Size([32])) must be the same as input size (torch.Size([32,2]))
原因
input 和 target 尺寸不匹配
解決方案:
將target轉為onehot
例如:
one_hot = torch.nn.functional.one_hot(masks, num_classes=args.num_classes)
二、Pytorch遇到權重不匹配的問題
最近,樓主在pytorch微調(diào)模型時遇到
size mismatch for fc.weight: copying a param with shape torch.Size([1000, 2048]) from checkpoint, the shape in current model is torch.Size([2, 2048]).
size mismatch for fc.bias: copying a param with shape torch.Size([1000]) from checkpoint, the shape in current model is torch.Size([2]).
這個是因為樓主下載的預訓練模型中的全連接層是1000類別的,而樓主本人的類別只有2類,所以會報不匹配的錯誤
解決方案:
從報錯信息可以看出,是fc層的權重參數(shù)不匹配,那我們只要不load 這一層的參數(shù)就可以了。
net = se_resnet50(num_classes=2)
pretrained_dict = torch.load("./senet/seresnet50-60a8950a85b2b.pkl")
model_dict = net.state_dict()
# 重新制作預訓練的權重,主要是減去參數(shù)不匹配的層,樓主這邊層名為“fc”
pretrained_dict = {k: v for k, v in pretrained_dict.items() if (k in model_dict and 'fc' not in k)}
# 更新權重
model_dict.update(pretrained_dict)
net.load_state_dict(model_dict)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Python實現(xiàn)遍歷數(shù)據(jù)庫并獲取key的值
本文給大家分享的是Python實現(xiàn)遍歷數(shù)據(jù)庫并獲取key的值的方法,主要是使用for循環(huán)來實現(xiàn),有需要的小伙伴可以參考下。2015-05-05
使用python把xmind轉換成excel測試用例的實現(xiàn)代碼
這篇文章主要介紹了使用python把xmind轉換成excel測試用例的實現(xiàn)代碼,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-10-10
在Python的Flask中使用WTForms表單框架的基礎教程
WTForms由Python寫成,為表單而生,提供了很多制作Web表單的實用API,和Flask框架結合使用效果拔群,這里我們就一起看一下在Python的Flask中使用WTForms表單框架的基礎教程2016-06-06

