Keras custom loss function with Mahalanobis distance loss how to
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
A custom loss function in Keras is useful when standard losses (for example MSE or MAE) do not reflect the true cost of prediction errors in your domain. For multivariate regression in particular, not all output dimensions are independent, and not all dimensions should be penalized equally.
Mahalanobis distance gives you a covariance-aware error metric. Instead of treating each target dimension as orthogonal (as plain Euclidean distance does), it scales and rotates the error by the inverse covariance structure. This is often better when outputs are correlated, have different variance scales, or have known uncertainty geometry.
Mahalanobis Distance
Mathematical Foundation
Mahalanobis distance between vectors x and y with covariance matrix S:
In training losses, we usually minimize the squared form (drop the square root) for smoother gradients and lower computational overhead:
To keep the matrix invertible in practice, add regularization:
Then use S_lambda^{-1} in the loss.
When This Beats MSE
Mahalanobis-style losses are especially helpful when:
- Anomaly Detection: Outliers get larger distance under learned covariance.
- Correlated Outputs: Errors along high-correlation directions are weighted correctly.
- Heteroscedastic Targets: High-variance target dimensions do not dominate loss unfairly.
- Physics/Geometry Constraints: Distance in transformed statistical space matters more than raw coordinate error.
Keras Custom Loss Function
The standard setup is:
- Estimate covariance from target data (or residuals).
- Regularize and invert it.
- Build a custom loss that computes the quadratic form per sample.
- Train with normal Keras compile/fit flow.
Step 1: Import Libraries
Step 2: Estimate Inverse Covariance
If your targets are time-dependent or regime-dependent, you can estimate covariance per segment and train separate models, or use a dynamic weighting strategy.
Step 3: Build a Mahalanobis Loss Factory
Step 4: Create and Compile a DNN Model
Step 5: Train
CNN Variant for Regression
For image-to-vector regression, only the backbone changes. The loss can stay the same.
Numerical Stability and Performance
For high output dimensions, direct inverse can be noisy. Prefer stable decomposition methods where possible:
- Compute
S_lambdawith regularization. - Use Cholesky decomposition.
- Solve linear systems instead of explicitly inverting matrices.
If training becomes slow, profile the custom loss and consider:
- Lower output dimension via learned projection.
- Mixed precision where safe.
- Precomputing static covariance once per training run.
Common Failure Modes
- Singular Covariance Matrix
Symptoms: NaNs, exploding loss, inversion errors.
Fix: add stronger diagonal regularization (lambda * I). - Incorrect Target Shape
Symptoms: einsum shape errors.
Fix: enforce[batch, d]target and prediction shapes. - Scale Instability
Symptoms: very large gradients, noisy convergence.
Fix: normalize targets before covariance estimation. - Overfitting with Complex Backbones
Symptoms: training loss down, validation loss up.
Fix: dropout, L2 regularization, early stopping. - Mismatch Between Train and Inference Pipelines
Symptoms: good offline metrics, bad production behavior.
Fix: identical preprocessing, target transforms, and postprocessing.
Model Saving and Loading
Because this is a custom loss, load with custom_objects:
For production workflows, package covariance and loss creation together so loading is deterministic.
Practical Checklist
- Covariance Regularization: If covariance is near-singular, add
lambda * Ibefore inversion. - Scale Sensitivity: Standardize targets/features before estimating covariance.
- Target Dimension Consistency: Keep output layer size equal to covariance dimension
d. - Metric Clarity: Track MAE/RMSE alongside custom loss for interpretability.
- Validation Discipline: Validate on held-out data from production-like distribution.
Related reading
- Keras custom loss implementation ValueError An operation has None for gradient
- Keras data augmentation pipeline for image segmentation dataset image and mask with same manipulation
- Keras deep learning model to android
- Keras Dense layer's input is not flattened
- Keras Dense layer's input is not flattened
- Keras Dice coefficient loss function is negative and increasing with epochs
- Keras Difference between AveragePooling1D layer and GlobalAveragePooling1D layer
- Keras difference between generator and sequence
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.