---
title: Cosine-based Affinity Matrices
url: https://www.emergentmind.com/topics/cosine-based-affinity-matrices
type: topic
---

# Cosine-based Affinity Matrices

Cosine-based affinity matrices are fundamental objects in data analysis, machine learning, and information retrieval, encoding pairwise similarity between data points via normalized inner products. These affinity matrices underpin memory-based recommendation, spectral clustering, biological association mining, and a wide range of embedding-based retrieval pipelines. Their construction, spectral properties, normalization strategies, and mathematical pitfalls have been investigated across multiple domains using advanced statistical and matrix analysis tools.

## 1. Construction and Definitions

Given $n$ data points $x_1,\dots,x_n$ in $\mathbb{R}^d$, the canonical cosine similarity between $x_i$ and $x_j$ is defined as
\[
\cos(x_i, x_j) = \frac{x_i^T x_j}{\|x_i\|\|x_j\|}.
\]
The resulting affinity matrix $A \in \mathbb{R}^{n \times n}$ has entries $A_{ij} = \cos(x_i, x_j)$. In collaborative filtering, given a user–item interaction matrix $X \in \mathbb{R}^{n \times m}$, the empirical cosine similarity matrix between items is
\[
S_{\mathrm{cos}} = D^{-1/2} (X^T X) D^{-1/2},
\]
where $D = \mathrm{diag}(d_1, \ldots, d_m)$ with $d_j = \|X_{\cdot,j}\|_2^2$ [1905.07370]. Equivalently, forming the column-normalized matrix $X' = X D^{-1/2}$, $S_{\mathrm{cos}} = X'^T X'$.

For alternative applications, cosine-based affinity matrices may arise from more general similarity measures, such as the "Bregman-angle" cosine between surface normals of a convex cost function $\phi$, $A_{ij} = \langle e(x_i), e(x_j) \rangle$, with $e(x) = [\nabla\phi(x); -1]/\|[\nabla\phi(x); -1]\|_2$ [1410.6093].

In bibliometrics, one constructs the item–item (author–author, word–word) co-occurrence matrix $C = A^T A$ from an occurrence matrix $A$. The correct recovery of cosine affinities in this setting employs the Ochiai coefficient [1503.08944]:
\[
\mathrm{Ochiai}(C_{\mu\nu}) = \frac{C_{\mu\nu}}{\sqrt{C_{\mu\mu} C_{\nu\nu}}}
\]
which yields the same values as computing the cosine directly from $A$.

## 2. Spectral Properties and Noise Effects

Random matrix theory describes the spectral behavior of empirical cosine affinity matrices, particularly under noisy input data. For $X$ a random $n \times m$ matrix with i.i.d. zero-mean unit-variance entries, the eigenvalue spectrum of $(1/n)X^T X$ converges to the Marčenko–Pastur law as $n,m \to \infty$ [1905.07370]. Key properties include:

- All nontrivial eigenvalues are confined to the interval $[\lambda_{\min}, \lambda_{\max}]$, $\lambda_{\max} = (1+\sqrt{q})^2$, $\lambda_{\min} = (1-\sqrt{q})^2$, with $q = m/n$.
- The spectrum of the cosine affinity matrix $S_{\mathrm{cos}}$ exhibits natural shrinkage of non-top eigenvalues compared to that of the (demeaned) Pearson correlation estimator: for $2 \leq k \leq F$, $\lambda_k(S_{\mathrm{cos}}) < \lambda_k(S_{\mathrm{pearson}})$, meaning vanilla cosine induces shrinkage "for free".
- Non-centered data leads to a top-eigenvalue overestimation: decomposing $X = \tilde{X} + M$ (centered + mean matrix), one extra rank-1 term $(1/n)M^TM$ lifts one eigenvalue by $\xi = \sum_{j=1}^m n (m_j/\sqrt{n})^2$ (with $m_j$ the mean of column $j$), necessitating explicit correction for accurate downstream use.

## 3. Normalization, Gauge Ambiguity, and Proper Construction

Cosine similarity’s meaning depends crucially on normalization. For embeddings learned with general dot-product objectives (e.g., matrix factorization), the similarity is arbitrary up to an invertible diagonal "gauge" matrix $D$, $X' = X D^{-1}$ [2602.19393]. The cosine between $x_i', x_j'$ in $X'$ is:
\[
\cos(x_i', x_j') = \frac{x_i^T D^{-2} x_j}{\sqrt{x_i^T D^{-2} x_i} \sqrt{x_j^T D^{-2} x_j}}
\]
which can be rendered arbitrary by adjusting $D$.

Enforcing L2-normalization of each embedding vector, restricting $x_i$ to the unit sphere $\mathbb{S}^{d-1}$, eliminates this gauge freedom entirely:
- For unit-normed embeddings, cosine similarity reduces to the plain dot product.
- On the sphere, cosine and squared Euclidean distance are linearly related:
  \[
  1 - \cos(x_i,x_j) = \frac{1}{2} \|x_i - x_j\|^2
  \]
  Thus, neighbor rankings under cosine and Euclidean distance become identical.

