RuntimeError: view size is not compatible with input tensor‘s size and stride解决记录
程序员文章站
2022-03-04 14:07:21
...
1、报错
Traceback (most recent call last):
File "main.py", line 419, in <module>
main()
File "main.py", line 209, in main
loss_temp, train_prec1_temp, train_prec5_temp = train(train_loader, model, criterion, optimizer, epoch)
File "main.py", line 275, in train
prec1, prec5 = accuracy(output, target, topk=(1, 5))
File "main.py", line 395, in accuracy
correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)
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
2、分析原因
这是因为view()需要Tensor中的元素地址是连续的,但可能出现Tensor不连续的情况,所以先用 .contiguous()。将其在内存中变成连续分布即可。
3、解决方案
correct_k = correct[:k].contiguous().view(-1).float().sum(0, keepdim=True)
运行,成功解决问题
上一篇: 20道CSS基础面试题
下一篇: DOM元素尺寸获取
推荐阅读
-
RuntimeError: view size is not compatible with input tensor‘s size and stride
-
PyTorch 错误 RuntimeError: view size is not compatible with input tensor‘s size and stride (at least o
-
RuntimeError: view size is not compatible with input tensor‘s size and stride
-
RuntimeError: view size is not compatible with input tensor‘s size and stride解决记录