Faster RCNN pytroch訓練問題:Warning: NaN or Inf found in input tensor.
阿新 • • 發佈:2020-12-19
problem
- 在自己的資料(voc格式)上訓練Faster RCNN(https://github.com/jwyang/faster-rcnn.pytorch)就出現了loss=nan的問題。
- 在Pascal voc和coco上訓練Faster RCNN都正常。
reason
- 可能是learning rate太大,調小learning rate。最有效的方法是learning rate設為0,看看是不是還有nan的問題。
- 大概率是自己的資料有問題(我的資料是voc格式),voc獲取左邊後是要減1的,如果你的資料的座標框本身就是從0開始的,那減1就會導致超出影象邊界。
solution
- 設定lr=0,如果不在出現loss=nan的問題,說明是learning rate太大,導致了梯度爆炸或梯度消失。可調整learning rate和weight decay。
- 如果lr=0後,依然存在loss=nan的問題,就修改pascal_voc.py中獲取座標框的程式碼:
原始碼
x1 = float(bbox.find('xmin').text) - 1
y1 = float(bbox.find('ymin').text) - 1
x2 = float(bbox.find('xmax').text) - 1
y2 = float(bbox.find('ymax').text) - 1
修改後
x1 = float(bbox.find('xmin').text)
y1 = float(bbox.find('ymin').text)
x2 = float(bbox.find('xmax').text)
y2 = float(bbox.find('ymax').text)
若設定了翻轉(cfg.TRAIN.USE_FLIPPED = True),則需要在imdb.py中的def append_flipped_images(self)方法:
原始碼
boxes[:, 0] = widths[i] - oldx2 - 1
boxes[:, 2] = widths[i] - oldx1 - 1
修改後
boxes[:, 0] = widths[i] - oldx2
boxes[:, 2] = widths[i] - oldx1
總結(可能導致loss=nan的情況)[2]
- Coordinates out of the image resolution------------> NaN Loss
- xmin=xmax-----------> Results in NaN Loss
- ymin==ymax-----------> Results in Nan Loss
- The size of bounding box was very small-----------> Results in NaN Loss
For the 4th case, we put a condition that the difference of |xmax -xmin| >= 20 and similarly |ymax- ymin| >=20
[1]https://github.com/VisionLearningGroup/DA_Detection/issues/11
[2]https://github.com/jwyang/faster-rcnn.pytorch/issues/136