osl_dynamics.models.base.VariationalModelBase#

class osl_dynamics.models.base.VariationalModelBase(config)#

Bases: osl_dynamics.models.base.model.ModelBase

Base class for models trained with amortized variational inference.

train(training_data, best_of=None, save_dir=None, init_kwargs=None, **kwargs)#

Initialize and fit the model, keeping the best of several runs.

Parameters:
training_dataosl_dynamics.data.Data or tf.data.Dataset

Training data.

best_ofint, optional

Number of runs. The run with the lowest free energy is kept. Defaults to config.best_of.

save_dirstr, optional

Directory to save each run to. If None, the runs are not saved.

init_kwargsdict, optional

Keyword arguments for initialization, e.g. method, n_init, n_epochs or stay_prob.

**kwargskeyword arguments

Keyword arguments for fit. All except epochs and the saving options (save_best_after, best_filepath, checkpoint_freq and checkpoint_dir) are also passed to initialization.

fit(training_data, epochs=None, learning_rate=None, learning_rate_decay=None, callbacks=None, verbose=1, save_best_after=None, best_filepath=None, checkpoint_freq=None, checkpoint_dir=None, **schedule_kwargs)#

Train the model.

Parameters:
training_dataosl_dynamics.data.Data or tf.data.Dataset

Training data.

epochsint, optional

Number of epochs. Defaults to config.n_epochs.

learning_ratefloat, optional

Initial learning rate. Defaults to config.learning_rate.

learning_rate_decayfloat, optional

Decay of the learning rate. Defaults to config.learning_rate_decay.

callbackslist, optional

Keras callbacks.

verboseint, optional

0 for no progress bars, 1 for a progress bar for each epoch and 2 for a single progress bar over the epochs.

save_best_afterint, optional

Epoch after which we save the model with the lowest loss. The best model is loaded at the end of training.

best_filepathstr, optional

Path to save the best model’s weights to (a .weights.h5 file). Defaults to a file in /tmp/model_weights.

checkpoint_freqint, optional

Frequency (in epochs) of checkpoints.

checkpoint_dirstr, optional

Directory to save the config and the checkpoints (in <checkpoint_dir>/checkpoints) to. Defaults to tmp. Load with osl_dynamics.models.load(checkpoint_dir, from_checkpoint=True).

**schedule_kwargskeyword arguments, optional

Settings that override the config for this call: kl_annealing (bool) and n_kl_annealing_epochs (int) for models with KL annealing, and gumbel_annealing (bool) for DyNeStE.

Returns:
historydict

Training history: a list with the value in each epoch of loss, the terms of the loss (nll_loss, and kl_loss for models with a KL loss), learning_rate, the other scheduled values (ema_decay, kl_factor or gumbel_temperature, depending on the model) and skipped_steps (the number of training steps skipped because of a NaN or inf).

initialization(*args, method=None, **kwargs)#

Run an initialization method.

Parameters:
*argsarguments

Arguments for the initialization method.

methodstr, optional

Initialization method name. Defaults to config.init_method.

**kwargskeyword arguments

Keyword arguments for the initialization method.

Returns:
historydict

Training history of the initialization.

random_subset_initialization(training_data, n_epochs=None, n_init=None, take=None, **kwargs)#

Random subset initialization.

The model is trained for a few epochs with different random subsets of the training dataset, starting from the parameters given by reset(). The best model is kept.

Parameters:
training_datatf.data.Dataset or osl_dynamics.data.Data

Dataset to use for training.

n_epochsint, optional

Number of epochs to train the model. By default we use the value passed in the config.

n_initint, optional

Number of initializations. By default we use the value passed in the config.

takefloat, optional

Fraction of total batches to take. By default we use the value passed in the config.

kwargskeyword arguments, optional

Keyword arguments for fit, e.g. n_kl_annealing_epochs for models with KL annealing.

Returns:
historydict

The training history of the best initialization.

random_state_time_course_initialization(training_data, n_epochs=None, n_init=None, take=None, stay_prob=0.9, n_batches=N_ESTIMATION_BATCHES, **kwargs)#

Random state time course initialization.

A state time course is sampled and each state’s parameters are set from the data assigned to it in n_batches batches. The model is then trained for a few epochs and the best candidate is kept.

Parameters:
training_datatf.data.Dataset or osl_dynamics.data.Data

Dataset to use for training.

n_epochsint, optional

Number of epochs to train the model. By default we use the value passed in the config.

n_initint, optional

Number of initializations. By default we use the value passed in the config.

takefloat, optional

