Quantcast
Channel: Redino blog
Viewing all articles
Browse latest Browse all 80

RuntimeError: view size is not compatible with input tensor’s size and stride (at least one dimension spans across two contiguous subspaces)

$
0
0

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

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

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

to

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

or

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

The post RuntimeError: view size is not compatible with input tensor’s size and stride (at least one dimension spans across two contiguous subspaces) appeared first on Redino blog.


Viewing all articles
Browse latest Browse all 80

Trending Articles