Linear Algebra and Matrix Mechanics for Machine Learning
vector spaces, matrix operations, and mathematical representations of data
Core Concepts Covered
- Vectors, operations, dot products, and angles
- Matrix operations, systems of linear equations, and inverses
- Vector spaces, linear independence, basis, and transformations
Local Setup Recommendation
To execute and experiment with the code cells below on your local machine, ensure you have set up your isolated virtual environments and scientific libraries by following the detailed protocols in Unit 03: Environment Setup or run them in Google Colab.
1. Vectors, Dot Products, and Semantic Similarities
Machine learning turns data into vectors. One vector can describe a single sample, and a matrix can hold many samples at once. Linear algebra tells us how to compare, transform, and combine those representations, even when they have thousands of dimensions.
A vector is an ordered sequence of real numbers. We can add vectors element-wise and multiply them by scalar values.
The Dot Product (or inner product) of two vectors multiplies corresponding elements and sums the results, producing a single scalar. The formula is:
Semantic Similarity Example: In Natural Language Processing, words are represented as numeric vectors ('word embeddings'). Suppose the word king is mapped to and the word queen to . Their dot product is . Mathematically, the dot product is related to the angle between the vectors by . By calculating the cosine similarity , we measure how semantically similar the words are. Here: A cosine similarity of (close to ) shows that the model successfully understands these words are highly related!
A set of vectors spans a vector space if any coordinate in that space can be reached through a linear combination of those vectors. If no vector in a set can be written as a linear combination of the others, the vectors are linearly independent. A set of linearly independent vectors that spans a space forms a basis.
A Matrix Transforms Basis Vectors
Read diagram labels
- original basis
- columns of A
- A →
Independence and Coordinates
Do and form a basis for the two-dimensional real coordinate space, ? Express in that basis.
1.Place the vectors in . Since , its columns are independent and form a basis.
2.Solve and . This gives and .
Therefore .
A nonzero determinant certifies that two vectors span the plane without redundancy.
2. Matrix Mechanics and Linear Transformations
A matrix is a 2D grid of numbers representing a linear transformation. When we multiply a matrix by a vector (written as ), we are geometrically transforming the vector (scaling, rotating, or projecting it) into a new coordinate space.
Shape compatibility is non-negotiable: can multiply because the inner dimensions match, and the result has the outer dimensions:
• Matrix Multiplication (): To compute elements of , we take the dot product of the -th row of with the -th column of :
• Determinant (): A scalar measuring how much the linear transformation scales the area or volume of space. If , the matrix squashes space into a lower dimension (e.g. flatting a 2D plane into a 1D line), meaning the matrix is singular and cannot be inverted.
• Matrix Inverse (): If an inverse exists, . It can express as , although numerical software normally solves the system directly.
For a machine-learning batch and weights , the score matrix has shape : one row per sample and one column per output. A bias is broadcast across all 32 rows.
Matrix Multiplication Shape Flow
Read diagram labels
- A: 3 × 4
- ×
- B: 4 × 2
- =
- C: 3 × 2
- inner dimensions 4 must match
import numpy as np
# Define matrices A and B
A = np.array([[2, 1], [1, 3]])
B = np.array([[1, 0], [2, 1]])
# 1. Matrix Multiplication (AB)
C = np.dot(A, B) # Or: A @ B
print("Matrix C = A @ B:\n", C)
# 2. Compute Determinant of A
det_A = np.linalg.det(A)
print("Determinant of A:", round(det_A, 2))
# 3. Compute Matrix Inverse of A
A_inv = np.linalg.inv(A)
print("Inverse of A:\n", A_inv)
print("A_inv @ A (Identity):\n", np.round(A_inv @ A))Matrix C = A @ B:
[[4 1]
[7 3]]
Determinant of A: 5.0
Inverse of A:
[[ 0.6 -0.2]
[-0.2 0.4]]
A_inv @ A (Identity):
[[1. 0.]
[0. 1.]]Matrix–Vector Multiplication Entry by Entry
Compute for and .
1.The first output is the first row dotted with : .
2.The second output is .
Thus ; the shape is .
Matrix–Matrix Multiplication and Shape
Multiply by .
1. and .
2. and .
. The shape trace is .
3. Vector and Matrix Norms
In machine learning, we need to measure the size, length, or magnitude of vectors and matrices (especially inside regularization terms to prevent overfitting). We calculate magnitude using mathematical functions called norms.
• Norm (Taxicab Norm): Sums the absolute values of the vector coordinates. It promotes sparsity (forcing weights to exactly zero, helpful for feature selection):
• Norm (Euclidean Norm): Measures the standard straight-line distance from the origin. It is the most common norm used in weight decay and Ridge regressions:
• Frobenius Norm (for matrices): Measures the overall scale of a matrix by taking the square root of the sum of all squared entries:
Norms and Regularization
For , calculate and .
1..
.
and measure size differently, so their regularizers encourage different weight patterns.
Cumulative Linear-System Check
For and , solve and verify the result.
1.Elimination gives and .
.
Interactive Practice Quiz
Test your understanding with instant feedback
Calculate the dot product of vectors and :
Under what condition does a square matrix NOT have an inverse matrix ?
Which vector norm promotes weight 'sparsity' (forcing parameter weights to be exactly zero) during regularization optimization?
Calculate the Norm of the coordinate vector :
If a set of vectors spans a space and is completely linearly independent, what is this set called?
Compute the matrix-vector product where and :
Compute the determinant of the matrix :
Compute the Frobenius Norm of the matrix :
If two vectors and have a cosine similarity of , what does this mathematically represent?
What is the key characteristic of an Identity Matrix ?
Further Readings
Explore these highly recommended external references to deepen your understanding
Mathematics for Machine Learning
https://mml-book.github.io/
NumPy: Matrix Products
https://numpy.org/doc/stable/reference/generated/numpy.matmul.html
NumPy Linear Algebra Documentation
https://numpy.org/doc/stable/reference/routines.linalg.html
3Blue1Brown: Essence of Linear Algebra
https://www.3blue1brown.com/topics/linear-algebra
