pytorch中欧式距离

欧式距离公式 不必多说

衡量两个向量之间的距离

code PN论文中

import torch

def euclidean_dist(x, y):
    # x: N x D
    # y: M x D
    n = x.size(0)
    m = y.size(0)
    d = x.size(1)
    assert d == y.size(1)

    x = x.unsqueeze(1).expand(n, m, d)
    y = y.unsqueeze(0).expand(n, m, d)

    return torch.pow(x - y, 2).sum(2)

实验

x = torch.tensor([[1, 1], [2, 2]])
y = torch.tensor([[1, 1], [2, 2]])

d = euclidean_dist(x, y)
print(d)

结果 

tensor([[0, 2],
        [2, 0]])

unsqueeze 扩充维度

如下

import torch
import numpy as np
x = torch.tensor([[1, 1], [2, 2]])
y = torch.tensor([[1, 1], [2, 2]])

print(np.shape(x))
print(np.shape(y))

print(x.unsqueeze(1))
print(y.unsqueeze(0))
print(np.shape(x.unsqueeze(1)))
print(np.shape(x.unsqueeze(0)))

结果

torch.Size([2, 2])
torch.Size([2, 2])

tensor([[[1, 1]],

        [[2, 2]]])
tensor([[[1, 1],
         [2, 2]]])

torch.Size([2, 1, 2])
torch.Size([1, 2, 2])

expand, 

import torch
import numpy as np


x = torch.tensor([[1, 1], [2, 2]])
y = torch.tensor([[1, 1], [2, 2]])
x = x.unsqueeze(1).expand(n, m, d)
y = y.unsqueeze(0).expand(n, m, d)

print(x)
print(y)

结果

tensor([[[1, 1],
         [1, 1]],

        [[2, 2],
         [2, 2]]])


tensor([[[1, 1],
         [2, 2]],

        [[1, 1],
         [2, 2]]])

torch.pow(x, n)  求元素n次幂

.sum(n)对某一维度求和

你可能感兴趣的:(pytorch,python,深度学习)