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

在PyTorch模型类中使用nn.Sequential时遇TypeError异常求助

问题:创建PyTorch模型时触发TypeError错误

我尝试用nn.Sequential构建一个简单神经网络做测试,但运行代码时出现错误。

我的代码

# Create Model
import torch.nn as nn

class Net(nn.Module):
    def __init__(self):
        super().__init__()

        # Define Network
        self.stack = nn.Sequential(
            nn.Linear(in_features=3, out_features=8),
            nn.ReLU(),
            nn.Linear(in_features=8, out_features=8),
            nn.ReLU(),
            nn.Linear(in_features=8, out_features=1),
            nn.Sigmoid(),
        )

    def forward(self, x):
        # Define Forward Pass
        return self.stack(x)


# Instance Of Model
model = Net(X_train[:5])

错误信息

TypeError                                 Traceback (most recent call last)
<ipython-input-32-f947c74336f3> in <cell line: 31>()
     29 # Instance Of Model
     30 
---> 31 model = Net(X_train[0])

TypeError: Net.__init__() takes 1 positional argument but 2 were given

我原本想传入训练数据X_train的前5个样本测试模型,期望得到5个0到1之间的输出值,却触发了上述错误。


解决方案

错误根源是你把测试数据传到了模型的实例化步骤中,而Net类的__init__方法只接受self这一个参数,不需要传入数据。

正确的操作分两步:

  1. 先实例化模型(仅定义网络结构,不处理数据)
  2. 调用实例化后的模型,传入测试数据获取输出

修正后的代码:

# 先实例化模型
model = Net()
# 传入测试数据得到输出
outputs = model(X_train[:5])
# 查看输出结果
print(outputs)

解释:PyTorch中,模型类的__init__方法仅用于定义网络层结构,forward方法才是处理输入数据的逻辑。实例化模型后,直接把模型当作函数调用,就会自动触发forward方法处理输入数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 14:24:48