Transforms

Map predictions of a transformed measure (e.g. log) back to the original scale, via Predictions.to_dataframe(transform=...).

Transforms for mapping predictions from the scale a measure is modeled on (e.g. log) back to its original scale.

class torchcast.state_space.transforms.Transform(bias_adjust: float | Mapping[str, float] | None = None)

Bases:

Maps a measure from its original to the scale it’s modeled on (and vice versa), e.g. for Predictions.to_dataframe(transform=...).

Subclasses implement transform() (the transformation applied before modeling – e.g. by TimeSeriesDataset.from_dataframe(transform=...)) and its inverse, inverse(), which must be elementwise and monotonically increasing (so quantiles can be back-transformed directly). The back-transformed mean, inverse_mean(), is E[inverse(Y)] where Y = mean + sqrt(var) * Z, and Z is standard normal. This is computed by gauss-hermite quadrature by default; subclasses can override _expected_inverse with a closed form, or _noise_nodes to use a different distribution for Z (see SmearingTransform).

Parameters:

bias_adjust – How much bias-adjustment to apply when back-transforming the mean, between 0 and 1. The back-transformed mean is computed with the variance scaled by this: 1 (the default, None) gives the mean of the back-transformed distribution; 0 gives no bias-adjustment (i.e. the back-transformed median). Doesn’t affect intervals. For monte-carlo means (e.g. use_map=False for nonlinear measures), the variance of the sampled state is scaled too. For a measure with mixture components, this can be a dictionary by regime: {component_id: value} ('__standard__' for the standard regime; regimes that aren’t in it get 1) – e.g. {'low': 0.} for the median of a low-outlier regime. (For a measure with a nonlinear measured-mean, a regime’s value must be 0, or the same as its other regimes’ nonzero values.) Ignored (with a warning) for Predictions.to_dataframe(derived=...), which back-transforms samples.

get_var_multi(regime: str = '__standard__') → float
Parameters:

regime – For a measure with mixture components: the id of the regime ('__standard__', or a component’s).

Returns:

The factor the variance is scaled by, for the back-transformed mean (see bias_adjust).

transform(x: Tensor) → Tensor
Parameters:

x – Values on the original scale.

Returns:

Values on the modeled (transformed) scale.

inverse(x: Tensor) → Tensor
Parameters:

x – Values on the modeled (transformed) scale.

Returns:

Values on the original scale.

inverse_mean(mean: Tensor, var: Tensor, adjust_bias: bool = True, regime: str = '__standard__') → Tensor

The mean on the original scale, E[inverse(Y)], for Y on the modeled scale with the given mean and variance – with the variance scaled by bias_adjust, unless adjust_bias=False.

Parameters:
  • mean – The mean of Y.

  • var – The variance of Y, same shape as mean (or broadcastable to it).

  • adjust_bias – Whether to apply bias_adjust (False: the mean of the back-transformed distribution, whatever bias_adjust is).

  • regime – For a measure with mixture components, the id of the regime that mean and var are for ('__standard__', or a component’s). Only matters for a transform whose noise-distribution differs by regime (a SmearingTransform from SmearingTransform.from_predictions()).

Returns:

A tensor with the same shape as mean.

class torchcast.state_space.transforms.LogTransform(offset: float = 0.0, base: float = 2.718281828459045, bias_adjust: float | Mapping[str | None, float] | None = None)

Bases: Transform

For a measure that was log-transformed before modeling.

Parameters:
  • offset – A value to be added before transforming (e.g. to prevent passing zero to log) and removed after back-transforming.

  • base – The base of the logarithm; defaults to e.

  • bias_adjust – See Transform.

class torchcast.state_space.transforms.BoxCoxTransform(lmbda: float, bias_adjust: float | Mapping[str | None, float] | None = None)

Bases: Transform

For a measure that was Box-Cox transformed before modeling: (y ** lmbda - 1) / lmbda (log(y) if lmbda == 0).

Parameters:
  • lmbda – The Box-Cox parameter. Must be non-negative: for negative values, the back-transformed mean of a gaussian does not exist (it’s infinite).

  • bias_adjust – See Transform.

class torchcast.state_space.transforms.SmearingTransform(base: Transform, residuals: Tensor, weights: Tensor | None = None, num_nodes: int = 100, component_residuals: Mapping[str, tuple[Tensor, Tensor | None]] | None = None)

Bases: Transform

Wraps a base transform; back-transformed means use the empirical distribution of standardized residuals instead of assuming the noise is gaussian (Duan’s “smearing” estimator). Useful when the residuals on the modeled scale have heavier (or lighter) tails, or skew, than a gaussian – which the back-transformed mean is sensitive to. Intervals are unaffected (they’re still the model’s gaussian quantiles, back-transformed).

The mean is sum_i w_i * inverse(mean + sqrt(var) * z_i), where z_i are standardized residuals: residuals divided by the predicted standard-deviation, e.g. from the model’s (1-step-ahead) predictions on its training data. They’re not re-standardized, so if the predicted variance is too small (large) on average, the smearing corrects for that too. See from_predictions().

For a measure with mixture components, each regime has its own mean and variance (a component’s regime is the standard one, offset, with extra variance); residuals are used for every regime – except components with their own, in component_residuals (see from_predictions(), which smears each regime with its own residuals).

Parameters:
  • base – The transform that was applied before modeling, e.g. LogTransform. Its bias_adjust (which scales var above) is used.

  • residuals – A 1-D tensor of standardized residuals. Non-finite values are dropped.

  • weights – Optional weights for the residuals (e.g. the probability that each came from the standard regime of a mixture measure).

  • num_nodes – The residuals’ (weighted) empirical distribution is summarized by this many quantiles (so the cost doesn’t grow with the number of residuals). If there are fewer residuals than this, they’re used directly.

  • component_residuals – Optionally, for mixture components with their own standardized residuals: {component_id: (residuals, weights)} (weights can be None), used for that component’s regime.

classmethod from_predictions(base: Transform, predictions: Predictions, y: Tensor, measure: str, num_nodes: int = 100) → SmearingTransform

Create from the standardized residuals of predictions for measure – typically 1-step-ahead predictions on the training data.

For a measure with mixture components, each regime is smeared with its own residuals: each observation’s residual standardized by that regime’s predicted mean and variance, and weighted by the probability (given the observation) that it came from that regime. So a component’s back-transformed mean uses the residuals attributed to it – rather than e.g. a lognormal mean, which is sensitive to a large component variance. (With few observations attributed to a component, this is correspondingly noisy; a component with none uses the standard regime’s.)

Parameters:
  • base – See SmearingTransform.

  • predictions – A Predictions object.

  • y – The observations, laid out like the input to the model ((num_groups, num_timesteps, num_measures)); can have fewer timesteps than predictions.

  • measure – The measure.

  • num_nodes – See SmearingTransform.

Returns:

A SmearingTransform.