python - 让两个输入之间的欧几里德距离在一个循环内填充一个矩阵

标签 python pytorch knn

我采用两个维度张量(批量大小,D1、D2、D3)并将它们展平为(批量大小,D1)。然后,我尝试获取一个(火车)张量的每一行与第二个张量(测试)的每一行之间的欧几里德距离。我无法理解如何将张量之间的距离组合填充到第 i 列的每个行元素中。

  # Flatten
  train = x_train.view(num_train, x_train[1].view(1, -1).shape[1])
  test = x_test.view(num_test, x_test[1].view(1, -1).shape[1])

  # 1 Loop
  for i in range(num_test):
    dists[:,i] = torch.sqrt(torch.sum(torch.square(train-test[i])))

在一个循环中执行此操作,每个第 i 列都将填充相同的标量值。我正在努力做到这一点

[1,i] = Euclidean distance between 1st image of train and 1st image of test ...
[2,i] = Euclidean distance between 1st image of train and 2nd image of test ...
[3,i] = Euclidean distance between 1st image of train and 3rd image of test
...
[(last element),i] = Euclidean distance between 1st image of train and (last element) image of test ...
[1,i+1] = Euclidean distance between 2nd image of train and 1st image of test

最佳答案

好吧,我在 torch.sum() 中遗漏了一个非常重要的参数,我不知道它可以解决这个问题。添加 1,使其看起来像 torch.sqrt(torch.sum(torch.square(train-test[i]), 1)) 输出到我想要的内容。

关于python - 让两个输入之间的欧几里德距离在一个循环内填充一个矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69059279/

相关文章:

python - 使用多索引 reshape 数据框并相应地填充数据

python - Seaborn 箱线图中的连接方式

python - Pytorch 与转置之间的不同输出

machine-learning - 为什么预训练的 ResNet18 比训练的验证精度更高?

python - sqlalchemy在一对多关系中添加 child

python - 调用 sys.exit() 后不触发 atexit

Pytorch `torch.no_grad()` 不影响模块

javascript - JavaScript 最近邻库

python - 有没有办法让这个 Python kNN 函数更高效?

machine-learning - K-NN : training MSE with K=1 not equal to 0