Orthonormalise a set of vectors with Gram-Schmidt
Many tricks need a set of directions that are all at right angles and all of length 1. Gram-Schmidt builds that from any set of vectors: take each vector, subtract its shadow on the ones you already have, and normalise what is left.
Write gram_schmidt(V) where the rows of V are vectors. Return a matrix with the same shape whose rows are orthonormal and span the same space, processed in row order.
You may assume the rows are linearly independent.
def gram_schmidt(V)Understand the idea
Gram-Schmidt turns any set of independent vectors into an orthonormal set: all at right angles and all of length 1. Take each vector in order, remove its shadow on every direction you already have, then scale what is left to length 1. Like straightening a leaning pole so it stands exactly upright. Worked example: v1 = [3, 4] has length 5, so u1 = [0.6, 0.8]. Next v2 = [1, 0]. Its shadow on u1 has size v2 . u1 = 0.6, so subtract 0.6 * [0.6, 0.8] = [0.36, 0.48], leaving [0.64, -0.48]. Its length is 0.8, so u2 = [0.8, -0.6]. Check: u1 . u2 = 0.48 - 0.48 = 0. Rule: w = v; for each kept u, w = w - (w . u) u; then u_new = w / |w|. Using the partly cleaned w each time (the modified version) is more stable. QR decomposition, and orthogonal initialisation of neural network weights, rest on this procedure.