Feature Scaling in Machine Learning: Standardization vs. Normalization
In real-world datasets, numerical features rarely share the same scale. A dataset might contain age ranging from 18 to 80, credit_utilization ranging from 0.0 to 1.0, and annual_income ranging from ₹25,000 to ₹500,000.
When these raw values are passed directly into certain machine learning algorithms, features with larger numerical magnitudes can dominate the calculations—not necessarily because they contain more useful information, but simply because their values are larger.
Feature scaling is a data preprocessing technique that transforms numerical features onto comparable scales. It helps distance-based algorithms calculate meaningful distances, improves optimization for gradient-based models, and makes regularization behave more consistently.
Two of the most widely used scaling techniques are:
- Standardization: transforms features to have a mean of approximately 0 and a standard deviation of 1.
- Normalization: commonly transforms feature values into a fixed range, such as 0 to 1. In some contexts, normalization also refers to scaling each observation to a unit norm.
Let's understand how these techniques work, when to use them, and how to implement them with Python and Scikit-learn.
1. Why Is Feature Scaling Important?
Consider a dataset with three features:
| Feature | Minimum | Maximum |
|---|---|---|
| Age | 18 | 80 |
| Credit utilization | 0.0 | 1.0 |
| Annual income | ₹25,000 | ₹500,000 |
The difference between two annual income values could be hundreds of thousands, while the difference between two ages might be only a few years.
This creates problems for several algorithms.
1.1 Distance-Based Algorithms
Algorithms such as K-Nearest Neighbors (KNN), K-Means, and distance-based SVMs rely on distance calculations.
For example, Euclidean distance between two observations is:
\[ d(x,z)=\sqrt{\sum_{j=1}^{n}(x_j-z_j)^2} \]
Suppose two customers have these values:
| Feature | Customer A | Customer B | Difference |
|---|---|---|---|
| Age | 25 | 35 | 10 |
| Income | ₹30,000 | ₹80,000 | ₹50,000 |
The squared income difference is vastly larger than the squared age difference. Consequently, income dominates the Euclidean distance.
This can cause KNN or K-Means to identify similarity primarily through income, even when age and other features should also contribute.
Scaling brings the numerical ranges closer together so distance calculations are less dominated by raw magnitude.
1.2 Gradient-Based Optimization
Algorithms such as Linear Regression trained with gradient descent, Logistic Regression, and Neural Networks can also benefit from scaling.
When features have very different scales, the loss function may have poorly conditioned contours. Gradient descent can take inefficient zigzagging steps instead of moving more directly toward the minimum.
Scaling often improves the conditioning of the optimization problem and helps gradient-based algorithms converge more efficiently.
Important: Scaling does not guarantee a perfectly circular loss surface. The result depends on the data, model, and correlations between features.
1.3 Regularized Models
Regularization techniques such as Ridge, Lasso, and Elastic Net penalize model coefficients.
L2 regularization:
\[ L2=\lambda\sum_{j=1}^{n}w_j^2 \]
L1 regularization:
\[ L1=\lambda\sum_{j=1}^{n}|w_j| \]
If features have very different scales, their corresponding coefficients may have very different magnitudes simply because of the units used.
This can make regularization behave unevenly across features. Scaling numerical predictors before fitting these models makes coefficient penalties more comparable.
1.4 Algorithms That Usually Do Not Need Scaling
Not every machine learning algorithm is sensitive to feature magnitude.
| Algorithm | Scaling generally needed? | Reason |
|---|---|---|
| KNN | Yes | Uses distance calculations |
| K-Means | Yes | Uses distances to cluster centers |
| SVM | Usually yes | Sensitive to feature scales, especially with RBF kernels |
| Logistic Regression | Usually yes | Helps optimization and regularization |
| Linear Regression with gradient descent | Often yes | Improves optimization conditioning |
| Neural Networks | Usually yes | Helps optimization stability |
| PCA | Usually yes | Features with large variance can dominate components |
| Decision Trees | Usually no | Splits depend on feature thresholds and ordering |
| Random Forest | Usually no | Built from decision trees |
| Gradient Boosted Trees | Usually no | Tree splits are generally scale-insensitive |
Scaling is not automatically beneficial for every model. Choose preprocessing based on the algorithm and the data.
2. Standardization: Mean = 0 and Standard Deviation = 1
Standardization transforms numerical features so that each feature has a mean of approximately 0 and a standard deviation of approximately 1.
It is also called Z-score scaling.
Formula
\[ z=\frac{x-\mu}{\sigma} \]
Where:
- \(x\) = Original feature value
- \(\mu\) = Mean of the feature
- \(\sigma\) = Standard deviation of the feature
- \(z\) = Standardized value
Example
Suppose a dataset contains annual salaries with:
- Mean salary = ₹50,000
- Standard deviation = ₹10,000
- Individual salary = ₹70,000
Applying standardization:
\[ z=\frac{70000-50000}{10000} \]
\[ z=2 \]
The standardized value is 2. This means the salary is two standard deviations above the mean.
<LearningViz type_id="STANDARD_SCORE_Z" />
Python Implementation
import numpy as np
from sklearn.preprocessing import StandardScaler
# Original data
data = np.array([
[20000],
[30000],
[40000],
[50000],
[60000]
])
# Create scaler
scaler = StandardScaler()
# Transform data
scaled_data = scaler.fit_transform(data)
print("Original Data:")
print(data)
print("Standardized Data:")
print(scaled_data)
print("Mean:", scaled_data.mean())
print("Standard Deviation:", scaled_data.std())
The transformed feature will have a mean close to 0 and a population standard deviation close to 1, subject to floating-point precision.
When Should You Use Standardization?
Standardization is often a good choice when:
- Features have different units and ranges.
- Data is approximately normally distributed, although normality is not required.
- You are training Logistic Regression or regularized linear models.
- You are using SVM, PCA, or KNN.
- You are training a neural network with numerical inputs.
Important: Standardization does not make data normally distributed. It changes the mean and standard deviation, not the underlying distribution's shape.
3. Normalization: Scaling Values to a Fixed Range
In many machine learning workflows, normalization refers to transforming feature values into a fixed range, commonly between 0 and 1.
The most common technique is Min-Max Scaling.
Formula
\[ X_{scaled}=\frac{X-X_{min}}{X_{max}-X_{min}} \]
Where:
- \(X\) = Original value
- \(X_{min}\) = Minimum value in the feature
- \(X_{max}\) = Maximum value in the feature
- \(X_{scaled}\) = Transformed value
Example
Suppose the age feature contains:
- Minimum age = 20
- Maximum age = 60
- Individual age = 40
Applying Min-Max Scaling:
\[ X_{scaled}=\frac{40-20}{60-20} \]
\[ X_{scaled}=\frac{20}{40}=0.5 \]
The original age of 40 becomes 0.5.
Python Implementation
import numpy as np
from sklearn.preprocessing import MinMaxScaler
# Original data
data = np.array([
[20],
[30],
[40],
[50],
[60]
])
# Create scaler
scaler = MinMaxScaler()
# Transform data
scaled_data = scaler.fit_transform(data)
print("Original Data:")
print(data)
print("Normalized Data:")
print(scaled_data)
The resulting values will range from 0 to 1 for the data used to fit the scaler.
When Should You Use Min-Max Scaling?
Min-Max Scaling is useful when:
- A model or workflow expects bounded numerical inputs.
- You want to preserve the relative ordering of values.
- Features have known meaningful bounds.
- You are preparing inputs for some neural network workflows.
- You want all numerical features represented within a common interval.
Limitation: Min-Max Scaling is sensitive to outliers. An extremely large value can stretch the range and compress most other observations into a narrow interval.
For example, if almost all salaries lie between ₹20,000 and ₹80,000 but one salary is ₹10,00,000, the majority of scaled values may become very close to zero.
4. Standardization vs. Normalization: Key Differences
Both techniques change feature scales, but they use different mathematical approaches.
| Parameter | Standardization | Min-Max Normalization |
|---|---|---|
| Main technique | Z-score scaling | Min-Max scaling |
| Formula | \((X-\mu)/\sigma\) | \((X-X_{min})/(X_{max}-X_{min})\) |
| Mean | Approximately 0 | Not necessarily 0 |
| Standard deviation | Approximately 1 | Not necessarily 1 |
| Output range | Not fixed | Usually 0 to 1 |
| Outlier sensitivity | Mean and standard deviation are affected by outliers | Highly sensitive to extreme minimum and maximum values |
| Distribution shape | Does not make data normal | Does not make data normal |
| Common applications | SVM, Logistic Regression, PCA, regularized models | Bounded inputs and workflows requiring a fixed range |
Which One Is Better?
Neither is universally better.
- Choose Standardization when you want features centered around zero and expressed in standard deviation units.
- Choose Min-Max Scaling when a fixed feature range is useful or required.
- Consider Robust Scaling when substantial outliers are present.
The correct choice depends on the data, model, and problem.
5. Robust Scaling: Handling Outliers
Standardization uses the mean and standard deviation, while Min-Max Scaling uses the minimum and maximum.
Both can be strongly affected by extreme observations.
Robust Scaling uses the median and interquartile range (IQR), making it less sensitive to outliers.
Formula
\[ X_{scaled}=\frac{X-\text{Median}(X)}{Q_3-Q_1} \]
Where:
- \(Q_1\) = First quartile (25th percentile)
- \(Q_3\) = Third quartile (75th percentile)
- \(IQR=Q_3-Q_1\)
Example
Suppose annual income values are:
25000, 30000, 35000, 40000, 45000, 50000, 500000
The final value is much larger than the other observations.
Standardization and Min-Max Scaling can be influenced significantly by this extreme value. Robust Scaling instead uses the median and IQR, which are less affected.
Python Implementation
import numpy as np
from sklearn.preprocessing import RobustScaler
data = np.array([
[25000],
[30000],
[35000],
[40000],
[45000],
[50000],
[500000]
])
scaler = RobustScaler()
scaled_data = scaler.fit_transform(data)
print("Original Data:")
print(data)
print("Robust Scaled Data:")
print(scaled_data)
When Should You Use Robust Scaling?
- Your dataset contains substantial outliers.
- You are working with income, transaction amounts, or other skewed numerical features.
- You want scaling based on robust statistics rather than the mean and standard deviation.
Robust Scaling does not remove outliers. It reduces their influence on the scaling parameters.
6. MaxAbs Scaling: Preserving Sparse Data
MaxAbs Scaling divides each feature by its maximum absolute value.
Formula
\[ X_{scaled}=\frac{X}{|X|_{max}} \]
The transformed values generally lie between -1 and 1.
Python Implementation
import numpy as np
from sklearn.preprocessing import MaxAbsScaler
data = np.array([
[10, -100],
[20, -200],
[30, 200],
[40, 100]
])
scaler = MaxAbsScaler()
scaled_data = scaler.fit_transform(data)
print(scaled_data)
When Should You Use It?
- Your dataset contains sparse numerical features.
- You want to preserve zero values.
- You do not want to center the data around zero by subtracting the mean.
Unlike StandardScaler with mean centering, MaxAbsScaler can preserve sparsity.
7. Normalization Using Unit Vectors
There is another meaning of normalization in machine learning: scaling each observation to a unit norm.
Unlike Standardization and Min-Max Scaling, which generally operate feature by feature, unit-vector normalization operates on each row or observation.
For L2 normalization:
\[ X_{normalized}=\frac{X}{\|X\|_2} \]
Where:
\[ \|X\|_2=\sqrt{x_1^2+x_2^2+\cdots+x_n^2} \]
The resulting vector has a Euclidean length of 1, provided the original vector is nonzero.
Example
Consider:
\[ X=[3,4] \]
Its L2 norm is:
\[ \sqrt{3^2+4^2}=\sqrt{25}=5 \]
The normalized vector becomes:
\[ X_{normalized}=[3/5,4/5]=[0.6,0.8] \]
Its length is now 1.
Python Implementation
import numpy as np
from sklearn.preprocessing import Normalizer
data = np.array([
[3, 4],
[6, 8],
[5, 12]
])
normalizer = Normalizer(norm="l2")
normalized_data = normalizer.fit_transform(data)
print(normalized_data)
When Should You Use Unit-Norm Normalization?
- Text classification using TF-IDF vectors.
- Document similarity calculations.
- Cosine similarity workflows.
- Applications where the direction of a feature vector matters more than its magnitude.
Remember: Min-Max Scaling and unit-vector normalization are different operations, even though both are sometimes called normalization.
8. Comparing Different Scaling Techniques
| Technique | Uses | Output behavior | Outlier sensitivity |
|---|---|---|---|
| StandardScaler | Mean and standard deviation | Mean 0, standard deviation 1 | Affected |
| MinMaxScaler | Minimum and maximum | Usually 0 to 1 | High |
| RobustScaler | Median and IQR | Centered around median | Lower |
| MaxAbsScaler | Maximum absolute value | Usually -1 to 1 | Affected by extreme maximum |
| Normalizer | Vector norm | Each nonzero row has unit norm | Depends on vector composition |
Each scaler solves a different problem. Do not select a scaler simply because it is popular.
9. Implementing Feature Scaling with Scikit-Learn
Let's build a small example using a customer dataset.
Step 1: Create a Dataset
import pandas as pd
data = {
"age": [22, 25, 30, 35, 40],
"income": [25000, 30000, 45000, 60000, 80000],
"credit_score": [600, 650, 700, 750, 800]
}
df = pd.DataFrame(data)
print(df)
Step 2: Separate Features and Target
X = df[["age", "income", "credit_score"]]
In a supervised learning problem, you would also separate the target variable:
# Example:
# y = df["approved"]
Step 3: Split the Data Before Fitting the Scaler
from sklearn.model_selection import train_test_split
X_train, X_test = train_test_split(
X,
test_size=0.2,
random_state=42
)
Step 4: Apply Standardization
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
# Learn scaling parameters from training data
X_train_scaled = scaler.fit_transform(X_train)
# Reuse the same parameters on test data
X_test_scaled = scaler.transform(X_test)
print("Scaled Training Data:")
print(X_train_scaled)
print("Scaled Testing Data:")
print(X_test_scaled)
Notice the difference:
fit()learns parameters such as the mean and standard deviation.transform()applies the learned parameters.fit_transform()learns parameters and transforms the supplied data.
Never fit a scaler separately on the test dataset. The test data must be transformed using parameters learned from the training data.
10. Feature Scaling with a Scikit-Learn Pipeline
For real-world projects, using a Scikit-learn Pipeline is a safer and more maintainable approach.
A pipeline ensures that preprocessing is fitted correctly during model training and repeated consistently during evaluation.
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
# Example dataset
df = pd.DataFrame({
"age": [22, 25, 30, 35, 40, 45, 50, 55],
"income": [25000, 30000, 45000, 60000, 80000, 90000, 100000, 120000],
"credit_score": [600, 620, 650, 680, 700, 720, 750, 780],
"approved": [0, 0, 0, 1, 1, 1, 1, 1]
})
# Separate features and target
X = df.drop("approved", axis=1)
y = df["approved"]
# Split data
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.25,
random_state=42,
stratify=y
)
# Create pipeline
pipeline = Pipeline([
("imputer", SimpleImputer(strategy="median")),
("scaler", StandardScaler()),
("model", LogisticRegression())
])
# Train
pipeline.fit(X_train, y_train)
# Predict
predictions = pipeline.predict(X_test)
# Evaluate
print("Predictions:", predictions)
print("Accuracy:", pipeline.score(X_test, y_test))
The pipeline applies the following steps:
- Replaces missing numerical values using training-set medians.
- Standardizes the numerical features.
- Trains Logistic Regression.
- Applies the same fitted preprocessing steps when making predictions.
For datasets containing both numerical and categorical columns, use a ColumnTransformer to apply different preprocessing steps to each column group.
11. Common Mistakes in Feature Scaling
Mistake 1: Scaling Before Train-Test Splitting
Incorrect:
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
X_train, X_test, y_train, y_test = train_test_split(
X_scaled, y, test_size=0.2
)
This allows information from the test features to influence the scaling parameters.
Correct approach:
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
An even safer approach is to use a Pipeline.
Mistake 2: Using the Same Scaler for Every Dataset
Different datasets have different distributions and outlier patterns. StandardScaler is not always the right choice.
Choose a scaler based on the data and algorithm.
Mistake 3: Scaling Categorical Features Incorrectly
Categorical values such as:
City = Delhi, Mumbai, Bangalore
should generally be encoded before being supplied to algorithms that require numerical inputs.
Encoding and scaling are separate preprocessing operations. For example, one-hot encoded binary features often do not need additional scaling.
Mistake 4: Ignoring Outliers
Min-Max Scaling can compress most observations when extreme values are present.
Inspect the data first and consider RobustScaler when appropriate.
Mistake 5: Scaling the Target Variable Without a Plan
Feature scaling usually refers to transforming input variables \(X\).
For some regression models, scaling the target \(y\) can also be useful, particularly for neural networks. If you transform the target, remember to reverse the transformation before interpreting predictions in the original units. Scikit-learn's TransformedTargetRegressor can help manage this process.
Mistake 6: Forgetting Cross-Validation Leakage
When using cross-validation, the scaler must be fitted separately within each training fold.
A Pipeline handles this correctly when passed to cross-validation tools such as cross_val_score or GridSearchCV.
12. Best Practices for Feature Scaling
- Understand your algorithm: Determine whether it is sensitive to feature scales.
- Inspect feature distributions: Look for skewness, outliers, and extreme values.
- Split before fitting preprocessing: Learn scaling parameters from training data only.
- Use pipelines: Keep preprocessing and model training together.
- Choose the scaler carefully: StandardScaler, MinMaxScaler, RobustScaler, and Normalizer have different purposes.
- Apply consistent transformations: Use the same fitted scaler for validation, test, and production data.
- Avoid unnecessary scaling: Tree-based models generally work well without it.
- Evaluate alternatives: Compare model performance using cross-validation rather than assuming one scaler is best.
13. Real-World Applications of Feature Scaling
| Application | Why scaling matters | Common approach |
|---|---|---|
| Customer segmentation | Prevents large monetary values from dominating distance calculations | StandardScaler or RobustScaler |
| Fraud detection | Helps distance-based and regularized models use numerical features consistently | StandardScaler or RobustScaler |
| Recommendation systems | Helps compare numerical representations and similarity features | Standardization or unit-norm normalization, depending on the model |
| Image processing | Pixel values may be mapped to a bounded range | Min-Max-style scaling |
| Text classification | Document vectors are often normalized by length | L2 Normalization |
| Credit risk prediction | Income, age, and utilization can have different units | StandardScaler or RobustScaler |
The right transformation still depends on the data representation and model.
14. Final Conclusion
Feature scaling is an important preprocessing step in many machine learning workflows. It ensures that differences in numerical magnitude do not unnecessarily dominate distance calculations, optimization, or regularization.
The main techniques serve different purposes:
- Standardization: Centers features around zero and scales them to unit standard deviation.
- Min-Max Scaling: Transforms feature values into a fixed range, commonly 0 to 1.
- Robust Scaling: Uses the median and IQR to reduce the influence of outliers on scaling parameters.
- MaxAbs Scaling: Scales features by their maximum absolute values while preserving zero values.
- Unit-Norm Normalization: Scales each observation to a specified vector length.
There is no universally best scaling technique. The best choice depends on your dataset, feature distributions, and machine learning algorithm.
One rule should always be followed: fit preprocessing transformations on training data only, and reuse those fitted transformations on validation, test, and future data.
Understanding feature scaling helps build more reliable, efficient, and consistent machine learning pipelines.