簡體   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=order.item()

但它不起作用

我在這里的 github 問題中找到了解決方案

嘗試改變

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

i = order # works for PyTorch>=0.5.

我試圖使用 PyTorch 在 MNIST 上運行標准的卷積神經網絡 (LeNet)。 我收到這個錯誤

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

改變

loss_train = loss.data[0]

loss_train = loss.data

解決了這個問題。

您應該將循環體更改為:

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

代碼i = order[0]給出錯誤時僅存在一個留在元件order

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM