解決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轉(zhuǎn)為onehot
例如:
one_hot = torch.nn.functional.one_hot(masks, num_classes=args.num_classes)
二、Pytorch遇到權(quán)重不匹配的問題
最近,樓主在pytorch微調(diào)模型時(shí)遇到
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]).
這個(gè)是因?yàn)闃侵飨螺d的預(yù)訓(xùn)練模型中的全連接層是1000類別的,而樓主本人的類別只有2類,所以會(huì)報(bào)不匹配的錯(cuò)誤
解決方案:
從報(bào)錯(cuò)信息可以看出,是fc層的權(quán)重參數(shù)不匹配,那我們只要不load 這一層的參數(shù)就可以了。
net = se_resnet50(num_classes=2) pretrained_dict = torch.load("./senet/seresnet50-60a8950a85b2b.pkl") model_dict = net.state_dict() # 重新制作預(yù)訓(xùn)練的權(quán)重,主要是減去參數(shù)不匹配的層,樓主這邊層名為“fc” pretrained_dict = {k: v for k, v in pretrained_dict.items() if (k in model_dict and 'fc' not in k)} # 更新權(quán)重 model_dict.update(pretrained_dict) net.load_state_dict(model_dict)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Tornado實(shí)現(xiàn)多進(jìn)程/多線程的HTTP服務(wù)詳解
這篇文章主要介紹了Tornado實(shí)現(xiàn)多進(jìn)程/多線程的HTTP服務(wù)詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值2019-07-07JupyterNotebook設(shè)置Python環(huán)境的方法步驟
這篇文章主要介紹了JupyterNotebook設(shè)置Python環(huán)境的方法步驟,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12Python實(shí)現(xiàn)3行代碼解簡(jiǎn)單的一元一次方程
這篇文章主要介紹了Python實(shí)現(xiàn)3行代碼解簡(jiǎn)單的一元一次方程,很適合Python初學(xué)者學(xué)習(xí)借鑒,需要的朋友可以參考下2014-08-08Python設(shè)計(jì)模式之裝飾模式實(shí)例詳解
這篇文章主要介紹了Python設(shè)計(jì)模式之裝飾模式,結(jié)合實(shí)例形式詳細(xì)分析了裝飾模式的概念、原理并結(jié)合Python實(shí)例形式分析了裝飾模式的相關(guān)使用技巧,需要的朋友可以參考下2019-01-01Python入門之三角函數(shù)sin()函數(shù)實(shí)例詳解
這篇文章主要介紹了Python入門之三角函數(shù)sin()函數(shù)實(shí)例詳解,分享了相關(guān)實(shí)例,具有一定參考價(jià)值,需要的朋友可以了解下。2017-11-11