SNLDS#
Switching non-linear dynamical system trained with collapsed amortized variational inference (CAVI-SNLDS).
Warning
Experimental. In a historical pilot on 54 series of TSB-SEG (TSSB, UTSA, SKAB, MoCap), SNLDS scored below a random segmentation (bidirectional covering 0.074 against 0.377, ARI 0.066 against 0.208): its labels change about 200 times more often than the true regimes. Training five times longer did not help on the two series tried. It is kept for further study, not as a recommended detector. These measurements predate the numerical corrections described below and do not evaluate the corrected implementation.
Description#
SNLDS models a time series with a discrete regime \(s_t \in \{1, \dots, K\}\), a continuous latent state \(z_t\) and an observation \(x_t\). Each regime has its own non-linear transition \(p(z_t \mid z_{t-1}, s_t)\), an MLP; the regime switches follow \(p(s_t \mid s_{t-1}, x_{t-1})\), and \(x_t\) is emitted from \(z_t\) by a shared network.
Training maximises an evidence lower bound. An RNN infers the continuous states \(q(z_{1:T} \mid x_{1:T})\), and the discrete states are integrated out exactly with the forward-backward algorithm.
After training, each time step receives the regime of highest posterior probability \(p(s_t \mid x_{1:T}, z_{1:T})\).
The paper offers two devices against the collapse onto a single regime: a
cross-entropy regulariser between the regime posterior and a uniform prior,
with weight \(\beta\), and a temperature \(\tau\) on the discrete
transitions. Both start large and decay, \(\beta\) first, then
\(\tau\) down to 1. The paper uses them on its Reacher experiment and not
on the bouncing ball, where they are not needed. By default tsseg does not use
them either, and trains at a learning rate of 1e-3, the paper’s
(use_temperature_annealing=False, use_cross_entropy_reg=False): see
Default training regime. When switched on, they follow the schedule of the
Reacher experiment (\(\beta_0 = \tau_0 = 1000\), decay by 0.975 every 500
steps after steps 50,000 and 100,000, out of 300,000), scaled to
n_train_steps: the decays start after n_train_steps / 6 and
n_train_steps / 3 steps, with a factor 0.975 every n_train_steps / 600
steps.
Each gradient step uses batch_size windows of train_window points drawn
at random positions of the series, which bounds the cost of a step; prediction
runs on the whole series. The paper trains on minibatches of 32 short
sequences (50 to 100 steps) from many trajectories; tsseg draws its windows from
the single series it segments.
n_states is the number of regimes)n_train_steps, B batch_size, L train_window, or
n if smaller), then \(O(n)\) time steps for the prediction pass. Each
time step evaluates the K continuous transition networks (K is
n_states), the discrete transition network, \(O(d\,K^{2} + K^{4})\),
and the forward-backward recursion, \(O(K^{2})\)tf-keras
(pip install tsseg[snlds])Note
Training is slow. A step processes \(B\,L\) time steps for batch_size
\(B\) windows of \(L\) points, independent of the length of the
series: about
0.1 s on one CPU thread with the defaults, so about 3 minutes for the 2,000
default steps. The first call also spends a few seconds compiling the training
graph.
Note
With an integer random_state, fit and predict are reproducible: two
fits start from the same weights, draw the same windows and the same
posterior samples, and give the same model; two calls to predict on
one fitted model give the same labels. The inference network samples the
continuous states inside a TensorFlow while loop that runs several steps
in parallel, and each step draws its noise with a stateless seed derived
from the step index, so the order in which the steps run does not matter.
This holds on one machine and one TensorFlow build (checked on CPU; GPU
kernels were not checked). With random_state=None, every fit draws new
windows and initial weights. The outcome depends strongly on the seed: on
a series of three segments with clear mean shifts (1,000 points), seeds 0
to 4 gave adjusted Rand indices of 0.03 to 0.57.
Earlier versions took the noise draws in a variable order, so two fits with
the same random_state differed (three runs gave 0.43, 0.43 and 0.40 on
the series above), and so could two predictions. The figures on this page
were measured with those versions: the draws are now different ones, so
individual fits differ from the reported ones.
Implementation audit#
The November 2026 audit found four reproducible implementation errors:
The pairwise posterior uses axes
[destination, source], but the expected complete-data likelihood broadcast the current emission over the source state. A two-state, three-point example with eight enumerated paths gives an expected complete-data log likelihood of -2.692044; the old code gave -7.117615.The objectives called
elboandiwaeused the expected complete-data score instead of the log likelihood with discrete paths marginalized out. This omits the entropy of the discrete posterior. Differentiating through that posterior also changes the gradient. Even after fixing the state axis, the example above gave -2.692044 instead of the exact marginal log likelihood -1.907844. Both objectives now use the sum of the forward normalizers, with the continuous posterior entropy or importance weights as appropriate.initial_likelihoodandsequence_likelihoodremain diagnostics of the expected complete-data score.Gaussian scales were transformed into eager tensors in the constructors, outside the training gradient tape. Their raw parameters were also absent from Keras 3’s tracked weights.
trainable_cov=Truetherefore did not train the continuous transition covariance. Raw scales are now Keras weights, transformed when used. Covariances configured as fixed stay fixed.The Keras 3 fallback for
lstmcreated one initial state instead of the hidden and cell states, so fitting failed. The cell now supplies its own initial state structure.
These errors originate in the vendored calculations or their Keras port.
They prevent attributing the historical pilot’s poor scores entirely to the
method or the data. The regression tests check values and gradients against
enumerated paths, covariance updates under tf.function, and all three RNN
types. They do not establish segmentation quality on a benchmark.
Small before/after diagnostic#
With 2,000 updates, seed 42, the true state count and the training regime of the time (learning rate 1e-4, temperature annealing and cross-entropy regulariser on, see Default training regime), a diagnostic on Python 3.12 / TensorFlow 2.21 / Keras 3.14 gave:
Series |
Implementation |
ARI |
BiC |
Predicted changes |
Fit (s) |
|---|---|---|---|---|---|
Mean shifts (1,000 points, 2 true changes) |
Before |
0.813 |
0.710 |
99 |
239 |
Mean shifts |
Corrected |
0.095 |
0.009 |
653 |
242 |
MoCap trial 0 (4,579 points, 6 true changes) |
Before |
0.118 |
0.090 |
506 |
267 |
MoCap trial 0 |
Corrected |
0.033 |
0.037 |
2,141 |
269 |
Numerical correctness did not improve these two segmentations: both accuracy and oversegmentation became worse in these runs. Prediction took about one second. Two predictions of each fitted model disagreed on at most 0.4% of labels, much less than the amount of oversegmentation. The fit used one CPU thread per process; runs were concurrent, so these times are not an isolated performance benchmark. There is one run per case and implementation, and training is nondeterministic: this is not an estimate of mean performance or an ablation separating the individual corrections.
The correction is a candidate for further evaluation, not evidence that this detector is now a useful baseline. In particular, increasing training time or changing defaults is not justified by this diagnostic alone.
scripts/diagnostics/snlds_audit.py regenerates these measurements;
snlds_audit_results.json beside it records the raw results and source hashes.
Run the same script on the baseline commit (e0b09b3) and on the corrected
checkout (--regime audit, the default of the script, keeps the training
regime of the audit; --regime default uses the current defaults), for
example:
python -m scripts.diagnostics.snlds_audit --case mean-shifts
python -m scripts.diagnostics.snlds_audit --case mocap
Default training regime#
Until version 0.4.0, the defaults were a learning rate of 1e-4 with both schedules on, compressed into the 2,000 default steps. In that regime the learned transitions stay close to uniform (mean self-transition probability 0.30 on MoCap, against 0.48 with the new defaults), or even favour switching, and the labels change hundreds of times. The defaults are now a learning rate of 1e-3 without temperature annealing or regulariser, as for the paper’s bouncing ball, at the same cost. On the nine bundled MoCap trials, with the true number of states and seeds 0 to 2 (27 fits per regime):
Regime |
ARI |
BiC |
SMS |
Predicted changes |
|---|---|---|---|---|
1e-4, schedules on (former defaults) |
0.078 |
0.035 |
0.323 |
3,393 |
1e-3, schedules off (defaults) |
0.171 |
0.203 |
0.429 |
1,119 |
The new defaults score higher on 21 (ARI), 26 (BiC) and 24 (SMS) of the 27
fits. On the cases of the diagnostic above (seed 42), they give ARI 0.546,
BiC 0.046 and 340 changes on the mean shifts, and ARI 0.092, BiC 0.108 and 180
changes on MoCap trial 0. This is still poor: a single MoCap fit of the 27
reaches an ARI of 0.7, and the labels change about 1,100 times per trial for 5
to 10 true changes. Training five times longer (10,000 steps, schedules off)
on three trials cuts the changes from 697 to 117 per trial but does not raise
the scores reliably (higher BiC on 5 of 9 fits, lower mean ARI), for 4.3 times
the fit time. The former behaviour is
SNLDSDetector(learning_rate=1e-4, use_temperature_annealing=True,
use_cross_entropy_reg=True).
Why training is slow#
The defaults process \(2000 \times 8 \times 256 = 4\,096\,000\) latent time steps for each series. Each window requires an autoregressive RNN with sampling, forward and backward recursions over discrete states, and reverse mode differentiation. These time recursions limit parallel execution even for small networks. The discrete transition MLP has a hidden layer of \(4K^2\) units and \(K^2\) outputs, hence \(4K^4\) weights in that layer alone: supplying many states can be expensive. Compilation is an additional cost for each newly fitted detector; prediction also creates a new compiled function on each call.
Windows already bound training cost independently of series length. More training steps increase cost linearly and do not repair a wrong objective. The corrections above address correctness; no general speedup is promised.
Method and data limitations#
The wrapper is an adaptation of the authors’ example, not a reproduction of
the architectures and training regimes in their experiments. In particular,
network_input_embedding is the identity: the continuous posterior sees
past observations through a forward RNN, without the paper’s bidirectional
encoder. The discrete posterior still uses forward-backward smoothing.
The default inference RNN has four units, and training lasts 2,000 updates
at a fixed learning rate, against 10,000 for the paper’s bouncing ball.
The paper’s MoCap experiment trained on 29 salsa trajectories, using 93 coordinates per frame, and evaluated a held-out trajectory qualitatively, without ground-truth segmentation. Its states describe primitive directions of motion. Fitting windows from a single four-channel MoCap series and scoring activity labels is a different experiment. This makes data diversity and the meaning of the target states plausible limitations; it does not prove that switching dynamics cannot describe the benchmark signals.
There is no explicit segment-duration prior or minimum dwell time. Pointwise posterior argmax on one continuous-state sample can produce rapid switching; learning good reconstruction or dynamics does not guarantee matching semantic activity labels. The default emission standard deviation is fixed at 0.05 for standardized univariate input, and the latent dimension is eight even for one observed channel. The suitability of these assumptions needs an ablation, rather than increasing training time alone.
Known residual issues include stateful sampling in a parallel loop (run-to-run variation), and initial-state prior parameters that are not tracked as Keras 3 weights. This correction does not validate the entire model as a faithful reproduction of the paper. It left the defaults, the decoding policy and the estimator tags unchanged; the defaults changed afterwards (see Default training regime).
The mathematical reference is Dong et al., ICML 2020, especially Eq. (12) and the experimental details in the supplement.
Parameters#
Name |
Type |
Default |
Description |
|---|---|---|---|
|
int |
|
Number of discrete regimes \(K\). |
|
int |
|
Dimension of the continuous latent state \(z_t\). |
|
int |
|
Hidden size of the inference RNN. |
|
str |
|
Inference RNN cell ( |
|
int |
|
Number of gradient steps; the schedules, when on, scale with it. |
|
float |
|
Adam learning rate. |
|
int |
|
Training windows per gradient step. |
|
int / None |
|
Length of the training windows ( |
|
str |
|
Training objective ( |
|
bool |
|
Anneal the temperature of the discrete transitions down to 1. |
|
float |
|
Initial temperature. |
|
bool |
|
Add the cross-entropy regulariser on regime usage. |
|
float |
|
Initial weight of the regulariser. |
|
int / None |
|
Seed of the training windows, of the initial weights and of TensorFlow, which seeds the posterior samples (fit and predict are reproducible, see the note above). |
|
int |
|
Log the objective every tenth of training when |
|
int |
|
Time axis. |
Usage#
from tsseg.algorithms import SNLDSDetector
detector = SNLDSDetector(n_states=3)
labels = detector.fit_predict(X)
Implementation: wrapper around the authors’ TensorFlow code (Google
Research, Apache License 2.0), vendored in
tsseg/algorithms/snlds/vendor with relative imports, Keras 3 compatibility
fixes, corrected collapsed objectives and trainable Gaussian scales.
Reference: Dong, Seybold, Murphy & Bui (2020), Collapsed Amortized Variational Inference for Switching Nonlinear Dynamical Systems, ICML.
API reference#
SNLDS (Switching Non-Linear Dynamical System) detector for time series segmentation.
- Wraps the CAVI-SNLDS model from:
Dong, Z., Seybold, B., Murphy, K., & Bui, H. (2020). Collapsed Amortized Variational Inference for Switching Nonlinear Dynamical Systems. ICML 2020.
The model learns discrete regime labels via variational inference with a forward-backward algorithm over discrete states, making it a natural state detector.
- class SNLDSDetector(*, n_states=3, hidden_dim=8, rnn_dim=4, rnn_type='simplernn', n_train_steps=2000, learning_rate=0.001, batch_size=8, train_window=256, objective='elbo', use_temperature_annealing=False, temperature_init=1000.0, use_cross_entropy_reg=False, xent_init=1000.0, random_state=42, verbose=0, axis=0)[source]#
Bases:
BaseSegmenterState detector based on Switching Non-Linear Dynamical Systems (CAVI-SNLDS).
Uses collapsed amortized variational inference to learn discrete regimes in time series data. After training, the discrete state posterior
p(s_t | x_{1:T}, z_{1:T})is used to assign a regime label to each time-step.Warning
Experimental. A historical TSB-SEG pilot, before the numerical corrections to the objectives and covariances, scored below a random segmentation and switched labels far too often. Benchmark quality of the corrected model has not been established. See the documentation page.
- Parameters:
n_states (
int) – Number of discrete regimes (K).hidden_dim (
int) – Dimension of the continuous latent state z_t.rnn_dim (
int) – Hidden dimension of the posterior inference RNN.rnn_type (
str) – RNN cell type for inference network (“gru”, “lstm”, “simplernn”).n_train_steps (
int) – Number of gradient steps for training.learning_rate (
float) – Learning rate for Adam optimiser.batch_size (
int) – Number of training windows per gradient step.train_window (
int|None) – Length of the training windows, drawn at random positions of the series at each step.None(or a value at least the length of the series) trains on the whole series, withbatch_sizecopies of it.objective (
str) – Training objective (“elbo” or “iwae”).use_temperature_annealing (
bool) – Anneal the temperature of the discrete transitions fromtemperature_initdown to 1 (see Notes).temperature_init (
float) – Initial temperature.use_cross_entropy_reg (
bool) – Add the cross-entropy regulariser on regime usage, with a weight that decays fromxent_inittowards 0 (see Notes).xent_init (
float) – Initial weight of the cross-entropy regulariser.random_state (
int|None) – Seed of the training windows, of the initial weights, and of TensorFlow (global seed, set at the start offitandpredict), which seeds the posterior samples. With an integer, fit and predict are reproducible (see Notes);Nonedraws new windows and weights at every fit.verbose (
int) – Log the objective ten times during training when>= 1.axis (
int) – Time axis of the input array.
Notes
By default, training uses neither the temperature annealing nor the cross-entropy regulariser, at a learning rate of 1e-3, as in the paper’s bouncing ball experiment (appendix), where they are not needed. Compressed into a few thousand steps, the schedules keep the learned transitions close to uniform, or even favour switching, so that the labels change hundreds of times.
When switched on, the schedules follow the paper’s Reacher experiment, scaled to
n_train_steps: there, the regulariser weight starts at 1,000 and decays by a factor 0.975 every 500 steps after step 50,000, the temperature does the same after step 100,000 (down to 1), and training lasts 300,000 steps. Here the weight decays aftern_train_steps / 6steps and the temperature aftern_train_steps / 3, by 0.975 everyn_train_steps / 600steps, so that both reach the same final values.Training on random windows bounds the cost of a step, which otherwise runs a forward-backward pass over the whole series. The paper trains on minibatches of 32 short sequences (50 to 100 steps) from many trajectories; here the windows come from the single series to segment. Prediction uses the whole series.
Two fits with the same
random_statestart from the same weights, draw the same windows and the same posterior samples, so they give the same model, and two calls topredicton one fitted model give the same labels. The inference network samples the continuous states inside a TensorFlow while loop that runs several steps in parallel; each step draws its noise with a stateless seed derived from the step index, so the order in which the steps run does not change the draws. This holds for one machine and one TensorFlow build (checked on CPU). The outcome still depends strongly on the seed: on a series of three segments with clear mean shifts (1,000 points), seeds 0 to 4 gave adjusted Rand indices of 0.03 to 0.57 (measured before the sampling was made reproducible).The vendored model code comes from Google Research (Apache License 2.0), see
tsseg/algorithms/snlds/vendor.References
- set_fit_request(*, axis='$UNCHANGED$')#
Configure whether metadata should be requested to be passed to the
fitmethod.Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with
enable_metadata_routing=True(seesklearn.set_config()). Please check the User Guide on how the routing mechanism works.The options for each parameter are:
True: metadata is requested, and passed tofitif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it tofit.None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (
sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.Added in version 1.3.
- set_predict_request(*, axis='$UNCHANGED$')#
Configure whether metadata should be requested to be passed to the
predictmethod.Note that this method is only relevant when this estimator is used as a sub-estimator within a meta-estimator and metadata routing is enabled with
enable_metadata_routing=True(seesklearn.set_config()). Please check the User Guide on how the routing mechanism works.The options for each parameter are:
True: metadata is requested, and passed topredictif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it topredict.None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (
sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.Added in version 1.3.