Skip to content

Loss Functions

torchregress provides a comprehensive library of loss functions for regression — from simple point predictions to full distributional models with uncertainty quantification. This page is the catalogue: every loss family with its formula, use case, and link to the full guide.

From likelihood to loss

Almost every loss here is the negative log-likelihood of a conditional model. Given inputs \(x\), a target \(y\), and a model that predicts distribution parameters \(\theta(x)\), training minimises

\[ \mathcal{L}(\theta) = -\,\mathbb{E}_{(x,y)\sim\mathcal{D}}\big[\log p_\theta(y \mid x)\big]. \]

The choice of \(p_\theta\) is the choice of loss: a fixed-variance Gaussian gives squared error, a Laplace gives absolute error, a Gaussian whose variance is also predicted gives GaussianNLLLoss, a mixture gives MixtureDensityLoss, and so on. Several losses are instead scoring rules: pinball is a consistent score for a quantile, while CRPS, the energy score and the Gaussian Wasserstein bound are proper scores for the whole predictive distribution even when no parametric likelihood is assumed. That distinction matters when reading the tables below: likelihood losses are tied to a distributional family, scoring rules are not.

All losses share the same call contract and the same reduction semantics:

loss_fn(y_pred, target, mask=None, weights=None)   # mask: True = valid, False = missing

mask removes missing entries from the denominator and weights scales samples; reduction="mean" is always the weighted mean over valid entries (see Base Classes for the exact zero-fill rule).

Where to start?

Use the Task-First Method Selection Matrix to shortlist losses by problem type. For prediction intervals with coverage guarantees, see Conformal Prediction.

Reading order: start with Standard Losses and Gaussian Losses, then jump to the section matching your data's pathology (outliers, censoring, imbalance, measurement error, etc.).


At a Glance

graph LR
    A["Your Data"] --> B{"What do you need?"}
    B -->|Point prediction| C["WeightedMSELoss / WeightedHuberLoss"]
    B -->|Uncertainty| D["GaussianNLLLoss / BetaNLLLoss"]
    B -->|Robustness| E["CauchyLoss / TukeyBiweightLoss"]
    B -->|Intervals| F["QuantileLoss + CQR"]
    B -->|Full distribution| G["MixtureDensityLoss / NormalizingFlowLoss"]
    B -->|Count data| H["PoissonDevianceLoss / TweedieLoss"]

Standard Losses

The building blocks — these wrap PyTorch losses with unified support for masks, sample weights, and consistent reduction semantics.


torchregress vs PyTorch native — why both exist

Several torchregress losses share names with torch.nn primitives. They are not redundant — each adds mask/weight support that native losses lack:

torchregress PyTorch nearest Why torchregress exists API
WeightedMSELoss nn.MSELoss Adds mask (missing-data) and per-sample weight support WeightedMSELoss
WeightedL1Loss nn.L1Loss Same mask + weight pattern WeightedL1Loss
WeightedHuberLoss nn.HuberLoss Same mask + weight pattern WeightedHuberLoss
WeightedLossWrapper any nn.Module Generic wrapper adding mask/weight to any PyTorch loss WeightedLossWrapper
WeightedCrossEntropyLoss nn.CrossEntropyLoss Mask + weight for regression-as-classification workflows WeightedCrossEntropyLoss
WeightedNLLLoss nn.NLLLoss Mask + weight for regression-as-classification workflows WeightedNLLLoss
GaussianNLLLoss nn.GaussianNLLLoss Adds covariance-type dispatch (diagonal / full / low-rank) via create_gaussian_nll(), mask support, and self-agreement contracts GaussianNLLLoss
PseudoHuberLoss nn.HuberLoss Continuous second derivative (C² smooth) vs native Huber's C¹; mask support PseudoHuberLoss

Every other loss in torchregress has no PyTorch-native equivalent — they are domain-specific formulations for uncertainty quantification, robust regression, censored/ordinal targets, error-in-variables, conformal prediction, etc.

Rule of thumb

  • Use torch.nn.MSELoss / L1Loss for plain regression with no missing data.
  • Use torchregress Weighted* wrappers when you need mask or per-sample weight support.
  • Use torchregress probabilistic losses (GaussianNLLLoss, MixtureDensityLoss, etc.) for uncertainty-aware regression — they handle distribution contracts that native losses don't.

Loss Formula (per sample) Implied Distribution API
WeightedMSELoss \((y - \hat{y})^2\) Gaussian (fixed \(\sigma\)) WeightedMSELoss
WeightedL1Loss \(\lvert y - \hat{y}\rvert\) Laplace WeightedL1Loss
WeightedHuberLoss Quadratic core + linear tails Gaussian-Laplace hybrid WeightedHuberLoss
GaussianNLLLoss Heteroscedastic NLL wrapper Gaussian GaussianNLLLoss
WeightedCrossEntropyLoss Classification wrapper Categorical Losses API (weighted wrappers)

See Base Classes for foundations.


Gaussian Losses

Parametric losses for the Gaussian family — supporting heteroscedastic (input-dependent) variance.

Loss Outputs Predicted Use Case API
GaussianNLLLoss \(\mu, \log\sigma^2\) Heteroscedastic uncertainty per sample GaussianNLLLoss
BetaNLLLoss \(\mu, \log\sigma^2\) Heteroscedastic NLL with detached variance rescaling (β-NLL) BetaNLLLoss
GaussianWassersteinBoundLoss \(\mu\), covariance params Mean + matrix-root Frobenius surrogate vs target covariance GaussianWassersteinBoundLoss
GaussianNLLLoss(fixed_variance=σ²) \(\mu\) only Homoscedastic (reduces to scaled MSE) GaussianNLLLoss
MultivariateGaussianLoss \(\boldsymbol{\mu}, \mathbf{L}\) Correlated multi-output regression MultivariateGaussianLoss
LowRankGaussianLoss \(\boldsymbol{\mu}, \mathbf{U}, \mathbf{d}\) Scalable multivariate (\(\Sigma = UU^\top + \text{diag}(d)\)) LowRankGaussianLoss
create_gaussian_nll() — Factory: picks the right variant

GaussianNLL ↔ WeightedMSE continuum

Setting GaussianNLLLoss(fixed_variance=σ²) makes the model predict only the mean, and the loss reduces to a scaled MSE. The factory create_gaussian_nll(use_mse_for_unit_variance=True) returns WeightedMSELoss when variance is fixed at 1. This means GaussianNLL and MSE are endpoints of a single continuum.

Read the full Gaussian losses guide for deep dives on diagonal, full-covariance, and low-rank variants. Also see Beta-NLL for stabilized training, Faithful Gaussian & CRPS for decoupled mean/variance training and a proper-score alternative, and Wasserstein bound for covariance supervision.


Robust Losses

Bounded-influence losses for data with outliers or heavy-tailed noise.

Loss Score Function \(\rho(r)\) Tail Behaviour Robustness
PseudoHuberLoss \(\delta^2(\sqrt{1 + r^2/\delta^2} - 1)\) Linear ⭐⭐
LogCoshLoss \(\log\cosh(r)\) Linear ⭐⭐
CharbonnierLoss \(\sqrt{r^2 + \epsilon^2} - \epsilon\) Linear ⭐⭐
CauchyLoss \(\log(1 + r^2/c^2)\) Logarithmic ⭐⭐⭐
TukeyBiweightLoss Bounded (rejects \(\lvert r\rvert > c\)) Zero ⭐⭐⭐⭐
CVaRLoss Worst-\(\alpha\) fraction Tail-focused ⭐⭐⭐

Read the full Robust losses guide — influence functions, redescending behavior, Barron family, CVaR.


Quantile & Expectile Losses

Distribution-free models for specific aspects of the conditional distribution.

