【问题标题】:Converting numpy code to pytorch removing for loop将 numpy 代码转换为 pytorch 删除 for 循环
【发布时间】:2020-10-15 17:59:50
【问题描述】:

我的理解是,在 python 中使用 for 循环会使我们的代码变慢。因此,应尽可能避免它们。我有这段代码,我正在尝试将其转换为 PyTorch。有没有一种聪明的方法来编写它,这样我们就没有 for 循环了?

def nms(dets, scores, thresh):
    '''
    dets is a numpy array : num_dets, 6
    scores ia  nump array : num_dets,
    '''
    x1 = dets[:, 0]
    y1 = dets[:, 1]
    z1 = dets[:, 2]
    x2 = dets[:, 3]
    y2 = dets[:, 4]
    z2 = dets[:, 5]

    volume = (x2 - x1 + 1) * (y2 - y1 + 1) * (z2 - z1 + 1)
    order = scores.argsort()[::-1]  # get boxes with more ious first

    keep = []
    while order.size > 0:
        i = order[0]  # pick maxmum iou box
        keep.append(i)
        xx1 = np.maximum(x1[i], x1[order[1:]])
        yy1 = np.maximum(y1[i], y1[order[1:]])
        zz1 = np.maximum(z1[i], z1[order[1:]])
        xx2 = np.minimum(x2[i], x2[order[1:]])
        yy2 = np.minimum(y2[i], y2[order[1:]])
        zz2 = np.minimum(z2[i], z2[order[1:]])

        w = np.maximum(0.0, xx2 - xx1 + 1)  # maximum width
        h = np.maximum(0.0, yy2 - yy1 + 1)  # maxiumum height
        l = np.maximum(0.0, zz2 - zz1 + 1)  # maxiumum length
        inter = w * h * l
        ovr = inter / (volume[i] + volume[order[1:]] - inter)

        inds = np.where(ovr <= thresh)[0]
        order = order[inds + 1]

    return keep

我真的很感谢一些帮助,看看我们是否可以使用索引来以某种方式替换 for 循环。

【问题讨论】:

    标签: python numpy pytorch vision


    【解决方案1】:

    这个算法只是顺序的,因为每次下一次迭代都依赖于前一次。因此,您无法从这里的向量并行化中受益。

    【讨论】:

    • 那么是否可以使用其他方式来实现基于 pytorch 的 nms 功能?
    • 当然。只需将 numpy 函数 (np.argsort, np.maximum, np.minimum, np.where) 替换为 Torch 类似物 (torch.argsort, ...)。参见 torch.Tensor ops here
    • 但是我仍然有 for 循环,然后它仍然很慢,对吧?
    • 是的,你仍然有 while 循环。尝试执行代码分析,并记住在确定它是瓶颈之前不需要优化复杂代码。另外,我不太明白你的代码是做什么的。如果不理解,该算法无法适应向量并行化。
    猜你喜欢
    • 1970-01-01
    • 2021-10-22
    • 2017-12-31
    • 2014-03-30
    • 1970-01-01
    • 2023-01-22
    • 2021-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多