pytorch 复制、粘贴、替换Model某一层的训练参数

使用pytorch保存模型参数与加载模型参数的方法可以对某一层的参数进行替换、复制:

打印当前网络的参数:nn.Model.state_dict()

加载网络参数:nn.Model.load_state_dict()

代码示例

mport torch.nn as nn


class Net1(nn.Module):
    def __init__(self, input_dim, output_dim):
        super().__init__()
        self.linear1 = nn.Linear(input_dim, output_dim)  # 输入的个数,输出的个数
        self.linear2 = nn.Linear(output_dim, 2)

    def forward(self, x):
        out = self.linear1(x)
        out = self.linear2(out)
        return out


class Net2(nn.Module):
    def __init__(self, input_dim, output_dim):
        super().__init__()
        self.linear = nn.Linear(input_dim, output_dim)  # 输入的个数,输出的个数

    def forward(self, x):
        out = self.linear(x)
        return out


if __name__ == '__main__':
    net1 = Net1(20, 2) # 模型1
    net2 = Net2(20, 2) # 模型2
    # 这里可以打断点,debug一下确认参数是否变更哟
    net2.linear.load_state_dict(net1.linear1.state_dict()) # 把模型2的fc层参数替换为模型1的linear1参数

更多《计算机视觉与图形学》知识,可关注下方公众号:
在这里插入图片描述

参考文章

pytorch获取模型某一层参数名及参数值方式:https://www.cnblogs.com/expttt/p/12461775.html  
In Pytorch, what is the most efficient way to copy the learned params of a model as the initialization for a second model of the same architecture?:https://stackoverflow.com/questions/59183865/in-pytorch-what-is-the-most-efficient-way-to-copy-the-learned-params-of-a-model
在使用PyTorch进行训练时,我们可以通过多种方式来固定某一层参数,以确保它们在反向传播过程中不会被更新。 一种常见的方法是通过将参数的`requires_grad`属性设置为False来固定参数。`requires_grad`是一个布尔值,默认为True,它指示是否计算梯度。当我们将其设置为False时,即可固定该层的参数。例如,假设我们要固定模型的第二层,可以使用以下代码: ``` import torch import torch.nn as nn class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() self.layer1 = nn.Linear(10, 20) self.layer2 = nn.Linear(20, 30) self.layer3 = nn.Linear(30, 40) def forward(self, x): x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) return x model = MyModel() model.layer2.requires_grad = False # 在训练过程中,只有模型中非固定参数会更新 ``` 在这个例子中,我们将模型的第二层的`requires_grad`属性设置为False,这样在训练过程中,只有模型中没有被固定的参数会更新。 除了通过设置`requires_grad`属性来固定参数外,我们还可以选择性地为不同的参数组设置不同的学习率或优化器。例如,我们可以将固定的参数放入一个单独的参数组,并将其学习率设置为零,以确保固定参数不会被更新。 总的来说,通过设置`requires_grad`属性或选择性地设置学习率和优化器,我们可以在训练过程中灵活地固定某一层参数,以满足不同的需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值