BLOGLLM Logo
Go Pro
Guest
Not signed in
所有博客课程练习面试准备系列标签书签价格
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboard游戏
Articles
练习 / Calculus and gradients7 of 14 in topic

44. 推导余弦相似度对单个向量的梯度

MediumCalculus and gradients

对比学习 embedding 训练会提高匹配对的 cosine similarity。为此,你需要计算 cos(x, y) = x.y / (|x| |y|) 对 x 的梯度。

编写 cosine_grad(x, y),输入为等长的 1D float 数组。返回 cos(x, y) 对 x 的梯度,形状与 x 相同。如果 x 或 y 是零向量,则返回 zeros。

检查:梯度始终与 x 正交,因为缩放 x 不会改变 cosine。

函数def cosine_grad(x, y)

示例 1

输入: x = [1, 0], y = [1, 1]

输出: [0.0, 0.70710678]

示例 2

输入: x = [-1.738266, -1.336643, -1.361107, -0.351617, -2.312582], y = [-0.188897, -0.957229, 0.8936, 0.956847, 1.392258]

输出: [-0.085937, -0.174719, 0.072058, 0.11575, 0.10557]

示例 3

输入: x = [0.76747, -0.05303, 0.859794], y = [1.505481, -0.653595, 0.610351]

输出: [0.255779, -0.289708, -0.246182]

约束条件

  • Python 3 with NumPy. Code runs in your browser.
  • Your code must pass all 5 tests to be accepted.
提示 1

使用商法则。

提示 2

结果为 y / (|x| |y|) 减去 cos(x, y) * x / |x|^2。

理解思路

Cosine similarity 仅取决于方向,因此增加 x 的长度不会改变它。其对 x 的梯度包含两部分:y / (|x| |y|) 将 x 拉向 y,而 - cos x x / |x|^2 则消除了仅会拉伸 x 的部分。结果始终与 x 垂直。

Worked example

x = [1, 1], y = [1, 0]. |x| = 1.414, |y| = 1, cos = 1 / 1.414 = 0.707. 第一项: [1, 0] / 1.414 = [0.707, 0]. 第二项: 0.707 x [1, 1] / 2 = [0.354, 0.354]. Gradient = [0.354, -0.354]. 检查: 它与 x 的点积为 0.354 - 0.354 = 0. 如果去掉第二项,得到的梯度也会奖励增加 x 的长度。如果 x 或 y 全为零,则返回 zeros。

d cos / dx = y / (|x||y|) - cos(x, y) x / |x|^2. 对比学习 embedding 训练(例如 sentence embedding 模型)会通过此公式进行反向传播。
主题
Calculus and gradients
相似题目
  • 推导 softmax 加上 cross-entropy 的梯度Medium
  • 计算逻辑回归损失的 Hessian 矩阵Medium
  • 使用 Armijo 回溯线性搜索选择步长Medium
  • 对均值和 log sigma 求高斯负对数似然的导数Medium
所有 Calculus and gradients 道题目
反馈
44 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def cosine_grad(x, y):
# your code here
pass
​

Run 会在浏览器中检查这些用例,无需登录。 Submit 会检查所有 5 个测试。

Ctrl/按 + 回车 运行
© BlogLLM, Bengaluru, India关于条款隐私退款DMCA联系我们RSS