快捷方式

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()),從而使輸出 Tensor 減少 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, 可選) – 計算餘弦相似度的維度。 預設值:1

  • eps (float, 可選) – 用於避免除以零的微小值。 預設值:1e-8

示例

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

文件

訪問 PyTorch 的完整開發者文件

檢視文件

教程

獲取針對初學者和高階開發者的深入教程

檢視教程

資源

查詢開發資源並獲得問題解答

檢視資源