Implement InfoNCE Loss for contrastive learning. This is the core loss function used in SimCLR, CLIP, and many other self-supervised learning methods.
InfoNCE Loss Formula:
Similarity matrix:
S=τZ1Z2TInfoNCE Loss:
L=−N1i=1∑Nlog(∑j=1Nexp(Si,j)exp(Si,i))where τ is temperature, Si,i are positive pairs
Z1: array-like - First embedding batch (N, D)Z2: array-like - Second embedding batch (N, D)temperature: float = 0.1 - Temperature parameter (τ)Input: Z1=[[1,0],[0,1]], Z2=[[1,0],[0,1]], temperature=0.1
Output: ~0.0 (low loss)
Perfect alignment: positive pairs have highest similarity
Input: Z1=[[1,0],[0,1]], Z2=[[0,1],[1,0]], temperature=0.1
Output: ~10.0 (high loss)
Misaligned: positive pairs have low similarity
Input: Z1=[[1,0],[0,1]], Z2=[[1,0],[0,1]], temperature=1.0
Output: ~0.31 (moderate loss)
Higher temperature reduces contrast between similarities
Compute similarity matrix: S = np.dot() / temperature.
For numerical stability: S_stable = S - np.max() before applying exp.
Extract diagonal elements (positive pairs): np.diag() and compute cross-entropy loss.
Sign in to take notes on this problem
Accepts: array
Accepts: array
Accepts: number
Implement InfoNCE Loss for contrastive learning. This is the core loss function used in SimCLR, CLIP, and many other self-supervised learning methods.
InfoNCE Loss Formula:
Similarity matrix:
S=τZ1Z2TInfoNCE Loss:
L=−N1i=1∑Nlog(∑j=1Nexp(Si,j)exp(Si,i))where τ is temperature, Si,i are positive pairs
Z1: array-like - First embedding batch (N, D)Z2: array-like - Second embedding batch (N, D)temperature: float = 0.1 - Temperature parameter (τ)Input: Z1=[[1,0],[0,1]], Z2=[[1,0],[0,1]], temperature=0.1
Output: ~0.0 (low loss)
Perfect alignment: positive pairs have highest similarity
Input: Z1=[[1,0],[0,1]], Z2=[[0,1],[1,0]], temperature=0.1
Output: ~10.0 (high loss)
Misaligned: positive pairs have low similarity
Input: Z1=[[1,0],[0,1]], Z2=[[1,0],[0,1]], temperature=1.0
Output: ~0.31 (moderate loss)
Higher temperature reduces contrast between similarities
Compute similarity matrix: S = np.dot() / temperature.
For numerical stability: S_stable = S - np.max() before applying exp.
Extract diagonal elements (positive pairs): np.diag() and compute cross-entropy loss.
Sign in to take notes on this problem
Accepts: array
Accepts: array
Accepts: number