完整報錯
Traceback (most recent call last): File "D:\360MoveData\Users\HONOR\whu\TwoStageTraining.py", line 590, in <module> criterion=seg_criterion, save_dir='./models', writer=writer_first_stage) File "D:\360MoveData\Users\HONOR\whu\TwoStageTraining.py", line 317, in train_segmentation_only iou = calculate_iou(seg_preds, masks, num_classes=2, ignore_index=0) File "D:\360MoveData\Users\HONOR\whu\TwoStageTraining.py", line 229, in calculate_iou targets = targets.view(-1) RuntimeError: view size is not compatible with input tensor's size and stride (at least one dimension spans across two contiguous subspaces). Use .reshape(...) instead. Process finished with exit code 1
報錯原因
PyTorch 的 .view()
方法要求張量在內存中是連續存儲的。如果張量經過某些操作(如 transpose
, permute
)后不再是連續存儲,.view()
就會報錯。
應該使用 .reshape()
來代替 .view()
,因為 .reshape()
在必要時會自動復制數據以保證形狀正確,即使張量不連續也能工作。
解決辦法
將.view()改為.reshape()
比如修改前:
preds = preds.view(-1)
targets = targets.view(-1)
則修改后:
preds = preds.reshape(-1)
targets = targets.reshape(-1)