j-devlog
KO
~/nav

// categories

// tags

[MMD]

Linear Algebra in Practice: Problems You'll Actually Face in ML

·10 min read·

This post is a collection of practice problems that apply the concepts from Linear Algebra Chapters 1–4 to real-world machine learning scenarios. The focus is on applying and interpreting concepts rather than mechanical calculation.


Part 1. Data and Matrices#

Problem 1-1. Interpreting the Rank of a Data Matrix#

A dataset has 1,000 samples and 50 features. When represented as a matrix XX, its rank turns out to be 30. What does this mean?

Show answer

A rank of 30 means there are effectively 30 linearly independent features.

  • Of the 50 features, 20 can be expressed as linear combinations of the others → redundant information
  • The true dimensionality of the information in this dataset is 30, not 50

Practical implication: Applying PCA can reduce the data from 50 to 30 dimensions with zero information loss. In practice, the top few principal components typically explain most of the variance, so you can often reduce even further below 30.


Problem 1-2. The Multicollinearity Problem#

When training a linear regression model, suppose the features satisfy x3=2x1+x2x_3 = 2x_1 + x_2. What property does the matrix XTXX^T X have, and how does this affect model training?

Show answer

Since x3=2x1+x2x_3 = 2x_1 + x_2, the columns of the data matrix are linearly dependent.

This makes XTXX^T X a singular matrix, so:


det(XTX)=0(XTX)1 does not exist\det(X^T X) = 0 \Rightarrow (X^T X)^{-1} \text{ does not exist}


The closed-form solution for linear regression, w^=(XTX)1XTy\hat{w} = (X^T X)^{-1} X^T y, cannot be computed.

Solutions:

  • Remove the redundant feature
  • L2 regularization (Ridge): (XTX+λI)1(X^T X + \lambda I)^{-1} — the inverse always exists
  • Use PCA to extract only independent components

Problem 1-3. Batch Normalization as a Matrix Operation#

In deep learning, Batch Normalization transforms each batch to have mean 0 and variance 1. How can this process be expressed as matrix operations?

Show answer

For a batch matrix XX (rows = samples, columns = features):

Step 1 — Mean centering:


Xcentered=X1μTX_{\text{centered}} = X - \mathbf{1}\mu^T


where μ\mu is the mean vector of each feature and 1\mathbf{1} is a ones vector

Step 2 — Divide by standard deviation:


Xnorm=XcenteredσX_{\text{norm}} = X_{\text{centered}} \oslash \sigma


This is the same operation as the data centering step in PCA. From a linear algebra perspective, it is a preparatory step for aligning the data along the eigenvector directions of the covariance matrix.


Part 2. Model Training and Optimization#

Problem 2-1. Determinant and Model Convergence#

During neural network training, if the determinant of a weight matrix keeps approaching 0, what problems arise?

Show answer

det(W)0\det(W) \to 0 for a weight matrix WW means the matrix is approaching singularity.

Problems that follow:

  1. Vanishing Gradient: During backpropagation, gradients are propagated via matrix multiplication — multiplying by a near-singular matrix drives the gradient toward 0
  2. Loss of representational capacity: As the rank drops, the space the neural network can represent shrinks
  3. Numerically unstable inverse: Computing W1W^{-1} becomes numerically unreliable

Solutions: Batch normalization, residual connections (ResNet), proper weight initialization (Xavier, He initialization)


Problem 2-2. A Layer as a Linear Transformation#

In a neural network layer y=Wx+by = Wx + b, if the weight matrix WW is 4×34 \times 3, what transformation does this layer perform? Is the inverse transformation possible?

Show answer

If WW is 4×34 \times 3 (4 rows, 3 columns):

  • Input dimension: 3 (a 3-dimensional vector xx)
  • Output dimension: 4 (a 4-dimensional vector yy)

This layer performs a linear transformation from 3-dimensional space → 4-dimensional space.

No inverse: Since WW is not square, its inverse does not exist. However, the pseudoinverse W+=(WTW)1WTW^+ = (W^T W)^{-1} W^T can be used for an approximate inverse transformation.

Intuition: Lifting 3-dimensional data into 4 dimensions is analogous to embedding. The encoder/decoder in an autoencoder uses this kind of non-square transformation.


Problem 2-3. SVD and Model Compression#