Fraction of total batches to take. By default we use the value passed in the config.

stay_probfloat, optional

Stay probability (diagonal for the transition probability matrix) of the sampled state time course. Other states have uniform probability.

n_batchesint, optional

Number of batches used to set each candidate’s initial parameters, None for the whole dataset (which is held in memory). With more batches the candidates differ less.

kwargskeyword arguments, optional

Keyword arguments for fit, e.g. n_kl_annealing_epochs for models with KL annealing.

Returns:
historydict

The training history of the best initialization.

nfindr_initialization(training_data, n_epochs=None, n_init=None, take=None, window_length=20, n_restarts=10, n_batches=N_ESTIMATION_BATCHES, **kwargs)#

N-FINDR initialization.

For models whose covariance at each time point is a sum-to-one mixture of the mode covariances (e.g. DyNeMo and DIVE’s group covariances), the second moment of a short window of data is also a mixture, so the windows lie in a simplex whose vertices are the mode covariances. The mode covariances are set to the vertices found with N-FINDR (nfindr_covariances()) and the model is then trained for a few epochs with different random subsets of the training dataset, each starting from these covariances. The best model is kept and a later reset() returns to the N-FINDR covariances.

Assumes zero-mean data (the means are not initialized). If the covariances are not learned or initial_covariances were passed, the covariances are left as they are and this is the same as random_subset_initialization.

Parameters:
training_datatf.data.Dataset or osl_dynamics.data.Data

Dataset to use for training. The windows are cut from the sequences the model is trained on, so for a Data object only the sessions in training_data.keep are used.

n_epochsint, optional

Number of epochs to train the model. By default we use the value passed in the config.

n_initint, optional

Number of initializations. By default we use the value passed in the config.

takefloat, optional

Fraction of total batches to take. By default we use the value passed in the config.

window_lengthint, optional

Number of samples in each window. Shorter windows are closer to a single mode but noisier. Should be at most the sequence length.

n_restartsint, optional

Number of random starts for N-FINDR.

n_batchesint, optional

Number of batches the windows are cut from, None for the whole dataset (after take). The upper triangle of the covariance of each window is held in memory.

kwargskeyword arguments, optional

Keyword arguments for fit, e.g. n_kl_annealing_epochs for models with KL annealing.

Returns:
historydict

The training history of the best initialization.

single_subject_initialization(training_data, n_epochs=None, n_init=None, **kwargs)#

Single subject initialization.

Pick a subject at random, train a model, repeat a few times. Use the weights from the best model.

Parameters:
training_datalist of tf.data.Dataset or osl_dynamics.data.Data

Datasets for each subject.

n_epochsint, optional

Number of epochs to train. By default we use the value passed in the config.

n_initint, optional

How many subjects should we train on? By default we use the value passed in the config.

kwargskeyword arguments, optional

Keyword arguments for fit, e.g. n_kl_annealing_epochs for models with KL annealing.

Returns:
historydict

The training history of the best initialization.

get_alpha(dataset, concatenate=False, remove_edge_effects=False, verbose=1)#

Mixing coefficients, alpha.

Parameters:
datasetosl_dynamics.data.Data or tf.data.Dataset

Data.

concatenatebool, optional

Should we concatenate the sessions?

remove_edge_effectsbool, optional

Edge effects can arise from separating the data into sequences. Passing True predicts with sequences that overlap by 50% and keeps only the central half of each sequence.

verboseint, optional

Pass 0 for no progress bar.

Returns:
alphalist or np.ndarray

Shape is (n_sessions, n_samples, n_modes) or (n_samples, n_modes).

get_theta(dataset, concatenate=False, remove_edge_effects=False, verbose=1)#

Logits, theta, inferred by the inference network.

Parameters:
datasetosl_dynamics.data.Data or tf.data.Dataset

Data.

concatenatebool, optional

Should we concatenate the sessions?

remove_edge_effectsbool, optional

Edge effects can arise from separating the data into sequences. Passing True predicts with sequences that overlap by 50% and keeps only the central half of each sequence.

verboseint, optional

Pass 0 for no progress bar.

Returns:
thetalist or np.ndarray

Shape is (n_sessions, n_samples, n_modes) or (n_samples, n_modes).

free_energy(dataset, concatenate=True, verbose=1)#

Variational free energy.

theta is the posterior mean rather than a sample, which gives a lower KL loss than in training.

Parameters:
datasetosl_dynamics.data.Data or tf.data.Dataset

Data.

concatenatebool, optional

Should we calculate a single free energy for all sessions? If False, a free energy is calculated for each session.

verboseint, optional

