26 Important Concepts that you should learn in Linear Algebra for Machine Learning — PART II
From the publisher’s feed, collected in the ZeroLabs newsroom.
26 Important Concepts that you should learn in Linear Algebra for Machine Learning — PART IILinear Algebra, being one of the most important subjects, is essential for anyone who’s working with data and predictive algorithms. This is Part II of the two-part linear algebra series.You can read Part I of this series and continue with this blog.26 Important Concepts that you should learn in Linear Algebra for Machine Learning — PART IIronically, most people ask how much math is enough for machine learning. While there is no universal quantitative answer available, it is evident that you need math to understand machine learning. At any point, if you feel you don’t understand any derivation or mathematical definition, you have to brush up on your mathematical concepts.If you are a complete beginner, this is a great place to start and get a bigger picture of how things work together. If you are already familiar with mathematics, this blog could help you to brush up and rewire your mathematical knowledge. The earlier part of this series covered the most fundamental concepts of linear algebra. This part intends to cover more advanced and interesting concepts, and it’s real-time applications in machine learning.14. Inner ProductsInner tells you how similar two vectors are and how much one vector “projects” onto another.Why inner products matter in ML?import numpy as npu = np.array([1, 2, 3])v = np.array([4, 5, 6])# Inner productdot = np.dot(u, v)print("Dot product:", dot) # 1*4 + 2*5 + 3*6 = 32# Normsnorm_u = np.linalg.norm(u)norm_v = np.linalg.norm(v)# Cosine similaritycos_sim = dot / (norm_u * norm_v)print("Cosine similarity:", cos_sim)# Projection of u onto vproj = (dot / (norm_v**2)) * vprint("Projection:", proj)15. Orthogonal vectorsTwo vectors are said to be orthogonal when their inner product is zero.Geometrically, this means that the vectors are at a 90° angle to each other.Orthogonality implies no linear dependence along the direction of each other.In the context of machine learning:Feature independenceSimplifying computationsReduces multicollinearityimport numpy as np# Define two vectorsu = np.array([1, 0])v = np.array([0, 1])# Check orthogonalitydot_product = np.dot(u, v)print("Dot product:", dot_product) # 0 → orthogonal# Orthonormal vectorsu_norm = u / np.linalg.norm(u)v_norm = v / np.linalg.norm(v)print("Are they orthonormal?", np.isclose(np.dot(u_norm, v_norm), 0))16. ProjectionsA projection is an operation of mapping a vector onto a subspace. Intuitively, it is about dropping a high-dimensional vector onto a direction or plane. The projected vector is the closest point (Euclidean distance) to the original vector within the subspace.The projection is mainly used in linear regression, PCA dimensionality reduction, denoising, embedding, etc.In ML, “projection” generally refers to dimensionality reduction, where high-dimensional data is mapped to a lower-dimensional space to make it easier to visualize, analyze, or train models.17. Orthonormal basesimport numpy as npA = np.array([ [1, 1], [1, 0]])Q, R = np.linalg.qr(A)print("Orthonormal basis (Q):")print(Q)18. Gram-Schmidt ProcessThe Gram-Schmidt process is used to convert a set of vectors into an orthonormal basis. There are two basic concepts:Orthogonality: Two vectors are orthogonal if the dot product equals zero. This implies that they are 90 degrees to one another.Normalization: A vector becomes normalized if its magnitude equals one. It is achieved by dividing all elements of the vector by its magnitude. Normalization ensures data does not get affected by differences in scale and stabilized learning algorithms.Step-by-Step ProcedureThe Gram-Schmidt process accepts a set of linearly independent vectors and converts them into an orthonormal set.Key benefits of the Gram-Schmidt Process:1. Numerical Stability2. Dimensionality Reduction3. Effective Matrix Decomposition4. Feature Selectionimport numpy as npdef gram_schmidt(V): """ Classical Gram-Schmidt process. Input: V is a matrix whose columns are the vectors v1, v2, ..., vk Output: Q is a matrix whose columns are the orthonormal basis u1, u2, ..., uk """ V = np.array(V, dtype=float) n, k = V.shape Q = np.zeros((n, k)) for i in range(k): # Start with v_i qi = V[:, i] # Subtract projections onto previous q_j for j in range(i): proj = np.dot(Q[:, j], qi) * Q[:, j] qi = qi - proj # Normalize Q[:, i] = qi / np.linalg.norm(qi) return QV = np.array([ [1, 1], [1, 0]])Q = gram_schmidt(V)print("Orthonormal basis (Classical GS):")print(Q)19. Eigenvalues and EigenvectorsEigenvalues and Eigenvectors in PCAPCA identifies the directions in data where the variance is high and marks the directions as important.These directions are the eigen vectors of the covariance matrix of the dataEach eigen vector points in a direction that captures some structure in the data, such as a pattern, trend, or relationship.The corresponding eigenvalue represents how much variance lies along the direction.import numpy as np# Example matrixA = np.array([ [4, 2], [1, 3]])# Built-in functioneigenvalues, eigenvectors = np.linalg.eig(A)print("Eigenvalues:")print(eigenvalues)print("\nEigenvectors (columns):")print(eigenvectors)# verify the eigen equationfor i in range(len(eigenvalues)): v = eigenvectors[:, i] λ = eigenvalues[i] print("\nCheck for eigenvalue:", λ) print("A @ v:", A @ v) print("λ * v:", λ * v)20. DiagonalizationMatrix Diagonalization is the process of reducing a square matrix into its diagonal form using a similarity transformation.A matrix is diagonalizable if it has no defective eigenvalues, meaning each eigenvalue’s geometric multiplicity is equal to its algebraic multiplicityOnce a matrix is diagonalized, it becomes very easy to raise it to integer powers.Diagonalization appears almost everywhere in machine learning.It helps to convert a complicated transformation into a simple, independent one-dimensional problem.It is mainly used in PCA (diagonalization of the covariance matrix), Decorrelating data, Ridge regression, solving optimization problems efficiently, etc.import numpy as npA = np.array([[4, 1], [2, 3]])# Step 1: eigenvalues & eigenvectorseigenvalues, eigenvectors = np.linalg.eig(A)# Step 2: Construct D (diagonal matrix)D = np.diag(eigenvalues)# Step 3: Matrix P (eigenvectors)P = eigenvectors# Step 4: Find P inverseP_inv = np.linalg.inv(P)# Step 5: Reconstruct A (should be equal to original A)A_reconstructed = P @ D @ P_invprint("Eigenvalues:\n", eigenvalues)print("Eigenvectors (P):\n", P)print("Diagonal matrix D:\n", D)print("P inverse:\n", P_inv)print("Reconstructed A:\n", A_reconstructed)21. Symmetric Matricesimport numpy as np# Symmetric matrixA = np.array([[2, 1, 0], [1, 2, 1], [0, 1, 2]])# Verify symmetryprint("Is symmetric:", np.allclose(A, A.T))# Eigen decompositioneigvals, eigvecs = np.linalg.eigh(A) # eigh is optimized for symmetric/hermitianprint("Eigenvalues:", eigvals)print("Eigenvectors (columns):\n", eigvecs)# Verify orthogonality of eigenvectorsprint("Q^T Q:\n", eigvecs.T @ eigvecs) # Should be identity22. Spectral TheoremThe spectral theorem is about the result produced when the matrix is diagonalized.This is extremely useful because computations involving a diagonalizable matrix can often be reduced to much simpler computations involving the corresponding diagonal matrix.The spectral theorem states that “any symmetric matrix can be rotated so that in the new coordinate system it only stretches or shrinks along certain directions, with no rotations”.23. Singular Value Decompositionimport numpy as npimport matplotlib.pyplot as plt# Example: random 5x4 matrixX = np.random.randn(5, 4)# SVDU, S, VT = np.linalg.svd(X, full_matrices=False)print("U:\n", U)print("Singular values:", S)print("V^T:\n", VT)# Rankrank = np.sum(S > 1e-10)print("Rank of X:", rank)# Low-rank approximation (keep top 2 singular values)k = 2U_k = U[:, :k]S_k = np.diag(S[:k])VT_k = VT[:k, :]X_approx = U_k @ S_k @ VT_kprint("Low-rank approx:\n", X_approx)24. NormsNorms are directly built from inner products:Why it’s important:Defines the distance between data pointsUsed in gradient descentEssential for regularization (L1, L2)Forms the basis of cosine similarityThis pairs naturally with inner products since the two are mathematically linked.25. Cosine SimilarityCosine similarity measures the similarity between two non-zero vectors by calculating the cosine of the angle between them. Similarity measure calculates the distance between data objects based on their feature dimensions in a dataset. A smaller distance indicates a higher similarity, while a larger distance indicates a lower similarity. Cosine similarity is a metric, helpful in determining how similar the data objects are, irrespective of their size.26. Positive Semi-Definite (PSD) MatricesThis is equivalent to the matrix having all non-negative eigenvaluesIn ML, many algorithms — especially SVMs, Gaussian Processes, Kernel PCA, Spectral Clustering — require the kernel matrix to be positive semi-definite.PSD matrices ensure valid inner products in high-dimensional (possibly infinite-dimensional) feature spaces.Understanding PSD matrices gives insight into:Why some similarity functions qualify as kernels and others do notHow optimization behaves in convex settingsStability and geometry of many ML algorithms“Machine learning is nothing without mathematics” — I have heard a lot of them saying this. However, I truly understood it only when I deep dived into the machine learning algorithms. A solid understanding of linear algebra concepts helps to understand how machine learning works in a better and effective way.With that, this blog comes to an end. This is only the beginning! I’m also planning to write detailed articles on probability, statistics, and calculus for machine learning, so stay tuned for more posts that will help you strengthen your mathematical foundation for ML.If this series helped you, consider following me to get updates — there’s plenty more interesting stuff on the way.Note: Most of the content is represented as images due to the lack of LaTeX compatibility in Medium.References:https://www.geeksforgeeks.org/machine-learning/orthogonalization-for-machine-learning/https://www.geeksforgeeks.org/machine-learning/gram-schmidt-process-for-ml/https://medium.com/@HannahIgboke/making-sense-of-eigenvectors-and-eigenvalues-with-a-loaf-of-bread-5bc4980377d4https://www.statlect.com/matrix-algebra/matrix-diagonalizationhttps://www.geeksforgeeks.org/dsa/matrix-diagonalization/https://en.wikipedia.org/wiki/Symmetric_matrixhttps://en.wikipedia.org/wiki/Spectral_theoremhttps://www.geeksforgeeks.org/dbms/cosine-similarity/https://en.wikipedia.org/wiki/Definite_matrix26 Important Concepts that you should learn in Linear Algebra for Machine Learning — PART II was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.