在 PyTorch 的模型类中使用 nn.Sequential 时出现异常错误

问题描述 投票:0回答:1

只是在这里创建一个简单的神经网络来尝试 nn.Sequential,由于某种原因我收到了这个错误

这是代码:

# Create Model

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

在这里,我尝试通过输入训练数据的前 5 个值来测试我的模型是否有效,而不是获取 0 到 1 之间的 5 个数字,例如。 [0.1, 0.2, 0.43, 0.67, .78] 我收到上面的错误。

python deep-learning pytorch
1个回答
0
投票

您正在将输入传递给模型构造函数。您需要在调用

forward
方法之前实例化模型。

model = Net()
out = model(torch.randn(8, 3))
© www.soinside.com 2019 - 2024. All rights reserved.