Skip to content

v2.0.0

Latest

Choose a tag to compare

@jwdink jwdink released this 22 Nov 22:25
3e9dad3

New features

Mixture components (experimental)

A measure can now have alternative regimes, e.g. for outliers that shouldn't drag the state or inflate the variance. Pass KalmanFilter(mixture=[MixtureComponent(...), ...]) (or a MixtureModel, from the new torchcast.mixture module). Each component is an offset from the standard regime: a learned shift of the measured-mean, extra variance, and base-rate. E.g. a 'quick visit' component means "spend well below this customer's usual level".

  • Regime-probabilities are tracked jointly across measures and carried through time. The default StickyTransition learns how persistent each regime is; custom transitions can be passed via MixtureModel(..., transition=).
  • A component's base-rate can depend on predictors (MixtureComponent(..., predictors=[...])), and latent classes (MixtureModel(..., classes=[LatentClass(...), ...])) give groups their own base-rates, as a discrete random effect.
  • log_prob() is the exact marginal likelihood. to_dataframe()/plot() intervals use the mixture's exact quantiles, and Predictions.get_mixture(measure) returns each regime's probability, mean and variance.
  • Supported on any measure with a gaussian likelihood, including measures with a nonlinear measurement and the non-binary measures of a BinomialFilter.

Back-transforming predictions

Predictions.to_dataframe(transform=LogTransform()) (or {measure: transform}) maps predictions of transformed measures back to the original scale. Intervals are transformed exactly, and the mean is E[inverse(Y)] rather than inverse(E[Y]). LogTransform, BoxCoxTransform and SmearingTransform (Duan's smearing, from the model's residuals) are provided, and bias_adjust controls how much bias-adjustment the mean gets. TimeSeriesDataset.from_dataframe(transform=...) applies the same transform going in.

Sampling and derived quantities

  • Predictions.sample() draws from the predictive distribution, jointly across measures (and regimes, for mixture models).
  • to_dataframe(derived={'total': lambda s: s['a'] + s['b']}) adds quantities computed from several measures, from joint samples on the scale given by transform.
  • Sample-based outputs are reproducible: their seed comes from torch.manual_seed(), or pass generator=.
  • A model's fixed monte-carlo noise for the log-prob (mc_sampling, a FixedWhiteNoise, used e.g. by a BinomialFilter) is now seeded from torch.initial_seed(), so calling torch.manual_seed() before creating the model makes its fits reproducible. Before, each new model drew its noise from numpy's unseeded random state, so refitting a re-created model on the same data could land at different parameters.

Better-identified covariances

  • Covariance.from_processes(processes, corr_groups=[[...]]) (or from_measures) makes the listed processes correlated with each other but not with the rest. E.g. a random-walk level and a decaying level on the same measure are poorly identified when their process-noise is correlated. KalmanFilter now warns about such pairs, including an example of the corr_groups value that could be passed to fix the issue.
  • Covariance.from_processes(processes, cov_type='initial', stationary=[...]) ties decaying processes' initial covariance to their stationary covariance, rather than free parameters that trade off against the decay rate. KalmanFilter warns when a decaying level has a free initial variance, again with the warning message including the stationary=[...] value(s) to pass to fix.
  • A new 'sd_corr' method for Covariance separates scale from correlation (diag(std) @ R @ diag(std)). Covariance.to_method() converts a fitted module exactly.

Behavior changes

  • Predictions.get_state_at_times() returns a StateTuple, which behaves like the (mean, cov) tuple it replaces, but also carries the regime-probabilities and adaptive-scaling state, so forecasts continue where they left off. Code that checks isinstance(..., tuple) will need updating.
  • Covariance(method='low_rank') is removed for new models, and every covariance now defaults to 'log_cholesky' (before, a measure-covariance with more than 5 measures used 'low_rank'). Empirically, low_rank fit about as well, but forecast worse. Pickled models with a low_rank covariance still load (convert them with .to_method('log_cholesky')). Loading such a state-dict raises an error that explains how to keep the fitted covariance.
  • BinomialFilter(do_post_hoc_correction=...) takes 'auto' (the default), 'static', 'num_obs' or 'none'. The previous True/False did not allow for separating problems where the correction-factor's relationship to num_obs should vs. should not be learned. The previous default (True) therefore attempted to fit a slope to log(num_obs) even when num_obs didn't vary in the fit data and so wasn't identified. The new default 'auto' picks 'static' in that case, at fit(). True/False are deprecated but can still be passed with a warning; they mean 'num_obs'/'none', so code that passes them keeps its previous behavior. Older models load with the same predictions.
  • Passing a Covariance in the wrong role (e.g. process_covariance=Covariance.from_processes(processes, cov_type='initial')) now raises, rather than a hard-to-understand warning.
  • Long-deprecated arguments now raise: fit(tol=, patience=, max_iter=) (use stopping=), to_dataframe(type='components') (use 'observed_states'), and complete_times(group_colname=, global_max=). Stopping.from_dict() is removed.

Bug fixes

  • Adaptive scaling when forecasting from initial_state: a forward-pass started from get_state_at_times(...) restarted the adaptive scaler, so a continued forecast differed from the same forecast made in one pass. The state now carries the scaler's state.
  • to_dataframe(conf=None): the std column was 0.76x the actual standard-deviation. Code that uses it (e.g. for exp(mean + std**2 / 2)) will get larger, correct values; consider to_dataframe(transform=...) instead.
  • simulate() now outputs the simulated states, so its means, sample() and to_dataframe() describe observations around the simulated trajectories. Before, each timestep's output was the one-step prior, which understated the variance. Code that uses simulate() will get different (correct) values. forward(simulate=...) now errors if n_step!=1 is passed.
  • simulate() failed for float64 (or non-cpu) models, now fixed.
  • BinomialFilter(measure_covariance=...) failed when passed a Covariance (rather than a dict of its arguments).

Other changes

  • KalmanFilter(joseph_form=False) uses the simpler covariance update P - K H P: less memory and faster, but less numerically robust. The default is unchanged. Mixture models can use it just for their non-standard regimes (MixtureModel(..., joseph_form=False)), where the tradeoff is more likely worth it: the update runs once per regime-combo, so mixtures are the memory-heavy part of training, and the non-standard regimes' extra variance makes their updates better conditioned.
  • Monte-carlo intervals (for measures with a nonlinear measured-mean) reuse the samples drawn for the means: much faster (e.g. ~11x for to_dataframe() of a BinomialFilter with mixture components).
  • to_dataframe(conf=False) returns just the means, skipping the intervals; Predictions.get_means() returns them as a tensor.
  • load_state_dict() warns when an EWMAdaptiveScaler's state-dict is missing its _extra_state entry (it then gets the pre-1.2.0 behavior).
  • Covariance.log_chol_to_chol() is deprecated in favor of the function torchcast.covariance.log_chol_to_chol(). The old torchcast.covariance.base import path now warns with a FutureWarning (was a DeprecationWarning, which Python usually hides).
  • load_air_quality_data(outage_prob=...) can simulate sensor outages, and benchmarks/profile_simple_model.py checks performance against other git refs.

See CHANGELOG.md for details.