osl_dynamics.models.hmm_poisson.Model#
- class osl_dynamics.models.hmm_poisson.Model(config)#
Bases:
osl_dynamics.models.base.markov.MarkovModelBaseHidden Markov Model with a Poisson observation model.
See
osl_dynamics.models.hmm_poissonfor a description of the model.- Parameters:
- configosl_dynamics.models.hmm_poisson.Config
Settings of the model.
Examples
Train the model and get the inferred parameters:
model = Model(config) model.train(data) gamma = model.get_gamma(data) rates = model.get_rates()
- 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.
- 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_batchesbatches. 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,
Nonefor 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_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.
- get_gamma(dataset, concatenate=False, remove_edge_effects=False, verbose=1)#
Marginal posterior of the states, \(\gamma_t = q(s_t)\).
- 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:
- gammalist or np.ndarray
State probabilities with shape (n_sessions, n_samples, n_states) or (n_samples, n_states).
- get_viterbi_path(dataset, concatenate=False)#
Most likely state sequence with the Viterbi algorithm.
- Parameters:
- datasetosl_dynamics.data.Data or tf.data.Dataset
Data.
- concatenatebool, optional
Should we concatenate the sessions?
- Returns:
- viterbi_pathlist or np.ndarray
One-hot state time course with shape (n_sessions, n_samples, n_states) or (n_samples, n_states).
- free_energy(dataset, concatenate=True)#
Variational free energy.
\[\mathcal{F} = \int q(s_{1:T}) \log \left[ \ \frac{q(s_{1:T})}{p(x_{1:T}, s_{1:T})} \right] \ ds_{1:T}\]- 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.
- Returns:
- free_energyfloat or np.ndarray
Free energy, or free energy of each session if
concatenate=False(shape (n_sessions,)).
- evidence(dataset)#
Model evidence, \(\log p(x)\), averaged over sequences.
- Parameters:
- datasetosl_dynamics.data.Data or tf.data.Dataset
Data.
- Returns:
- evidencefloat
Log-evidence. Divided by the sequence length if
config.loss_reduction='mean'.
- get_log_likelihood(x)#
Log-likelihood of each state.
- Parameters:
- xnp.ndarray
Data. Shape is (batch_size, sequence_length, n_channels).
- Returns:
- log_likelihoodnp.ndarray
Shape is (batch_size, sequence_length, n_states).
- get_log_rates()#
Get the log-rates.
- Returns:
- log_ratesnp.ndarray
Logarithm of the rate of each state and channel. Shape is (n_states, n_channels).
- get_rates()#
Get the rates.
- Returns:
- ratesnp.ndarray
Rate of each state and channel. Shape is (n_states, n_channels).
- get_observation_model_parameters()#
Get the log-rates.
- Returns:
- log_ratesnp.ndarray
Logarithm of the rate of each state and channel. Shape is (n_states, n_channels).
- get_trans_prob()#
Get the transition probability matrix.
- Returns:
- trans_probnp.ndarray
Element (i, j) is the probability of state j following state i. Shape is (n_states, n_states).
- get_initial_state_probs()#
Get the initial state probabilities.
- Returns:
- initial_state_probsnp.ndarray
Probability of each state at the start of a sequence. Shape is (n_states,).
- set_log_rates(log_rates, update_initializer=True)#
Set the log-rates.
- Parameters:
- log_ratesnp.ndarray
Log-rates. Shape is (n_states, n_channels).
- update_initializerbool, optional
Should we use this value when the model is reset?
- set_rates(rates, epsilon=1e-06, update_initializer=True)#
Set the rates.
- Parameters:
- ratesnp.ndarray
Rates. Shape is (n_states, n_channels).
- epsilonfloat, optional
Value added to the rates before taking the log.
- update_initializerbool, optional
Should we use this value when the model is reset?
- set_observation_model_parameters(log_rates, update_initializer=True)#
Set the log-rates.
- Parameters:
- log_ratesnp.ndarray
Log-rates. Shape is (n_states, n_channels).
- update_initializerbool, optional
Should we use this value when the model is reset?
- set_trans_prob(trans_prob, update_initializer=True)#
Set the transition probability matrix.
- Parameters:
- trans_probnp.ndarray
Transition probability matrix. Shape must be (n_states, n_states). Rows must sum to one.
- update_initializerbool, optional
Should we use this value when the model is reset?
- sample_state_time_course(n_samples)#
Sample a state time course from the transition probability matrix.
- Parameters:
- n_samplesint
Number of samples.
- Returns:
- state_time_coursenp.ndarray
One-hot state time course with shape (n_samples, n_states).
- 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?