欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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)

运行,成功解决问题

相关标签: python 深度学习