You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyTorch中如何创建手动初始化且权重固定的单层线性模型

PyTorch固定权重线性层实现方案

这个需求完全可以实现,以下是具体操作方法和替代方案:

基于nn.Linear的标准实现

你提供的nn.Linear方案只需做少量适配即可满足要求,操作步骤如下:

  • 注意参数形状适配:nn.Linear(4,1,bias=False)的默认权重形状为[1,4](输出维度在前,输入维度在后),你给出的权重形状为[4,1],需要先转置再赋值。
  • 手动赋值权重:直接修改层参数的data属性完成赋值,不会触发计算图记录。
  • 冻结权重更新:将权重的requires_grad属性设为False,反向传播时不会计算该参数的梯度,自然不会被优化器更新。

完整示例代码:

import torch
import torch.nn as nn

# 实例化线性层,禁用偏置
layer = nn.Linear(4, 1, bias=False)
# 自定义权重
custom_weights = torch.tensor([[0.6], [0.25], [0.1], [0.05]], dtype=torch.float64)
# 转置后赋值给层的权重参数
layer.weight.data.copy_(custom_weights.T)
# 冻结权重,禁止训练时更新
layer.weight.requires_grad = False

# 测试运行
input_x = torch.randn(3, 4, dtype=torch.float64)
output = layer(input_x)
print(output)

如果将该层嵌入到更大的模型中,只要保持requires_grad=False的设置,哪怕调用model.train()、优化器传入全量模型参数,该权重也不会被更新。

替代实现方案

如果你不需要将该线性变换作为模型子模块管理,可以用更轻便的方案,天然不需要考虑权重冻结的问题:

  • 直接用矩阵乘法实现,适合轻量场景:
custom_weights = torch.tensor([[0.6], [0.25], [0.1], [0.05]], dtype=torch.float64)
input_x = torch.randn(3, 4, dtype=torch.float64)
output = input_x @ custom_weights
  • 用nn.functional.linear函数实现,适配性更强:
import torch.nn.functional as F

custom_weights = torch.tensor([[0.6], [0.25], [0.1], [0.05]], dtype=torch.float64)
input_x = torch.randn(3, 4, dtype=torch.float64)
output = F.linear(input_x, weight=custom_weights.T, bias=None)

以上两种方案的权重都没有被注册为模型的可学习参数,训练过程中不会被修改,适配不需要纳入模型参数管理的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 06:48:04