Normalize Features (Min-Max Scaling) - Data Preprocessing
Implement Normalize Features (Min-Max Scaling) in Python with NumPy. easy exercise with examples, hints, and instant feedback. No setup or signup required.
Normalize Features (Min-Max Scaling)
What you'll build
A function that rescales a 1-D array linearly so its smallest value becomes 0 and its largest becomes 1.
Background
Distance-based models and gradient descent are sensitive to feature scale: a feature in the thousands swamps one in fractions. Min-max scaling puts every feature on the same [0, 1] range. It is what scikit-learn's MinMaxScaler does for each column.
Formula
x_norm[i] = (x[i] - min(x)) / (max(x) - min(x))
where min(x) and max(x) are taken over the whole array.
Inputs
arr: 1-D array of shape(n,),2 <= n <= 1000, finite ints or floats (tests may pass a Python list, so convert withnp.asarray(arr, dtype=float))
Expected return format
A float array of shape (n,) with values in [0, 1]: the minimum maps to 0.0 and the maximum to 1.0.
Edge cases and conventions
- Constant input (
max == min): the formula would divide by zero. Return an array of zeros instead, likeMinMaxScaler. - The order of the elements is preserved; the input doesn't need to be sorted.
Constraints
- Use NumPy only; no loops are needed.
Follow-up
- How would you scale a 2-D
(n_samples, n_features)matrix column by column? - Why is min-max scaling a poor choice when the data has outliers?
Examples
Input: normalize(np.array([1, 2, 3, 4, 5])) Output: [0.0, 0.25, 0.5, 0.75, 1.0]
min = 1 and max = 5, so each value maps to (x - 1) / 4.
Input: normalize(np.array([3.0, -1.0, 7.0, 1.0])) Output: [0.5, 0.0, 1.0, 0.25]
Range 8: the order is kept, and -1 (the minimum) maps to 0.
Input: normalize(np.array([4.0, 4.0, 4.0])) Output: [0.0, 0.0, 0.0]
Constant input: max - min = 0, so return zeros instead of dividing by zero.
Practice in Python
import numpy as np
def normalize(arr: np.ndarray) -> np.ndarray:
"""
Min-max scale a 1-D array to [0, 1].
Args:
arr: 1-D array (or list) of finite numbers, shape (n,)
Returns:
Float array of shape (n,): (arr - min) / (max - min),
or all zeros if every value is the same
"""
# Your code here
pass
The interactive editor loads with Python and NumPy. Run your implementation against 6 tests, or use the progressive hints.