osl_dynamics.models.scdynemo.Model#
- class osl_dynamics.models.scdynemo.Model(config)#
Bases:
osl_dynamics.models.dynemo.ModelSingle-channel Dynamic Network Modes.
See
osl_dynamics.models.scdynemofor a description of the model.set_regularizersonly sets a regularizer for the means.- Parameters:
- configosl_dynamics.models.scdynemo.Config
Settings of the model.
Examples
Train the model and get the inferred parameters:
model = Model(config) model.train(data) alpha = model.get_alpha(data) parameters = model.get_oscillator_parameters()
- 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_epochsorstay_prob.- **kwargskeyword arguments
Keyword arguments for
fit. All exceptepochsand the saving options (save_best_after,best_filepath,checkpoint_freqandcheckpoint_dir) are also passed toinitialization.
- 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
0for no progress bars,1for a progress bar for each epoch and2for 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.h5file). 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 totmp. Load withosl_dynamics.models.load(checkpoint_dir, from_checkpoint=True).- **schedule_kwargskeyword arguments, optional
Settings that override the config for this call:
kl_annealing(bool) andn_kl_annealing_epochs(int) for models with KL annealing, andgumbel_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, andkl_lossfor models with a KL loss),learning_rate, the other scheduled values (ema_decay,kl_factororgumbel_temperature, depending on the model) andskipped_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_epochsfor 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_epochsfor models with KL annealing.
- Returns:
- historydict
The training history of the best initialization.
- set_regularizers(training_data)#
Set regularizers for the means and covariances from the data.
A multivariate normal prior is applied to the means with
mu=0,sigma=diag((range/2)**2). Ifconfig.diagonal_covariances=True, a log-normal prior is applied to the diagonal of the covariances withmu=0,sigma=sqrt(log(2*range)), otherwise an inverse Wishart prior is applied to the covariances withnu=n_channels-1+0.1andpsi=diag(range).rangeis the range of each channel in the data. For models with session-specific parameters, these priors are on the group parameters, and the KL divergence of the deviation magnitudes and the regularization of the deviation decoders are divided by the number of sequences in the data (and the sequence length ifconfig.loss_reduction='mean').- Parameters:
- training_dataosl_dynamics.data.Data or tf.data.Dataset
Training data.
- 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
Truepredicts with sequences that overlap by 50% and keeps only the central half of each sequence.- verboseint, optional
Pass
0for 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
Truepredicts with sequences that overlap by 50% and keeps only the central half of each sequence.- verboseint, optional
Pass
0for 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.
thetais 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
0for 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.
thetais the posterior mean (no sampling).- Parameters:
- datasetosl_dynamics.data.Data or tf.data.Dataset
Data.
- verboseint, optional
Pass
0for no progress bar.
- Returns:
- nll_lossfloat
Negative log-likelihood loss.
- kl_lossfloat
KL divergence loss.
- get_amplitudes()#
Get the oscillator amplitudes.
- Returns:
- amplitudesnp.ndarray
Amplitude of each mode. Shape is (n_modes, 1).
- get_frequencies()#
Get the oscillator frequencies.
- Returns:
- frequenciesnp.ndarray
Frequency of each mode in Hz. Shape is (n_modes, 1).
- get_variances()#
Get the variances added to the diagonal of the covariances.
- Returns:
- variancesnp.ndarray
Variance of each mode. Shape is (n_modes, 1, 1).
- get_oscillator_parameters()#
Get the oscillator amplitudes, frequencies and variances.
- Returns:
- parametersdict
The arrays returned by
get_amplitudes,get_frequenciesandget_variances, with keys'amplitudes','frequencies'and'variances'.
- get_means()#
Get the means.
- Returns:
- meansnp.ndarray
Mean of each state or mode. Shape is (n_states, n_channels) or (n_modes, n_channels).
- get_covariances()#
Get the covariances.
- Returns:
- covariancesnp.ndarray
Covariance of each state or mode. Shape is (n_states, n_channels, n_channels) or (n_modes, n_channels, n_channels).
- get_observation_model_parameters()#
Get the means and covariances.
- Returns:
- meansnp.ndarray
Mean of each state or mode. Shape is (n_states, n_channels) or (n_modes, n_channels).
- covariancesnp.ndarray
Covariance of each state or mode. Shape is (n_states, n_channels, n_channels) or (n_modes, n_channels, n_channels).
- abstractmethod set_covariances(covariances, update_initializer=True)#
Not available: the covariances are calculated from the oscillator parameters.
- Parameters:
- covariancesnp.ndarray
Not used.
- update_initializerbool, optional
Not used.
- set_means(means, update_initializer=True)#
Set the means.
- Parameters:
- meansnp.ndarray
Mean of each state or mode. Shape is (n_states, n_channels) or (n_modes, n_channels).
- update_initializerbool, optional
Should we use this value when the model is reset?
- set_observation_model_parameters(parameters, update_initializer=True)#
Set the means and covariances.
- Parameters:
- parameterstuple
Means and covariances, as returned by
get_observation_model_parameters.- update_initializerbool, optional
Should we use these values when the model is reset?
- dual_estimation(training_data, n_epochs=None, learning_rate=None)#
Dual estimation of session-specific observation model parameters.
The means and covariances are trained on the data from each session with the inference and model networks held fixed.
- Parameters:
- training_dataosl_dynamics.data.Data or list of tf.data.Dataset
Training data.
- n_epochsint, optional
Number of epochs. Defaults to
config.n_epochs.- learning_ratefloat, optional
Learning rate. Defaults to
config.learning_rate.
- Returns:
- meansnp.ndarray
Session-specific means. Shape is (n_sessions, n_modes, n_channels).
- covariancesnp.ndarray
Session-specific covariances. Shape is (n_sessions, n_modes, n_channels, n_channels).
- fine_tuning(training_data, n_epochs=None, learning_rate=None)#
Fine tune the model for each session.
The inference network and observation model are trained on the data from each session with the model network held fixed.
- Parameters:
- training_dataosl_dynamics.data.Data
Training data.
- n_epochsint, optional
Number of epochs. Defaults to
config.n_epochs.- learning_ratefloat, optional
Learning rate. Defaults to
config.learning_rate.
- Returns:
- alphalist of np.ndarray
Session-specific mixing coefficients. Each element has shape (n_samples, n_modes).
- meansnp.ndarray
Session-specific means. Shape is (n_sessions, n_modes, n_channels).
- covariancesnp.ndarray
Session-specific covariances. Shape is (n_sessions, n_modes, n_channels, n_channels).
- sample_alpha(n_samples, theta=None)#
Sample mixing coefficients,
alpha, with the model network.- Parameters:
- n_samplesint
Number of samples to take.
- thetanp.ndarray, optional
Logits to start the sampling with. Shape must be (sequence_length, n_modes).
- Returns:
- alphanp.ndarray
Sampled alpha. Shape is (n_samples, n_modes).
- 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.ymland 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.ymlin.
- 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.h5file.
- load_weights(filepath)#
Load the weights of the Keras model.
- Parameters:
- filepathstr
Path to a
.weights.h5file.
- 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_covariancesor 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
strornp.ndarrayis first converted into a Data object. A dataset (e.g. fromosl_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?