_, pred = output.topk(maxk, 1, True, True) RuntimeError: selected index k out of range

" i have 2 classes "
prec1, prec5 = accuracy(output.data, target, topk=(1,5))

def accuracy(output, target, topk=(1,)):

maxk = max(topk)

batch_size = target.size(0)

print(maxk)

_, 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)

    res.append(correct_k.mul_(100.0 / batch_size))

return res

The error is raised, if the k value is larger than the size of the specified dimension as seen here:

output = torch.randn(3, 2)

maxk = 1
_, pred = output.topk(maxk, 1, True, True) # works

maxk = 2
_, pred = output.topk(maxk, 1, True, True) # works

maxk = 3
_, pred = output.topk(maxk, 1, True, True) # fails
> RuntimeError: selected index k out of range

so you would have to check output.shape and make sure dim1 is larger or equal to maxk.

1 Like

output.shape is [64,2]

The passed topk argument as topk=(1,5) would yield this error, since maxk would be 5, which is larger than the size in dim1, which is 2.

Since maxk == dim1 fails, I believe this would work only for the larger case but not equal.