pytorch处理inf和nan数值的简单方法 用torch.where替换
作者:amcomputer
在pytorch训练中遇到tensor出现inf或nan?本文教你使用torch.where函数轻松替换这些异常值,无需numpy,简单高效,了解如何先处理nan再处理inf,并注意grad属性,让你的网络训练更稳定
pytorch处理inf和nan数值
在构建网络框架后,运行代码,发现很多tensor出现了inf值或者nan,在很多博客上没有找到对应的解决方法,大部分是基于numpy写的,比较麻烦。
下面基于torch BIF函数实现替换这2个值。
a = torch.Tensor([[1, 2, np.nan], [np.inf, np.nan, 4], [3, 4, 5]])
a
Out[158]:
tensor([[1., 2., nan],
[inf, nan, 4.],
[3., 4., 5.]])下面把nan值还为0:
a = torch.where(torch.isnan(a), torch.full_like(a, 0), a)
a
Out[160]:
tensor([[1., 2., 0.],
[inf, 0., 4.],
[3., 4., 5.]])接着把inf替换为1:
a = torch.where(torch.isinf(a), torch.full_like(a, 0), a)
a
Out[162]:
tensor([[1., 2., 0.],
[0., 0., 4.],
[3., 4., 5.]])简单回顾
tips:对于某些tensor,可能已经开启了grad功能,需要把它先转为普通tensor(使用.data)
torch.where(condition,T,F) 函数有三个输入值:
- 第一个是判断条件
- 第二个是符合条件的设置值
- 第三个是不符合条件的设置值
torch.full_like(input, fill_value, …) 返回与input相同size,单位值为fill_value的矩阵
#如下面这个例子,a为3*3的tensor
b =torch.full_like(a, 0,)
b
Out[165]:
tensor([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]])总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
