評價此頁

torch.nn.functional.cosine_similarity#

torch.nn.functional.cosine_similarity(x1, x2, dim=1, eps=1e-8) Tensor#

返回 x1x2 之間的餘弦相似度,沿 dim 計算。x1x2 必須可廣播到公共形狀。dim 指的是此公共形狀中的維度。輸出的 dim 維度被擠壓(參見 torch.squeeze()),導致輸出張量維度少 1。

similarity=x1x2max(x12,ϵ)max(x22,ϵ)\text{similarity} = \dfrac{x_1 \cdot x_2}{\max(\Vert x_1 \Vert _2, \epsilon) \cdot \max(\Vert x_2 \Vert _2, \epsilon)}

支援 型別提升

引數
  • x1 (Tensor) – 第一個輸入。

  • x2 (Tensor) – 第二個輸入。

  • dim (int, optional) – 計算餘弦相似度的維度。預設為 1。

  • eps (float, optional) – 避免除以零的小值。預設為:1e-8

示例

>>> input1 = torch.randn(100, 128)
>>> input2 = torch.randn(100, 128)
>>> output = F.cosine_similarity(input1, input2)
>>> print(output)