Linear Algebra for Machine Learning
Linear Algebra for Machine Learning
Linear algebra provides ways to represent data numerically, transform those representations, compare them, and identify structure in large datasets. Three important machine-learning applications illustrate these ideas:
Data representation: converting information into vectors that computers can process.
Vector embeddings: replacing large or uninformative vectors with smaller vectors that capture useful relationships.
Dimensionality reduction: finding a lower-dimensional space that preserves important structure in the data.
Data Representations: Turning Information into Vectors
Computers work naturally with numbers, while many kinds of information—such as images, language, and user preferences—are not inherently numerical. A common solution is to organize information into a vector, a one-dimensional array of numbers.
A vector’s entries can represent measurements or features of an object. For instance, a patient could be represented by a vector containing height, weight, and age. The entries are useful because each has an interpretation tied to the object being described.
A collection of vectors with the same number of entries belongs to a vector space of that dimension. For example, vectors with three entries are elements of a three-dimensional vector space. In machine learning, a vector space used to represent objects is often called a feature space, and an individual representation is called a feature vector.
Common vector representations
Images: A black-and-white image can be represented by assigning a number to each pixel, such as 0 for black and 1 for white. A grayscale image can assign each pixel a value from 0 to 255. The image initially forms a matrix of pixel values. It can be converted into a vector by listing the first row’s values, followed by the second row’s values, and continuing through the image. This process is often called flattening the image.
Text and documents: A word can be represented by counting how many times it appears in each document. For example, the vector for “dog” might contain one entry per article, with each entry recording the number of occurrences in that article. With many documents, these vectors may have very high dimensions.
User preferences and interactions: A user can be represented by a vector whose entries record interactions with individual items, such as movies. Entries might indicate whether the user watched an item, or record a rating. The vector’s positions correspond to items, and its values describe the user’s interactions with them.
One-hot encodings
When a category or word needs a numerical representation but has no natural numerical value, it can be encoded using a one-hot vector. This is a vector containing one 1 and zeros everywhere else.
For a vocabulary containing “apple,” “cat,” “house,” and “tiger,” each word receives a vector with four entries:
“Apple” is represented by a 1 in the first position.
“Cat” is represented by a 1 in the second position.
“House” is represented by a 1 in the third position.
“Tiger” is represented by a 1 in the fourth position.
All other entries in each vector are 0. In mathematics, these vectors are examples of standard basis vectors. A vocabulary with tens of thousands of words would require vectors with tens of thousands of entries.
Limitations of basic representations
Two important limitations of simple data representations are sparsity and the failure to encode meaningful relationships.
Sparsity: A vector is sparse when most of its entries are zero. One-hot vectors are highly sparse. User–item data can also be sparse: if there are many users and many movies, most users will not have interacted with most movies. Unknown interactions may be stored as zeros, leaving a large matrix dominated by zeros.
Missing relationships: A representation may identify categories as different without expressing how related they are. One-hot vectors for “cat” and “tiger” are just as distinct as the vectors for “cat” and “apple.” The encoding marks each word’s identity but does not express that cats and tigers are more closely related than cats and apples.
These limitations motivate the search for representations that are more compact and that encode useful relationships among data points.
Dot Products and Similarity
The dot product is an operation that combines two vectors of the same length to produce a single number. For vectors with n entries, it multiplies corresponding entries and adds the results:
For example, the dot product of three-entry vectors is:
Geometrically, the dot product is related to how much one vector points in the direction of another. For nonzero vectors, it can also be expressed as:
Here, ∥v∥ and ∥w∥ are the vectors’ lengths, and θ is the angle between them. If one vector has length 1, the dot product gives the signed length of the other vector’s projection onto it. More generally, the dot product depends on both alignment and vector lengths, so it is a useful similarity signal but not a universal measure of similarity in every setting.
For two distinct one-hot vectors, the dot product is 0: their 1s occur in different positions, so every pair of corresponding entries contains at least one zero. Consequently, the one-hot representations of “cat” and “tiger” have the same dot product as those of “cat” and “apple.” This illustrates why one-hot encodings do not capture semantic relationships. A representation intended to reflect similarity needs to place related items in a form that makes their vector relationships meaningful.
Vector Embeddings: Smaller, More Meaningful Representations
A vector embedding represents an object using a vector in a space with fewer dimensions than the object’s original representation. The goal is not simply to shorten a vector: a useful embedding should also preserve or reveal relationships that matter in the data.
For example, an object originally represented by a vector with thousands of entries might be embedded as a vector with only a few dozen entries. The smaller space can make computation more efficient, and its coordinates may capture underlying patterns that are not explicit in the original data.
A useful mental picture is a lower-dimensional space sitting inside a larger one. A two-dimensional plane, for example, is contained within the three-dimensional space around it. In machine learning, embeddings aim to locate a lower-dimensional representation that retains important information from the original data.
Matrices as transformations
A matrix is a two-dimensional array of numbers. A matrix can act on a vector and produce another vector. Geometrically, this action can stretch, shrink, rotate, or otherwise transform vectors. It is best understood as a transformation that acts on an entire vector space, not merely as a rule for changing one individual vector.
When a matrix acts on a vector, the result is often written as:
The matrix A describes the transformation, x is the input vector, and y is the output vector.
Matrices can also be multiplied together. In matrix multiplication, the number of columns in the first matrix must match the number of rows in the second. A product of matrices represents a composition of transformations: applying one matrix and then another can be represented by a single product matrix.
Matrix factorization
Matrix factorization reverses the usual direction of matrix multiplication. Instead of multiplying smaller matrices to obtain a larger matrix, factorization starts with a matrix and seeks matrices whose product equals or approximates it.
The central idea is similar to ordinary number factorization: a number can be written as a product of other numbers, and a matrix can be written as a product of other matrices. Matrix factorizations are useful because the factors may reveal structure that is difficult to see in the original matrix.
One important factorization is the singular value decomposition (SVD). An n×m matrix A can be expressed as:
The factors have special structure:
U and V contain orthonormal columns. Orthonormal vectors have length 1 and are perpendicular to one another.
Σ is a diagonal matrix whose diagonal entries are singular values.
The transpose, written VT, switches the rows and columns of V.
The SVD is a fundamental linear-algebra tool used in fields including machine learning, statistics, physics, genomics, and robotics. Its special structure makes it useful for understanding and compressing matrices.
How factorization produces embeddings
When a data matrix is factorized, rows or columns of the resulting factor matrices can serve as lower-dimensional vector representations of the original data. In this way, factorization can replace a large, sparse representation with a compact vector that may capture recurring patterns.
For example, a user represented by a long vector of movie interactions may receive a much shorter embedding. Instead of recording every movie interaction directly, the embedding can locate the user in a smaller space whose dimensions capture patterns shared across users and movies.
The result is a candidate embedding rather than automatically a perfect one. The useful properties of the embedding depend on the factorization method and the data, and information may be lost when the representation is compressed.
Example: User–Movie Data and Latent Features
A user–movie dataset can be organized as a matrix:
Each row corresponds to a user.
Each column corresponds to a movie.
Each entry records whether the user watched or rated that movie.
A user’s row is a basic vector representation of that user. A movie’s column similarly provides a basic representation of that movie. These vectors directly record observed interactions, but they may be very long and sparse.
The data can also contain latent features: underlying characteristics that are not explicitly recorded in the matrix but may help explain the interactions. For example:
Users may differ by age group or interests.
Movies may differ in audience, genre, or style.
Some movies may appeal to younger audiences, while others appeal to older audiences.
Some may be mainstream blockbusters, while others are more specialized.
A lower-dimensional latent space aims to capture such underlying structure. In a simplified two-dimensional example, one coordinate might represent an audience-related feature and the other might represent a movie-style feature. The exact meaning of each dimension depends on the data and model; it is not necessarily specified in advance.
Factorizing the user–movie matrix can produce one compact vector for each user and another for each movie. If the factorization is useful, users and movies with related interaction patterns may lie near each other in the latent space. For instance, a user whose behavior suggests an interest in a particular kind of movie may have an embedding close to that movie’s embedding.
The dot product between a user embedding and a movie embedding can then help indicate how well they align. A larger dot product may signal a stronger predicted match, depending on the model and how its vectors are scaled. This provides a mathematical basis for tasks such as predicting ratings or recommending items.
Neural Networks as Another Route to Embeddings
Matrix factorization is one way to obtain embeddings. Neural networks provide another. A neural network can take an original, high-dimensional data vector as input and produce a smaller vector as output. That output can be used as an embedding.
A neural network typically contains matrices that transform vectors, along with other components that go beyond basic linear algebra. Multiple such transformations can be combined to learn complex patterns, which connects embeddings to deep learning.
Regardless of whether embeddings come from matrix factorization or a neural network, the broad objective is similar: compress high-dimensional data into a smaller, more meaningful space while retaining important information.
Dimensionality Reduction and Eigenvectors
Dimensionality reduction seeks a lower-dimensional representation of data that preserves important structure. It can improve computational efficiency, reduce resource use, and help reveal patterns that are obscured in a high-dimensional space.
A key linear-algebra concept used in dimensionality reduction is the eigenvector. A matrix transformation generally changes a vector’s length and direction. An eigenvector is a special nonzero vector whose direction does not change under the transformation; it is only scaled.
If M is a matrix, v is an eigenvector, and λ is its eigenvalue, then:
The scalar λ is the eigenvalue. It describes how the transformation scales the eigenvector:
If λ>1, the vector is stretched.
If 0<λ<1, the vector is shortened.
If λ<0, its direction is reversed as well as scaled.
If λ=0, the vector is mapped to the zero vector.
Eigenvectors matter in data analysis because they can describe prominent directions in a dataset.
Principal directions in data
Suppose a dataset contains many data points, each represented as a vector in an m-dimensional space. The vectors can be arranged as the rows or columns of a data matrix, depending on the chosen convention.
Although the data may live in a high-dimensional space, its points may be concentrated near a line or a lower-dimensional subspace. Identifying that subspace helps reveal the main structure of the data and makes it possible to work with fewer dimensions.
A typical approach is to analyze a square matrix derived from the data matrix, such as a covariance matrix or a product involving the data matrix and its transpose. The covariance matrix describes how variables vary together. Centering the data—subtracting each feature’s mean—helps ensure that the analysis describes variation around the data’s average rather than the average location itself.
The eigenvectors of this derived matrix point in characteristic directions of the data. The eigenvector associated with the largest eigenvalue gives a direction in which the data varies most. If the points are concentrated along a line, that direction identifies the line’s principal orientation.
Principal component analysis
This approach underlies principal component analysis (PCA). PCA identifies directions that account for large amounts of variation in the data. These directions are called principal components.
In broad terms, PCA:
Organizes the observations into a data matrix.
Centers the data by subtracting the mean of each feature.
Examines the covariance structure, often through eigenvectors and eigenvalues, or through an equivalent SVD-based calculation.
Selects the directions with the largest eigenvalues.
Represents the data using its coordinates along those directions.
Keeping only a few principal components reduces the number of dimensions. The largest eigenvalues indicate directions that account for more of the data’s variation; smaller eigenvalues correspond to directions with less variation. Reducing dimensions therefore involves a tradeoff: it saves resources but discards some information.
Why dimensionality reduction is useful
Relevant data often occupies only a small portion of a much larger ambient vector space. Finding that smaller space can:
Make storage and computation more efficient.
Focus analysis on the directions where the data varies most.
Reveal patterns that are difficult to notice in the original representation.
Provide compact representations for later machine-learning tasks.
Dimensionality reduction does not guarantee that every important property will be preserved. The selected dimensions and the information discarded need to be appropriate for the task.
Key Connections
Vectors encode objects as ordered numerical features.
Dot products provide a way to assess alignment between vectors, but the usefulness of that comparison depends on the representation.
One-hot encodings distinguish categories but do not, by themselves, express meaningful similarities among them.
Embeddings map objects into smaller vector spaces where useful relationships may be represented.
Matrix factorization, including SVD, can reveal compact representations within large data matrices.
Eigenvectors and PCA identify directions that capture prominent structure or variation, supporting dimensionality reduction.
The central principle is that linear algebra helps transform raw data into representations that are more compact, computationally manageable, and informative.

Ask anything
We've read this whole study set, so questions about it get the best answers.