当前位置 博文首页 > pytorch 梯度NAN异常值的解决方案

    pytorch 梯度NAN异常值的解决方案

    作者:sini2018 时间:2021-08-10 18:40

    pytorch 梯度NAN异常值

    gradient 为nan可能原因:

    1、梯度爆炸

    2、学习率太大

    3、数据本身有问题

    4、backward时,某些方法造成0在分母上, 如:使用方法sqrt()

    定位造成nan的代码:

    import torch
    # 异常检测开启
    torch.autograd.set_detect_anomaly(True)
    # 反向传播时检测是否有异常值,定位code
    with 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]])
     
    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.]])

    以上为个人经验,希望能给大家一个参考,也希望大家多多支持站长博客。

    jsjbwy