我第一次玩Pytork,我注意到在训练我的神经网络时,大约四分之一左右的损失会向左转向无穷远,然后很快就会消失。我看到了一些关于南宁的其他问题,但那里的建议似乎基本上是为了实现标准化;但是在我的网络下面的第一层是这样一个规范化,我仍然看到这个问题!完整的网络是a bit convoluted,但是我已经做了一些调试,试图生成一个非常小的、可以理解的网络,它仍然显示相同的问题
代码如下;它由16个输入(0-1)组成,这些输入通过批处理规范化,然后通过完全连接的层传递到单个输出。我想让它学习总是输出1的函数,所以我取1的平方误差作为损失
import torch as t
import torch.nn as tn
import torch.optim as to
if __name__ == '__main__':
board = t.rand([1,1,1,16])
net = tn.Sequential \
( tn.BatchNorm2d(1)
, tn.Conv2d(1, 1, [1,16])
)
optimizer = to.SGD(net.parameters(), lr=0.1)
for i in range(10):
net.zero_grad()
nn_outputs = net.forward(board)
loss = t.sum((nn_outputs - 1)**2)
print(i, nn_outputs, loss)
loss.backward()
optimizer.step()
如果您运行几次,最终会看到如下运行:
0 tensor([[[[-0.7594]]]], grad_fn=<MkldnnConvolutionBackward>) tensor(3.0953, grad_fn=<SumBackward0>)
1 tensor([[[[4.0954]]]], grad_fn=<MkldnnConvolutionBackward>) tensor(9.5812, grad_fn=<SumBackward0>)
2 tensor([[[[5.5210]]]], grad_fn=<MkldnnConvolutionBackward>) tensor(20.4391, grad_fn=<SumBackward0>)
3 tensor([[[[-3.4042]]]], grad_fn=<MkldnnConvolutionBackward>) tensor(19.3966, grad_fn=<SumBackward0>)
4 tensor([[[[823.6523]]]], grad_fn=<MkldnnConvolutionBackward>) tensor(676756.7500, grad_fn=<SumBackward0>)
5 tensor([[[[3.5471e+08]]]], grad_fn=<MkldnnConvolutionBackward>) tensor(1.2582e+17, grad_fn=<SumBackward0>)
6 tensor([[[[2.8560e+25]]]], grad_fn=<MkldnnConvolutionBackward>) tensor(inf, grad_fn=<SumBackward0>)
7 tensor([[[[inf]]]], grad_fn=<MkldnnConvolutionBackward>) tensor(inf, grad_fn=<SumBackward0>)
8 tensor([[[[nan]]]], grad_fn=<MkldnnConvolutionBackward>) tensor(nan, grad_fn=<SumBackward0>)
9 tensor([[[[nan]]]], grad_fn=<MkldnnConvolutionBackward>) tensor(nan, grad_fn=<SumBackward0>)
为什么我的损失归南,我能做些什么
欢迎来到pytorch
以下是我如何安排您的培训。请检查评论
关于批处理规范的一条评论。对于每个维度,它计算批次的平均值和标准偏差(查看文档https://pytorch.org/docs/stable/generated/torch.nn.BatchNorm2d.html#torch.nn.BatchNorm2d):
其中,缩放和平移是可学习的参数。如果每个批只给出一个示例,
x.std(0) = 0
将使x_normalized
包含非常大的值为了使批次规范有效,您希望培训批次较大。
在2d或3d批次规范的情况下,“有效批次”还包括特征地图的空间/时间维度。在您的示例中,您有
batch_size=1
,并且只有16个样本在空间上排列。这可能太小,批处理规范无法有效工作。 尝试增加“有效批量大小”:看看这对你的训练有什么影响
顺便说一句,如果你删除批量标准,你的玩具例子会发生什么
相关问题 更多 >
编程相关推荐