pytorch固定部分參數


pytorch固定部分參數

不用梯度

如果是Variable,則可以初始化時指定

j = Variable(torch.randn(5,5), requires_grad=True)

但是如果是m = nn.Linear(10,10)是沒有requires_grad傳入的

for i in m.parameters():
    i.requires_grad=False

另外一個小技巧就是在nn.Module里,可以在中間插入這個

for p in self.parameters():
    p.requires_grad=False
    
 
# eg  前面的參數就是False,而后面的不變
class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(1, 6, 5)
        self.conv2 = nn.Conv2d(6, 16, 5)

        for p in self.parameters():
            p.requires_grad=False

        self.fc1 = nn.Linear(16 * 5 * 5, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 10)
def freeze(test_net):
    ct = 0
    for child in test_net.children():
        ct += 1
        if ct < 3:
            for param in child.parameters():
                param.requires_grad = False

過濾

optimizer.SGD(filter(lambda p: p.requires_grad, model.parameters()), lr=1e-3)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM