Measuring Relationships: From Inner Products to Attention · Chapter 1
Inner products, covariance and correlation
Starting from the inner product, centering gives covariance and normalizing gives correlation; the correlation coefficient is the cosine of the angle between the centered vectors. This chapter derives the chain in full and shows where these quantities appear in state estimation and point-cloud processing.
Series contentsChapter 1 of 4
Series
Measuring Relationships: From Inner Products to Attention- 01Inner products, covariance and correlation
- 02Cross-correlation and convolution: the sliding inner product
- 03From convolution to attention
- 04Mutual information: dependence beyond linearity
The question
Given two vectors, or two random variables, how do we summarize with a single number how strongly they are related?
Every later idea in this series builds on the answer. Cross-correlation evaluates it at every shift, attention evaluates it for every pair of tokens, and mutual information extends it beyond linear relationships.
This chapter makes the relationship between three basic quantities precise: the inner product, covariance and the correlation coefficient. It then settles a common misconception, namely that zero correlation means “unrelated”.
Intuition
Multiply two vectors component by component and add up the products. Three things can happen:
- If matching components share a sign and are large, the products are large and positive, and so is the sum.
- If the signs are mixed, positive and negative terms cancel and the sum is near zero.
- If the signs are systematically opposite, the sum is negative.
The inner product therefore measures how well two patterns line up.
It has two defects.
First, it reacts to offsets. Add 100 to two unrelated columns of numbers and their inner product becomes large.
Second, it reacts to scale. Switch from meters to millimeters and it grows by a factor of 1000.
Covariance fixes the first defect by subtracting each mean, so that only the deviations from the typical value are compared. Correlation fixes the second by dividing by each standard deviation, which leaves only directional information.
Geometrically the three steps are: inner product, inner product after moving the cloud to the origin, and cosine of the angle after moving it to the origin.
Formalism
Inner product, norm and cosine
For :
The cosine similarity is
The Cauchy–Schwarz inequality is what guarantees that this lies in .
The Cauchy–Schwarz inequality
Let . For every real ,
The right-hand side is a quadratic in that is never negative, so its discriminant cannot be positive:
Equality holds exactly when for some , that is, when the vectors are collinear.
The proof uses only three properties of the inner product: bilinearity, symmetry and positive definiteness. It therefore holds for any inner product, which we need immediately.
Covariance is an inner product on random variables
For random variables with finite variance, define . It is bilinear and symmetric, and with equality only when almost surely. So it is an inner product.
Covariance is this inner product applied to centered variables:
Expanding gives the familiar form . Under this inner product:
- the variance is the squared norm of the centered variable, ;
- the standard deviation is that norm.
For samples with mean , write the centered vector as , and likewise. Then
so the sample covariance is the inner product of the centered vectors, up to a constant.
Bilinearity also gives . Covariance ignores shifts but scales with units.
Correlation is the cosine of the centered vectors
The Pearson correlation coefficient is
which is exactly the cosine of the angle between the centered variables. In the sample version the factor cancels:
Cauchy–Schwarz gives at once. exactly when almost surely, that is, when with .
The scaling rule gives , so units drop out entirely.
| Step | Expression | Geometric meaning |
|---|---|---|
| Inner product | Raw alignment | |
| Center → covariance | Alignment after moving to the mean | |
| Normalize → correlation | Cosine of the angle after moving to the mean |
The covariance matrix
For a random vector , the covariance matrix is , with . Two properties are used below.
Linear maps. For ,
Positive semidefiniteness. For every , . Hence with orthonormal : the eigenvectors are the principal directions of spread, and the eigenvalues are the variances along them.
Zero correlation is not independence
Let be symmetric about zero, so that and , and set . Then
The covariance is exactly zero, yet is a deterministic function of .
The reason is that covariance only sees co-variation along a linear trend. For positive and negative , moves in opposite directions relative to , and the two halves cancel.
Zero correlation implies independence only in special cases, such as jointly Gaussian variables. Measuring general dependence requires mutual information, the subject of Chapter 4.
In robotics
Propagating uncertainty in state estimation
The motion model of an extended Kalman filter (EKF) is with . Linearizing at the current estimate gives the Jacobian , and the linear-map rule above yields the prediction step
In SLAM, covariances describe the uncertainty of poses and landmarks. In ROS 2, geometry_msgs/msg/PoseWithCovariance (the type of the pose field in nav_msgs/msg/Odometry) carries a covariance stored row-major as 36 numbers.
Data association commonly gates candidate matches with the Mahalanobis distance
where is the innovation covariance. With the Cholesky factorization , . The Mahalanobis distance is therefore the Euclidean distance after the covariance has been whitened away.
Under a Gaussian model, follows a distribution with as many degrees of freedom as the measurement has dimensions, so the gate threshold comes straight from a table.
Estimating point-cloud normals
Take the nearest neighbours of a point, with mean . Fit a plane through that minimizes the sum of squared point-to-plane distances:
is times the sample covariance. Setting the gradient of the Lagrangian to zero gives , and at such a point the objective equals .
The normal is therefore the eigenvector of the smallest eigenvalue. The share of that eigenvalue in the sum of all three is a common flatness measure.
This is the method of Hoppe et al. (1992), and it underlies normal estimation in PCL and Open3D. Ground segmentation and plane fitting on drone LiDAR scans rely on it.
Experiment
The script below checks four things in turn: correlation equals the cosine of the centered vectors; covariance depends on units while correlation does not; the case; and the plane normal recovered as the smallest eigenvector.
import numpy as np
rng = np.random.default_rng(0)
# 1. correlation = cosine of the centered vectors
x = rng.standard_normal(1000)
y = 2.0 * x + rng.standard_normal(1000)
xc, yc = x - x.mean(), y - y.mean()
cos_centered = xc @ yc / (np.linalg.norm(xc) * np.linalg.norm(yc))
print(cos_centered, np.corrcoef(x, y)[0, 1]) # identical
# 2. change of units: covariance grows 1000x, correlation does not
print(np.cov(x, y)[0, 1], np.cov(1000 * x, y)[0, 1])
print(np.corrcoef(1000 * x, y)[0, 1])
# 3. Y = X^2: fully dependent, correlation close to 0
u = rng.uniform(-1, 1, 100_000)
print(np.corrcoef(u, u**2)[0, 1])
# 4. plane normal = eigenvector of the smallest covariance eigenvalue
n_true = np.array([1.0, 2.0, 2.0]) / 3.0
_, _, Vt = np.linalg.svd(n_true[None, :]) # Vt[1:] spans the plane
coeffs = rng.uniform(-1, 1, (500, 2))
noise = 0.01 * rng.standard_normal((500, 1))
P = coeffs @ Vt[1:] + noise * n_true
evals, evecs = np.linalg.eigh(np.cov(P.T)) # ascending eigenvalues
print(evals, abs(evecs[:, 0] @ n_true)) # last value close to 1
References
- Hoppe, H., DeRose, T., Duchamp, T., McDonald, J., & Stuetzle, W. (1992). Surface reconstruction from unorganized points. Proceedings of SIGGRAPH ‘92, 71–78.
- Thrun, S., Burgard, W., & Fox, D. (2005). Probabilistic Robotics. MIT Press.
- Wasserman, L. (2004). All of Statistics. Springer.
- Strang, G. (2016). Introduction to Linear Algebra (5th ed.). Wellesley-Cambridge Press.
- StatQuest (YouTube channel): introductory videos on covariance and correlation. https://www.youtube.com/@statquest