Loss What it Predicts Math
QuantileLoss \(\hat{q}_\tau\): conditional quantile \(\rho_\tau(y - \hat{q}_\tau)\) where \(\rho_\tau(u) = u(\tau - \mathbf{1}_{u<0})\)
MultiQuantileLoss Multiple quantiles simultaneously \(\sum_\tau \rho_\tau(y - \hat{q}_\tau)\)
ExpectileLoss \(\hat{e}_\tau\): conditional expectile \(\lvert\tau - \mathbf{1}_{y < \hat{e}_\tau}\rvert(y - \hat{e}_\tau)^2\)
MultiExpectileLoss Multiple expectiles —
QuantileCrossoverLoss — Penalises \(\hat{q}_{\tau_1} > \hat{q}_{\tau_2}\) when \(\tau_1 < \tau_2\)

Read the full Quantile & Expectile guide — crossover penalties, multi-level prediction intervals, expectile-to-quantile conversion. For minimum-volume prediction sets with a learned level-set boundary, see Super-Level-Set (SLS) regression.


Ordinal Losses

For ordered categorical targets where class distance matters.

Loss Method Outputs
OrdinalCrossEntropyLoss Standard CE (baseline) \(K\) logits
CumulativeLinkLoss Cumulative-threshold model \(K-1\) logits
CumulativeLinkLoss Cumulative link / CORAL objective \(K-1\) binary logits

Read the full Ordinal losses guide — cumulative link, CORAL, cross-entropy baselines.


Censored Regression Losses

For partially observed outcomes — right/left/interval censoring.

Loss Censoring Model Use Case
CensoredGaussianNLLLoss Gaussian + \(\Phi\) Clipped sensors, detection limits
CensoredQuantileLoss Quantile + censoring Non-parametric censored regression
AFTLoss Accelerated Failure Time Survival analysis

Read the full Censored losses guide — Gaussian censored NLL, AFT survival models, quantile censoring.


Poisson, Tweedie & Count Losses

For count data and targets with specific mean-variance relationships.

Loss Model Best For
PoissonDevianceLoss \(\text{Var} = \mu\) Standard counts
NegativeBinomialNLLLoss \(\text{Var} = \mu + \mu^2/r\) Overdispersed counts
ZeroInflatedPoissonNLLLoss ZI-Poisson Counts with excess zeros
TweedieLoss \(\text{Var} = \phi\mu^p\) Flexible power model
GammaLoss Gamma Positive, right-skewed
InverseGaussianLoss Inverse Gaussian Positive, \(\text{Var} \propto \mu^3\)
CompoundPoissonLoss Compound Poisson Zeros + continuous positives

Read the Poisson & Tweedie guide for count models and Poisson-Gaussian for shot noise plus read noise (PoissonGaussianLoss).


Evidential Regression

Single-forward-pass aleatoric + epistemic decomposition via a Normal-Inverse-Gamma prior:

\[\mu \sim \mathcal{N}\!\bigl(\gamma,\, \sigma^2/\nu\bigr), \qquad \sigma^2 \sim \text{Inv-Gamma}(\alpha, \beta)\]
Loss What it Does
EvidentialRegressionLoss Predicts \((\gamma, \nu, \alpha, \beta)\); uncertainty without ensembles

Read the full Evidential regression guide — Normal-Inverse-Gamma prior, single-pass decomposition, calibration caveats.


Mixture Density Networks (MDN)

For multimodal conditional distributions:

\[p(y \mid x) = \sum_{k=1}^K \pi_k(x)\,\mathcal{N}\!\bigl(y \mid \mu_k(x),\, \sigma_k^2(x)\bigr)\]
Loss Description
MixtureDensityLoss NLL for Gaussian mixtures

Read the full MDN guide — component selection, label switching, mixture-of-mixtures ensembles.


Normalizing Flows

For arbitrarily complex conditional distributions:

Loss Description
NormalizingFlowLoss NLL via change-of-variables (requires zuko)
NoiseAwareDensityLoss Marginal likelihood with Gaussian label noise (GH/analytic/MC)
ContrastiveFlowLoss InfoNCE/contrastive likelihood-ratio ranking over positive vs alternate contexts (flow log-densities)
create_flow_model(..., flow_type="bpf") Bernstein-polynomial flow (scalar/joint)
create_flow_model(..., flow_type="cinn") Conditional affine-coupling (cINN-style) flow
NeuralRatioLoss Classifier-based neural ratio estimation (binary/multiclass) for parameter inference
create_flow_model() / create_flow_loss() / create_contrastive_flow_loss() Factory functions

Read the full Normalizing flows guide — NSF/cNSF, cINN/RealNVP, BPF, contrastive flow variant, inference sampling — and the neural ratio estimation guide for the classifier-based likelihood-ratio estimator, posterior-weight utilities and SBI calibration diagnostics. The flow design notes record why exact conditional likelihood is the default for low-dimensional tabular regression and when flow matching or diffusion is the better fit.


Grid & Basis Densities

For heads that output a whole distribution on a fixed 1D support (binned or spline-basis):

Symbol Description
utils.BSplineDensityBasis Unit-integral B-spline (M-spline) basis: softmax coefficients give a normalised density; exact bin integrals and E|U - x|
DiscreteWasserstein1Loss 1-Wasserstein between mass vectors on a shared grid (displacement-aware complement to KL)
RankNContrastLoss Rank-N-Contrast: order features by continuous label distance (Zha et al. 2023)

Read the Grid & basis densities guide.


Error-in-Variables Losses

For regression when inputs have measurement uncertainty:

Loss Model When to Use
StructuralEIVLoss Known error ratio \(\lambda\) Known \(\sigma_x / \sigma_y\)
FunctionalEIVLoss Per-sample \(\sigma_x\) Heteroscedastic input noise
OrthogonalDistanceRegressionLoss Perpendicular distances General EIV
EnsembleEIVLoss Ensemble disagreement No known error model
SplitMeasurementLoss Two independent measurements Paired/repeat exposures, no noise model needed
CorrectedScoreEIVLoss Stefanski–Nakamura corrected score Known \(\Sigma_x\), avoids attenuation without latent parameters

Read the full EIV losses guide for loss-based correction, split-measurement and corrected-score losses for attenuation-free objectives, or see the algorithm pages for Regression Calibration, SIMEX and forward generative inversion.


Imbalanced Regression

For targets with significant distribution imbalance:

Loss Strategy
DensityWeightedLoss Inverse target-density reweighting
FocalRLoss Focus on hard examples
LDSLoss Label Distribution Smoothing
PropensityWeightedLoss Inverse propensity scores
FeatureDistributionSmoother FDS: feature-moment calibration across target bins
PrimeLoss PRIME: learnable proxies with uniformly spaced targets
ConR Contrastive collapse penalty weighted by label density
UncertaintyAwareConR ConR with Gaussian-softened pair membership
BalancedMSEBMC Noise-adaptive Balanced MSE (BMC) of Ren et al. 2022; batch-coupled
RankSimLoss Ranking-similarity regularization on features (Gong et al. 2022)

Read the full Imbalanced regression guide — density weighting, Focal-R, LDS, propensity weighting — and PRIME & ConR for representation-level methods, plus Balanced MSE (BMC) and RankSim. Group-robust training over target bins is covered by Continuous Group DRO.


Noisy Labels & Uncertain Ground Truth

Loss Strategy
NoisyTargetGaussianNLL Adds known target-noise \(\sigma_y^2\) to predicted variance
NoiseAwareDensityLoss Marginal likelihood for flow/MDN density under label noise
BinnedDensityLoss Smoothed histogram / ordinal-CDF scalar density
JointBinnedDensityLoss Joint low-dimensional multi-target binned density/CDF (capped histogram)
ConsistencyRegLoss Teacher-student consistency
PseudoLabelNLL Blends observed + pseudo labels
PseudoLabelConsistencyLoss Single objective for pseudo-label + teacher-consistency point-regression training

Read the Noisy labels guide, the noise-aware density guide, for target-noise-aware NLL/densities and consistency losses, or the Uncertain GT guide for pseudo-label workflows.