Pass 0 for no progress bar.

Returns:
free_energyfloat or np.ndarray

Free energy, or free energy of each session if concatenate=False (shape (n_sessions,)).

losses(dataset, verbose=1)#

Negative log-likelihood and KL losses, averaged over sequences.

theta is the posterior mean (no sampling).

Parameters:
datasetosl_dynamics.data.Data or tf.data.Dataset

Data.

verboseint, optional

Pass 0 for no progress bar.

Returns:
nll_lossfloat

Negative log-likelihood loss.

kl_lossfloat

KL divergence loss.

save(dirname)#

Save the config and weights.

Parameters:
dirnamestr

Directory to save the config and weights in.

classmethod load(dirname, from_checkpoint=False, single_gpu=True)#

Load a model saved with save.

Models saved with osl-dynamics 3.0 to 3.9 are converted (see legacy).

Parameters:
dirnamestr

Directory containing config.yml and the weights.

from_checkpointbool, optional

Should we load the weights from the latest checkpoint in <dirname>/checkpoints?

single_gpubool, optional

Should we load the model on a single GPU?

Returns:
modelModel

Model object.

save_config(dirname)#

Save the config as <dirname>/config.yml.

Parameters:
dirnamestr

Directory to save config.yml in.

static load_config(dirname)#

Load a config from <dirname>/config.yml.

Parameters:
dirnamestr

Directory containing config.yml.

Returns:
configdict

Values used to create the config.

versionstr

Version of osl-dynamics used to save the config. None if the file does not contain the version.

save_weights(filepath)#

Save the weights of the Keras model.

Parameters:
filepathstr

Path to a .weights.h5 file.

load_weights(filepath)#

Load the weights of the Keras model.

Parameters:
filepathstr

Path to a .weights.h5 file.

get_weights()#

Get the values of all weights in the Keras model.

Returns:
weightslist of np.ndarray

Value of each weight, in the order of keras_model.weights.

set_weights(weights)#

Set the values of all weights in the Keras model.

Parameters:
weightslist of np.ndarray

Values from get_weights.

reset()#

Re-initialize the weights and reset the optimizer.

reset_weights(keep=None)#

Re-initialize the weights.

Weights are given new random values. If a parameter has been set with update_initializer=True (e.g. set_covariances or an initialization method), it is reset to that value instead.

Parameters:
keeplist of str, optional

Names of the layers of the Keras model to not re-initialize.

reset_optimizer()#

Set the optimizer variables (e.g. moments and learning rate) back to their initial values.

freeze(*names)#

Context manager to hold layers of the Keras model fixed during training.

Parameters:
*namesstr

Names of the layers (attributes of keras_model).

make_dataset(inputs, shuffle=False, concatenate=False, step_size=None, drop_last_batch=False)#

Convert a Data object into a TensorFlow Dataset.

Parameters:
inputsosl_dynamics.data.Data or str or np.ndarray or tf.data.Dataset

Data object. A str or np.ndarray is first converted into a Data object. A dataset (e.g. from osl_dynamics.data.load_tfrecord_dataset()) or list of datasets is passed through.

shufflebool, optional

Should we shuffle the data? A prebuilt dataset is used as is, but a shuffled one is rejected if ordered per-session output is needed (shuffle=False, concatenate=False).

concatenatebool, optional

Should we return a single dataset or a list of datasets (one for each session)?

step_sizeint, optional

Number of samples to slide the sequence across the data. Default is no overlap. A prebuilt dataset must have been made with the requested step size.

drop_last_batchbool, optional

Should we drop the last batch if it is smaller than the batch size? For a prebuilt dataset this is only done if it is from osl_dynamics.data.load_tfrecord_dataset().

Returns:
datasettf.data.Dataset or list

Dataset or list of datasets.

get_training_time_series(training_data, prepared=True, concatenate=False)#

Time series used for training, trimmed to whole sequences.

Parameters:
training_dataosl_dynamics.data.Data

Data object.

preparedbool, optional

Should we return the prepared data? If not, we return the raw data.

concatenatebool, optional

Should we concatenate the data for each session?

Returns:
training_datanp.ndarray or list

Training data time series.

summary()#

Print a summary of the model.

Lists the parameters of the model, their shape (or a description of a network), how each is learned and the number of learned values, followed by the training settings.

summary_table(renderer='html')#

Table of the parameters shown by summary.

Parameters:
rendererstr, optional

Either 'html', 'latex' or 'text'.

Returns:
tablestr

The table.

property is_multi_gpu: bool#

Is the model trained with multiple GPUs?