这篇教程pytorch 梯度NAN异常值的解决方案写得很实用,希望能帮到您。 pytorch 梯度NAN异常值gradient 为nan可能原因:1、梯度爆炸 2、学习率太大 3、数据本身有问题 4、backward时,某些方法造成0在分母上, 如:使用方法sqrt() 定位造成nan的代码: import torch# 异常检测开启torch.autograd.set_detect_anomaly(True)# 反向传播时检测是否有异常值,定位codewith torch.autograd.detect_anomaly(): loss.backward() 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]]) aOut[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) aOut[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) aOut[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的tensorb =torch.full_like(a, 0,) bOut[165]: tensor([[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]]) 以上为个人经验,希望能给大家一个参考,也希望大家多多支持51zixue.net。 pytorch 权重weight 与 梯度grad 可视化操作 Pytorch反向传播中的细节-计算梯度时的默认累加操作 |