【问题标题】:Finding euclidean distance given an index array and a pytorch tensor在给定索引数组和 pytorch 张量的情况下查找欧几里得距离
【发布时间】:2018-11-12 11:06:14
【问题描述】:

我有一个 pytorch 张量:

Z = np.random.rand(100,2)
tZ = autograd.Variable(torch.cuda.FloatTensor(Z), requires_grad=True)

和一个索引数组:

idx = (np.array([0, 0, 0, 4, 3, 8], dtype="int64"),
       np.array([0, 1, 2, 3, 7, 4], dtype="int64"))

我需要使用 idx 数组作为索引来查找我的 tZ 张量中所有点对的距离。

现在我正在使用 numpy 来做这件事,但如果这一切都可以使用 torch 来完成就好了

dist = np.linalg.norm(tZ.cpu().data.numpy()[idx[0]]-tZ.cpu().data.numpy()[idx[1]], axis=1)

如果有人知道如何使用 pytorch 来加速它,那将是一个很大的帮助!

【问题讨论】:

    标签: python numpy pytorch torch


    【解决方案1】:

    使用torch.index_select()

    Z = np.random.rand(100,2)
    tZ = autograd.Variable(torch.cuda.FloatTensor(Z), requires_grad=True)
    
    idx = (np.array([0, 0, 0, 4, 3, 8], dtype="int64"),
           np.array([0, 1, 2, 3, 7, 4], dtype="int64"))
    
    tZ_gathered = [torch.index_select(tZ, dim=0,
                                      index=torch.cuda.LongTensor(idx[i]))
                                      # note: you may have to wrap it in a Variable too
                                      # (thanks @rvd for the comment):
                                      # index = autograd.Variable(torch.cuda.LongTensor(idx[i])))
                   for i in range(len(idx))]
    
    print(tZ_gathered[0].shape)
    # > torch.Size([6, 2])
    
    dist = torch.norm(tZ_gathered[0] - tZ_gathered[1])
    

    【讨论】:

    • 运行您的代码时出现运行时错误:RuntimeError: index_select(): argument 'index' must be Variable, not torch.cuda.LongTensor
    • 尝试将index 参数包装在一个变量中:autograd.Variable(torch.cuda.LongTensor(idx[i]))
    • 嗯,有趣的是,我使用 Pytorch 0.4.0 运行我编写的代码没有任何错误。但它也适用于@rdv 的建议,这可能会解决您的问题。
    猜你喜欢
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 2013-03-02
    • 2012-12-21
    • 2021-10-11
    • 2018-01-08
    相关资源
    最近更新 更多