捷徑

torch.nn.functional.cosine_similarity

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

傳回 x1x2 之間的 cosine 相似度,沿著維度 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) – 計算 cosine 相似度的維度。預設值:1

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

範例

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

文件

Access comprehensive developer documentation for PyTorch

View Docs

Tutorials

Get in-depth tutorials for beginners and advanced developers

View Tutorials

Resources

Find development resources and get your questions answered

View Resources