【问题标题】:IndexError: invalid index of a 0-dim tensor. Use tensor.item() to convert a 0-dim tensor to a Python numberIndexError:0-dim 张量的无效索引。使用 tensor.item() 将 0-dim 张量转换为 Python 数字
【发布时间】:2019-10-22 07:12:10
【问题描述】:
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()

但它不起作用

【问题讨论】:

    标签: python-3.x pytorch


    【解决方案1】:

    我在github问题here找到了解决方案

    尝试改变

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

    i = order # works for PyTorch>=0.5.
    

    【讨论】:

      【解决方案2】:

      我尝试使用 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
      

      解决了问题。

      【讨论】:

      • 这个答案看起来像一个与原始问题不匹配的问答。您可能应该提出一个新问题,如果您自己提供答案,请添加答案。
      【解决方案3】:

      您应该将循环体更改为:

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

      order 中只剩下一个元素时,代码i = order[0] 会出错。

      【讨论】:

        猜你喜欢
        • 2020-01-19
        • 1970-01-01
        • 1970-01-01
        • 2019-11-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-03
        • 2020-10-31
        相关资源
        最近更新 更多