在用torch搭建深度學習模型時,很容易在數據中存在inf與nan的情況,對應的數據類型分別時torch.inf與torch.nan。
大多數情況下,產生nan數據的原因基本上是出現了分母為0的情況,所以需要檢查張量計算過程中是否有除法運算,比如softmax就有除法。
判斷一個張量中是否有nan值:
torch.isnan(tensor).any() # 有一個True(非NAN)則都為 True
torch.isnan(tensor).all() # 有一個 NAN 則為 False
與之類似,用tensor.isinf()方法也可以查看有沒有無窮數在張量里。
torch.isinf(tensor).any()
torch.isinf(tensor).all()
————————————————
原文鏈接:https://blog.csdn.net/weixin_43483381/article/details/121864858