赞
踩
对于三维张量:
- import torch
-
- a = torch.tensor([[[-1., 0]], [[1., 0]]])
- b = torch.tensor([[[1., 1.], [2., 1.]]])
- print(a.shape)
- print(b.shape)
-
- x = torch.nn.CosineSimilarity(-1)
- result = x(a, b)
- print(result)
输出:
- torch.Size([2, 1, 2]) # 张量a的形状
- torch.Size([1, 2, 2]) # 张量b的形状
- # 余弦相似度
- tensor([[-0.7071, -0.8944],
- [ 0.7071, 0.8944]])
为什么两个三维张量的余弦相似度是一个二维张量呢?二维张量中的数分别代表了什么意义?
验证一下
- from scipy import spatial
-
- print('\nresult[0][0]')
- data1 = [-1, 0]
- data2 = [1., 1.]
- x = 1-spatial.distance.cosine(data1, data2)
- print(x)
-
- print('\nresult[0][1]')
- data1 = [-1, 0]
- data2 = [2., 1.]
- x = 1-spatial.distance.cosine(data1, data2)
- print(x)
-
- print('\nresult[1][0]')
- data1 = [1., 0]
- data2 = [1., 1.]
- x = 1-spatial.distance.cosine(data1, data2)
- print(x)
-
- print('\nresult[1][1]:')
- data1 = [1., 0]
- data2 = [2., 1.]
- x = 1-spatial.distance.cosine(data1, data2)
- print(x)

输出:
- result[0][0]
- -0.7071067811865475
-
- result[0][1]
- -0.8944271909999157
-
- result[1][0]
- 0.7071067811865475
-
- result[1][1]:
- 0.8944271909999159
验证成功,对于三维张量,可以看作是两个矩阵(第一维是矩阵的行,第二维是矩阵的列,而第三维对应该矩阵中的元素,它是一个向量)。
这个顺序就和高数中含有多个变量的函数求偏导的顺序很像。
参考:torch.nn.functional.cosine_similarity使用详解_JasonLiu1919的博客-CSDN博客
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。