【问题标题】:Why does my pytorch NN return a tensor of nan?为什么我的 pytorch NN 返回一个 nan 的张量?
【发布时间】:2021-06-11 23:46:37
【问题描述】:

我有一个非常简单的神经网络,它以一个扁平的 6x6 网格作为输入,并且应该输出要在该网格上执行的四个操作的值,因此是一个 1x4 的值张量。

有时经过几次运行后,由于某种原因,我得到了一个 1x4 的 nan 张量

tensor([[nan, nan, nan, nan]], grad_fn=<ReluBackward0>)

我的模型看起来像这样,输入昏暗为 36,输出昏暗为 4:

class Model(nn.Module):
    def __init__(self, input_dim, output_dim):
        # super relates to nn.Module so this initializes nn.Module
        super(Model, self).__init__()
        # Gridsize as input,
        # last layer needs 4 outputs because of 4 possible actions: left, right, up, down
        # output values are Q Values need activation function for those like argmax
        self.lin1 = nn.Linear(input_dim, 24)
        self.lin2 = nn.Linear(24, 24)
        self.lin3 = nn.Linear(24, output_dim)

    # function to feed the input through the net
    def forward(self, x):
        # rectified linear as activation function for the first two layers
        if isinstance(x, np.ndarray):
            x = torch.tensor(x, dtype=torch.float)

        activation1 = F.relu(self.lin1(x))
        activation2 = F.relu(self.lin2(activation1))
        output = F.relu(self.lin3(activation2))

        return output

输入是:

tensor([[0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 1.0000, 0.0000, 0.0000, 0.0000,
         0.0000, 0.0000, 0.3333, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.3333,
         0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.3333, 0.0000, 0.0000, 0.0000,
         0.0000, 0.0000, 0.3333, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.6667]])

产生 nan 输出的可能原因是什么,我该如何解决?

【问题讨论】:

  • 您的输入未标准化,您仅使用 relu 激活。这可能会导致高值。您知道输入中可能出现的最高值是多少吗?如果是,请先将每个输入样本除以该数字。
  • 感谢您的提醒。我尝试了标准化输入,但遗憾的是仍然有同样的问题。
  • 请参阅this thread 了解训练期间的 NaN。
  • @Shir 非常感谢,该线程为我指明了正确的方向。我的损失函数使用标准差,而 pytorch 的 .std() 函数为单个值返回 nan。
  • 找到问题的好工作!每次遇到 NaN 问题时,我都会将此线程添加为书签并关注它。

标签: python deep-learning neural-network pytorch


【解决方案1】:

nan 值作为输出只是意味着训练是不稳定的,它可能有几乎所有可能的原因,包括代码中的各种错误。如果您认为您的代码是正确的,您可以尝试通过降低学习率或使用gradient clipping 来解决不稳定性。

【讨论】:

    猜你喜欢
    • 2017-05-10
    • 2020-07-01
    • 2018-11-08
    • 2020-10-03
    • 2019-05-21
    • 2017-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多