Skip to content
E
Educatum

Effects of feature scaling on logistic regression

Curated by Educatum AI teamLast updated:
Basic Concepts
Direct Answer

Feature scaling does not alter the optimal decision boundary of unregularized logistic regression once converged, because weights rescale inversely with feature units. However, scaling dramatically improves gradient-based optimization convergence by conditioning the Hessian, and it is strictly essential whenever L1 or L2 regularization is applied so large-weight penalties treat all features fairly.

Study Card: Effects of Feature Scaling on Logistic Regression

Direct Answer

Feature scaling (such as standardization or min-max scaling) plays two distinct roles in logistic regression depending on whether regularization is used:

  1. Optimization Conditioning (Always Beneficial for Gradient Solvers): When features span vastly different numerical ranges, the log-loss Hessian becomes ill-conditioned with elongated elliptical level sets. Gradient-based and quasi-Newton optimizers (like SGD or L-BFGS) oscillate across narrow valleys and require many more iterations—or fail to converge within default iteration limits. Standardization transforms contours to be far more isotropic, accelerating convergence.
  2. Regularization Fairness (Changes the Decision Boundary): For unregularized logistic regression (penalty=None), scaling feature xj↦cxjx_j \mapsto c x_j simply scales the optimal weight wj↦wj/cw_j \mapsto w_j / c, leaving w⊤x+bw^\top x + b and the decision boundary mathematically invariant (once converged). However, regularized logistic regression—including scikit-learn’s default L2 penalty—penalizes λ∥w∥22\lambda \|w\|_2^2 or λ∥w∥1\lambda \|w\|_1. Without scaling, features with small numerical units need larger weights wjw_j to exert the same predictive effect and are therefore penalized far more heavily, changing both the learned decision boundary and feature-importance rankings.

Key Terms

  • Feature Scaling: Rescaling input features to comparable magnitudes—commonly standardization (z=(x−μ)/σz = (x - \mu)/\sigma) or min-max normalization (x′=(x−xmin⁡)/(xmax⁡−xmin⁡)x' = (x - x_{\min}) / (x_{\max} - x_{\min})).
  • Condition Number (κ\kappa): The ratio of largest to smallest Hessian eigenvalues; unscaled features inflate κ\kappa and slow gradient convergence.
  • Scale Invariance (Unregularized Only): Unregularized MLE predictions are invariant to invertible linear feature rescaling, whereas L1/L2 regularized predictions are not scale invariant.
  • Regularization (L1L_1 / L2L_2): Penalizes coefficient magnitudes, making standardization mandatory so penalty terms compare features on an equal footing.

Example

Suppose we predict customer churn using monthly_bill (ranging from 20 dollars to 200 dollars) and tenure (ranging from 1 month to 50 months), measured in raw units versus standardized units.

  • Without regularization, changing monthly_bill from dollars to cents multiplies the feature by 100 and divides its fitted weight by 100—the hyperplane w1⋅bill+w2⋅tenure+b=0w_1 \cdot \text{bill} + w_2 \cdot \text{tenure} + b = 0 maps to the exact same boundary, though unscaled L-BFGS or SGD converges much more slowly due to ill-conditioned loss contours.
  • With standard L2 regularization (the default in LogisticRegression), a large-scale feature in cents can achieve its effect with a tiny weight (hardly penalized by λw12\lambda w_1^2), while a small-scale feature needs a larger weight and gets unfairly shrunk. Standardizing both features ensures the boundary 2⋅billscaled+0.5⋅tenurescaled+b=02 \cdot \text{bill}_{\text{scaled}} + 0.5 \cdot \text{tenure}_{\text{scaled}} + b = 0 reflects standardized effect sizes fairly.

Code Implementation

import pandas as pd
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

# Load breast cancer dataset (features span ~0.001 to ~4000)
data = load_breast_cancer()
X = pd.DataFrame(data.data, columns=data.feature_names)
y = data.target

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y
)

# 1. L-BFGS without scaling (needs high max_iter due to ill-conditioned features)
lr_unscaled = LogisticRegression(solver='lbfgs', max_iter=5000, random_state=42)
lr_unscaled.fit(X_train, y_train)
acc_unscaled = accuracy_score(y_test, lr_unscaled.predict(X_test))

# 2. Fit StandardScaler strictly on X_train, then transform both splits
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)

lr_scaled = LogisticRegression(solver='lbfgs', max_iter=5000, random_state=42)
lr_scaled.fit(X_train_scaled, y_train)
acc_scaled = accuracy_score(y_test, lr_scaled.predict(X_test_scaled))

print(f"Unscaled - Accuracy: {acc_unscaled:.4f}, Iterations: {lr_unscaled.n_iter_[0]}")
print(f"Scaled   - Accuracy: {acc_scaled:.4f}, Iterations: {lr_scaled.n_iter_[0]}")
  • Regularization & Feature Attribution: Only after standardizing features to mean 0 and unit variance do L2/L1 logistic regression weight magnitudes ∣wj∣|w_j| meaningfully reflect relative feature importance.
  • Scaling Methods: Standardization (StandardScaler) handles unbounded features well; MinMaxScaler preserves sparse zeros or bounded ranges; RobustScaler (median/IQR) resists extreme outliers.
  • Data Leakage Prevention: Always fit scalers on the training split (or inside a Pipeline per CV fold) before transforming validation and test sets.
  • Scale-Invariant Models: Tree-based models (Decision Trees, Random Forests, XGBoost) split on rank order thresholds and generally do not require feature scaling.
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.