Transform Losses

Loss Strategy
LogTransformLoss Optimize in log space for positive multiplicative-noise targets
BoxCoxTransformLoss Tunable positive-support power transform
SqrtTransformLoss Variance-stabilizing square-root transform
YeoJohnsonTransformLoss Signed-target power transform

Read the full Transform losses guide — log, Box-Cox, sqrt, Yeo-Johnson transforms, and the generic TransformedTargetLoss wrapper.


Flexible-Shape Families (losses.families)

Parametric NLLs for non-Gaussian conditional distributions — skew, heavy-tailed, bounded, and extreme-value families. See the full Families guide for formulas, usage, and the unconstrained_inputs pattern.

Loss Distribution Key Property
SkewNormalNLLLoss Skew-normal (Azzalini 1985) Gaussian at alpha=0
SkewTLoss Skew-t (Azzalini & Capitanio 2003) Student-t at alpha=0; heavy tails
BetaRegressionNLLLoss Beta (Ferrari & Cribari-Neto 2004) Targets in (0, 1)
JohnsonSUNLLLoss Johnson SU Flexible (gamma, delta) shapes
SinhArcsinhNLLLoss Sinh-arcsinh (Jones & Pewsey 2009) Gaussian at epsilon=0, delta=1
GEVNLLLoss GEV (Coles 2001) Analytic Gumbel limit as xi→0
AsymmetricLaplaceNLLLoss Asymmetric Laplace Pinball correspondence tau=1/(1+kappa²)
SQRLoss Sorted quantiles (SQR) Distribution-free; cummax-sorted levels

All NLL families (except SQRLoss) expose unconstrained_inputs=True (default): positivity-constrained parameters are mapped internally as softplus(raw)+eps. Set unconstrained_inputs=False when your head already outputs positive values — the loss applies the inverse softplus transform internally to avoid softplus(softplus(x)).

Read the full Families guide — skew/t, beta, Johnson SU, sinh-arcsinh, GEV, asymmetric Laplace, SQR, and the unconstrained_inputs contract.


Conformal Prediction Wrappers

Conformal prediction is a post-hoc layer, not a likelihood: it turns any point or quantile predictor into intervals with finite-sample coverage. The predictors are exported from torchregress.losses for convenience, but the methodology (split, CQR, CV+, weighted/non-exchangeable, distributional) is documented in Conformal Prediction and the methods section.


Loss Selection Guide

If you need… Start with… Then consider…
Simple regression WeightedMSELoss WeightedHuberLoss for robustness
Outlier robustness WeightedHuberLoss CauchyLoss or TukeyBiweightLoss
Prediction intervals MultiQuantileLoss + CQR for guarantees
Heteroscedastic uncertainty GaussianNLLLoss + Ensemble for epistemic
Full distribution MixtureDensityLoss NormalizingFlowLoss for more flexibility
Single-pass uncertainty EvidentialRegressionLoss Ensemble for better calibration
Count data PoissonDevianceLoss NegativeBinomialNLLLoss for overdispersion
Data with zeros TweedieLoss CompoundPoissonLoss for mixed
Imbalanced targets DensityWeightedLoss FocalRLoss or LDSLoss
Noisy labels NoisyTargetGaussianNLL ConsistencyRegLoss
Semi-supervised regression PseudoLabelConsistencyLoss PseudoLabelNLL
Strong target skew / multiplicative noise LogTransformLoss BoxCoxTransformLoss or SqrtTransformLoss
Measurement error StructuralEIVLoss RC or SIMEX
Ordered categories CumulativeLinkLoss OrdinalCrossEntropyLoss
Censored/survival CensoredGaussianNLLLoss AFTLoss

For a generic scalar binned-CDF training objective, use CumulativeCDFLoss or cumulative_cdf_loss. The astronomy-specific recipe/model composites and stellar-spectrum examples are removed from the core library; applications can compose the generic losses and FTTransformer in their own training pipelines.