A matrix WW can be decomposed via SVD as W=UΣVTW = U\Sigma V^T. How does using a truncated W^\hat{W} that retains only the top kk singular values help with model compression?

Show answer

SVD decomposes a matrix in order of information importance. Larger singular values = directions carrying more information.

Original matrix: W=i=1rσiuiviTW = \sum_{i=1}^{r} \sigma_i \vec{u}_i \vec{v}_i^T

Keeping only kk terms: W^=i=1kσiuiviT\hat{W} = \sum_{i=1}^{k} \sigma_i \vec{u}_i \vec{v}_i^T

Compression gain:

  • Original storage: m×nm \times n parameters
  • Compressed storage: k(m+n+1)k(m + n + 1) parameters
  • When kmin(m,n)k \ll \min(m, n), the compression ratio is significant

Real-world application: LoRA (Low-Rank Adaptation) uses this principle to fine-tune LLMs efficiently, approximating large weight matrices with two low-rank matrices.


Part 3. Dimensionality Reduction and Embeddings#

Problem 3-1. PCA vs Feature Selection#

You need to reduce 100 features down to 10. What is the difference between using PCA and simply selecting the top 10 features?

Show answer
Feature SelectionPCA
OutputKeeps 10 original featuresCreates 10 new principal components
InterpretabilityHigh (original feature meaning preserved)Low (principal components are linear combinations)
Information retentionLoses information from the 90 dropped featuresMaximally preserves variance
MulticollinearityCan still be presentPrincipal components are perfectly orthogonal (independent)

When to choose which:

  • Interpretability matters → Feature selection
  • Information retention matters → PCA
  • Multicollinearity is a problem → PCA is the solution

Problem 3-2. Computing Explained Variance from Eigenvalues#

Given covariance matrix eigenvalues of [8.5,5.2,3.1,1.8,0.9,][8.5, 5.2, 3.1, 1.8, 0.9, \ldots] and a total sum of 25, what percentage of total variance do the first 2 principal components explain?

Show answer

Explained variance ratio=λ1+λ2iλi=8.5+5.225=13.725=54.8%\text{Explained variance ratio} = \frac{\lambda_1 + \lambda_2}{\sum_i \lambda_i} = \frac{8.5 + 5.2}{25} = \frac{13.7}{25} = 54.8\%


Interpretation: The first two principal components alone explain roughly 55% of the total variance in the data.

Practical decision guidelines:

  • Typically, choose enough principal components to retain 80–95%+ of explained variance
  • On a Scree Plot (eigenvalues plotted in descending order), select the point where the slope sharply flattens (the "elbow")

Problem 3-3. Vector Similarity and Recommendation Systems#

User AA's movie preference vector is a=(3,1,4,1,5)\vec{a} = (3, 1, 4, 1, 5) and user BB's is b=(1,5,2,6,1)\vec{b} = (1, 5, 2, 6, 1). Do they have similar taste? What metric do you use?

Show answer

Use cosine similarity (dot product divided by the product of L2-norms):


cosθ=aba2b2\cos\theta = \frac{\vec{a} \cdot \vec{b}}{\|\vec{a}\|_2 \|\vec{b}\|_2}


ab=3+5+8+6+5=27\vec{a} \cdot \vec{b} = 3 + 5 + 8 + 6 + 5 = 27


a2=9+1+16+1+25=527.21\|\vec{a}\|_2 = \sqrt{9+1+16+1+25} = \sqrt{52} \approx 7.21


b2=1+25+4+36+1=678.19\|\vec{b}\|_2 = \sqrt{1+25+4+36+1} = \sqrt{67} \approx 8.19


cosθ=277.21×8.190.457\cos\theta = \frac{27}{7.21 \times 8.19} \approx 0.457


A cosine similarity of 0.46 is low. The two users have quite different tastes (A prefers action/sci-fi, B prefers romance/drama).

In practice: Collaborative Filtering recommendation systems are built on this principle.


Part 4. Neural Networks and Matrices#

Problem 4-1. The Forward Pass as Matrix Multiplication#

Express the forward pass of a 2-layer neural network as matrix operations:

  • Input: xR3x \in \mathbb{R}^3
  • Layer 1 weights: W1R4×3W_1 \in \mathbb{R}^{4 \times 3}, bias: b1R4b_1 \in \mathbb{R}^4
  • Layer 2 weights: W2R2×4W_2 \in \mathbb{R}^{2 \times 4}, bias: b2R2b_2 \in \mathbb{R}^2
  • Activation function: σ\sigma (ReLU)
Show answer

h1=σ(W1x+b1)(4×3)(3×1)+(4×1)=(4×1)h_1 = \sigma(W_1 x + b_1) \quad (4 \times 3)(3 \times 1) + (4 \times 1) = (4 \times 1)


y=W2h1+b2(2×4)(4×1)+(2×1)=(2×1)y = W_2 h_1 + b_2 \quad (2 \times 4)(4 \times 1) + (2 \times 1) = (2 \times 1)


When processing a full batch (nn samples):


H1=σ(XW1T+1b1T)(n×3)(3×4)=(n×4)H_1 = \sigma(X W_1^T + \mathbf{1}b_1^T) \quad (n \times 3)(3 \times 4) = (n \times 4)


Y=H1W2T+1b2T(n×4)(4×2)=(n×2)Y = H_1 W_2^T + \mathbf{1}b_2^T \quad (n \times 4)(4 \times 2) = (n \times 2)


As this shows, the entire neural network forward pass is a sequence of matrix multiplications. GPUs are optimized to parallelize exactly these large-scale matrix multiplications.


Problem 4-2. Backpropagation and the Chain Rule#

Explain the process of computing the gradient LW1\frac{\partial L}{\partial W_1} of loss LL with respect to W1W_1 from a linear algebra perspective.

Show answer

Backpropagation is the matrix version of the chain rule.


LW1=Lh1h1W1\frac{\partial L}{\partial W_1} = \frac{\partial L}{\partial h_1} \cdot \frac{\partial h_1}{\partial W_1}


Step by step:

  1. Compute gradient at the output layer: δ2=Ly\delta_2 = \frac{\partial L}{\partial y}

  2. Backpropagate to layer 1: δ1=(W2Tδ2)σ(z1)\delta_1 = (W_2^T \delta_2) \odot \sigma'(z_1)

    • W2TW_2^T: multiply by the transpose matrix to match dimensions
    • \odot: element-wise multiplication (Hadamard product)
  3. Gradient for W1W_1: LW1=δ1xT\frac{\partial L}{\partial W_1} = \delta_1 x^T

Key insight: The reason transpose matrices appear in backpropagation is that we are tracing the forward-pass linear transformations in reverse. The reverse of a linear transformation = multiplication by its transpose.



Quiz: Putting It All Together#

Q1. Which of the following matrices has an inverse?


A=[2412],B=[3112],C=[0000]A = \begin{bmatrix} 2 & 4 \\ 1 & 2 \end{bmatrix}, \quad B = \begin{bmatrix} 3 & 1 \\ 1 & 2 \end{bmatrix}, \quad C = \begin{bmatrix} 0 & 0 \\ 0 & 0 \end{bmatrix}


Show answer
  • det(A)=44=0\det(A) = 4 - 4 = 0Singular, no inverse
  • det(B)=61=50\det(B) = 6 - 1 = 5 \neq 0Non-singular, inverse exists
  • det(C)=0\det(C) = 0Singular, no inverse

Answer: B


Q2. What is the linear algebra reason that L2 regularization (Ridge) solves the multicollinearity problem in machine learning?

Show answer

With multicollinearity, XTXX^T X becomes singular and its inverse does not exist.

L2 regularization adds λ\lambda to the diagonal entries:


(XTX+λI)1(X^T X + \lambda I)^{-1}


Adding the identity matrix II shifts every eigenvalue by λ\lambda:


λi(XTX+λI)=λi(XTX)+λλ>0\lambda_i(X^T X + \lambda I) = \lambda_i(X^T X) + \lambda \geq \lambda > 0


This guarantees the determinant is always positive and the inverse always exists.


Q3. Why are eigenvectors in PCA mutually orthogonal?

Show answer

The covariance matrix Σ\Sigma is a symmetric matrix (Σ=ΣT\Sigma = \Sigma^T).

Properties of symmetric matrices:

  • Eigenvectors corresponding to distinct eigenvalues are always orthogonal
  • This is known as the Spectral Theorem

Because the principal components point in mutually orthogonal directions, each one captures independent, non-overlapping information. This is exactly why PCA automatically eliminates multicollinearity.

// Related Posts