我需要计算log(1 + exp(x))
,然后对其使用自动微分。但是对于过大的x
,它会输出inf
,这是因为求幂:
>>> x = torch.tensor([0., 1., 100.], requires_grad=True)
>>> x.exp().log1p()
tensor([0.6931, 1.3133, inf], grad_fn=<Log1PBackward>)
由于log(1 + exp(x)) ≈ x
对于大的x
,我想我可以用torch.where
将{nan
,因为梯度值太大了。你知道为什么会发生这种情况吗?有没有其他方法可以让它起作用?在
我发现的一个解决方法是用反向对应的方法手动实现
Log1PlusExp
函数。但这并不能解释torch.where
在问题中的不良行为。在如果x>;=20,则函数输出约为x。 使用Pythorch方法torch.softplus公司. 这有助于解决问题。在
这就是为什么x永远不要太大。理想情况下应在[-1,1]范围内。 如果不是这样,您应该规范化您的输入。在
相关问题 更多 >
编程相关推荐