梯度出现Nan值的追踪

1. torch.autograd.detect_anomaly()

转自点击 ,

import torch
# 正向传播时:开启自动求导的异常侦测
torch.autograd.set_detect_anomaly(True)

# 反向传播时:在求导时开启侦测
with torch.autograd.detect_anomaly():
    loss.backward()

上面的代码就会给出具体是哪句代码求导出现的问题。

2.Debug

https://medium.com/@me_26124/debugging-neural-networks-6fa65742efd

  • 通常在使用sqrt/exp的时候会出现非常大或非常小的数,从而导致溢出或者是除0,从而出现Nan值。
原文地址:https://www.cnblogs.com/BlueBlueSea/p/13348098.html