PyTorch线性回归模型初始化报错TypeError,求代码修正方案
PyTorch线性回归模型代码修正
原代码存在的问题:
- 未导入
torch核心库,导致torch.randn、torch.Tensor等API无法调用 nn.parameter拼写错误,正确类名为nn.Parameter(首字母大写)torch.randn传入了非法参数requires_gradient:该参数不属于torch.randn的入参列表,nn.Parameter会自动将包裹的张量设置为requires_grad=True,无需手动指定- 类型注解使用了小写的
torch.tensor,正确的张量类应为大写的torch.Tensor
修正后的完整代码:
import torch from torch import nn class LinearRegressionModel(nn.Module): def __init__(self): super().__init__() # 使用nn.Parameter自动处理梯度追踪,无需手动设置requires_grad self.weights = nn.Parameter(torch.randn(1, dtype=torch.float)) self.bias = nn.Parameter(torch.randn(1, dtype=torch.float)) def forward(self, X: torch.Tensor) -> torch.Tensor: return self.weights * X + self.bias torch.manual_seed(32) model_0 = LinearRegressionModel() # 查看模型参数迭代器 print(model_0.parameters()) # 查看参数具体数值 for param in model_0.parameters(): print(param)
补充说明:
实例化模型后,通过model_0.parameters()可获取所有可训练参数的迭代器,遍历即可查看权重和偏置的具体数值,解决原问题中查看参数失败的问题。
内容的提问来源于stack exchange,提问作者ADITTTI
相关产品推荐
相关产品推荐

