← back

Min-Max Scaling of Feature Values

#112 · Data Preprocessing · Easy

⊣ Solve on deep-ml.com

Problem

Implement Min-Max Scaling to normalize feature values to a specified range (typically [0, 1]). Given a dataset, transform each feature so that the minimum value maps to 0 and the maximum maps to 1.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import numpy as np

def min_max_scaling(X: np.ndarray, feature_range: tuple = (0, 1)) -> np.ndarray:
    min_val = np.min(X, axis=0)
    max_val = np.max(X, axis=0)

    scale_min, scale_max = feature_range
    denom = max_val - min_val

    # Avoid division by zero for constant features
    denom = np.where(denom == 0, 1, denom)

    X_scaled = (X - min_val) / denom
    X_scaled = X_scaled * (scale_max - scale_min) + scale_min

    return X_scaled

Explanation

  1. Compute range: Find the minimum and maximum of each feature (column-wise).
  2. Normalize to [0, 1]: Subtract the minimum and divide by the range (max - min).
  3. Scale to target range: Multiply by (scale_max - scale_min) and add scale_min to map to the desired range.
  4. Handle constant features: If a feature has zero variance (min == max), set denominator to 1 to avoid division by zero.

Complexity

  • Time: O(n * d) where n is samples and d is features
  • Space: O(n * d) for the scaled output