Mathematical Foundations for Machine Learning in NLP
local graph
Chapter 2 — Mathematical Foundations for Machine Learning in NLP
Section titled “Chapter 2 — Mathematical Foundations for Machine Learning in NLP”Modern machine learning (ML) and NLP are grounded in a rich mathematical framework. To build, analyze, and improve today’s AI systems, you must understand the fundamental mathematical tools that allow these models to represent data, quantify uncertainty, and optimize performance. In this chapter, you’ll explore several of these essential concepts, including:
- An introduction to linear algebra
- Eigenvalues and eigenvectors
- Basic probability for machine learning
These topics form the backbone of NLP and ML because they provide the language and structure with which models operate. Linear algebra enables you to express text, images, and signals as vectors and matrices, making it possible to apply transformations, extract meaningful features, compute similarities, and ultimately model relationships within data. Probability theory equips you to quantify uncertainty, estimate distributions, and perform principled inference, all key ingredients in predictive modeling, generative language systems, and decision-making under uncertainty.
Together, these mathematical foundations underpin many of the systems discussed throughout this book, from word embeddings and attention mechanisms to large language models, classification architectures, and sequence-to-sequence frameworks. Developing a strong grasp of these areas will prepare you to understand both the theoretical underpinnings and the practical implementations of modern AI systems.
This chapter provides a comprehensive yet accessible introduction to these core concepts. We begin with the essentials of linear algebra: vectors, matrices, and the operations that govern them, including dot products, norms, matrix multiplication, and eigenvalue–eigenvector decomposition. These tools form the computational basis for representing high-dimensional linguistic and visual data. For example, even a simple three-dimensional representation of a document, capturing word frequency, sentiment, and syntactic complexity, relies on vector algebra to encode and compare information.
Next, we introduce key ideas in probability and statistics that are fundamental to machine learning. Concepts such as random variables, probability distributions, expectation, variance, correlation, and Bayes’ theorem will be illustrated through practical examples rooted in NLP tasks. Understanding these statistical principles will help you interpret uncertainty, evaluate model performance, and reason about data-driven predictions.
To connect these ideas with real ML workflows, we also introduce foundational optimization principles. Optimization plays a central role in learning algorithms by guiding model parameters to minimize loss functions, maximize likelihoods, and adapt efficiently to complex datasets.
By the end of this chapter, you will have developed a strong mathematical foundation to support your work in NLP and ML. Whether you are fine-tuning a transformer model, designing a new text classifier, or implementing a novel embedding technique, the concepts introduced here will serve as a crucial guide throughout the more advanced chapters that follow.
Introduction to linear algebra
Section titled “Introduction to linear algebra”Let’s start by first understanding scalars, vectors, and matrices:
- Scalars: A scalar is a single numerical value, typically drawn from the real numbers in most machine learning applications. In NLP, common examples include quantities such as the frequency of a word in a corpus, or the probability assigned to a particular token.
- Vectors: A vector is a collection of numerical elements. Each of these elements can be termed as an entry, component, or dimension, and the count of these components defines the vector’s dimensionality. Within NLP, a vector could hold components related to elements such as word frequency, sentiment ranking, and more.
- Matrices: A matrix can be perceived as a rectangular collection of numerical elements composed of rows and columns. To retrieve an element from the matrix, one needs to denote its row and column indices. In the field of NLP, a data matrix might include rows that align with distinct text documents and columns that align with different text attributes, such as word frequency, sentiment, and so on. The dimensions of such a matrix are represented by the notation, where is the number of rows (i.e., text documents), and is the number of columns (i.e., attributes).
Let’s move on to the basic operations for scalars, vectors, and matrices next.
The basic operations for scalars, vectors, and matrices, which are addition and subtraction, can be carried out on vectors with the same dimensions. Let’s have two vectors:
Then the vector subtraction can be defined as follows:
For example, if we have two vectors, a = [4,1] and b = [2,4], then a + b = [6,5].
Let’s visualize this as follows:

Figure 2.1 – Adding two vectors (a = [4,1] and b = [2,4]) means that a + b = [6,5]
It is possible to scale a vector by multiplying it by a scalar. This operation is performed by multiplying each component of the vector by the scalar value. For example, let’s consider an n-dimensional vector, The process of scaling this vector by a factor of ‘’ can be represented mathematically as follows:
This operation results in a new vector that has the same dimensionality as the original vector but with each component multiplied by the scalar value.
There are two primary ways to multiply vectors: the dot product and the cross product. Both operations serve different purposes and capture different geometric relationships between vectors.
The dot product is a mathematical operation that can be applied to two vectors, and. It has many practical applications, one of which is to help determine their similarity. It is defined as the sum of the products of the corresponding elements of the two vectors. The dot product of and is represented by the symbol (having a dot in the middle) and is defined as the following:

Where n represents the dimensionality of the vectors. The dot product is a scalar quantity and can be used to measure the angle between two vectors, as well as the projection of one vector onto another. It also serves a vital function in numerous machine learning algorithms, including linear regression and neural networks.
The dot product is commutative, meaning that the order of the vectors does not affect the result. This means that. Furthermore, the dot product maintains the distributive property of scalar multiplication, implying the following:
The dot product of a vector with itself is also known as its squared norm or Euclidean norm. The norm, symbolized by, signifies the length of the vector and is computed as:

