【报错】view size is not compatible with input tensor‘s size and stride
完整报错
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)