天天看點

pytorch訓練 loss=inf或者訓練過程中loss=Nan原代碼修改後

造成 loss=inf的原因之一:data underflow

最近在測試Giou的測試效果,在mobilenetssd上面測試Giou loss相對smoothl1的效果;

改完後訓練出現loss=inf

pytorch訓練 loss=inf或者訓練過程中loss=Nan原代碼修改後

原因: 在使用log函數時出現 data underflow

解決方法:增加一個bias

原代碼

# match wh / prior wh
    g_wh = (matched[:, 2:] - matched[:, :2]) / priors[:, 2:]
    g_wh = torch.log(g_wh) / variances[1]
    # return target for smooth_l1_loss
    return torch.cat([g_cxcy, g_wh], 1)  # [num_priors,4]
           

修改後

eps = 1e-5
    # match wh / prior wh
    g_wh = (matched[:, 2:] - matched[:, :2]) / priors[:, 2:]
    g_wh = torch.log(g_wh + eps) / variances[1]
    # return target for smooth_l1_loss
    return torch.cat([g_cxcy, g_wh], 1)  # [num_priors,4]
           

造成訓練過程中loss=Nan

一、log函數與exp也是産生NaN的大戶

當網絡訓練到達一定程度的時候,模型對分類的判斷可能會産生0這樣的數值,log(0)本身是沒有問題的,-inf可以安全的參與絕大部分運算,除了(-inf * 0),會産生NaN。NaN的話,一旦參與reduce運算會讓結果完蛋的… 是以呢,如果有
y_truth * log(y_predict)      
# when y_truth[i] is 0, it is likely that y_predict[i] would be 0

           
這樣的表達式,要考慮對log中的變量進行clip. 比如
safe_log = tf.clip_by_value(some_tensor, 1e-10, 1e100)
bin_tensor * tf.log(safe_log)
           

二、資料問題

這也是常見的原因;髒資料要篩選掉,手動篩選或者半自動,半自動就是把batchsize設為1,把資料增強關掉,并列印出問題資料;

繼續閱讀