The normalization of vectors can be achieved by dividing them by their norm, also known as the Euclidean norm or the length of the vector. This results in a vector with a unit length, denoted by. The normalization process can be shown as

Where is the original vector and
represents its norm. It should be noted that normalizing a vector retains its direction while setting its length to 1, allowing for the meaningful comparison of vectors in different spaces.
The cosine similarity between two vectors and is mathematically represented as the dot product of the two vectors after they have been normalized to unit length. This can be written as:

Where
and
are the norms of the vectors and, respectively. This computed cosine similarity between and is equivalent to the cosine of the angle between the two vectors, denoted as.
Vectors with a dot product of 0 are deemed orthogonal, implying that in the case of having both non-0 vectors, the angle between them is 90 degrees. We can conclude that a 0 vector is orthogonal to any vector. A group of vectors is considered orthonormal if each pair of distinct vectors is orthogonal and each vector possesses a norm of 1. Such orthonormal sets prove to be valuable in numerous mathematical contexts. For instance, they come into play when transforming between different orthogonal coordinate systems, where the new coordinates of a point are computed in relation to the modified direction set. This approach, known as coordinate transformation in the field of analytical geometry, finds widespread application in the realm of linear algebra. For example consider vectors
,,. Their pairwise dot products are:
and each vector has norm 1. Therefore, they form an orthonormal set. This orthonormal basis corresponds to the standard x, y, and z axes.
Basic operations on matrices and vectors
Section titled “Basic operations on matrices and vectors”Matrix transpose is the process of obtaining the transpose of a matrix and involves interchanging its rows and columns. This means that the element originally at the position in the matrix now occupies the position in its transpose. As a result, a matrix that was originally of size becomes an matrix when transposed. The transpose of a matrix is denoted by. Here is an illustrative example of a matrix transposition operation:


Crucially, the transpose of the transpose of matrix, that is, reverts to the original matrix. Moreover, it is clear that row vectors can be transposed into column vectors and vice versa. Additionally, the following holds true for both matrices and vectors:
It’s also noteworthy that dot products are commutative for vectors:
This is for, column vectors.
Matrix multiplication is not commutative, meaning that the order of the matrices being multiplied can affect the result. However, it is associative, meaning that the grouping of the matrices being multiplied does not matter. This can be expressed as (associativity). Additionally, matrix multiplication is distributive, meaning that it follows the same rules of distribution as scalar multiplication. This can be expressed as and (distributivity).
Matrix definitions
Section titled “Matrix definitions”In this section, we’ll cover the different types of matrix definitions:
- Symmetric matrix: A symmetric matrix is a type of square matrix where the transpose of the matrix is equal to the original matrix. In mathematical terms, if a matrix is symmetric, then. For example the following matrix is symmetric:

- Rectangular diagonal matrix: This is a matrix that is in size, with non-0 values only on the main diagonal (i.e., where i = j). For example:

- Upper (or Lower) triangular matrix: A matrix is called an upper (triangular) matrix if all the entries (i,j) below (above) its main diagonal is 0. For example, below is a 3*3 upper triangular matrix:

Next, we are going to describe matrix operations.
Determinants
Section titled “Determinants”The determinant of a square matrix provides a notion of its impact on the volume of a d-dimensional object when multiplied by its coordinate vectors. The determinant, symbolized as, represents the (signed) volume of the parallelepiped formed by the row or column vectors of the matrix. This interpretation holds consistently, as the volume determined by the row and column vectors is mathematically identical. When a diagonalizable matrix interacts with a group of coordinate vectors, the ensuing distortion is termed anisotropic scaling. The determinant can aid in establishing the scale factors of this conversion. The determinant of a square matrix carries crucial insights about the linear alteration accomplished by the multiplication with the matrix. Particularly, the sign of the determinant mirrors the impact of the transformation on the basis of the system’s orientation.
Calculating a determinant is as follows:
- For a matrix, its determinant is equivalent to the single scalar present within it.
- For larger matrices, the determinant can be calculated by securing a column, j, and then broadening using the elements within that column. As another option, it’s possible to fix a row,, and expand along that particular row. Regardless of whether you opt to fix a row or column, the end result, which is the determinant of the matrix, will remain consistent.
- With asa fixed value ranging from 1 to,

- With the fixed i,

