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.

The causing code is

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
def accuracy(output, target, topk=(1,)): """Computes the accuracy over the k top predictions for the specified values of k""" with torch.no_grad(): maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, -1).expand_as(pred)) res = [] for k in topk: correct_k = correct[:k].view(-1).float().sum(0, keepdim=True) res.append(correct_k.mul_(100.0 / batch_size)) return res |

This error didn't happen before, so it's introduced by new version of pytorch (now my current used pytorch is 1.8.1).

And printing the array, I found it's a boolean array.

## Solution

Add `.contiguous()`

before `view()`

or use `reshape`

to replace `view`

So change the line

1 |
correct_k = correct[:k].view(-1).float().sum(0, keepdim=True) |

to

1 |
correct_k = correct[:k].contiguous().view(-1).float().sum(0, keepdim=True) |

or

1 |
correct_k = correct[:k].reshape(-1).float().sum(0, keepdim=True) |