Repository navigation
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
StickyTransitionlearns how persistent each regime is; custom transitions can be passed viaMixtureModel(..., 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, andPredictions.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 bytransform.- Sample-based outputs are reproducible: their seed comes from
torch.manual_seed(), or passgenerator=. - A model's fixed monte-carlo noise for the log-prob (
mc_sampling, aFixedWhiteNoise, used e.g. by aBinomialFilter) is now seeded fromtorch.initial_seed(), so callingtorch.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=[[...]])(orfrom_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.KalmanFilternow warns about such pairs, including an example of thecorr_groupsvalue 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.KalmanFilterwarns when a decaying level has a free initial variance, again with the warning message including thestationary=[...]value(s) to pass to fix.- A new 'sd_corr' method for
Covarianceseparates scale from correlation (diag(std) @ R @ diag(std)).Covariance.to_method()converts a fitted module exactly.
Behavior changes
Predictions.get_state_at_times()returns aStateTuple, 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 checksisinstance(..., 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_rankfit about as well, but forecast worse. Pickled models with alow_rankcovariance 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 tonum_obsshould vs. should not be learned. The previous default (True) therefore attempted to fit a slope tolog(num_obs)even whennum_obsdidn't vary in the fit data and so wasn't identified. The new default 'auto' picks'static'in that case, atfit().True/Falseare 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
Covariancein 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=)(usestopping=),to_dataframe(type='components')(use'observed_states'), andcomplete_times(group_colname=, global_max=).Stopping.from_dict()is removed.
Bug fixes
- Adaptive scaling when forecasting from
initial_state: a forward-pass started fromget_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): thestdcolumn was 0.76x the actual standard-deviation. Code that uses it (e.g. forexp(mean + std**2 / 2)) will get larger, correct values; considerto_dataframe(transform=...)instead.simulate()now outputs the simulated states, so itsmeans,sample()andto_dataframe()describe observations around the simulated trajectories. Before, each timestep's output was the one-step prior, which understated the variance. Code that usessimulate()will get different (correct) values.forward(simulate=...)now errors ifn_step!=1is passed.simulate()failed for float64 (or non-cpu) models, now fixed.BinomialFilter(measure_covariance=...)failed when passed aCovariance(rather than a dict of its arguments).
Other changes
KalmanFilter(joseph_form=False)uses the simpler covariance updateP - 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 aBinomialFilterwith 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 anEWMAdaptiveScaler's state-dict is missing its_extra_stateentry (it then gets the pre-1.2.0 behavior).Covariance.log_chol_to_chol()is deprecated in favor of the functiontorchcast.covariance.log_chol_to_chol(). The oldtorchcast.covariance.baseimport path now warns with aFutureWarning(was aDeprecationWarning, which Python usually hides).load_air_quality_data(outage_prob=...)can simulate sensor outages, andbenchmarks/profile_simple_model.pychecks performance against other git refs.
See CHANGELOG.md for details.