- With asa fixed value ranging from 1 to,
Based on the following equations, we can see that some of the cases can be easily calculated:
- Diagonal matrix: For a diagonal matrix, the determinant is the product of its diagonal elements.
- Triangular matrix: In the context of a triangular matrix, the determinant is found by multiplying all its diagonal elements. If all components of a matrix’s row or column are 0, the determinant is also 0.
For a matrix of, its determinant can be computed as. If we consider a matrix,, the determinant is calculated as follows:
Let’s now move on to eigenvalues and eigenvectors next.
Eigenvalues and eigenvectors
Section titled “Eigenvalues and eigenvectors”A vector, belonging to a matrix, is an eigenvector if it satisfies the equation, where represents the eigenvalue associated with the matrix. This relationship delineates the link between matrix and its corresponding eigenvector, which can be perceived as the “stretching direction” of the matrix. In the case where is a matrix that can be diagonalized, it can be deconstructed into a invertible matrix,, and a diagonal matrix,, such that:
The columns of encompass eigenvectors, while the diagonal entries of house the corresponding eigenvalues. The linear transformation can be visually understood through a sequence of three operations. Initially, the multiplication of by calculates X’s coordinates in a non-orthogonal basis associated with ’s columns. Subsequently, the multiplication of by scales these coordinates using the factors in, aligned with the eigenvectors’ directions. Finally, the multiplication with V restores the coordinates to the original basis, resulting in an anisotropic scaling along the eigenvector directions.
Diagonalizable matrices signify transformations involving anisotropic scaling along d-linearly independent directions. When ’s columns are orthonormal vectors, equals its transpose,, indicating scaling along mutually orthogonal directions. In such cases, matrix is always diagonalizable and exhibits symmetry when ’s columns are orthonormal vectors, as affirmed by the following relationship.
Computational approaches to eigenvalues and eigenvectors
Section titled “Computational approaches to eigenvalues and eigenvectors”The conventional method to ascertain the eigenvectors of a matrix involves locating the d roots,, of the equation:
Some of these roots might be repeated. The subsequent step involves solving linear systems in the form, typically achieved using the Gaussian elimination method. However, this method might not always be the most stable or precise, as solvers of polynomial equations can exhibit ill-conditioning and numerical instability in practical applications. Indeed, a prevalent technique for resolving high-degree polynomial equations in engineering involves constructing a companion matrix with the same characteristic polynomial as the original polynomial and then determining its eigenvalues.
Eigenvalue decomposition
Section titled “Eigenvalue decomposition”Eigenvalue decomposition, also known as the eigen-decomposition or the diagonalization of a matrix, is a powerful mathematical tool used in linear algebra and computational mathematics. The goal of eigenvalue decomposition is to decompose a given matrix into a product of matrices that represent the eigenvectors and eigenvalues of the matrix.
The eigenvalue decomposition of matrix is a factorization of the matrix into the product of two matrices: the eigenvectors of matrix and the eigenvalues of matrix.
The eigenvectors matrix contains the eigenvectors of matrix, and the eigenvalues matrix is a diagonal matrix that contains the corresponding eigenvalues.
The eigenvalue problem is to find the non-0 vectors,, and the scalars,, such that,where is a square matrix and is an eigenvector of. The scalar is called the eigenvalue of matrix, and is called the eigenvector. The eigenvalue problem can be written in matrix form as, where is the identity matrix.
The process of determining eigenvalues is intimately linked to the characteristic equation of matrix, which is the polynomial equation derived from. The characteristic equation can be solved for the eigenvalues,, which are the roots of the equation. Once the eigenvalues are found, the eigenvectors can be found by solving the system of linear equations.
One important property of eigenvalue decomposition is that it allows us to diagonalize a matrix, which means that we can transform the matrix into a diagonal form by using an appropriate eigenvector matrix. The diagonal form of a matrix is useful because it allows us to calculate the trace and determinant of the matrix easily.
Another important property of eigenvalue decomposition is that it provides insight into the structure of the matrix. For example, the eigenvalues of a symmetric matrix are always real, and the eigenvectors are orthogonal, which means that they are perpendicular to each other. In the case of non-symmetric matrices, the eigenvalues can be complex, and the eigenvectors are not necessarily orthogonal.
The eigenvalue decomposition of a matrix has many applications in mathematics, physics, engineering, and computer science. In numerical analysis, eigenvalue decomposition is used to find the solution of linear systems, compute the eigenvalues of a matrix, and find the eigenvectors of a matrix. In physics, eigenvalue decomposition is used to analyze the stability of systems, such as the stability of an equilibrium point in a differential equation. In engineering, eigenvalue decomposition is used to study the dynamics of systems, such as the vibrations of a mechanical system.
Within the field of computer science, eigenvalue decomposition finds versatile applications across various domains, including machine learning and data analysis. In machine learning, eigenvalue decomposition plays a pivotal role in enabling principal component analysis (PCA), a technique employed for dimensionality reduction in extensive datasets. In the realm of data analysis, eigenvalue decomposition is harnessed to calculate the singular value decomposition (SVD), a potent tool for dissecting and understanding complex datasets.
Singular value decomposition
Section titled “Singular value decomposition”The problem of minimizing, where has a unit norm, and is a symmetric data matrix, is a typical problem encountered in numerous machine learning contexts. This problem type is often found in applications such as principal component analysis, singular value decomposition, and spectral clustering, all of which involve feature engineering and dimensionality reduction. The optimization problem can be articulated as follows:
Minimize
Subject to

