Ma trận đơn vị (Identity Matrix) là ma trận vuông có phần tử trên đường chéo chính bằng 1, các phần tử còn lại bằng 0.
Ví dụ
def print_identity_matrix(n):
"""In ma trận đơn vị cấp n."""
print(f"Ma trận đơn vị {n}×{n}:")
for i in range(n):
row = []
for j in range(n):
if i == j:
row.append('1')
else:
row.append('0')
print(' '.join(row))
def identity_matrix(n):
"""Trả về ma trận đơn vị dạng list of lists."""
return [[1 if i == j else 0 for j in range(n)] for i in range(n)]
# Test
n = 4
print_identity_matrix(n)
print("\nDạng list:")
matrix = identity_matrix(n)
for row in matrix:
print(row)
# Kiểm tra tính chất: A × I = A
import numpy as np
A = np.array([[2, 3], [4, 5]])
I = np.eye(2, dtype=int)
print(f"\nA = \n{A}")
print(f"I = \n{I}")
print(f"A × I = \n{A @ I}")
Kết quả
Ma trận đơn vị 4×4: 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 Dạng list: [1, 0, 0, 0] [0, 1, 0, 0] [0, 0, 1, 0] [0, 0, 0, 1] A = [[2 3] [4 5]] I = [[1 0] [0 1]] A × I = [[2 3] [4 5]]
Giải thích
- Vòng lặp ngoài
iduyệt hàng (0 đến n-1). - Vòng lặp trong
jduyệt cột (0 đến n-1). - Nếu
i == j(đường chéo chính) -> in 1, ngược lại in 0. - Ma trận đơn vị có tính chất:
A × I = I × A = Acho mọi ma trận vuông A cùng cấp.
Cách ngắn gọn: List comprehension
n = 5
I = [[1 if i == j else 0 for j in range(n)] for i in range(n)]
for row in I:
print(' '.join(map(str, row)))
NumPy: numpy.eye() hoặc numpy.identity()
import numpy as np # eye: tạo ma trận đơn vị (có thể không vuông) print(np.eye(3, dtype=int)) # [[1 0 0] # [0 1 0] # [0 0 1]] # identity: chỉ ma trận vuông print(np.identity(3, dtype=int))
Ma trận đơn vị dạng sparse (scipy)
from scipy.sparse import eye
import numpy as np
# Ma trận thưa 1000x1000
I_sparse = eye(1000, format='csr')
print(f"Shape: {I_sparse.shape}")
print(f"Non-zero elements: {I_sparse.nnz}") # 1000
print(f"Memory efficient: chỉ lưu {I_sparse.nnz} phần tử thay vì 1,000,000")
Ứng dụng: Khởi tạo trọng lượng neural network
def initialize_weights(input_size, output_size):
"""Xavier/Glorot initialization."""
import numpy as np
limit = np.sqrt(6 / (input_size + output_size))
return np.random.uniform(-limit, limit, (input_size, output_size))
# Identity initialization cho residual connections
def identity_init(size):
return np.eye(size) * 0.1 # Small identity