For co-occurrence matrices, applying standard cosine normalization or Pearson $r$ to $C$ induces double normalization—overestimating affinities and distorting downstream clustering [1503.08944]. The correct approach is to use the Ochiai coefficient on $C$ or the cosine directly on the original occurrence matrix $A$.

## 4. Variance of Cosine Similarity and the Isotropic Principle

The statistical properties of entries in cosine-based affinity matrices depend on the input data's covariance structure. For zero-mean data with covariance $\Sigma = \mathrm{diag}(\sigma_1^2,\ldots,\sigma_n^2)$, asymptotic analysis shows [2310.13994]:
\[
\mathbb{E}[\cos(x,y)] = 0, \qquad \mathrm{Var}[\cos(x,y)] \approx \frac{\sum_i \sigma_i^4}{(\sum_j \sigma_j^2)^2}
\]
The variance of cosine similarity is minimized when the covariance is isotropic ($\sigma_i^2$ constant over $i$): this is the "isotropic principle". Preprocessing data via whitening ($T = \widehat{\Sigma}^{-1/2}$) or more general isotropic linear maps ensures the affinity matrix's null distribution is as sharp as possible, improving discriminative power for clustering and retrieval tasks.

Modern practice extends this by optimizing over a parameterized family of transformations $T_\theta$, maximizing downstream objectives (e.g., spectral cutting, recall) in an end-to-end manner, backpropagating gradients through the cosine similarities.

## 5. Generalizations: Convex Cost Functions and Bregman-Angle Matrices

Cosine-based affinity can be generalized via the angular structure of surface normals to convex cost functions ("Bregman-angle" similarity) [1410.6093]. Let $\phi$ be a strictly convex (possibly non-differentiable) function. For each $x$, define the (possibly sub-)gradient $g = \nabla \phi(x)$ and lifted normal $E(x) = [g; -1]$, then normalize $e(x) = E(x)/\|E(x)\|_2$. The affinity between $x$ and $y$ can be formulated as:
\[
A_{ij} = \langle e(x_i), e(x_j) \rangle
\]
or via the angle $\theta_{ij} = \arccos(A_{ij})$. Choice of $\phi$ can encode domain structure, such as negative entropy for distributions, or total variation for signals. Using Gaussian kernels of these angles, $A_{ij} = \exp(-\theta_{ij}^2/(2\sigma^2))$, often yields positive-definite affinity matrices suitable for clustering and spectral analysis.

This construction yields true angle metrics on the manifold of surface normals. Bregman-angle affinity may provide robustness to global shifts, is more faithful for structured signals, and relates to (but is distinct from) Bregman divergence, which measures tangential, rather than angular, differences.

## 6. Practical Algorithms and Applications

Algorithmic recipes for large-scale cosine-based affinity computation proceed via:

- For standard use: L2-normalize each row (or column) vector, then compute the Gram matrix of dot products [2602.19393].
- In collaborative filtering, scale $X$ columns, compute the top singular vectors of $X'$, correct the top singular value by subtracting the estimated rank-1 mean-overestimate, and reconstruct a low-rank affinity approximation (Clean-KNN) [1905.07370].
- In situations with only a co-occurrence matrix, use the Ochiai normalization, not raw cosine, to recover proper affinity values [1503.08944].

Empirical results in recommendation tasks demonstrate that cleaning cosine-based affinity matrices (by bias removal and noise-bulk eigenvalue clipping) yields substantial improvements in recall, NDCG, AUC, and catalog diversity compared to uncorrected cosine or SVD-type baselines [1905.07370].

In clustering, isotropy pre-processing maximizes statistical power for detecting structure as well as calibrating affinity thresholds based on the null distribution.

In bibliometrics, improper normalization of co-occurrence matrices distorts downstream multidimensional scaling and clustering outputs, often erasing subfield distinctions; Ochiai-normalization corrects this artefact [1503.08944].

## 7. Domain-Specific Considerations and Recommendations

Proper construction and interpretation of cosine-based affinity matrices depend strongly on context:

- Embedding-based retrieval: Always enforce L2-normalization before affinity computation. Dot-product objectives alone do not ensure meaningful cosine geometry. Post-processing by projection to the unit sphere suffices [2602.19393].
- Recommender systems: Centering and correcting empirical cosine matrices for mean-bias and noise improves accuracy and diversity, outperforming vanilla nearest neighbor and SVD-based models [1905.07370].
- Statistical power in biology or clustering: Whitening and isotropic scaling of data sharpen the null distribution and maximize sensitivity. Optimize data transformations to approach isotropy in the feature space [2310.13994].
- Bibliometric mapping: Never apply cosine similarity or Pearson correlation directly to a co-occurrence matrix $C = A^T A$; instead, use the Ochiai coefficient, which is mathematically equivalent to the cosine similarity on $A$ and avoids double normalization [1503.08944].
- Structured/signal data: Where linear geometry is insufficient, generalize similarity by constructing affinity matrices via convex-cost surface-normals or Bregman-angles, choosing the convex function to match domain assumptions [1410.6093].

Meticulous normalization and a careful understanding of the statistical and algebraic subtleties are essential for the reliable use of cosine-based affinity matrices in both foundational research and applied machine learning.

Source: https://www.emergentmind.com/topics/cosine-based-affinity-matrices