We can solve the optimization problem as a maximization or minimization form. Imposing the constraint that vector must be a unit vector significantly changes the nature of the optimization problem. In contrast to the prior section, the positive semi-definiteness of matrix is no longer crucial for determining the solution. Even when is indefinite, the constraint on the norm of vector ensures a well-defined solution, preventing the involvement of vectors with unbounded magnitudes or trivial solutions, such as the vector. This constrained formulation motivates the use of matrix decomposition techniques to analyze the problem. SVD is a mathematical technique that takes a rectangular matrix,, and decomposes it into three matrices:
,
, and
. Matrix is defined as an
matrix. The theorem of SVD states that can be represented as the product of three matrices:
, where
, and
, and
and are orthogonal matrices.
The
matrix’s columns are known as the left singular vectors, while the rows of the transpose of the matrix (
) are the right singular vectors. The
matrix, with singular values, is a diagonal matrix of the same size as. SVD decomposes the original data into a co-ordinate system where the defining vectors are orthonormal (both orthogonal and normal). SVD computation involves identifying the eigenvalues and eigenvectors of matrices
and
. Matrix ’s columns consist of eigenvectors from
, and matrix
’s columns consist of eigenvectors from
. Singular values in the
matrix are derived from the square roots of eigenvalues from either
or
, organized in decreasing order. These singular values are real numbers. If is a real matrix,
and will also be real.
To illustrate the calculation of SVD, an example is provided. Consider a
matrix. The eigenvalues of the matrix can be found by computing
and
and then determining the eigenvectors of these matrices.
’s columns are formed by the eigenvectors of
, and ’s columns are formed by the eigenvectors of
. The
matrix comprises the square roots of eigenvalues from either
or
. Eigenvalues are found by solving the characteristic equation in the given example
, where
is the matrix,
is the unit matrix, and
is the eigenvalue. The eigenvectors are then found by solving the set of equations derived from the eigenvalue equations. The final matrices
,
, and
are then obtained by combining the eigenvectors and singular values.
It should be noted that the singular values are in descending order, with 
Let’s now move on to the basic probability for machine learning.
Basic probability for machine learning
Section titled “Basic probability for machine learning”Probability provides information about the likelihood of an event occurring. In this field, there are several key terms that are important to understand:
- Trial or experiment: An action that results in a certain outcome with a certain likelihood
- Sample space: This encompasses all potential outcomes of a given experiment
- Event: This denotes a non-empty portion of the sample space
Therefore, in technical terms, probability is a measure of the likelihood of an event occurring when an experiment is conducted.
In this very simple case, the probability of an event
with one outcome is equal to the count of events
(one) divided by the count of all possible events. For example, in flipping a fair coin, there are two outcomes with the same chance: heads and tails. The chance of having heads will be
.
In order to calculate the probability, given an event,
, with outcomes and a sample space,
, the probability of event
is calculated as

where
represents the outcomes in
. Assuming all results of the experiment have equal probability, and the selection of one does not influence the selection of others in subsequent rounds (meaning the events in different rounds are statistically independent), then

Hence, the value of probability ranges from 0 to 1, with the sample space embodying the complete set of potential outcomes, denoted as
.
Statistically independent
Section titled “Statistically independent”In the realm of statistics, two events are defined as independent if the occurrence of one event doesn’t influence the likelihood of the other event’s occurrence. To put it formally, events
and
are independent precisely when
, where
and
are the respective probabilities of events
and
happening.
Consider this example to clarify the concept of statistical independence: imagine we possess two coins, one fair (an equal chance of turning up heads or tails) and the other biased (showing a head is more likely than a tail). If we flip the fair coin and the biased coin, these two events are statistically independent because the outcome of one coin flip doesn’t alter the probability of the other coin turning up heads or tails. Specifically, the likelihood of both coins showing heads is the product of the individual probabilities:
.
Statistical independence is a pivotal concept in statistics and probability theory, frequently leveraged in machine learning to outline the connections between variables within a dataset. By comprehending these relationships, machine learning algorithms can better spot patterns and deliver more precise predictions. We will describe the relationship between different types of events in the following:
- Complementary event: The complementary event to
, signified as
, encompasses the probability of all potential outcomes in the sample space not included in
. It’s critical to understand that
and
are statistically dependent:

- Union and intersection: The probability of the intersection of two events
and
, denoted by
, represents the probability that both events occur simultaneously. Similarly, the probability of the union of events
and
, denoted by
, is given by the addition rule of probability:

- Mutually exclusive: When two events have no shared outcomes, they are viewed as mutually exclusive. In other words, if
and
are mutually exclusive events, then
. This conclusion can be drawn from the addition rule of probability, as
and
are disjointed events:

- Independent: Two events are deemed independent when the occurrence of one doesn’t impact the occurrence of the other. If
and
are two independent events, then

Next, we are going to describe the discrete random variable, its distribution, and how to use it to calculate the probabilities.
Discrete random variables and their distributions
Section titled “Discrete random variables and their distributions”A discrete random variable refers to a variable that can assume a finite or countably infinite number of potential outcomes. Examples of such variables might be the count of heads resulting from a coin toss, the tally of cars crossing a toll booth within a specific time span, or the number of blonde-haired students in a classroom.
The probability distribution of a discrete random variable assigns a certain likelihood to each potential outcome the variable could adopt. For instance, in the case of a coin toss, the probability distribution assigns a 0.5 probability to both 0 and 1, representing tails and heads, respectively. For the car toll booth scenario, the distribution could assign a probability of 0.1 to no cars passing, 0.3 to one car, 0.4 to two cars, 0.15 to three cars, and 0.05 to four or more cars.
A graphical representation of the probability distribution of a discrete random variable can be achieved through a probability mass function (PMF), which correlates each possible outcome of the variable to its likelihood of occurrence. This function is usually represented as a bar chart or histogram, with each bar signifying the probability of a specific value.
The PMF is bound by two key principles:
- It must be non-negative across all possible values of the random variable.
- The total sum of probabilities for all possible outcomes must equal 1.
The expected value of a discrete random variable offers an insight into its central tendency, computed as the probability-weighted average of its possible outcomes. This expected value is signified as
, with X representing the random variable.
Probability density function
Section titled “Probability density function”The probability density function (PDF) is a tool used to describe the distribution of a continuous random variable. It can be used to calculate the probability of a value falling within a specific range. In simpler terms, it helps determine the likelihood of a continuous variable, X, taking a value within the interval [a, b], which in statistical terms can be expressed as:

