【问题标题】:Pytorch Neural Network ErrorsPytorch 神经网络错误
【发布时间】:2021-03-11 03:31:49
【问题描述】:

我正在尝试使用 Pytorch 计算某个机器学习模型的损失和准确性,但在初始化数据集以便它可以运行时遇到了问题。使用 Moon 数据集,我在运行代码时遇到了一些错误。我首先初始化数据集:

X, y = make_moons(200, noise=0.2, random_state=42)

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30, random_state=1, stratify = y)
x, y = Variable (torch.from_numpy(X_train)).float(), Variable(torch.from_numpy(y_train)).float()

然后当我运行神经网络时:

    def __init__(self):
        super(SoftmaxRegression, self).__init__()
        self.fc = nn.Linear(200, 1)
        self.softmax = nn.Softmax()

    def forward(self, x):
        x = self.fc(x)
        x = self.softmax(x)
        return x

我收到以下错误: serWarning:softmax 的隐式维度选择已被弃用。更改调用以包含 dim=X 作为参数。 x = F.softmax(self.layer(x))
ret = torch._C._nn.nll_loss(输入,目标,权重,_Reduction.get_enum(reduction),ignore_index) IndexError:目标 1 超出范围。

我该如何解决这个问题,以便它可以运行数据集并输出损失和准确性?

【问题讨论】:

  • 你能提供完整的追溯吗?
  • @null 这是我迄今为止开发的代码X, y = sklearn.datasets.make_moons(200, noise=0.20) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30, random_state=1, stratify = y) def __init__(self): super(SoftmaxRegression, self).__init__() self.fc = nn.Linear(500, 1) self.softmax = nn.Softmax() def forward(self, x): x = self.fc(x) x = self.softmax(x) return x 每次我尝试运行它时都指出参数至少需要是 1D,但它们是 0D 和 2D。
  • @null 所以我尝试将它们转换为张量,但它仍然不起作用。我正在尝试通过在该数据集上运行来打印出神经网络的损失和准确性。
  • 我的意思是完整的“错误”回溯。你能把它放在答案中吗?
  • @null 我再次编辑了这个问题,但这是我得到的错误:错误:serWarning:softmax 的隐式维度选择已被弃用。更改调用以包含 dim=X 作为参数。 x = F.softmax(self.layer(x)) ret = torch._C._nn.nll_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index) IndexError: Target 1 is out of bounds.

标签: machine-learning neural-network pytorch


【解决方案1】:

(很抱歉将此作为答案,但不幸的是堆栈溢出不会让我发表评论:/)。

即使 Softmax 工作,它也绝对没有意义。(除非你在你的批次中进行 softmaxing,但这真的很奇怪)。您的代码显示您有一个从 200 到 1 的张量的线性层。单个值上的 Softmax 只会返回该值,Softmaxing 只能用于 2 个或更多值。

如果您希望进行二进制分类,我会将代码更改为:

    import torch.nn.functional as F

    def forward(self, x):
        x = self.fc(x)
        x = F.sigmoid(x)
        return x

【讨论】:

  • @user13382352 那么我应该运行什么而不是softmax?我尝试了逻辑回归,程序以大约 50% 的准确率解析。
  • 您应该改用self.sig = nn.Sigmoid(),这样您的代码将变为x = self.fc(x),后跟x=self.sig(x)。那就是如果你正在做二进制分类
  • 那么类的代码会变成这样吗? ` class Sigmoid(nn.Module): def __init__(self): super(Sigmoid, self).__init__() self.fc(x) x = self.sig(x) `
  • 我已经编辑了我的答案以显示我将如何更改代码,您可以删除用于在 __init__() 中创建 softmax 的行。顺便说一句,你知道 super 是做什么的吗?
  • 所以当我运行这段代码时:class Sigmoid(nn.Module): def __init__(self): super(Sigmoid, self).__init__() self.fc(x) #x = self.sig(x) def forward(self, x): x = self.fc(x) x = F.sigmoid(x) return x 我收到了这个新的错误消息:raise ModuleAttributeError("'{}' object has no attribute '{}'".format(torch.nn.modules .module.ModuleAttributeError: 'Sigmoid' 对象没有属性 'fc'
猜你喜欢
  • 2018-12-16
  • 2019-03-08
  • 2017-11-20
  • 1970-01-01
  • 1970-01-01
  • 2017-08-28
  • 2015-10-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多