CodeBlanks Logo Icon CodeBlanks

Identity matrix

An identity matrix is a square matrix with 1s on the diagonal and 0s elsewhere.

Identity matrix

The identity matrix is a square matrix with 1s on the diagonal and 0s elsewhere. It is like 1 among numbers: A @ I = A.

I = np.eye(3)
print(I)
# [[1. 0. 0.]
#  [0. 1. 0.]
#  [0. 0. 1.]]
A = np.array([[2, 1], [0, 3]])
print(A @ np.eye(2))   # the same as A

Ridge regression writes XᵀX + αI; adding a small value to the diagonal makes the solution stable.

Inverse matrix

The inverse A⁻¹ of A satisfies A @ A⁻¹ = I. Only square, non-singular (non-zero determinant) matrices have an inverse.

A = np.array([[2.0, 1.0], [1.0, 1.0]])
Ai = np.linalg.inv(A)
print(Ai)                         # [[ 1. -1.] [-1.  2.]]
print(np.allclose(A @ Ai, np.eye(2)))   # True
print(np.linalg.det(A))           # 1.0

Because of floating-point errors the results may not be exactly equal; np.allclose is used for comparison.

Practice Verify the inverse

Take the inverse of A with np.linalg.inv and print it. Then print whether A @ Ai is close to the identity matrix using np.allclose and np.eye.

Starter code

model.py
import numpy as np

A = np.array([[4.0, 7.0], [2.0, 6.0]])

# buraya yaz

Sample solution

model.py
import numpy as np

A = np.array([[4.0, 7.0], [2.0, 6.0]])

Ai = np.linalg.inv(A)
print(Ai)
print(np.allclose(A @ Ai, np.eye(2)))

Expected output

[[ 0.6 -0.7]
 [-0.2  0.4]]
True

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How many 1s does <code>np.eye(4)</code> contain?

  • 4 Correct answer
  • 16
  • 1
  • 8

Explanation: Only the diagonal is 1; a 4×4 matrix has 4 diagonal elements.

2 Create a 3×3 identity matrix.

Question
I = np.____(3)
Answer
I = np.eye(3)

Explanation: np.eye(n) produces an n×n identity matrix.

3 Match the concepts.

Term Meaning
np.eye Identity matrix
np.linalg.inv Inverse matrix
np.linalg.det Determinant
np.allclose Approximate equality

All lessons in Beginner

13 Project: Classification

  1. Preparing data
  2. Training model
  3. Prediction
  4. Evaluation