For continuous variables, the probability of a single value occurring is always 0, which is in contrast to discrete variables which can assign non- 0 probabilities to distinct values. As a result, PDFs provide a way to estimate the likelihood of a value falling within a given range instead of a single value. For example, you can use a PDF to find the probability that the next measured IQ score falls between 100 and 120. In statistics, PDF refers to the probability density function.

Figure 2.2 – Probability density function for IQ from 100–120
To ascertain the distribution of a discrete random variable, one can either provide its probability mass function (PMF) or cumulative distribution function (CDF). In the case of continuous random variables, however, we primarily utilize the CDF, as it is well established. The PMF is no longer suitable for these types of variables because
equals for all
in the set of real numbers, given that X can assume any real value between a and b. Therefore, continuous random variables are typically defined using a probability density function (PDF) instead.
Conceptually, the PDF resembles the concept of mass density in physics, signifying the concentration of probability rather than probability itself. Its unit is the probability per unit length. To get a grasp of this idea, let’s analyze a continuous random variable,
, and establish the function
as follows:
,
if the limit exists.
The function
provides the probability density at a given point,
. This is equivalent to the limit of the ratio of the probability of the interval
to the length of the interval as that length approaches zero. The PDF can also be expressed in relation to the CDF. Specifically, if the CDF
is differentiable at
, then:

Consequently, we can establish the following definition: let’s contemplate a continuous random variable,
, possessing an absolutely continuous cumulative distribution function (CDF), denoted as
. If
is differentiable at
, the function
, defined as:

is referred to as the probability density function (PDF) of
.
For example, let’s consider a uniform random variable,
, with a uniform (a, b) distribution. Its PDF is given by the following equation:

If
, which is 0 unless otherwise stated. And its PDF can be obtained by taking the derivative of the CDF. By using integration, the CDF can be obtained from PDF conversely:

Using this relationship, the probability that
lies within an interval
can be written as:

When the PDF is integrated over the entire real line, the result is 1:

Explicitly, when integrating the PDF across the entire real number line, the result should equal 1. This signifies that the area beneath the PDF curve must equate to 1, or
, which remains true for the uniform distribution. The PDF signifies the density of probability; thus, it must be non-negative and can exceed 1.
For a continuous random variable,
, with PDF represented as
, the following properties are applicable:


Next, we’ll move on to cover maximum likelihood.
Maximum likelihood estimation
Section titled “Maximum likelihood estimation”Maximum likelihood is a statistical approach used to estimate the parameters of a probability distribution. The objective is to identify the parameter values that maximize the likelihood of observing the data, essentially determining the parameters most likely to have generated the data.
Suppose we have a random sample,
, drawn from a population with probability distribution
, where is a vector of parameters. The likelihood of observing the sample,
, given the parameters,, is defined as:

In the case of having independent and identically distributed observations, the likelihood function can be expressed as the product of the univariate density functions, each evaluated at the corresponding observation:

The maximum likelihood estimate (MLE) is the value of the parameter vector
that provides the maximum value for the likelihood function across the parameter space.
Log-likelihood and parameter estimation
Section titled “Log-likelihood and parameter estimation”In many cases, it’s more convenient to employ the natural logarithm of the likelihood function, referred to as the log-likelihood. Taking the logarithm transforms the product of probabilities into a sum, which simplifies both analytical derivations and numerical optimization:

The peak of the log-likelihood occurs at the same parameter values as the original likelihood function’s maximum. If the log-likelihood is differentiable with respect to the parameters, the maximum likelihood estimate (MLE) can be obtained by setting the partial derivatives with respect to each parameter equal to 0:




where
is the number of parameters in.
The MLEs of the parameters,
, are the values that maximize the likelihood function. In other words, the MLEs are the values of that make the observed data,
, most probable.
The goal of a maximum likelihood estimator is to find
such that

Once the MLEs have been found, they can be used to make predictions about the population based on the sample data. Maximum likelihood is widely used in many fields, including psychology, economics, engineering, and biology. One common use case or scenario where MLE significantly impacts ML model performance is its usage in linear regression. When building a linear regression model, MLE is often used to estimate the coefficients that define the relationship between input features and the target variable. MLE helps find the values for the coefficients that maximize the likelihood of observing the given data under the assumed linear regression model, improving the accuracy of the predictions.
In a statistical or machine learning context, the transition from probability to optimization requires a crucial “equation shift.” If we define our original log-likelihood for independent and identically distributed (IID) data as
,
we encounter a practical hurdle: most standard optimization algorithms, such as Gradient Descent, are designed to find the minimum of a function (the “valley”) rather than the maximum (the “peak”). To align our statistical goals with these numerical tools, we define the negative log-likelihood (NLL) by simply negating the sum:

Consequently, the objective of the model shifts from finding
finding the specific parameter vector
that minimizes the loss:

