Lecture 03 - Stats / Linear Algebra Review
The fundamental math skills for deep learning - tensors and PyTorch, vectors, matrices and broadcasting, probability basics, estimation (MLE and MAP), and linear regression.
1. Motivation: Why We Need This Math
Today’s roadmap is:
- Tensors in deep learning
- Tensors and PyTorch
- Vectors, matrices, and broadcasting
- Probability basics
- Estimation methods
- Linear regression
2. Tensors in Deep Learning
2.1 Scalars, vectors, and matrices
A scalar is an order-0 tensor, written with a lowercase symbol:
A vector is an order-1 tensor, written with a bold lowercase symbol:
In this lecture, vectors are assumed to be column vectors:
Its transpose is a row vector:
A matrix is an order-2 tensor, written with a bold capital symbol:
Each step up in tensor order adds another axis (dimension).
2.2 The design matrix convention
$\mathbf{X}$ denotes the design matrix (also called the feature matrix or input matrix), containing training examples and their features:
where $n$ is the number of training examples (rows) and $m$ is the number of features (columns).
A superscript in square brackets indexes the example and a subscript indexes the feature. For example,
is the second feature value of the first training example.
In lecture. Fluency with this notation matters as nearly every model in the course is expressed via the design matrix and operations on it.
2.3 Higher-order tensors
A 3D tensor (order-3 tensor) can be pictured as a stack of matrices:
Here $m,n,p$ denote the sizes of the three tensor dimensions.
In lecture. We usually say scalar, vector, or matrix for orders 0–2, and commonly use the word “tensor” once the order is 3 or higher, even though technically all of these objects are tensors.
A 3D tensor can represent a color image: three stacked matrices corresponding to the red, green, and blue channels, each storing one intensity per pixel.
A 4D tensor can represent a batch of images. Stacking 3D image tensors creates a 4D tensor whose first axis indexes the image in the batch.
2.4 For our purposes: tensor = multidimensional array
For this course, a tensor is a multidimensional array. The tensor’s dimensionality (or order) is the number of axes in its .shape.
3. Tensors and PyTorch
3.1 NumPy arrays to PyTorch tensors
Both numpy.array / numpy.ndarray and torch.tensor / torch.Tensor are data-structure representations of tensors.
3.2 NumPy and PyTorch syntax is similar
For two 1D vectors, matmul, dot, and @ all compute the inner product.
3.3 Data types
| NumPy data type | PyTorch tensor type | Note |
|---|---|---|
numpy.uint8 |
torch.ByteTensor |
|
numpy.int16 |
torch.ShortTensor |
|
numpy.int32 |
torch.IntTensor |
|
numpy.int64 |
torch.LongTensor |
Default integer type in the lecture examples; numpy.int is a removed legacy alias |
numpy.float16 |
torch.HalfTensor |
|
numpy.float32 |
torch.FloatTensor |
Default float in PyTorch |
numpy.float64 |
torch.DoubleTensor |
Default float in the lecture’s NumPy examples; numpy.float is a removed legacy alias |
The dtype can be specified explicitly:
In lecture. Dtypes can cause setup problems when operations mix incompatible types. Converting to lower precision throws information away, while higher precision consumes more memory.
A classic dtype bug is:
3.4 Why not just use NumPy?
PyTorch offers NumPy-like operations, but it is designed for deep learning:
- GPU support: tensor operations can run on compatible GPUs.
- Automatic differentiation (autograd): PyTorch records a computation graph and can traverse it in reverse to compute gradients automatically.
- DL convenience functions: layers, loss functions, optimizers, data loaders, and related utilities.
3.5 Loading data onto a GPU
If CUDA is installed, nvidia-smi can be used to inspect the available NVIDIA GPUs, including their memory usage, utilization, driver, and CUDA version.
3.6 Installing PyTorch
The lecture recommends using the selector on the PyTorch website to choose the operating system, package manager, language, and compute platform, then running the generated install command.
4. Vectors, Matrices, and Broadcasting
4.1 Vectors: the pre-activation of a neuron
For one observation,
where $\mathbf{x}$ is the input feature vector, $\mathbf{w}$ is the weight vector, $b$ is the bias, and $z$ is the pre-activation (also called the net input).
Equivalently,
4.2 Matrices: computing outputs for multiple examples
Stacking examples as rows of the design matrix lets us compute all pre-activations at once:
where
Each entry of $\mathbf{z}$ is the pre-activation for one example.
In lecture: Big-O cost of matrix multiplication. For two $N\times N$ matrices, the standard matrix-multiplication algorithm is $O(N^3)$: there are $N^2$ output entries and each is a dot product of length $N$. Faster asymptotic algorithms exist, but in practice the lecture assumes approximately $O(N^3)$.
4.3 A common notational convenience
Strictly, $\mathbf{X}\mathbf{w}$ is an $n\times1$ vector and $b$ is a scalar, so the fully explicit expression is
In deep-learning notation, we typically write
and assume broadcasting.
4.4 Broadcasting
Broadcasting can silently produce an unintended result when shapes are compatible, so tensor shapes are important when debugging.
Beyond the slides: linear algebra facts used later.
Matrix product:
Transpose:
Norms:
Inverse:
Gradients:
and, for symmetric $A$,
5. Probability Basics
5.1 Definitions
A discrete random variable takes values from a countable set, such as a coin flip.
A continuous random variable can take values over a continuous range, such as a height.
For discrete $X$, a probability mass function (PMF) is
For continuous $X$, a probability density function (PDF) is
Beyond the slides. A PMF gives actual point probabilities:
A PDF gives a density. Probabilities come from areas:
A density value $f(x)$ can be larger than 1, while for a continuous random variable $P(X=x)=0$ for any single point.
5.2 Key distributions
Distributions are parameterized; the lecture generally uses $\theta$ for parameters.
Bernoulli distribution:
For a fair coin, $\theta=0.5$. For Bernoulli $X$,
Gaussian distribution: with mean $\mu$ and variance $\sigma^2$,
The standard normal has
5.3 Central Limit Theorem (CLT)
Let $X_1,X_2,\ldots,X_n$ be i.i.d. random variables with mean $\mu$ and variance $\sigma^2$. Define the sample mean
Then, as $n\rightarrow\infty$,
in distribution.
In lecture. Under the usual CLT assumptions, if we average many independent variables from the same distribution, subtract the mean, and divide by the standard error $\sigma/n^{1/2}$, the standardized average approaches a standard normal as $n$ becomes large.
5.4 Joint, marginal, and conditional probabilities
Joint:
the probability of two events occurring together.
Marginal:
the sum of joint probabilities over one variable.
Conditional:
the probability of $A$ given $B$.
Beyond the slides: rules that follow.
Product rule:
Independence:
Law of total probability:
5.5 Expectation and variance
Expectation:
Variance:
equivalently,
Beyond the slides: why the two variance formulas agree. Let $\mu=E[X]$. Expanding the square,
5.6 Linearity of expectation
For constants $a,b$,
For multiple random variables,
In lecture. Independence is not required for linearity of expectation. Independence matters for variance:
Thus variances add when $\operatorname{Cov}(X_1,X_2)=0$, as for independent variables.
For the sample mean,
which gives the standard error $\sigma/n^{1/2}$ used in the CLT.
5.7 Expectation of functions
For a function $g$,
Discrete example: if $X\sim\operatorname{Bernoulli}(\theta)$ and $g(X)=X^2$,
Continuous example: if $X\sim\operatorname{Uniform}(0,1)$ and $g(X)=X^2$,
5.8 Variance of functions
Beyond the slides: finishing the two examples.
For Bernoulli $X$, since $X^4=X$ when $X\in{0,1}$,
For $X\sim\operatorname{Uniform}(0,1)$,
so
5.9 Covariance and correlation
Covariance:
Properties:
If $X,Y$ are independent,
Correlation:
- $\rho=1$: perfect positive linear relationship.
- $\rho=0$: no linear correlation.
- $\rho=-1$: perfect negative linear relationship.
Beyond the slides: the converse is false. Zero covariance does not imply independence. If $X\sim\operatorname{Uniform}(-1,1)$ and $Y=X^2$, then $Y$ is completely determined by $X$, yet
Correlation detects linear dependence, not every kind of dependence.
5.10 Bayes’ rule
For a medical test,
Beyond the slides: plugging in numbers. Suppose 1% of people have the disease, the test catches 99% of cases, and the false-positive rate is 5%.
Therefore,
The prior/base rate matters here: MAP incorporates prior information, while MLE uses the likelihood alone.
6. Estimation Methods
6.1 Introduction to estimation
The goal of estimation is to infer unknown parameters $\theta$ from observed data.
Types of estimation:
- Point estimation: a single value, such as an MLE.
- Interval estimation: a range of plausible values, such as a confidence interval.
Common methods:
- Maximum Likelihood Estimation (MLE)
- Maximum A Posteriori (MAP)
- Method of Moments
Beyond the slides: the two methods not covered in detail.
For a large-sample mean, an approximate 95% confidence interval is
using the sample standard deviation $s$ when $\sigma$ is unknown.
For the method of moments, set theoretical moments equal to sample moments and solve for the parameter. For Bernoulli data,
6.2 Maximum Likelihood Estimation (MLE)
The MLE is
where $L(\theta)$ is the probability mass or probability density of the observed data given $\theta$, viewed as a function of $\theta$.
Bernoulli example
For the observed data
modeled as i.i.d. Bernoulli observations with $P(X=1\mid\theta)=\theta$,
The log-likelihood is
Let
Then
and
Setting the derivative to zero gives
For the dataset above, $k=3$ and $n=5$, so
Beyond the slides: why take the log, and why it matters for DL.
logis strictly increasing, so it does not change the location of the maximum.- It converts products into sums, which are easier to differentiate.
- Products of many probabilities can numerically underflow, while sums of log-probabilities are more stable.
- For a Bernoulli model, minimizing negative log-likelihood gives binary cross-entropy. Many common deep-learning losses have negative-log-likelihood interpretations.
The lecture also notes that the MLE:
- does not always exist,
- is not necessarily unique,
- is not necessarily admissible.
"Admissible" means that there is no other estimator with lower or equal risk for every parameter value and strictly lower risk for at least one.
6.3 Maximum A Posteriori (MAP) estimation
MAP selects the parameter that maximizes the posterior:
The evidence $P(\text{data})$ can be dropped from the argmax because it does not depend on $\theta$.
- $P(\text{data}\mid\theta)$ is the likelihood.
- $P(\theta)$ is the prior.
MLE ignores $P(\theta)$; MAP incorporates prior information.
Beyond the slides: MAP for the Bernoulli example. With a Beta$(\alpha,\beta)$ prior,
The posterior is proportional to
and, when the posterior has an interior mode, the MAP estimate is
With Beta$(2,2)$ and $k=3,n=5$,
6.4 Regularization is MAP
A regularized maximum-likelihood objective adds a penalty:
If
then
Thus regularization can be interpreted as MAP estimation under a corresponding prior.
7. Linear Regression
7.1 Model definition
Linear regression is written as
where
- $\mathbf{y}$ is the response variable, $n\times1$;
- $\mathbf{X}$ is the design matrix, $n\times m$;
- $\boldsymbol{\beta}$ is the coefficient vector, $m\times1$;
- $\boldsymbol{\epsilon}$ is the error term, often modeled with Gaussian noise.
The goal is to estimate $\boldsymbol{\beta}$. An intercept can be included by adding a column of ones to $\mathbf{X}$.
7.2 Evaluation metrics
Coefficient of determination:
where
and
It measures the proportion of variance in $y$ explained by the model.
Mean Squared Error (MSE):
Mean Absolute Error (MAE):
Beyond the slides. MSE penalizes large errors more heavily because errors are squared, while MAE is more robust to large outliers. RMSE,
has the same units as $y$.
7.3 Ordinary Least Squares (OLS)
The OLS objective is
Residuals are
When the inverse exists, the familiar closed-form expression is
Beyond the slides: deriving the OLS solution.
Expand the objective:
Taking the gradient and setting it to zero gives the normal equations:
so
In code, use a least-squares solver such as np.linalg.lstsq or torch.linalg.lstsq rather than explicitly forming a matrix inverse.
OLS is MLE under independent Gaussian noise. If
then
Maximizing the likelihood is therefore equivalent to minimizing squared error.
7.4 Regularization in linear regression (MAP)
Ridge regression (L2 regularization):
A Gaussian prior on the coefficients gives the MAP interpretation:
with
Lasso regression (L1 regularization):
This corresponds to a Laplace prior on each coefficient, with the exact scale depending on the chosen objective parameterization.
8. Summary and Practice Questions
Key takeaways
- Tensors are multidimensional arrays; order = number of axes =
.ndim. - In the design matrix $\mathbf{X}$, rows are examples and columns are features.
- PyTorch is NumPy-like but adds GPU support, autograd, and deep-learning utilities.
- $\mathbf{X}\mathbf{w}+b$ computes pre-activations for a whole batch, with $b$ handled by broadcasting.
- Linearity of expectation does not require independence.
- Independent variables have zero covariance, but zero covariance does not in general imply independence.
- MLE maximizes the likelihood; MAP maximizes likelihood times prior.
- L2 regularization corresponds to a Gaussian-prior MAP interpretation; L1 corresponds to a Laplace-prior interpretation.
- OLS is MLE under independent Gaussian noise; ridge and lasso have corresponding MAP interpretations.
Check your understanding
-
A batch of 64 grayscale $28\times28$ images: what is the tensor’s order and typical PyTorch shape?
Order 4, shape(64, 1, 28, 28). -
If $\mathbf{X}\in\mathbb{R}^{100\times5}$, what shapes must $\mathbf{w}$ and $\mathbf{z}$ have in $\mathbf{X}\mathbf{w}+b=\mathbf{z}$?
$\mathbf{w}$ has shape $5\times1$ and $\mathbf{z}$ has shape $100\times1$. -
You flip a coin 10 times and get 10 heads. What is the Bernoulli MLE? What is the MAP estimate with a Beta$(2,2)$ prior?
\hat\theta_{\mathrm{MLE}}=1, and
\hat\theta_{\mathrm{MAP}} = \frac{10+2-1}{10+2+2-2} = \frac{11}{12} \approx0.917.