With ordinary numbers, 0 and 1 are special. Adding 0 changes nothing, and multiplying by 1 changes nothing. Matrices have their own 0 and 1: the zero matrix and the identity matrix. Next to them sit diagonal matrices, which do the next simplest thing: they stretch each feature by its own amount and leave everything else alone.
These matrices are simple on purpose, and that's why they matter. Converting marks out of different totals into percentages, standardising features, encoding categories as one-hot vectors and looking up a word's embedding are all multiplications by these special matrices, even when the code never writes them down.
What you need first: matrix multiplication explained and unit vectors and normalisation (for the standard unit vectors).
Key terms
- Zero matrix: a matrix of all zeros. Adding it changes nothing.
- Identity matrix (I): a square matrix with 1s on the main diagonal and 0s everywhere else. Multiplying by it changes nothing.
- Diagonal matrix: a square matrix whose only non-zero entries are on the main diagonal. Written diag(d₁, d₂, …).
- One-hot vector: a vector of all 0s except a single 1, which marks one category.
- Embedding matrix: a table with one row of numbers per word, product or user, learned by a model.
The zero matrix and the identity matrix
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
A = np.array([[2, 7], [1, 8]])
Z = np.zeros((2, 2), dtype=int)
I = np.eye(2, dtype=int)
print(I)
print(np.array_equal(A + Z, A), np.array_equal(I @ A, A), np.array_equal(A @ I, A))
[[1 0]
[0 1]]
True True True
np.zeros makes a matrix of zeros and np.eye makes an identity matrix (the name comes from "I", pronounced "eye"). Adding the zero matrix does nothing, and multiplying by the identity on either side does nothing. They're the matrix versions of 0 and 1.
Why the identity does nothing
Look at its columns: (1, 0) and (0, 1). Those are the standard unit vectors from unit vectors and normalisation, one step along each axis. Now use the column view: Ix = x₁ × (1, 0) + x₂ × (0, 1) = (x₁, x₂). It rebuilds the vector from its own components, so nothing changes.
The identity matters because it's the target of "undoing". A matrix that undoes A is one that multiplies with it to give I, and that's the inverse, which you'll meet in the transformations module.
Diagonal matrices: a separate stretch for each feature
Three exams are marked out of different totals: English out of 80, science out of 50, maths out of 100. To compare them fairly, convert each to a percentage. That means multiplying the English column by 100/80, the science column by 100/50 and the maths column by 1. A diagonal matrix does exactly that:
raw = np.array([
[52, 35, 78], # Meera
[44, 40, 91], # Rohan
[70, 31, 70], # Kabir
])
D = np.diag([100 / 80, 100 / 50, 1.0])
print(D)
print(raw @ D)
[[1.25 0. 0. ]
[0. 2. 0. ]
[0. 0. 1. ]]
[[65. 70. 78. ]
[55. 80. 91. ]
[87.5 62. 70. ]]
np.diag builds a diagonal matrix from a list of numbers. Multiplying raw @ D scales each column by its diagonal entry: every English mark ×1.25, every science mark ×2. Meera's 35 out of 50 in science becomes 70%. Nothing mixes: the English column only ever affects English.
Which side the diagonal matrix goes on decides what gets scaled:
- X @ D scales the columns (features), as here.
- D @ X scales the rows (examples).
Here's what these special matrices look like as pictures. Their patterns are what make them special:
one_hot_rows = np.eye(4)[[2, 0, 3, 0, 1]]
fig, axes = plt.subplots(1, 3, figsize=(11, 3.6))
for ax, matrix, title in [(axes[0], np.eye(4), "identity I"),
(axes[1], np.diag([1.25, 2.0, 1.0, 0.5]), "diagonal diag(1.25, 2, 1, 0.5)"),
(axes[2], one_hot_rows, "rows of I: one-hot codes")]:
ax.imshow(matrix, cmap="Oranges", vmin=0, vmax=2)
for i in range(matrix.shape[0]):
for j in range(matrix.shape[1]):
ax.text(j, i, f"{matrix[i, j]:g}", ha="center", va="center", fontsize=12)
ax.set_title(title)
ax.set_xticks([])
ax.set_yticks([])
plt.tight_layout()
plt.show()
You usually don't build the diagonal matrix
Multiplying by a diagonal matrix is the same as broadcasting a vector of scales over the columns, and the vector is much cheaper: a 1,000-feature diagonal matrix holds a million numbers, almost all zeros. In code, you write the broadcast:
print(np.allclose(raw @ D, raw * np.array([1.25, 2.0, 1.0])))
True
So why learn the matrix? Because formulas in books and papers write scaling as a diagonal matrix, and seeing D should make you think "each feature stretched by its own amount".
Standardising is a diagonal matrix
Feature scaling with StandardScaler subtracts each column's mean, then divides each column by its standard deviation. The second step is multiplication by a diagonal matrix:
from sklearn.preprocessing import StandardScaler
means, stds = raw.mean(axis=0), raw.std(axis=0)
by_hand = (raw - means) @ np.diag(1 / stds)
print(np.allclose(by_hand, StandardScaler().fit_transform(raw)))
True
Centre by broadcasting, then stretch each feature by 1 ÷ its spread. That's all StandardScaler does.
Rows of the identity are one-hot codes
Each row of the identity has a single 1. That makes rows of I the perfect codes for categories. Say four cities are numbered 0 to 3, and five customers live in cities 2, 0, 3, 0 and 1. Picking those rows of a 4 × 4 identity gives each customer a one-hot vector, as in the third picture above:
cities = ["Delhi", "Pune", "Kochi", "Indore"]
codes = np.array([2, 0, 3, 0, 1])
one_hot = np.eye(4, dtype=int)[codes]
print(pd.DataFrame(one_hot, columns=cities))
Delhi Pune Kochi Indore
0 0 0 1 0
1 1 0 0 0
2 0 0 0 1
3 1 0 0 0
4 0 1 0 0
np.eye(4)[codes] picks row 2, then row 0, then row 3, and so on. This is exactly what OneHotEncoder produces.
One-hot times a matrix picks out a row
Now multiply a one-hot vector by any matrix. Predict what comes out of this one, where each row of E describes one city with three numbers:
E = np.array([
[0.9, 0.1, 0.4], # Delhi
[0.2, 0.8, 0.5], # Pune
[0.3, 0.6, 0.9], # Kochi
[0.7, 0.3, 0.2], # Indore
])
print(one_hot[0] @ E)
print(E[codes[0]])
[0.3 0.6 0.9]
[0.3 0.6 0.9]
The one-hot vector for Kochi, (0, 0, 1, 0), times E gives Kochi's row: the column view of x @ E takes 0 of every row except Kochi's. That's what an embedding layer in a neural network is. Each word, product or user has a learned row in an embedding matrix, and "multiply the one-hot code by the matrix" is the same as "look up that row", which is how libraries actually do it, because a lookup is much faster.
Common mistakes
- Confusing the two jobs of
np.diag. Given a 1D list, it builds a diagonal matrix. Given a 2D matrix, it extracts the diagonal as a vector. Check the shape of what you get. - Putting the diagonal matrix on the wrong side. XD scales columns (features); DX scales rows (examples).
- Building huge diagonal matrices. Broadcast a vector of scales instead.
- Thinking
np.eye(3)andnp.ones((3, 3))are similar. The identity has 1s only on the diagonal;onesfills every entry.
Practice
- What's diag(2, 3) @ (4, 5)? Explain it without the row-times-column rule.
Show the answer
(8, 15). A diagonal matrix stretches each coordinate separately: the first by 2 and the second by 3.
- Predict, then check:
np.diag(np.array([[1, 2], [3, 4]])).
Show the answer
print(np.diag(np.array([[1, 2], [3, 4]])))
[1 4]
Given a matrix, np.diag extracts its diagonal.
- A matrix D = diag(1, 1, 0) multiplies a dataset with 3 features, as XD. What happens to the data? When might you want this?
Show the answer
The third column becomes all zeros, so the third feature is dropped (masked), while the other two are unchanged. It's a way of switching a feature off, for example to see how a model does without it.
- What is D @ D for D = diag(2, 5)? What about the matrix that undoes D?
Show the answer
DD = diag(4, 25): diagonal matrices multiply entry by entry along the diagonal. The undoing matrix is diag(1/2, 1/5), because diag(2, 5) @ diag(1/2, 1/5) = I.
- With 50,000 words and embeddings of 300 numbers, what's the shape of the embedding matrix? Why do libraries look up rows instead of multiplying by one-hot vectors?
Show the answer
(50,000 × 300). A one-hot vector would have 50,000 entries, all but one of them 0, so multiplying by it does 15 million multiplications to copy 300 numbers. A lookup just copies the row.
- In your own words, explain why Ix = x, using the column view.
Show the answer
The columns of I are one step along each axis. The column view builds Ix as x₁ steps along the first axis plus x₂ along the second, and so on, which lands exactly at x.
Interview questions
What is the identity matrix, and why is it important?
A square matrix with ones on the main diagonal and zeros elsewhere. It's the multiplicative identity: AI = IA = A. It defines the inverse (AA⁻¹ = I), and it appears in regularisation, for example ridge regression adds λI to XᵀX.
How is an embedding layer related to matrix multiplication?
An embedding layer stores a matrix with one row per token. Multiplying a token's one-hot vector by this matrix selects its row, so the layer is mathematically a linear layer on one-hot inputs, implemented as a fast row lookup. The rows are learned by gradient descent.
Key takeaways
- The zero matrix and the identity are the matrix versions of 0 and 1: adding 0 or multiplying by I changes nothing.
- The columns of the identity are the standard unit vectors, which is why Ix = x.
- A diagonal matrix stretches each feature (or example) by its own amount; XD scales columns and DX scales rows.
- In code, broadcast a vector of scales instead of building a diagonal matrix. Standardising is centring plus a diagonal scaling.
- Rows of the identity are one-hot codes, and one-hot times a matrix picks a row: that's an embedding lookup.
Frequently asked questions
Does the identity have to be square?
Yes. For IA = A and AI = A to both work with the shape rule, I must have as many rows as columns. np.eye(3, 4) makes a rectangular matrix with 1s on its diagonal, but it isn't an identity matrix.
What's a scalar matrix?
A diagonal matrix with the same number everywhere on the diagonal, such as 5I. Multiplying by it is the same as multiplying by the plain number 5.
Why does ridge regression add a multiple of the identity?
Adding λI to XᵀX adds λ to each diagonal entry, one per feature. It pulls the weights towards zero and makes the calculation stable even when features are almost duplicates. You'll see it in the regularisation lessons of the machine learning course.
What to learn next
- Meet matrices with mirror, half-empty and right-angle patterns in symmetric, triangular and orthogonal matrices.
- Use one-hot codes on real data in encoding categorical data.
- Revisit the scaling step in feature scaling.