简体   繁体   English

IndexError:0 维张量的无效索引。 使用 tensor.item() 将 0-dim 张量转换为 Python 数字

[英]IndexError: invalid index of a 0-dim tensor. Use tensor.item() to convert a 0-dim tensor to a Python number

def nms(bboxes,scores,threshold=0.5):
    '''
    bboxes(tensor) [N,4]
    scores(tensor) [N,]
    '''
    x1 = bboxes[:,0]
    y1 = bboxes[:,1]
    x2 = bboxes[:,2]
    y2 = bboxes[:,3]
    areas = (x2-x1) * (y2-y1)

    _,order = scores.sort(0,descending=True)
    keep = []
    while order.numel() > 0:
        i = order[0]
        keep.append(i)

        if order.numel() == 1:
            break

        xx1 = x1[order[1:]].clamp(min=x1[i])
        yy1 = y1[order[1:]].clamp(min=y1[i])
        xx2 = x2[order[1:]].clamp(max=x2[i])
        yy2 = y2[order[1:]].clamp(max=y2[i])

        w = (xx2-xx1).clamp(min=0)
        h = (yy2-yy1).clamp(min=0)
        inter = w*h

        ovr = inter / (areas[i] + areas[order[1:]] - inter)
        ids = (ovr<=threshold).nonzero().squeeze()
        if ids.numel() == 0:
            break
        order = order[ids+1]
    return torch.LongTensor(keep)

I tried我试过

i=order.item()

But it does not work但它不起作用

I found the solution in the github issues here我在这里的 github 问题中找到了解决方案

Try to change尝试改变

i = order[0] # works for PyTorch 0.4.1.

to

i = order # works for PyTorch>=0.5.

I was trying to run a standard Convolutional Neural Network(LeNet) on MNIST using PyTorch.我试图使用 PyTorch 在 MNIST 上运行标准的卷积神经网络 (LeNet)。 I was getting this error我收到这个错误

IndexError                                Traceback (most recent call last

 79         y = net.forward(train_x, dropout_value)
 80         loss = net.loss(y,train_y,l2_regularization)
 81         loss_train = loss.data[0]
 82         loss_train += loss_val.data

 IndexError: invalid index of a 0-dim tensor. Use tensor.item() to convert a 
 0-dim tensor to a Python number

Changing改变

loss_train = loss.data[0]

To

loss_train = loss.data

fixed the problem.解决了这个问题。

You should change the loop body as:您应该将循环体更改为:

while order.numel() > 0:
        if order.numel() == 1:
            break
        i = order[0]
        keep.append(i)

The code i = order[0] gives error when there is only one element left in order .代码i = order[0]给出错误时仅存在一个留在元件order

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM