English
Matrix Calculus for Neural Networks: Deriving the MSE Gradient
Matrix calculus in deep learning is not about making notation look difficult. It is a way to verify tensor shapes, gradient directions, and code. Once you can derive the gradient of y_hat = Wx + b, backpropagation, convolution, and attention become much easier to debug.
This article starts with a single linear layer, a mean squared error loss, and a deterministic gradient check. The goal is to connect the formula, the hand calculation, and the runnable NumPy output.
1. Start With Shapes
Let x be a 3 x 1 column vector, W a 2 x 3 matrix, and b a 2 x 1 bias:
y_hat = W x + b
e = y_hat - y
L = 1/2 * e^T e
The important habit is shape checking. Wx is 2 x 1, so the error vector e is also 2 x 1. The gradient dL/dW must have the same shape as W, namely 2 x 3.
2. Hand Calculate One Gradient
For L = 1/2 * e^T e, we first get dL/de = e. Since e = Wx + b - y, the parameter gradients are:
dL/dW = e x^T
dL/db = e
Suppose the forward pass gives e = [0.2, 1.25]^T and x = [1.5, -2.0, 0.5]^T. Then:
dL/dW =
[0.2 ] [ 1.5, -2.0, 0.5 ] = [ 0.300, -0.400, 0.100 ]
[1.25] [ 1.875, -2.500, 0.625 ]
The companion lab writes the same numbers to gradient-check-results.csv: W00=0.300000, W11=-2.500000, and the finite-difference error is 0.000000.
3. Check With Finite Differences
Finite differences perturb one parameter at a time and estimate the loss slope from the change in loss.
def numeric_gradient(W, b, x, y, eps=1e-5):
grad = np.zeros_like(W)
for row in range(W.shape[0]):
for col in range(W.shape[1]):
original = W[row, col]
W[row, col] = original + eps
plus, _ = forward(W, b, x, y)
W[row, col] = original - eps
minus, _ = forward(W, b, x, y)
W[row, col] = original
grad[row, col] = (plus - minus) / (2 * eps)
return grad
Large disagreement usually points to a chain-rule, transpose, broadcasting, or shape bug rather than an optimizer problem.
4. What The Animation Shows
e x^T into the entries of dL/dW.Watch how the error vector controls the output dimension, the input transpose controls the input dimension, and their outer product fills the weight matrix.
5. Engineering Checklist
- Write the shape before writing the formula.
- Use the
1/2factor in MSE while hand-checking gradients. - Make bias broadcasting explicit during debugging.
- Run numerical checks on a tiny model before training a larger one.
The next article turns this linear layer into a computation graph and derives two-layer MLP backpropagation.
Chinese
神经网络矩阵微积分:从 y = Wx + b 推导 MSE 梯度
Open as a full page深度学习里的“矩阵微积分”不是为了把公式写复杂,而是为了让你检查每一层的维度、梯度方向和代码实现。只要能把 y_hat = Wx + b 的梯度手算清楚,后面的反向传播、卷积和注意力都会更容易落地。
这一篇从一个线性层开始:输入是列向量,参数是矩阵,损失是均方误差。我们用真实脚本做数值梯度检查,确认手算公式和代码输出一致。
一、先把形状写出来
设输入 x 是 3 x 1,权重 W 是 2 x 3,偏置 b 是 2 x 1:
y_hat = W x + b
e = y_hat - y
L = 1/2 * e^T e
这里的核心不是记住符号,而是检查形状:W x 得到 2 x 1,所以 e 也是 2 x 1。梯度 dL/dW 必须和 W 同形状,也就是 2 x 3。
二、手算一个梯度
对 L = 1/2 * e^T e,先有 dL/de = e。又因为 e = Wx + b - y,所以:
dL/dW = e x^T
dL/db = e
假设某次前向计算得到 e = [0.2, 1.25]^T,输入 x = [1.5, -2.0, 0.5]^T,那么:
dL/dW =
[0.2 ] [ 1.5, -2.0, 0.5 ] = [ 0.300, -0.400, 0.100 ]
[1.25] [ 1.875, -2.500, 0.625 ]
这个结果和实验包里的 gradient-check-results.csv 一致:W00=0.300000、W11=-2.500000,数值梯度差异为 0.000000。
三、用有限差分检查代码
数值梯度检查的思想是:稍微增加和减少一个参数,看 loss 的变化率是否等于解析梯度。
def numeric_gradient(W, b, x, y, eps=1e-5):
grad = np.zeros_like(W)
for row in range(W.shape[0]):
for col in range(W.shape[1]):
original = W[row, col]
W[row, col] = original + eps
plus, _ = forward(W, b, x, y)
W[row, col] = original - eps
minus, _ = forward(W, b, x, y)
W[row, col] = original
grad[row, col] = (plus - minus) / (2 * eps)
return grad
如果解析梯度和数值梯度差距很大,通常不是优化器问题,而是链式法则、广播、转置或 shape 写错了。
四、动画看什么
e 和 x^T 的外积展开成 dL/dW 的每个元素。看动画时重点观察三件事:误差向量控制输出维度,输入转置控制输入维度,外积刚好填满权重矩阵。
五、工程检查清单
- 每个中间张量先写 shape,再写公式。
- loss 最好先用
1/2系数,手算时可以消掉平方的2。 - 广播虽然方便,但调试梯度时要明确偏置是列向量还是一维数组。
- 小模型先跑数值梯度检查,再上批量训练和复杂网络。
下一篇会把这个线性层接入计算图,继续推导两层 MLP 的反向传播。
Matrix calculus in deep learning is not about making notation look difficult. It is a way to verify tensor shapes, gradient directions, and code. Once you can derive the gradient of y_hat = Wx + b, backpropagation, convolution, and attention become much easier to debug.
This article starts with a single linear layer, a mean squared error loss, and a deterministic gradient check. The goal is to connect the formula, the hand calculation, and the runnable NumPy output.
1. Start With Shapes
Let x be a 3 x 1 column vector, W a 2 x 3 matrix, and b a 2 x 1 bias:
y_hat = W x + b
e = y_hat - y
L = 1/2 * e^T e
The important habit is shape checking. Wx is 2 x 1, so the error vector e is also 2 x 1. The gradient dL/dW must have the same shape as W, namely 2 x 3.
2. Hand Calculate One Gradient
For L = 1/2 * e^T e, we first get dL/de = e. Since e = Wx + b - y, the parameter gradients are:
dL/dW = e x^T
dL/db = e
Suppose the forward pass gives e = [0.2, 1.25]^T and x = [1.5, -2.0, 0.5]^T. Then:
dL/dW =
[0.2 ] [ 1.5, -2.0, 0.5 ] = [ 0.300, -0.400, 0.100 ]
[1.25] [ 1.875, -2.500, 0.625 ]
The companion lab writes the same numbers to gradient-check-results.csv: W00=0.300000, W11=-2.500000, and the finite-difference error is 0.000000.
3. Check With Finite Differences
Finite differences perturb one parameter at a time and estimate the loss slope from the change in loss.
def numeric_gradient(W, b, x, y, eps=1e-5):
grad = np.zeros_like(W)
for row in range(W.shape[0]):
for col in range(W.shape[1]):
original = W[row, col]
W[row, col] = original + eps
plus, _ = forward(W, b, x, y)
W[row, col] = original - eps
minus, _ = forward(W, b, x, y)
W[row, col] = original
grad[row, col] = (plus - minus) / (2 * eps)
return grad
Large disagreement usually points to a chain-rule, transpose, broadcasting, or shape bug rather than an optimizer problem.
4. What The Animation Shows
e x^T into the entries of dL/dW.Watch how the error vector controls the output dimension, the input transpose controls the input dimension, and their outer product fills the weight matrix.
5. Engineering Checklist
- Write the shape before writing the formula.
- Use the
1/2factor in MSE while hand-checking gradients. - Make bias broadcasting explicit during debugging.
- Run numerical checks on a tiny model before training a larger one.
The next article turns this linear layer into a computation graph and derives two-layer MLP backpropagation.
Search questions
FAQ
Who is this article for?
This article is for readers who want an intermediate-level guide to Matrix Calculus for Neural Networks. It takes about 13 min and focuses on Matrix Calculus, NumPy, Gradient Check.
What should I read next?
The recommended next step is Backpropagation as a Computation Graph, so the article connects into a longer learning route instead of ending as an isolated note.
Does this article include runnable code or companion resources?
Yes. Use the run notes, resource cards, and download links on the page to reproduce the example or inspect the companion files.
How does this article fit into the larger site?
It is connected to the article context block, learning routes, resources, and project timeline so readers can move from concept to implementation.
Article context
AI Learning Project
A practical route from AI concepts to machine learning workflow, evaluation, neural networks, Python practice, handwritten digits, a CIFAR-10 CNN, adversarial traffic-defense notes, and AI security.
Derive dL/dW for y = Wx + b and verify it with finite differences.
Download share card Open share centerCompanion resources
AI Learning Project / GUIDE
Deep Learning Math Lab README
Setup commands, script entry points, generated outputs, and figure notes for the math series.
AI Learning Project / DATASET
Gradient check results CSV
Stores MSE analytic gradients, finite-difference gradients, and error norms.
AI Learning Project / DIAGRAM
Deep learning math figure set
Includes matrix shapes, computation graphs, loss contours, convolution scans, and attention heatmaps.
AI Learning Project / TOOL
Deep learning math interactive visualizer
Browser modules for gradient checking, optimizer paths, convolution output size, and attention heatmaps.
Project timeline
Published posts
- AI Basics Learning Roadmap Separate AI, machine learning, and deep learning before going into implementation details.
- Machine Learning Workflow Follow the practical path from data and features to training, prediction, and evaluation.
- Model Training and Evaluation Understand loss, overfitting, train/test splits, accuracy, recall, and F1.
- Neural Network Basics Move from perceptrons to activation, forward propagation, backpropagation, and training loops.
- Matrix Calculus for Neural Networks Derive dL/dW for y = Wx + b and verify it with finite differences.
- Backpropagation as a Computation Graph Trace local gradients through ReLU and softmax cross-entropy in a two-layer MLP.
- Gradient Descent and Optimizer Geometry Compare gradient descent, momentum, and Adam on a visible quadratic loss surface.
- Convolution and Receptive Field Math Compute convolution output size, receptive fields, channel mixing, and im2col layout.
- Transformer Attention Math Hand-calculate Q/K/V scores, softmax weights, masks, multi-head structure, and KV cache.
- NLP Basics: Understanding Bag of Words and TF-IDF An introduction to the most fundamental text representation methods in NLP: Bag of Words (BoW) and TF-IDF.
- RNN Basics: Handling Sequential Data with Memory Understand the core concepts of Recurrent Neural Networks (RNN), the role of hidden states, and their application in NLP.
- Transformer Self-Attention Read Q/K/V, scaled dot-product attention, multi-head attention, and positional encoding before exploring LLM internals.
- Python AI Mini Practice Run a small scikit-learn classification task and read the experiment output.
- Handwritten Digit Dataset Basics Read train.csv, test.csv, labels, and the flattened 28 by 28 pixel layout before training the classifier.
- Handwritten Digit Softmax in C Follow the C implementation from logits and softmax probabilities to confusion matrices and submission export.
- Handwritten Digit Playground Notes See how the offline classifier was adapted into a browser demo with drawing input and probability output.
- CIFAR-10 Tiny CNN Tutorial in C Build and train a small convolutional neural network for CIFAR-10 image classification, then read its loss and accuracy output.
- Building a Tiny CIFAR-10 CNN in C: Convolution, Pooling, and Backpropagation A source-based walkthrough of cifar10_tiny_cnn.c, covering CIFAR-10 binary input, 3x3 convolution, ReLU, max pooling, fully connected logits, softmax, backpropagation, and local commands.
- High-Entropy Traffic Defense Notes Study encrypted metadata leaks, entropy, traffic classifiers, and a defensive Python chaffing prototype.
- AI Security Threat Modeling Build a defense map with NIST adversarial ML, MITRE ATLAS, and OWASP LLM risks.
- Adversarial Examples and Robust Evaluation Evaluate clean and perturbed accuracy with an FGSM-style digits experiment.
- Data Poisoning and Backdoor Defense Study poison rate, trigger behavior, attack success rate, and training pipeline controls.
- Model Privacy and Extraction Defense Measure membership inference signal and surrogate fidelity against a local toy model.
- LLM, RAG, and Agent Security Separate instructions from data and enforce tool permissions against indirect prompt injection.
Published resources
- Python AI practice code guide The article includes a runnable scikit-learn classification script.
- digit_softmax_classifier.c The C source for the handwritten digit softmax classifier.
- train.csv.zip Compressed handwritten digit training set with 42000 labeled samples.
- test.csv.zip Compressed handwritten digit test set with 28000 unlabeled samples.
- sample_submission.csv The official submission format example for checking the final output columns.
- submission.csv The prediction file generated by the current C project.
- digit-playground-model.json The compact softmax demo model and sample set used by the browser playground.
- digit-sample-grid.svg A small handwritten digit preview grid extracted from the training set.
- Handwritten digit project bundle Contains the source file, compressed datasets, submission files, browser model, and preview grid.
- cifar10_tiny_cnn.c source Single-file C tiny CNN with CIFAR-10 loading, convolution, pooling, softmax, and backpropagation.
- model_weights.bin sample weights Model weights generated by one local small-sample run.
- test_predictions.csv sample predictions Sample test prediction output from the CIFAR-10 tiny CNN.
- CNN project explanation PDF Companion explanation material for the CNN project.
- Virtual Mirror redacted code skeleton A redacted mld_chaffing_v2.py control-flow skeleton with secrets, node topology, and target lists removed.
- Virtual Mirror stress-test template A redacted CSV template for CPU, memory, peak threads, pulse rate, latency, and error measurements.
- Virtual Mirror classifier-evaluation template A CSV template for TP, FN, FP, TN, accuracy, precision, recall, F1, ROC-AUC, entropy, and JS divergence.
- Virtual Mirror resource notes Notes explaining why the public resources include only redacted code, test templates, and architecture context.
- AI Security Lab README Setup, safety boundaries, and quick-run commands for the AI Security series.
- AI Security Lab full bundle Includes safe toy scripts, result CSVs, risk register, attack-defense matrix, and architecture diagram.
- AI security risk register CSV risk register template for AI threat modeling and release review.
- AI attack-defense matrix Maps attack surface, toy demo, metric, and defensive control into one CSV table.
- AI Security Lab architecture diagram Shows threat modeling, robustness, data integrity, model privacy, and RAG guardrails.
- FGSM digits robustness script FGSM-style perturbation and accuracy-drop experiment for a local digits classifier.
- Data poisoning and backdoor toy script Demonstrates poison rate, trigger behavior, and attack success rate on digits.
- Model privacy and extraction toy script Outputs membership AUC, target accuracy, surrogate fidelity, and surrogate accuracy.
- RAG prompt injection guard toy script Uses a deterministic toy agent to demonstrate external-data demotion and tool-policy blocking.
- Deep Learning Math Lab README Setup commands, script entry points, generated outputs, and figure notes for the math series.
- Deep learning math full lab bundle Bundles NumPy scripts, CSV outputs, formula diagrams, loss contours, convolution figures, and attention heatmaps.
- Gradient check results CSV Stores MSE analytic gradients, finite-difference gradients, and error norms.
- Optimizer path CSV Step-by-step coordinates and loss for gradient descent, momentum, and Adam on a 2D quadratic.
- Attention weights CSV Scores, softmax weights, and context vectors for a three-token scaled dot-product attention example.
- Deep learning math figure set Includes matrix shapes, computation graphs, loss contours, convolution scans, and attention heatmaps.
- Deep learning math interactive visualizer Browser modules for gradient checking, optimizer paths, convolution output size, and attention heatmaps.
- Deep Learning topic share card A 1200x630 SVG card for sharing the Deep Learning / CNN topic hub.
- Machine Learning From Scratch share card A 1200x630 SVG card for the K-means, Iris, and ML workflow topic hub.
- Student AI Projects share card A 1200x630 SVG card for handwritten digits, C classifiers, and browser demos.
- CNN convolution scan animation An 8-second Remotion animation showing how a 3x3 convolution kernel scans an input and builds a feature map.
Current route
- AI Basics Learning Roadmap Learning path step
- Machine Learning Workflow Learning path step
- Model Training and Evaluation Learning path step
- Neural Network Basics Learning path step
- Matrix Calculus for Neural Networks Learning path step
- Backpropagation as a Computation Graph Learning path step
- Gradient Descent and Optimizer Geometry Learning path step
- Convolution and Receptive Field Math Learning path step
- Transformer Attention Math Learning path step
- Transformer Self-Attention Learning path step
- LLM Visualizer Learning path step
- Python AI Mini Practice Learning path step
- Handwritten Digit Dataset Basics Learning path step
- Handwritten Digit Softmax in C Learning path step
- Handwritten Digit Playground Notes Learning path step
- CIFAR-10 Tiny CNN Tutorial in C Learning path step
- High-Entropy Traffic Defense Notes Learning path step
- AI Security Threat Modeling Learning path step
- Adversarial Examples and Robust Evaluation Learning path step
- Data Poisoning and Backdoor Defense Learning path step
- Model Privacy and Extraction Defense Learning path step
- LLM, RAG, and Agent Security Learning path step
Next notes
- Add more image-classification and error-analysis cases
- Turn common metrics into a quick reference
- Add more AI security defense experiment notes
