Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách thực hiện chuẩn hóa L1 (L1 Normalization) bằng scikit-learn trong Python

L1 Normalization (Least Absolute Deviations) scale từng mẫu sao cho tổng giá trị tuyệt đối = 1: ||x||₁ = Σ|xᵢ| = 1.

Ví dụ với sklearn.preprocessing.normalize


import numpy as np
from sklearn import preprocessing

input_data = np.array([
    [34.78, 31.9, -65.5],
    [-16.5, 2.45, -83.5],
    [0.5, -87.98, 45.62],
    [5.9, 2.38, -55.82]
])

data_normalized_l1 = preprocessing.normalize(input_data, norm='l1')
print("L1 normalized data:\n", data_normalized_l1)

Kết quả

[[ 0.2631  0.2413 -0.4955]
 [-0.1611  0.0239 -0.8150]
 [ 0.0037 -0.6561  0.3402]
 [ 0.0920  0.0371 -0.8708]]

Mỗi hàng: tổng giá trị tuyệt đối = 1.

So sánh L1 vs L2

Khi nào dùng L1?

  • Chuẩn hóa histogram (tần suất thành xác suất).
  • Sparse coding, compressed sensing.
  • Khi muốn bảo toàn độ thưa của vector.
Đặc điểmL1 NormL2 Norm
Công thứcΣ|xᵢ| = 1√(Σxᵢ²) = 1
Hình họcHình thoi (diamond)Hình cầu (sphere)
Độ thưa (sparsity)Khuyến khích sparsePhân bố đều
Ứng dụngLasso, feature selectionRidge, cosine similarity