This shift is most visible in real-world applications like Binary Cross-Entropy, the standard loss function for classification tasks (e.g., distinguishing between images of cats and dogs). When dealing with binary outcomes (0 or 1), the likelihood involves powers of probabilities; applying the negative logarithm transforms it into the well-known formula:

The presence of the negative sign at the front is essential for interpretability: it ensures that as the model’s prediction (
) moves closer to the actual label (
), the resulting loss value decreases toward zero. Without this negation, the “loss” would manifest as a negative number that grows larger as the model improves—a counterintuitive metric that would complicate the tracking of model performance.
Ultimately, the choice to use the negative sign is a choice to treat probability as a cost function. While a positive likelihood asks, “How well does this model fit the data?” (where higher is better), the negative log-likelihood asks, “How much error or uncertainty remains in this model?” (where lower is better).
From MLE to word prediction
Section titled “From MLE to word prediction”MLE serves as a potent tool for comprehending the connections among variables and for predicting outcomes based on observed data. For example, building a word predictor using maximum likelihood estimation. Word autocompletion, also known as word prediction is a feature in which an application predicts the next word a user is typing. The aim of word prediction is to save time and make typing easier by predicting what the user is likely to type next based on their previous inputs and other contextual factors. Word prediction can be found in various forms in many applications, including search engines, text editors, and mobile device keyboards, and is designed to save time and increase the accuracy of inputs.
Given a group of words that the user typed, how would we suggest the next word? If the words were “The United States of,” then it would be trivial to assume that the next word would be “America.” However, what about “How are”? One could suggest several next words.
Such are most cases, as there usually isn’t just one clear next word. Thus, we’d want to suggest the most likely word or perhaps even the most likely words. In that case, we would be interested in suggesting a probabilistic representation of the possible next words and picking the next word as the one that is most probable.
The MLE provides us with that precise capability. It can tell us which word is most probable given the previous words that the user typed.
N-gram counts and probability estimation
Section titled “N-gram counts and probability estimation”In order to calculate the MLE, we need to calculate the probability function of all word combinations. We can do that by processing large texts and counting how many times each combination of words occurs.
Consider reviewing a large cohort of text that has the following occurrences:
| “you” | “they” | “those” | “the” | Any other word | |
|---|---|---|---|---|---|
| “how are …” | 16 | 14 | 0 | 100 | 10 |
| not “how are…” | 200 | 100 | 300 | 1,000 | 30,000 |
Table 2.1 – Sample of n-gram occurrences in a document
There are 16 occurrences in the text where the sequence “how are you” appears. The total number of three-word sequences that start with “how are” is:

Similarly, the total number of three-word sequences that end with “you” is:

Now, the most likely word, based on MLE, is the word that maximizes:

where
is “how” and
is “are.”
There are five candidates for the next word; let’s calculate the probability for each of them:
- Prob(“how”, “are” | “you”) = 16 / (200 + 16) = 16/216 = 2/27
- Prob(“how”, “are” | “they”) = 14 / (100 +14) = 14/114 = 7/57
- Prob(“how”, “are” | “those”) = 0 / 300 = 0
- Prob(“how”, “are” | “the”) = 100 / (1000 + 100) = 100/1100 = 1/11
- Prob(“how”, “are” | any other word) = 10 / (30,000 + 10) = 10/30010 = 1/3001
Out of all the options, the highest value of probability is 7/57, which is achieved when “they” is the next word.
Interpreting the result
Section titled “Interpreting the result”Note that the intuition behind the MLE is that the suggested next word makes the words that the user typed most likely. One could wonder, why not take the word that is most probable given the first two words? From the table, we see that given the words “how are,” the most frequent third word is “the,” with a probability of 100/140. However, this approach wouldn’t take into account that the word “the” is extremely prevalent altogether, as it is most frequently used in the text in general. Thus, its high frequency isn’t due to its relationship to the first two words; it is because it is simply a very common word in general. The MLE takes that into account.
Bayesian estimation
Section titled “Bayesian estimation”Bayesian estimation is a statistical approach that involves updating our beliefs or probabilities about a quantity of interest based on new data. The term “Bayesian” refers to Thomas Bayes, an 18th-century statistician who first developed the concept of Bayesian probability.
In Bayesian estimation, we start with prior beliefs about the quantity of interest, which are expressed as a probability distribution. These prior beliefs are updated as we collect new data. The updated beliefs are represented as a posterior distribution. The Bayesian framework provides a systematic way of updating prior beliefs with new data, taking into account the degree of uncertainty in both the prior beliefs and the new data.
The posterior distribution is calculated using Bayes’ theorem, which is the fundamental equation of Bayesian estimation. Bayes’ theorem states that:

Where
is the quantity of interest,
is the new data,
is the posterior distribution,
is the likelihood of the data given the parameter value,
is the prior distribution, and
is the marginal likelihood or evidence.
The marginal likelihood is calculated as follows:

Where the integral is taken over the entire space of
. The marginal likelihood is often used as a normalizing constant, ensuring that the posterior distribution integrates to 1.
In Bayesian estimation, the choice of prior distribution is important, as it reflects our beliefs about the quantity of interest before collecting any data. The prior distribution can be chosen based on prior knowledge or previous studies. If no prior knowledge is available, a non-informative prior can be used, such as a uniform distribution.
Once the posterior distribution is calculated, it can be used to make predictions about the quantity of interest. As an example, the posterior distribution’s mean can serve as a point estimate, whereas the posterior distribution itself can be used to establish credible intervals. These intervals represent the probable range within which the true value of the target quantity resides.
Optimization
Section titled “Optimization”Optimization is the mathematical process of adjusting model parameters to minimize (or sometimes maximize) a certain function. In machine learning and NLP, that function is usually a loss function, which is a measure of how far off a model’s predictions are from the true values.
In simple terms, optimization tells a model how to learn from data by minimizing errors.
Why optimization matters in NLP and ML
Section titled “Why optimization matters in NLP and ML”Every modern NLP model from logistic regression to large transformers learns by minimizing a loss function. For example:
- In textclassification, we want to minimize classification error.
- In language modeling, we aim to minimize the difference between predicted and actual word sequences (often via cross-entropy loss).
- In embedding models, we may want to minimize distance between similar word vectors and maximize it between dissimilar ones.
Optimization is how we train these models, which is by finding the best set of weights that reduce this loss.
Core components of optimization
Section titled “Core components of optimization”At its core, optimization is about iteratively adjusting a model so that it makes fewer mistakes. This process relies on a few essential components:
- Objective Function (Loss Function): Denoted typically as
, where
are the model’s parameters. Examples include Mean Squared Error for regression and Cross-Entropy Loss for classification and language modeling - Parameters: These are the values (weights and biases) in your model that you want to adjust to reduce the loss.
- Gradients: The direction and rate of change of the loss with respect to each parameter. They are computed via back-propagation using partial derivatives, and we use linear algebra and calculus to propagate gradients through layers.
- Optimization Algorithm (Optimizer): It updates the model parameters based on the gradients. Common algorithms are:
- Gradient Descent (GD): Gradient Descent is the most common technique used to optimize models. The idea is simple:

- Compute the loss.
- Calculate the gradient (slope) of the loss.
- Take a small step in the direction that reduces the loss.
If you imagine the loss function as a mountain, gradient descent helps the model walk downhill toward the minimum error.
Challenges in optimization are as follows:
- Local Minima & Saddle Points: When we train a model, we define a loss function—a surface that maps parameter values (weights) to error values. The goal of optimization is to find the lowest point on this surface: the global minimum, where the model makes the fewest possible errors on the data.
However, in practice, the optimization process is rarely so simple, especially in deep learning. The loss surface is highly complex and non-convex, meaning it contains multiple low points, flat regions, and ridges. Two of the main obstacles are local minima and saddle points (where the gradient is zero but it is not a global minimum).
- Vanishing/exploding gradients: When training deep neural networks, particularly those with many layers or sequential structures such as recurrent neural networks (RNNs), it is common to encounter two numerical instabilities: vanishing gradients and exploding gradients. These phenomena arise during backpropagation, the process of computing gradients of the loss function with respect to model parameters, due to repeated application of the chain rule across multiple layers. This concept will be explained in more details in next chapters of the book.

A graph with a line graph AI-generated content may be incorrect.
Figure 2.3. Smooth loss function with clear local minima

Figure 2.4. Effect of learning rate on gradient descent
To view the preceding figures in color, access the free PDF version of this book and other associated benefits. Instructions are available in the Free benefits with your book section in the Preface.
- Learning Rate Tuning: A step size that’s too large can overshoot the minimum; too small can make training slow.
- Stochastic Gradient Descent (SGD): is a variant of gradient descent that updates model parameters using a single randomly selected training example at each iteration, rather than the full dataset. This makes it significantly more efficient for large-scale learning tasks.
To address these optimization challenges in practice, several variants of gradient descent and adaptive optimization algorithms have been developed.
Given a loss function
, where
are the model parameters,
is the learning rate,
is a randomly sampled training example, and
is the gradient of the loss with respect to
, model parameters are updated iteratively during optimization.
- Adam (short for Adaptive Moment Estimation) is a widely used optimization algorithm in deep learning. It combines the benefits of two earlier methods, Momentum and RMSProp, to provide adaptive learning rates for each parameter, along with smoother convergence.
At each iteration, Adam maintains the following:
The first moment estimate (mean of past gradients), the second moment estimate, The bias-corrected estimates, and The parameter update rule can be seen below:
- First-moment estimate (mean):

- Second-moment estimate (variance):

- Bias-corrected first moment estimate:

- Bias-corrected second moment estimate:

- Parameter update rule:

where
is the gradient of the loss function at time step t,
is the learning rate,
are exponential decay rates for the moment estimates (typically
=0.9,
=0.999), and
is a small constant (e.g., 10 8) to avoid division by zero.
- Adagrad: (Adaptive Gradient Algorithm) adapts the learning rate for each parameter individually by scaling it inversely proportional to the square root of the sum of all historical squared gradients. This makes it well-suited for sparse data and features.
The update rule for Adagrad is:


