Divide the array by its Euclidean ($L_2$) norm computed via np.linalg.norm(v)—for example, unit_v = v / np.linalg.norm(v) for a 1D vector or unit_rows = X / np.linalg.norm(X, axis=1, keepdims=True) for row-wise normalization of a 2D matrix—always guarding against zero-norm vectors (norm == 0) so division by zero does not produce NaN values.
Basic Example
import numpy as np
# 1. Recommended: Normalize a 1D vector to unit length (L2 norm == 1.0)
v = np.array([3.0, 4.0, 0.0])
norm = np.linalg.norm(v)
unit_v = v / norm if norm > 0 else np.zeros_like(v)
print(unit_v)
# Output: [0.6 0.8 0. ]
print(np.linalg.norm(unit_v))
# Output: 1.0
# 2. Row-wise unit normalization for a 2D batch of vectors (e.g., embeddings):
X = np.array([
[3.0, 4.0],
[0.0, 0.0], # Zero vector edge case
[1.0, 1.0],
])
norms = np.linalg.norm(X, axis=1, keepdims=True)
unit_X = np.divide(X, norms, out=np.zeros_like(X, dtype=float), where=norms != 0)
print(unit_X)
# Output:
# [[0.70710678 0.70710678]
# [0. 0. ]
# [0.70710678 0.70710678]]
Key Details & Edge Cases
- Guard against zero vectors (
norm == 0) to preventNaNpropagation:- Dividing a zero vector
[0.0, 0.0, 0.0]by0.0emits aRuntimeWarning: invalid value encountered in divideand fills the output withnan. Usingnp.divide(X, norms, out=np.zeros_like(X, dtype=float), where=norms != 0)(ornp.where(norms > 0, X / np.maximum(norms, 1e-12), 0.0)) cleanly leaves zero vectors as all zeros without warnings orNaNs.
- Dividing a zero vector
- Always pass
keepdims=Truewhen normalizing along an axis of a 2D+ array:- Without
keepdims=True,np.linalg.norm(X, axis=1)collapses shape(3, 2)into 1D shape(3,), causingX / normsto fail withValueError: operands could not be broadcast together with shapes (3,2) (3,)(or worse, silently broadcast along the wrong axis on square(3, 3)matrices!). Passingkeepdims=Truepreserves shape(3, 1)so each row divides by its own norm.
- Without
- Integer arrays (
dtype=int64) and float promotion:- In NumPy, true division (
/) automatically promotes integer inputs (np.array([3, 4])) tofloat64. However, if you pre-allocateout=np.zeros_like(X)fornp.divide(), explicitly passdtype=float(np.zeros_like(X, dtype=float)) so fractional results are not truncated to0.
- In NumPy, true division (
- Unit-vector ($L_2$) normalization vs. Min-Max scaling vs. Z-score standardization:
- Unit vector ($L_2$): Scales magnitude to length
1(v / ||v||_2), preserving vector direction for cosine similarity and geometry. - Min-Max
[0, 1]: Rescales values to[0, 1]via(x - x.min()) / (x.max() - x.min()). - Z-score standardization: Centers to mean
0and standard deviation1via(x - x.mean()) / x.std().
- Unit vector ($L_2$): Scales magnitude to length
- Pre-built Scikit-Learn utility for large 2D matrices (
sklearn.preprocessing.normalize):- If Scikit-Learn is already installed in your ML pipeline,
sklearn.preprocessing.normalize(X, norm="l2", axis=1)handles 2D sparse/dense matrices and zero-norm rows automatically in one call.
- If Scikit-Learn is already installed in your ML pipeline,
Comparison of Normalization & Scaling Methods in NumPy / SciPy Ecosystem
| Method | Resulting Mathematical Property | Handles Zero Vectors Without NaN? |
Works on 2D Batches (axis=1)? |
Best Used When |
|---|---|---|---|---|
v / np.linalg.norm(v) (with norms != 0 guard) (Recommended) |
$L_2$ Euclidean norm $|v|_2 = 1$ | Yes (with np.divide(..., where=norms != 0)) |
Yes (with axis=1, keepdims=True) |
Cosine similarity, directional vectors, unit normals, and embedding normalization. |
v / np.linalg.norm(v, ord=1) |
$L_1$ Manhattan norm $\sum | v_i | = 1$ | Yes (with where=norms != 0) |
sklearn.preprocessing.normalize(X, norm="l2") |
$L_2$ norm $= 1$ per row (or column) | Yes (built-in zero-row safety) | Yes (supports scipy.sparse matrices too) |
Machine learning pipelines already using scikit-learn or sparse TF-IDF matrices. |
(v - v.min()) / (v.max() - v.min()) (Min-Max) |
Values bounded inside [0.0, 1.0] |
No (fails if v.max() == v.min()) |
Yes (with axis=1, keepdims=True) |
Image pixel scaling or bounded feature preprocessing—not a geometric unit vector. |
You must log in or register to comment.
