Pytorch踩坑記錄

1、

使用現有模型時,如resnet、vgg16時,進行改進後,如果只想訓練自己改進後的參數,可以先將原來網絡參數的requires_grad = False

net = resnet50(pretrained = True)
for param in net.parameters():
    param.requires_grad = False
#添加自己定義的層
net.fc = nn.Linear(net.fc.in_features, 100)
#在訓練時,只需要在optizimer裏面設定部分參數
optimizer = torch.optim.Adam(["params": net.fc.parameters()], lr = 0.01)
#這樣就可以只訓練自定義部分參數

 2、

如果想將兩個模型訓練的結果融合,更好的做法是在網絡中直接實現,而不是放在主程序中實現

例如:

那可以創建一個融合的網絡,使得在主程序中只有一個net.train(),一個net1.eval()

class Fusion1(nn.Module):
    def __init__(self):
        super(Fusion1, self).__init__()
        self.RGB_generator = FCN32s1()
        self.HHA_generator = FCN32s2()
        self.conv1x1 = nn.Conv2d(2, 1, 1)
    def forward(self, x):
        RGB, HHA = x
        RGB_attention = self.RGB_generator(RGB)
        HHA_attention = self.HHA_generator(HHA)
        co_attention = torch.cat((RGB_attention, HHA_attention), dim=1)
        out = self.conv1x1(co_attention)
        out = torch.sigmoid(out)
        return out

 這樣在主程序就可以只寫一個 Fusion1().train()

 

3、

在使用dataloder,並使用nn.MSELoss()時,要注意最後讀取的數據只有一個的情況,此時nn.MSELoss()的輸入只有一維,會導致錯誤,詳見https://github.com/wangsff/coattention_object_segmentation/blob/master/main.ipynb

文件中在計算loss時沒有考慮,當讀取只有一張圖片的情況,會導致loss=0,從而出現

Element 0 of tensors does not require grad and does not have a grad_fn  的錯誤

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章