Linear Algebra and Geometry
Two expression profiles are vectors in a space with one coordinate per gene. Geometry gives several ways to compare those vectors. The choice determines whether absolute abundance, direction, or a particular biological contrast drives the comparison.
Read vectors and matrices first. The profiles below are invented measurements on the same scale.
Dot products and vector length
Section titled “Dot products and vector length”The dot product of x and y is the sum of their corresponding products. The Euclidean norm of x is sqrt(x @ x). Dividing a nonzero vector by its norm produces a unit vector with the same direction.
Cosine similarity divides the dot product by both vector norms. It compares direction. Euclidean distance is the norm of the difference and retains differences in magnitude.
import numpy as np
profile_a = np.array([1.0, 2.0, 3.0])profile_b = np.array([2.0, 4.0, 6.0])dot_product = profile_a @ profile_bdistance = np.linalg.norm(profile_a - profile_b)cosine = dot_product / ( np.linalg.norm(profile_a) * np.linalg.norm(profile_b))print(f"Dot product: {dot_product:.3f}")print(f"Euclidean distance: {distance:.3f}")print(f"Cosine similarity: {cosine:.3f}")Dot product: 28.000Euclidean distance: 3.742Cosine similarity: 1.000The second profile is a scaled copy of the first. Their direction agrees even though their measurements differ. Cosine similarity is undefined for a zero vector. Pearson correlation additionally centers each profile, so it answers a different question.
Project onto a direction
Section titled “Project onto a direction”For a unit vector u, the scalar x @ u is the signed coordinate of x along u. Multiplying that coordinate by u gives the projected vector. The residual is perpendicular to u.
direction = np.array([1.0, 1.0, 1.0])unit_direction = direction / np.linalg.norm(direction)coordinate = profile_a @ unit_directionprojection = coordinate * unit_directionresidual = profile_a - projectionprint("Projection:", np.round(projection, 3))print("Residual:", np.round(residual, 3))print(f"Residual dot direction: {residual @ unit_direction:.3f}")assert np.isclose(residual @ unit_direction, 0.0)Projection: [2. 2. 2.]Residual: [-1. -0. 1.]Residual dot direction: -0.000This direction assigns the same weight to every gene. PCA later chooses directions from the data instead. A direction is not automatically a biological pathway or cell type.
A projection separates a vector into a component along the chosen direction and a perpendicular residual. The projected component is the point on that line nearest the original vector in Euclidean distance. Moving along the line in either direction from that point increases the distance.
The unit-length requirement matters. If the direction vector has arbitrary length, use (x @ u)/(u @ u) as the coefficient multiplying u. Normalizing first makes the denominator equal to one. The resulting projected vector does not depend on the original length chosen for the direction.
The following diagram uses two coordinates so that the perpendicular residual is visible.
from pathlib import Path
import matplotlib.pyplot as plt
point = np.array([3.0, 2.0])projected_point = np.array([point[0], 0.0])fig, ax = plt.subplots(figsize=(6, 4))ax.axhline(0.0, color="0.5", linewidth=1)ax.quiver(0.0, 0.0, *point, angles="xy", scale_units="xy", scale=1, color="tab:blue", label="Original vector")ax.quiver(0.0, 0.0, *projected_point, angles="xy", scale_units="xy", scale=1, color="tab:orange", label="Projection")ax.plot([point[0], point[0]], [0.0, point[1]], "--", color="tab:green", label="Perpendicular residual")ax.set(xlim=(-0.5, 4.5), ylim=(-0.5, 3.5), xlabel="Coordinate 1", ylabel="Coordinate 2", aspect="equal")ax.legend(loc="upper left")fig.tight_layout()Path("outputs").mkdir(exist_ok=True)fig.savefig("outputs/vector_projection.png", dpi=160)plt.close(fig)
Solve a linear mixture
Section titled “Solve a linear mixture”In A @ x = b, the matrix A describes a linear transformation, x is an unknown vector, and b is observed. A simplified fluorescence model describes how two sources contribute to two detector channels.
Here, rows of the matrix identify detectors and columns identify sources. The off-diagonal entries describe spillover. These invented coefficients illustrate the mathematics, not a validated compensation procedure.
mixing = np.array([[1.0, 0.2], [0.1, 1.0]])observed = np.array([120.0, 110.0])sources = np.linalg.solve(mixing, observed)print("Estimated source signals:", np.round(sources, 3))print("Reconstructed detectors:", np.round(mixing @ sources, 3))assert np.allclose(mixing @ sources, observed)Estimated source signals: [100. 100.]Reconstructed detectors: [120. 110.]Use a linear solver instead of explicitly computing an inverse. A unique solution requires a square matrix with independent columns. More detector channels than sources lead to a least squares problem. Nearly dependent columns can make the estimate sensitive to measurement error.
The flow cytometry guide explains the experimental controls. The numerical accuracy guide shows why sensitivity matters.
Scaling changes geometry
Section titled “Scaling changes geometry”A gene measured on a much larger scale can dominate Euclidean distance. Standardization changes the geometry by weighting each feature relative to its spread. That can help an analysis, but it can also amplify a noisy feature with little variation.
Choose the transformation from the measurement process and the question. Equal treatment of columns is a modeling decision, not a consequence of matrix algebra.
Check your understanding
Section titled “Check your understanding”Why can two proportional expression profiles have perfect cosine similarity but nonzero Euclidean distance?
Cosine similarity divides out each profile’s length, leaving its direction. Euclidean distance uses the original coordinates, so a change in magnitude remains visible. Choosing between them depends on whether magnitude carries information or reflects an unwanted scale difference.
Further reading
Section titled “Further reading”-
The course develops vector spaces, projections, and linear systems. Its assignments extend the conditions for a unique mixture solution.
-
NumPy linear algebra reference
The reference lists vector norms, linear-system solvers, and least-squares solvers. Compare solve and lstsq when the detector system changes shape or loses rank.
Continue with probability.