def accuracy(output, target, topk=(1,)):
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].reshape(-1).float().sum(0)
res.append(correct_k.mul_(100.0/batch_size))
return res
full error sentence:
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.
i don’t know why it still cry an error like this…
The posted error is raised, if the tensor it not contiguous in memory and thus view
will fail.
You could either use .reshape
instead as suggested in the error message or .contiguous().view(...)
alternatively.
Neither .contiguous().view(…) nor .reshape(…) is working. I am using google colab. How to make it work?
def accuracy(output, target, topk=(1,)):
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))
print(correct.shape)
res =
for k in topk:
correct_k = correct[:k].reshape(-1).float().sum(0)
res.append(correct_k.mul_(100.0/batch_size))
return res
I am calling the same function i.e. accuracy(output, target, topk=(1,)); and same runtime error is reported as that reported by tree5680:
I checked with both changes i.e. .view(…) to .reshape(…) and .view(…) to .contiguous().view(…)
Could you post a minimal and executable code snippet reproducing the issue as I cannot trigger the error using:
pred = torch.randint(0, 2, (10, 10,))
target = torch.randint(0, 2, (1, 10))
correct = pred.eq(target.view(1, -1).expand_as(pred))
print(correct.shape)
# torch.Size([10, 10])
k = 3
correct_k = correct[:k].reshape(-1).float().sum(0)
print(correct_k)
# tensor(15.)
prec1, prec5 = utils.accuracy(logits, target, topk=(1, 5))
print(prec1)
print(prec5)
Thank you very much ptrblck for your time. I tried with another google account to use google colab, and surprisingly, both the alternatives of .view() as suggested by you worked.
Regards,
abhiskl