Project vectors onto the span of a few basis vectors
Removing a direction from embeddings, or keeping only the top principal components, is a projection.
Write project(V, B). V has shape (n, d) of vectors to project. B has shape (k, d) of linearly independent basis vectors that are not necessarily orthonormal. Return the (n, d) projections of each row of V onto span(B), using P = B.T (B B.T)^-1 B.
def project(V, B)Example
V = [[3, 4]], B = [[1, 0]] gives [[3, 0]].
Understand the idea
Projecting a vector onto a subspace finds its closest point in that subspace, like the shadow a stick casts on the floor. If the basis vectors are not unit length or not at right angles, you cannot just take dot products with them; you must solve a small k by k system that corrects for their lengths and overlaps. Worked example: V = [[3, 1]], B = [[1, 1]]. B B^T = 2, B v = 3 + 1 = 4, so the coefficient is 4 / 2 = 2 and the projection is 2 * [1, 1] = [2, 2]. The leftover [1, -1] is at right angles to B, as it should be. With a scaled basis B = [[2, 0]] and V = [[2, 3]]: B B^T = 4, B v = 4, coefficient 1, projection [2, 0]. Rule: P = B^T (B B^T)^-1 B, and each projected row is P v; in practice solve (B B^T) c = B v rather than forming an inverse. Assuming an orthonormal basis gives the wrong length for scaled or skewed bases. Used to remove a bias direction from embeddings and in PCA.