These optimization methods form the practical mechanism through which machine learning models adjust their parameters and improve their performance during training.
Summary
Section titled “Summary”This chapter was about linear algebra and probability for machine learning, and it covers the fundamental mathematical concepts that are essential to understanding many machine learning algorithms. The chapter began with a review of linear algebra, covering topics such as matrix multiplication, determinants, eigenvectors, and eigenvalues. It then moved on to discuss probability theory, introducing the basic concepts of random variables and probability distributions. We also covered key concepts in statistical inference, such as maximum likelihood estimation and Bayesian inference.
In the next chapter, we will cover the fundamentals of machine learning for natural language processing, including topics such as data exploration, feature engineering, selection methods, and model training and validation.
Questions
Section titled “Questions”- What role do linear algebra and probability play in modern NLP systems?
- In an NLP context, what are scalars, vectors, and matrices, and what might each represent?
- What is the dot product and how does it connect to similarity in NLP embeddings?
- What does it mean for vectors to be orthogonal or orthonormal, and why is that useful?
- What is an eigenvector and eigenvalue in intuitive terms, and what does diagonalization mean?
- Why is eigenvalue decomposition important in ML workflows like dimensionality reduction?
- What is SVD and what are the three matrices in the decomposition used for?
- How do PMF and PDF differ, and how does a PDF relate to a CDF?
- What is maximum likelihood estimation, and why is log likelihood commonly used?
- What is Bayesian estimation, and how does it update beliefs from data?
Further reading
Section titled “Further reading”Please find the additional reading content as follows:
- Householder reflection matrix: A Householder reflection matrix, or Householder matrix, is a type of linear transformation utilized in numerical linear algebra due to its computational effectiveness and numerical stability. This matrix is used to perform reflections of a given vector about a plane or hyperplane, transforming the vector so that it only has non- 0 components in one specific dimension. The Householder matrix (H) is defined by

Here, I is the identity matrix, and u is a unit vector defining the reflection plane.
The main purpose of Householder transformations is to perform QR factorization and to reduce matrices to a tridiagonal or Hessenberg form. The properties of being symmetric and orthogonal make the Householder matrix computationally efficient and numerically stable.
- Diagonalizable: A matrix is said to be diagonalizable if it can be written in the form
, where is the original matrix, is a diagonal matrix, and
is a matrix for which the columns are the eigenvectors of. Diagonalization simplifies many calculations in linear algebra, as computations with diagonal matrices are often more straightforward. For a matrix to be diagonalizable, it must have enough distinct eigenvectors to form a basis for its space, which is usually the case when all of its eigenvalues are distinct. - Invertible: An invertible matrix, also known as a non-singular matrix or a non-degenerate matrix, is a square matrix that has an inverse. If a matrix,, is invertible, there exists another matrix, often denoted as
, such that when they are multiplied together, they yield the identity matrix. In other words,
, where
is the identity matrix. The identity matrix is a special square matrix with 1 s on its main diagonal and 0 s everywhere else. The existence of an inverse heavily depends on the determinant of the matrix—a matrix is invertible if and only if its determinant is not 0. Invertible matrices are crucial in numerous areas of math, including solving systems of linear equations, matrix factorization, and many applications in engineering and physics. - Gaussian elimination method: Gaussian elimination is a fundamental algorithm in linear algebra for solving systems of linear equations. It accomplishes this by transforming the system to an equivalent one in which the equations are simpler to solve. This method uses a sequence of operations to modify the system of equations, with the objective of creating a row-echelon or reduced row-echelon form. Here’s a simplified step-by-step process of Gaussian elimination: First, swap the rows to move any rows with a leading coefficient (the first non- 0 number from the left, also called the pivot) so as to have 1 at the top. Then, multiply or divide any rows by a scalar to create a leading coefficient of 1 if not already present. Finally, add or subtract rows to create 0 s below and above the pivot. Once the matrix is in row-echelon form (all 0 rows are at the bottom, and each leading coefficient is to the right of the leading coefficient of the row above it), we can use back substitution to find the variables. If we further simplify the matrix to a reduced row-echelon form (each leading coefficient is the only non- 0 entry in its column), the solutions can be read directly from the matrix. Gaussian elimination can also be used to find the rank of a matrix, calculate the determinant, and carry out matrix inversion if the system is square and has a unique solution.
- Trace: The trace of a square matrix is the sum of its diagonal elements. It’s denoted as
or
, where is a square matrix. For example, if
, then
.
References
Section titled “References”- Alter O, Brown PO, Botstein D. (2000). Singular value decomposition for genome-wide expression data processing and modeling. Proc Natl Acad Sci U S A, 97, 10101-6.
- Golub GH, Van Loan CF. (1989). Matrix Computations, 2nd ed. Baltimore: Johns Hopkins University Press.
- Greenberg, M. (2001). Differential Equations & Linear Algebra. Upper Saddle River, N.J.: Prentice Hall.
- Strang, G. (1998). Introduction to Linear Algebra. Wellesley, MA: Wellesley-Cambridge Press.
- Lax, Peter D. (2007). Linear Algebra and Its Applications. Vol. 78. John Wiley & Sons.
- Dangeti, Pratap. Statistics for Machine Learning. Packt Publishing Ltd, 2017.
- DasGupta, Anirban. Probability for Statistics and Machine Learning: Fundamentals and Advanced Topics. New York: Springer, 2011.
- Dogo, Eustace M., et al. “A comparative analysis of gradient descent-based optimization algorithms on convolutional neural networks.” 2018 International Conference on Computational Techniques, Electronics and Mechanical Systems (CTEMS). IEEE, 2018.