eye, identity & diag
Create identity matrices with np.eye and np.identity, build diagonal matrices with np.diag, and extract a matrix's diagonal.
In a head-to-head table where rows and columns are the same teams, the cells where a team meets itself form the diagonal. Linear algebra (used heavily in Machine Learning) constantly needs matrices with special diagonals — NumPy creates them in one call.
Definition
An identity matrix is a square matrix with
1on the main diagonal (top-left to bottom-right) and0everywhere else.np.identity(n)creates an n×n identity matrix;np.eye(N, M, k)is the more flexible version that can be rectangular and can put the ones on a shifted diagonal.np.diag(v, k)builds a square matrix with the 1D arrayvon its diagonal — or, when given a 2D array, extracts its diagonal.
- Main diagonal — the positions
[0, 0],[1, 1],[2, 2]…, where row index = column index. k(diagonal offset) —k=0is the main diagonal,k=1is the one just above it,k=-1just below.- Identity — multiplying any matrix by the identity matrix leaves it unchanged (like multiplying a number by 1).
Syntax
python
np.eye(N, M=None, k=0, dtype=float)
np.identity(n, dtype=float)
np.diag(v, k=0)| Function / parameter | Meaning | Default |
|---|---|---|
np.eye → N | Number of rows | required |
np.eye → M | Number of columns | None (= N, square) |
np.eye → k | Which diagonal gets the ones | 0 (main) |
np.identity → n | Size of the square identity matrix | required |
dtype | Data type (both functions) | float64 |
np.diag → v | 1D array → build a diagonal matrix; 2D array → extract its diagonal | required |
np.diag → k | Which diagonal to build / extract | 0 |
Example — eye and identity
python
import numpy as np
print(np.eye(3))
print(np.eye(3, dtype=int))
print(np.eye(2, 4, dtype=int))
print(np.eye(4, k=1, dtype=int))
print(np.identity(3))text
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
[[1 0 0]
[0 1 0]
[0 0 1]]
[[1 0 0 0]
[0 1 0 0]]
[[0 1 0 0]
[0 0 1 0]
[0 0 0 1]
[0 0 0 0]]
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]How it works:
np.eye(3)andnp.identity(3)give the same 3×3 identity matrix (floats by default).np.eye(2, 4)is rectangular: 2 rows, 4 columns —identitycannot do this.k=1shifts the ones one place to the right (the "super-diagonal"), so the last row is all zeros.
Example — diag: build and extract
python
import numpy as np
print(np.diag([10, 20, 30]))
m = np.array([[72, 45, 88], [56, 0, 74], [45, 32, 0]])
print(np.diag(m))
print(np.diag(m, k=1))
print(np.diag([1, 2], k=1))text
[[10 0 0]
[ 0 20 0]
[ 0 0 30]]
[72 0 0]
[45 74]
[[0 1 0]
[0 0 2]
[0 0 0]]How it works: np.diag does two opposite jobs depending on the input:
- 1D input → builds a square matrix with those values on the diagonal (
[10, 20, 30]→ 3×3). - 2D input → extracts the diagonal as a 1D array:
m[0,0], m[1,1], m[2,2]= 72, 0, 0. Withk=1it readsm[0,1], m[1,2]= 45, 74. np.diag([1, 2], k=1)places the values above the main diagonal, so the matrix grows to 3×3.
Comparison
np.eye | np.identity | np.diag | |
|---|---|---|---|
| Shape | Square or rectangular | Square only | Square (when building) |
| Diagonal values | Always 1 | Always 1 | Any values you pass |
Offset diagonal (k) | ✅ | ❌ | ✅ |
| Extract a diagonal | ❌ | ❌ | ✅ (pass a 2D array) |
| Typical use | Masks, one-hot encoding, shifted diagonals | Textbook identity matrix | Scaling matrices, reading a diagonal |
Tip:
np.eye(n)rows are one-hot vectors — row 2 ofnp.eye(4)is[0, 0, 1, 0]. In ML,np.eye(num_classes)[labels]is a classic trick to one-hot encode labels.
Common mistakes
- ❌
np.identity(2, 4)for a rectangular matrix. ✅ Usenp.eye(2, 4). - ❌ Forgetting that
np.diagon a 2D array extracts instead of builds. ✅ Checkv.ndim: 1 → build, 2 → extract. - ❌ Expecting integers from
np.eye(3). ✅ It returns floats; adddtype=int.
Interview tip
Q: What is the difference between np.eye and np.identity?
A: np.identity(n) only makes a square n×n identity matrix. np.eye(N, M, k) can make rectangular matrices and place the ones on any diagonal via k. np.eye(n) with defaults equals np.identity(n).
Key points to remember
- An identity matrix has 1s on the main diagonal (row index = column index) and 0s elsewhere.
- np.identity(n) makes a square n×n identity matrix; np.eye(N, M, k) also supports rectangular shapes and offset diagonals.
- k=0 is the main diagonal, k=1 is above it, k=-1 is below it.
- np.diag(1D array) builds a diagonal matrix; np.diag(2D array) extracts the diagonal.
- eye and identity return float64 by default — pass dtype=int for integers.
- Rows of np.eye(n) are one-hot vectors, useful for encoding categories.
Try it yourself
eye vs identity
diag: build and extract
One-hot encoding with eye
Practice: identity check
Revision Flashcards
Tap a card to flip it and see the answer.
