Zero Labs
Industry News / AI

26 Important Concepts that you should learn in Linear Algebra for Machine Learning — PART I

Source · Towards AI By Rajendran S

From the publisher’s feed, collected in the ZeroLabs newsroom.

26 Important Concepts that you should learn in Linear Algebra for Machine Learning — PART IMachine Learning is the most fascinating field in the era of AI development. While many people put effort into learning machine learning, most of them fail to understand the core mathematics behind predictive models. You don’t need to learn very advanced math like PhD students do. You need to know very few fundamentals to understand things better in the world of machine learning. Especially, you will have to learn the basics in four domains:Linear AlgebraCalculusProbabilityStatisticsOnce you master these, you can break down any complex derivation that you see in the machine learning papers. Moreover, it helps to understand how traditional ML algorithms work. This blog dives into the most important concepts that you will have to know in linear algebra. This is a two-part blog, which has 13 concepts each. Each concept will be explained in terms of intuition, layman's explanation, formal and mathematical definition, and its application in machine learning.What is Linear Algebra?Linear algebra is the branch of mathematics that deals with vectors, matrices, and linear transformations. Its significance in machine learning cannot be overstated, as it provides the tools necessary to handle high-dimensional data and perform operations that are integral to the algorithm's functioning. It acts as the backbone of machine learning.Why do we need to learn linear algebra?Machine learning is impossible without linear algebra. All the significant operations that an ML engineer performs involve vectors and linear transformations.1. Data is stored as vectors and matrices: A grayscale image is stored as 2D matrix, colored images as a 3D matrix, and training data as a giant matrix.2. Neural networks are matrix multiplication machines: Every forward pass in a neural network is basically a linear transformation.3. Optimization uses gradients: Optimization techniques such as gradient descent, Lagrange multipliers, and Kuhn-Tucker conditions use gradients. Gradients are vectors, and Hessians are matrices.4. ML Inheritance from Linear Algebra: We get a lot of interesting ML concepts from linear algebra.Principal Component Analysis is made up of eigen vectors and eigen valuesSingular Value Decomposition is about matrix factorizationAttention is about dot products1. Scalars, Vectors, Matrices, and TensorsScalarsA scalar is a single numerical value that conveys magnitude but no direction or dimension.It is a zero-dimensional entity, meaning it cannot be decomposed into smaller parts.All numerical values can be represented as a scalar.In machine learning, the evaluation metrics, loss functions, mean, and variance are represented as scalar values.accuracy = 0.98 # scalar valueprint(accuracy)VectorsVectors are a one-dimensional array of numerical values representing both magnitude and direction in space.They help to represent features, weights, or data points where the dimension reflects one characteristic or attribute.import numpy as npvector = np.array([1, 2, 3, 4, 5])print(vector)MatricesA matrix is a two-dimensional grid or rectangular array of numbers arranged in rows and columns.It provides a structured representation of data where each row denotes an instance, and each column denotes a feature.Most of the training datasets are in the form of matrices.import numpy as npmatrix = np.array( [ [1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12] ])print(matrix)TensorsA tensor is a multidimensional generalization of scalars, vectors, and matrices.It can represent data in terms of three or more dimensions.It is more suitable for modeling high-dimensional data and complex relationships across multiple axes.Tensors are the core data structures in frameworks like TensorFlow and PyTorch, enabling efficient computation and automatic differentiation on GPUs.import numpy as nptensor = np.array( [ [[1,2], [2, 3]], [[3, 4], [4, 5]], [[5, 6], [6, 7]] ])print(tensor)2. Notations used in ML papers and frameworksYou will encounter a bunch of mathematical notations when reading about machine learning algorithms. Notations help to describe an algorithm, data preparation, results, test harness, or implications. Understanding the notations helps to read ML papers in an efficient way.3. Vector OperationsVectors enable mathematical transformations such as rotation, scaling, and translation. These are employed in methods such as Principal Component Analysis (PCA) to project datasets into lower dimensions. They are also used to determine the similarity between data points using Euclidean distance and cosine similarity.import numpy as npa = np.array([1, 2])b = np.array([2, 3])add = a + b # additionsub = a - b # subtractions = 3res = s * a # scalar multiplicationprod = np.dot(a, b) # dot productcprod = np.cross(a, b) # cross product4. Matrix OperationsMatrices are everywhere — machine learning, graphics, physics, optimization, and even Google’s PageRank. Understanding matrix operations helps you understand how data moves and transforms inside algorithms. A matrix is a rectangular grid of numbers arranged in rows and columns.import numpy as npA = np.array([[1,2,3], [4,5,6], [7,8,9]])B = np.array([[1,4,3], [5,8,6], [3,8,9]])C = A + B # additionD = A - B # subtractionE = A // B # divisionF = A.dot(B) # dot productb = 2G = A * b # matrix-scalar multiplicationv = [1, 2, 3]H = B * v # matrix-vector multiplication5. Linear Combinations6. Spans and SubspacesSpanThe span of a set of vectors is all the possible vectors that can be created using linear combinations of those vectors.SubspaceA subspace is any subset of a vector space thatcontains the zero vectoris closed under additionis closed under scalar multiplicationA subspace is a smaller space living inside a bigger space, formed by the span of some vectors. PCA finds the subspace where the data mostly lies during dimensionality reduction. Encoder compresses data into a latent subspace7. Linear Independence and RanksLinear IndependenceRankThe rank of a matrix $A$ is the maximum number of linearly independent rows or columns.The ranks help us to determine:How much unique information does the matrix containHow many independent directions does it map space intoHow many features or components actually matterIf rank multicollinearityunstable linear regressionPCA automatically reduces the dimension to rank8. Solving Linear Systemsimport numpy as np# Coefficient matrix A and vector bA = np.array([[2, 3], [4, -1]], dtype=float)b = np.array([5, 1], dtype=float)res = np.linalg.solve(A, b)print(res)9. Row ReductionRow reduction transforms a matrix step-by-step into a simpler version of itself without changing its solution set. All the allowed row operations keep the system logically the same.Three allowed moves:1. Swap rows2. Multiply a row by a non-zero constant3. Add/ subtract multiples of rows.Every pivot fixes one variable and turns the equation system into a staircase shape. It strips the system down from many equations to a few key ones.When reduction,If a row becomes [0 0 0 | 1] -> inconsistent systemIf a row becomes [0 0 0 | 0] -> redundant equationThus, the row reduction answer for:Solution exists?unique or infinite?How many independent equations?Rank of matrix?Application: Gaussian Elimination10. Matrix as a Linear TransformationEssentially, linear transformations preserve vector addition and scalar multiplication.In the context of machine learning,Feature transformationsDimensionality reductionLinear modelsData geometryimport numpy as npimport matplotlib.pyplot as plt# Original vectorsX = np.array([[1, 2], [3, 4], [5, 6]])# Linear transformation matrixA = np.array([[2, 0], [0, 3]])# Apply transformationY = X @ A # same as np.dot(X, A)print("Original:\n", X)print("Transformed:\n", Y)# Plotplt.scatter(X[:,0], X[:,1], color='blue', label='Original')plt.scatter(Y[:,0], Y[:,1], color='red', label='Transformed')plt.legend()plt.show()11. Geometric Effects: Rotate, Reflect, Scale, and Shearimport numpy as npimport matplotlib.pyplot as plt# Original squareX = np.array([[0,0],[1,0],[1,1],[0,1],[0,0]]).T # 2x5# Matricesscale = np.array([[2,0],[0,1.5]])rotate = np.array([[0, -1],[1, 0]]) # 90 degreesreflect = np.array([[1,0],[0,-1]]) # x-axisshear = np.array([[1,0.5],[0,1]]) # horizontalmatrices = [scale, rotate, reflect, shear]titles = ["Scale", "Rotate", "Reflect", "Shear"]plt.figure(figsize=(10,2.5))for i, M in enumerate(matrices): Y = M @ X plt.subplot(1,4,i+1) plt.plot(X[0], X[1], 'b-', label='Original') plt.plot(Y[0], Y[1], 'r--', label='Transformed') plt.axis('equal') plt.title(titles[i])plt.show()12. Determinantsimport numpy as npA = np.array([[2, 0], [0, 3]])det = np.linalg.det(A)print("Determinant:", det) # Output: 6.0# Geometric interpretationsquare_area = 1 # unit squaretransformed_area = abs(det) * square_areaprint("Transformed area:", transformed_area) # 6.013. Inverse Matrices and Pseudo-Inverseimport numpy as npA = np.array([[2, 0], [0, 3]])A_inv = np.linalg.inv(A)print("Inverse:\n", A_inv)# Verifyprint("\nA x A_inv =\n", A @ A_inv)import numpy as np# Rectangular matrix (3x2)X = np.array([[1, 2], [3, 4], [5, 6]])y = np.array([7, 8, 9])# Compute pseudo-inverseX_pinv = np.linalg.pinv(X)# Solve linear systemw = X_pinv @ yprint("Weights:", w)# Check predicted valuesy_pred = X @ wprint("Predictions:", y_pred)This brings us to the end of Part I of this two-part series on fundamental linear algebra concepts for machine learning. We covered the 13 most important concepts that form the backbone of modern ML techniques — from vectors and matrices to transformation and inverses.In Part II, we will go deeper into advanced topics and tie everything together with practical ML intuition. Each concept you learn brings you one step closer to truly understanding how ML works under the hood.I’m also planning to write more blogs on probability, statistics, and calculus. If you found this helpful, feel free to follow me on Medium so you can catch the upcoming parts and related topicsNote: Most of the content is represented as images due to the lack of LaTeX compatibility in Medium.References:1. https://www.geeksforgeeks.org/machine-learning/difference-between-scalar-vector-matrix-and-tensor/2. https://machinelearningmastery.com/basics-mathematical-notation-machine-learning/3. https://www.geeksforgeeks.org/machine-learning/vectors-for-ml/4. https://www.geeksforgeeks.org/machine-learning/matrices-and-matrix-arithmetic-for-machine-learning/5. https://www.geeksforgeeks.org/engineering-mathematics/linear-combinations/26 Important Concepts that you should learn in Linear Algebra for Machine Learning — PART I was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.