PCA, Normalization, and Logistic Regression Fundamentals
Machine LearningModel answerLast updated
Explain dimensionality reduction, preprocessing choices, backpropagation mechanics, threshold tuning, and domain-constrained modeling in a classification context.
You're building a binary classifier for a tabular dataset and need to explain your technical choices across preprocessing, training, and evaluation.
Answer the following:
-
PCA and normalization: Describe how principal component analysis reduces dimensions. Explain the difference between feature-wise standardization and sample-wise L2 normalization, and when each preprocessing step is appropriate.
-
Optimization mechanics: Derive the gradient of logistic regression loss with respect to the weights. Then explain how backpropagation generalizes this to deep networks.
-
Model selection: What baseline models would you compare, and what criteria matter when choosing between logistic regression and more complex alternatives?
-
Domain constraints: Define knowledge-informed machine learning and provide a specific example of incorporating domain expertise into model training.
-
Threshold tuning: Explain how moving the decision threshold affects true positive rate and false positive rate. Can you simultaneously improve both metrics by adjusting the threshold alone?
Structure your answer to show both mathematical understanding and practical judgment.
Hints
Hint 1
Principal components are eigenvectors of the covariance matrix, ranked by variance explained
Hint 2
The logistic gradient simplifies to (prediction − target) × input due to cross-entropy's pairing with sigmoid
Hint 3
Backpropagation applies the chain rule layer-by-layer in reverse, reusing cached forward-pass values
Hint 4
ROC curves trace the TPR-FPR tradeoff as threshold varies; both rates move in the same direction
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
A thorough response demonstrates mathematical rigor, practical experience with model pipelines, and awareness of real-world tradeoffs like interpretability and regulatory requirements.
1. PCA and Normalization
Principal Component Analysis
PCA finds orthogonal directions that capture maximum variance:
- Center the data: subtract the mean of each feature from the n × d matrix X.
- Compute covariance: Σ = (1/(n−1)) XᵀX. In practice, compute the singular value decomposition X = UΣVᵀ directly, which is numerically stable.
- Extract principal components: the columns of V are eigenvectors of the covariance matrix, ordered by eigenvalue magnitude (variance along that direction).
- Project: retain the top k components V_k and transform data as Z = XV_k.
The fraction of variance retained is Σᵢ₌₁ᵏ λᵢ / Σⱼ₌₁ᵈ λⱼ. Choose k by targeting a threshold (e.g., 95% variance) or examining the scree plot elbow.
Key properties: PCA produces uncorrelated features and is optimal for linear reconstruction under squared error. However, high-variance directions may not predict the target, and the transformed features lose interpretability.
Feature-wise standardization vs. sample-wise L2 normalization
| Aspect | Feature standardization | Sample L2 normalization |
|---|---|---|
| Formula | (x_j − μ_j) / σ_j for each column j | x / ‖x‖₂ for each row |
| Purpose | Equalize feature scales | Normalize sample magnitude |
| Use cases | Mixed-scale tabular data, PCA, regularized linear models, distance-based methods | Text features (TF-IDF), embeddings, cosine similarity |
| Information loss | None | Discards magnitude, which may be predictive |
When to apply each:
- Standardize features before PCA (it's scale-sensitive), before training regularized logistic regression (so penalty weights features fairly), and for distance-based models like k-NN or SVM.
- L2-normalize samples when direction matters more than magnitude: document vectors, user embeddings, or cosine-similarity tasks.
- Tree-based models need neither; they split on thresholds and are scale-invariant.
Critical detail: fit the scaler and PCA transformer only on training data to prevent leakage.
2. Logistic Regression Gradient and Backpropagation
Logistic regression derivation
Forward pass:
- Linear combination: z = wᵀx + b
- Sigmoid: p = σ(z) = 1 / (1 + e⁻ᶻ)
- Binary cross-entropy loss: L = −y log p − (1−y) log(1−p)
Gradient via chain rule:
- ∂L/∂p = (p − y) / (p(1−p))
- ∂p/∂z = σ(z)(1 − σ(z)) = p(1−p)
- ∂L/∂z = (∂L/∂p)(∂p/∂z) = p − y (the p(1−p) terms cancel)
Therefore:
- ∂L/∂w = (p − y) x
- ∂L/∂b = p − y
For a batch of n samples with L2 regularization: ∇_w = (1/n) Xᵀ(p − y) + λw.
The loss is convex (Hessian XᵀDX is positive semidefinite, where D = diag(p(1−p))), so gradient descent converges to the global optimum.
Generalization to multi-layer networks
For layer ℓ: z^(ℓ) = W^(ℓ) a^(ℓ−1) + b^(ℓ), then a^(ℓ) = f(z^(ℓ)).
Backpropagation algorithm:
- Forward pass: compute and cache all z^(ℓ) and a^(ℓ).
- Output gradient: δ^(L) = ∂L/∂z^(L). For cross-entropy with sigmoid/softmax, this is p − y.
- Backward recursion: δ^(ℓ) = ((W^(ℓ+1))ᵀ δ^(ℓ+1)) ⊙ f′(z^(ℓ)), propagating error backward through layers.
- Parameter gradients: ∂L/∂W^(ℓ) = δ^(ℓ) (a^(ℓ−1))ᵀ and ∂L/∂b^(ℓ) = δ^(ℓ).
- Update: apply SGD, Adam, or another optimizer.
Modern frameworks implement reverse-mode automatic differentiation, computing all gradients in roughly the same time as one forward pass.
Practical challenges: vanishing/exploding gradients from repeated matrix multiplication. Mitigations include ReLU activations, residual connections, normalization layers (BatchNorm/LayerNorm), careful initialization (Xavier/He), and gradient clipping.
3. Model Selection and Baselines
Progression of baselines:
- Constant predictor (majority class or mean) — ensures AUC > 0.5.
- Existing business rule or scorecard.
- Logistic regression with L2 regularization.
- Single decision tree (interpretable but high variance).
- Random forest (ensemble robustness).
- Gradient boosting (XGBoost, LightGBM, CatBoost).
- Neural network if warranted by data volume and task complexity.
Selection criteria:
- Predictive performance: cross-validated AUC-ROC, Gini coefficient, or PR-AUC (if classes are imbalanced).
- Calibration: Brier score, reliability diagrams (predicted probabilities should match observed rates).
- Stability: performance on out-of-time validation; population stability index (PSI).
- Interpretability: coefficient inspection, feature importance, reason codes for regulatory compliance.
- Latency and cost: inference speed, maintenance burden, retraining complexity.
Typical justification for logistic regression:
"Gradient boosting improved AUC by 0.008 over logistic regression, within cross-validation variance. Logistic regression delivered well-calibrated probabilities, transparent coefficients for audit and adverse-action reporting, simpler deployment, and better stability across quarters. The interpretability and operational simplicity outweighed the marginal accuracy gain."
The key is showing the decision was deliberate, with real numbers, not a default choice.
4. Knowledge-Informed Machine Learning
Definition: incorporating domain expertise or physical constraints into the learning process, rather than relying solely on observed data patterns.
Four injection points:
- Data: engineered features, synthetic examples, data augmentation guided by domain rules.
- Architecture: model structure or constraints (e.g., monotonicity, sparsity).
- Loss function: adding penalty terms for implausible behavior.
- Post-processing: validation checks, clamping outputs to feasible ranges.
Concrete example: monotonicity constraints in credit risk
Domain knowledge tells us that default risk should not decrease as debt utilization rises or as the number of recent delinquencies increases. You can enforce this by:
- Monotone constraints in gradient boosting: XGBoost and LightGBM support
monotone_constraintsparameters that force split decisions to respect monotonicity. - Weight-of-Evidence binning: bin continuous features into ordered groups, ensuring monotone WoE scores feed into logistic regression.
- Coefficient sign constraints: optimize logistic regression under inequality constraints (e.g., coefficient for utilization ≥ 0).
Benefits: prevents counterintuitive score inversions in sparse data regions, improves generalization, and produces explainable adverse-action reasons that align with policy and regulation.
Other examples: physics-informed neural networks add PDE residuals to the loss; fairness-aware models add demographic parity or equalized odds penalties.
5. Threshold Tuning and the ROC Tradeoff
Mechanics:
Classify as positive if predicted probability p̂ ≥ t.
- True Positive Rate (TPR) = P(p̂ ≥ t | y = 1) — fraction of actual positives correctly identified.
- False Positive Rate (FPR) = P(p̂ ≥ t | y = 0) — fraction of actual negatives incorrectly flagged.
As t decreases, more examples are classified positive, so both TPR and FPR increase. As t increases, both decrease.
Can you improve both FPR and TPR by moving the threshold? No.
A single threshold traces out one point on the ROC curve. Lowering FPR (moving right-to-left on the x-axis) necessarily means accepting lower or equal TPR. The two rates move together.
To improve both simultaneously, you need a better ranking — shifting the entire ROC curve northwest. Approaches include:
- Better feature engineering.
- A more expressive model.
- More or higher-quality training data.
- Ensemble methods or segment-specific models.
Choosing the threshold in practice:
- Cost-sensitive: set t where expected cost is minimized: predict positive if p̂ × cost(FN) + (1 − p̂) × cost(FP) favors action. Requires calibrated probabilities.
- Fixed constraint: satisfy a regulatory requirement (e.g., TPR ≥ 0.90) and choose the threshold that maximizes precision or minimizes FPR subject to that constraint.
- Youden's index: maximize TPR − FPR.
- Business metric: directly optimize revenue, approval rate, or another operational KPI.
Common Mistakes
- Confusing PCA (unsupervised variance maximization) with feature selection (supervised relevance).
- Applying row L2 normalization to tabular data and losing predictive magnitude.
- Forgetting that standardization and PCA must be fit only on training data.
- Claiming the logistic gradient is complex when it simplifies to (p − y) x.
- Choosing models based on popularity rather than quantified tradeoffs.
- Believing a threshold can improve the ROC curve itself, rather than just selecting an operating point.
Complexity notes: Logistic regression training is O(n d² + d³) per iteration via Newton's method; gradient descent is O(n d) per iteration. PCA via SVD is O(min(n d², d³)). Prediction is O(d) per sample.