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

PyTorch报错:'module' object is not callable 问题排查及代码修正

PyTorch线性回归模型报错:'module' object is not callable 解决方法

出现该报错是因为原代码存在两处错误:

  • 将可调用类nn.Parameter误写为模块nn.parameter(PyTorch中nn.Parameter是可实例化的类,而nn.parameter是包含该类的模块,无法直接调用)
  • 获取模型参数时调用model_0.parameter(),正确写法应为model_0.parameters()(方法名末尾缺少字母s,parameters()才是获取模型所有参数的正确方法)

修正后的完整代码

import torch
from torch import nn 
import matplotlib.pyplot as plt

class LinearRegressionModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.weight=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.weight*x+self.bias

torch.manual_seed(42)
model_0=LinearRegressionModel()
list(model_0.parameters())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 08:47:05