You need to enable JavaScript to run this app. PyTorch如何将已训练网络的权重迁移到删除冗余层的网络中继续训练
优惠活动
大模型
产品
解决方案
定价
更多

PyTorch如何将已训练网络的权重迁移到删除冗余层的网络中继续训练

PyTorch无用层删除后的权重迁移方案
  • 由于你原有模型中的l4/l5/l6从未参与前向传播,训练过程中这些层的参数不会对模型输出产生任何影响,仅需要保留原有有效层的参数加载到新模型即可,无需额外调整其他结构。
  • 具体操作步骤如下:
    1. 读取原有训练好的模型权重的状态字典(state_dict)
    2. 手动删除状态字典中对应三个无用层的参数键
    3. 实例化新的精简版网络结构,将处理后的状态字典加载到新模型中即可
  • 参考代码如下:
import torch
import torch.nn as nn

# 此处你的新NeuralNet类定义保持不变
class NeuralNet(nn.Module):
    def __init__(self, input_size, hidden_size, output_size):
        super(NeuralNet, self).__init__()
        self.input_size = input_size
        self.lin = nn.Linear(input_size, hidden_size)
        self.relu = torch.nn.ReLU()
        self.Tanh = torch.nn.Tanh()
        self.leakyrelu =nn.LeakyReLU(negative_slope=0.01, inplace=False)
        self.l2 = nn.Linear(hidden_size, hidden_size)
        self.l3 = nn.Linear(hidden_size, 1100)
        self.lout = nn.Linear(1100, output_size)

    def forward(self, x):
        out = self.lin(x)
        out = self.leakyrelu(out)
        out = self.l2(out)
        out = self.Tanh(out)
        out = self.l3(out)
        out = self.Tanh(out)
        out = self.lout(out)
        return out

# 1. 加载旧训练权重,替换为你自己的权重文件路径
old_state_dict = torch.load("your_trained_model.pth")

# 2. 移除无用层对应的参数
remove_keys = ["l4.weight", "l4.bias", "l5.weight", "l5.bias", "l6.weight", "l6.bias"]
for k in remove_keys:
    old_state_dict.pop(k, None)

# 3. 实例化新模型并加载权重,替换为你实际的维度参数
new_model = NeuralNet(input_size=你的输入维度, hidden_size=你的隐藏层维度, output_size=你的输出维度)
new_model.load_state_dict(old_state_dict, strict=True)

# 验证迁移正确性(可选)
# test_input = torch.randn(1, 你的输入维度)
# old_model = 你原有带l4/l5/l6的旧模型实例
# old_output = old_model(test_input)
# new_output = new_model(test_input)
# print(torch.allclose(old_output, new_output)) # 输出True则证明迁移无误
  • 注意事项:激活层(ReLU、Tanh、LeakyReLU)无训练参数,不需要做任何处理,迁移后模型的推理结果和训练效果和原有模型完全一致,可直接继续训练。

内容的提问来源于stack exchange,提问作者Farhang Amaji

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 22:06:03