Pytorch torch.norm, torch.cosine_similarity 对向量或者张量计算Cosine类似度, 欧式距离

torch.cosine_similarity 能够对两个向量或者张量计算类似度html

>>> input1 = torch.randn(100, 128)
>>> input2 = torch.randn(100, 128)
>>> output = torch.cosine_similarity(input1, input2, dim=1)
print(output.shape)函数

torch.Size([100])

hg1 = torch.FloatTensor(torch.randn([12]))
hg2 = torch.FloatTensor(torch.randn([12]))
torch.cosine_similarity(hg1, hg2, dim=0)code

tensor(-0.1543)

pytorch计算欧式距离htm

torch.dist(hg1, hg2, p=2)input

若是本身写的话就是:(由于很简单,大多数人本身写),Pytorch里封装了这个距离函数it

torch.sqrt(torch.sum((hg1-hg2)**2))class

Hamming 距离,汉密尔顿距离im

torch.dist(hg1, hg2, p=1)di