In Machine Learning, raw data is often "noisy" and exists on vastly different scales. Imagine a dataset where one feature is Annual Income (ranging from to ) and another is Number of Children ( to ). If we feed this data directly into a model, the large income values will "overpower" the small family values, leading to biased predictions.
To solve this, we use Vector Normalization (specifically the L2 Norm). Our goal is to transform any raw feature vector into a Unit Vector, where the total length (magnitude) is exactly .
Methodology
To transform a raw vector into a unit vector , we must follow a two-step mathematical pipeline:
Step 1: Calculate the Magnitude (L2 Norm) We first find the Euclidean distance of the vector from the origin. This is done by squaring every component, summing them up, and taking the square root.
Step 2: The Scaling Transformation Once we have the magnitude (a single scalar value), we divide every original component of the vector by that magnitude.
The Intuition:
By dividing a vector by its own length, we "shrink" or "stretch" it until it touches the boundary of a unit circle. It keeps its original direction but loses its original scale.
Implementation
Although standard loops can be used to solve this challenge, they are inefficient when handling large datasets. Instead, we utilize vectorization, which allows mathematical operations to be performed on entire arrays simultaneously. Your implementation should leverage NumPy's ability to square an entire array at once and perform element-wise division in a single operation.
System Note:
Your coding environment is already pre-configured to run
NumPy
. You can access it directly by using the
import numpy as np statement.
Consider this raw feature vector representing a user profile:
import numpy as np user_features = np.array([3.0, 4.0])
- Calculate squares:
[9.0, 16.0] - Sum squares:
25.0 - Square root (Magnitude):
5.0 - Resulting Unit Vector:
[3.0/5.0, 4.0/5.0][0.6, 0.8]
The Challenge
Implement the function normalize_features(vector). It must accept a 1D NumPy array and return a new NumPy array representing the unit vector.
Constraints & Edge Cases:
- Input will be a 1D
numpy.ndarray. - If the input vector is a Zero Vector (all components are 0), the magnitude will be 0. Dividing by zero is mathematically undefined. In this specific case, your function should return the original zero vector to avoid a crash.
def normalize_features(vector): # Step 1: Calculate the L2 magnitude using np.sqrt and np.sum # Step 2: Handle the zero-vector edge case # Step 3: Return the scaled unit vector pass
Validation
To ensure your solution passes our automated verification system (==), you must perform the following two steps before returning your result:
- Round the values to 1 decimal place using np.round(result, 1).
- Convert the NumPy array into a standard list using the
.tolist()method.
