实现 InfoNCE(对比学习)损失函数的计算。
给定一个 batch 的 n 个样本,每个样本有两个向量表示(正对 pair):anchor ai 和 positive pi,维度为 d。计算 InfoNCE 损失:
对每个 anchor ai,其正样本为 pi,其余 n−1 个 pj(j=i)为负样本。相似度为余弦相似度除以温度参数 τ:
sim(ai,pj)=∥ai∥⋅∥pj∥ai⋅pj/τ L=−n1i=1∑nlog∑j=1nexp(sim(ai,pj))exp(sim(ai,pi))第一行包含两个整数 n,d(2≤n≤64,1≤d≤32)和一个浮点数 τ(0.01≤τ≤1.0)。
接下来 n 行,每行 d 个浮点数,表示 anchor 矩阵 A。
接下来 n 行,每行 d 个浮点数,表示 positive 矩阵 P。
输出 InfoNCE 损失值,保留 4 位小数。
输入
3 2 0.5
1.0 0.0
0.0 1.0
1.0 1.0
1.0 0.0
0.0 1.0
1.0 1.0
输出
0.6000
说明
3 个样本,温度 τ=0.5。每个 anchor 与自己的 positive 是正对,余弦相似度为 1.0(自身匹配),缩放后为 2.0。与其他 positive 的相似度取决于向量夹角。
© CodeFun2000 · 使用条款
Scan the QR code below with WeChat to sign in
First-time scan will create your account automatically
请使用微信扫描下方二维码完成注册