leaspy.models.abstract_model module
- class AbstractModel(name: str, *, noise_model: str | BaseNoiseModel | Dict[str, Any], fit_metrics: Dict[str, float] | None = None, **kwargs)
Bases:
BaseModel
Contains the common attributes & methods of the different models.
- Parameters:
- name
str
The name of the model.
- noise_model
str
orBaseNoiseModel
The noise model for observations (keyword-only parameter).
- fit_metrics
dict
Metrics that should be measured during the fit of the model and reported back to the user.
- **kwargs
Hyperparameters for the model
- name
- Attributes:
- is_initialized
bool
Indicates if the model is initialized.
- name
str
The model’s name.
- features
list
ofstr
Names of the model features.
- parameters
dict
Contains the model’s parameters
- noise_model
BaseNoiseModel
The noise model associated to the model.
- regularization_distribution_factoryfunction dist params ->
torch.distributions.Distribution
Factory of torch distribution to compute log-likelihoods for regularization (gaussian by default) (Not used anymore)
- fit_metrics
dict
Contains the metrics that are measured during the fit of the model and reported to the user.
- is_initialized
Methods
Raise a
LeaspyModelInputError
is the provided noise model isn't compatible with the model instance.compute_canonical_loss_tensorized
(data, ...)Compute canonical loss, which depends on the noise model.
For one individual, compute age(s) at which the given features values are reached (given the subject's individual parameters).
compute_individual_ages_from_biomarker_values_tensorized
(...)For one individual, compute age(s) at which the given features values are reached (given the subject's individual parameters), with tensorized inputs.
Compute attachment term (per subject).
compute_individual_tensorized
(timepoints, ...)Compute the individual values at timepoints according to the model.
compute_individual_trajectory
(timepoints, ...)Compute scores values at the given time-point(s) given a subject's individual parameters.
compute_jacobian_tensorized
(timepoints, ...)Compute the jacobian of the model w.r.t.
compute_model_sufficient_statistics
(data, ...)Compute sufficient statistics from a
CollectionRealization
.Compute the regularity terms (and their gradients if requested), per individual variable of the model.
Compute regularity term for
IndividualRealization
.Compute regularity term for
PopulationRealization
.compute_regularity_realization
(realization)Compute regularity term for a
AbstractRealization
instance.compute_regularity_variable
(value, mean, std, *)Compute regularity term (Gaussian distribution) and optionally its gradient wrt value.
compute_sufficient_statistics
(data, realizations)Compute sufficient statistics from realizations.
Return the information on individual random variables relative to the model.
Get the names of the individual variables of the model.
Return the information on population random variables relative to the model.
Get the names of the population variables of the model.
initialize
(dataset[, method])Initialize the model given a
Dataset
and an initialization method.load_hyperparameters
(hyperparameters)Load model's hyperparameters.
load_parameters
(parameters)Instantiate or update the model's parameters.
move_to_device
(device)Move a model and its relevant attributes to the specified
torch.device
.save
(path, **kwargs)Save
Leaspy
object as json model parameter file.time_reparametrization
(timepoints, xi, tau)Tensorized time reparametrization formula.
to_dict
()Export model as a dictionary ready for export.
update_model_parameters_burn_in
(data, ...)Update model parameters (burn-in phase).
update_model_parameters_normal
(data, ...)Update model parameters (after burn-in phase).
update_parameters_burn_in
(data, ...)Update model parameters (burn-in phase).
update_parameters_normal
(data, ...)Update model parameters (after burn-in phase).
validate_compatibility_of_dataset
(dataset)Raise if the given
Dataset
is not compatible with the current model.- check_noise_model_compatibility(model: BaseNoiseModel) None
Raise a
LeaspyModelInputError
is the provided noise model isn’t compatible with the model instance.This needs to be implemented in subclasses.
- Parameters:
- model
BaseNoiseModel
The noise model with which to check compatibility.
- model
- compute_canonical_loss_tensorized(data: Dataset, param_ind: Dict[str, Tensor], *, attribute_type=None) Tensor
Compute canonical loss, which depends on the noise model.
- Parameters:
- Returns:
- loss
torch.Tensor
shape = * (depending on noise-model, always summed over individuals & visits)
- loss
- compute_individual_ages_from_biomarker_values(value: float | List[float], individual_parameters: Dict[str, Any], feature: str | None = None) Tensor
For one individual, compute age(s) at which the given features values are reached (given the subject’s individual parameters).
Consistency checks are done in the main API layer.
- Parameters:
- valuescalar or array_like[scalar] (
list
,tuple
,numpy.ndarray
) Contains the biomarker value(s) of the subject.
- individual_parameters
dict
Contains the individual parameters. Each individual parameter should be a scalar or array_like.
- feature
str
(or None) Name of the considered biomarker.
Note
Optional for
UnivariateModel
, compulsory forMultivariateModel
.
- valuescalar or array_like[scalar] (
- Returns:
torch.Tensor
Contains the subject’s ages computed at the given values(s). Shape of tensor is
(1, n_values)
.
- Raises:
LeaspyModelInputError
If computation is tried on more than 1 individual.
- abstract compute_individual_ages_from_biomarker_values_tensorized(value: Tensor, individual_parameters: Dict[str, Tensor], feature: str | None) Tensor
For one individual, compute age(s) at which the given features values are reached (given the subject’s individual parameters), with tensorized inputs.
- Parameters:
- value
torch.Tensor
of shape(1, n_values)
Contains the biomarker value(s) of the subject.
- individual_parametersDictParamsTorch
Contains the individual parameters. Each individual parameter should be a
torch.Tensor
.- feature
str
(or None) Name of the considered biomarker.
Note
Optional for
UnivariateModel
, compulsory forMultivariateModel
.
- value
- Returns:
torch.Tensor
Contains the subject’s ages computed at the given values(s). Shape of tensor is
(n_values, 1)
.
- compute_individual_attachment_tensorized(data: Dataset, param_ind: Dict[str, Tensor], *, attribute_type: str | None = None) Tensor
Compute attachment term (per subject).
- Parameters:
- Returns:
- attachment
torch.Tensor
Negative Log-likelihood, shape =
(n_subjects,)
.
- attachment
- abstract compute_individual_tensorized(timepoints: Tensor, individual_parameters: Dict[str, Tensor], *, attribute_type: str | None = None) Tensor
Compute the individual values at timepoints according to the model.
- Parameters:
- timepoints
torch.Tensor
Timepoints tensor of shape
(n_individuals, n_timepoints)
.- individual_parameters
dict
[ param_name:str
,torch.Tensor
] The tensors are of shape
(n_individuals, n_dims_param)
.- attribute_type
str
or None Flag to ask for MCMC attributes instead of model’s attributes.
- timepoints
- Returns:
torch.Tensor
of shape(n_individuals, n_timepoints, n_features)
- compute_individual_trajectory(timepoints, individual_parameters: Dict[str, Any], *, skip_ips_checks: bool = False) Tensor
Compute scores values at the given time-point(s) given a subject’s individual parameters.
- Parameters:
- timepointsscalar or array_like[scalar] (
list
,tuple
,numpy.ndarray
) Contains the age(s) of the subject.
- individual_parameters
dict
Contains the individual parameters. Each individual parameter should be a scalar or array_like.
- skip_ips_checks
bool
(default:False
) Flag to skip consistency/compatibility checks and tensorization of
individual_parameters
when it was done earlier (speed-up).
- timepointsscalar or array_like[scalar] (
- Returns:
torch.Tensor
Contains the subject’s scores computed at the given age(s) Shape of tensor is
(1, n_tpts, n_features)
.
- Raises:
LeaspyModelInputError
If computation is tried on more than 1 individual.
LeaspyIndividualParamsInputError
if invalid individual parameters.
- abstract compute_jacobian_tensorized(timepoints: Tensor, individual_parameters: Dict[str, Tensor], *, attribute_type: str | None = None) Dict[str, Tensor]
Compute the jacobian of the model w.r.t. each individual parameter.
This function aims to be used in
ScipyMinimize
to speed up optimization.Note
As most of numerical operations are repeated when computing model & jacobian, we should create a single method that is able to compute model & jacobian “together” (= efficiently) when requested with a flag for instance.
- Parameters:
- timepoints
torch.Tensor
of shape(n_individuals, n_timepoints)
- individual_parameters
dict
[ param_name:str
,torch.Tensor
] Tensors are of shape
(n_individuals, n_dims_param)
.- attribute_type
str
or None Flag to ask for MCMC attributes instead of model’s attributes.
- timepoints
- Returns:
dict
[ param_name:str
,torch.Tensor
]Tensors are of shape
(n_individuals, n_timepoints, n_features, n_dims_param)
.
- abstract compute_model_sufficient_statistics(data: Dataset, realizations: CollectionRealization) Dict[str, Tensor]
Compute sufficient statistics from a
CollectionRealization
.- Parameters:
- data
Dataset
- realizations
CollectionRealization
- data
- Returns:
dict
[ suff_stat:str
,torch.Tensor
]
- compute_regularity_individual_parameters(individual_parameters: Dict[str, Tensor], *, include_constant: bool = False) Tuple[Dict[str, Tensor], Dict[str, Tensor]]
Compute the regularity terms (and their gradients if requested), per individual variable of the model.
- Parameters:
- individual_parameters
dict
[str
,torch.Tensor
] Individual parameters as a dict of tensors of shape
(n_ind, n_dims_param)
.- include_constant
bool
, optional Whether to include a constant term or not. Default=False.
- individual_parameters
- Returns:
- regularity
dict
[ param_name:str
,torch.Tensor
] Regularity of the patient(s) corresponding to the given individual parameters. Tensors have shape
(n_individuals)
.- regularity_grads
dict
[ param_name:str
,torch.Tensor
] Gradient of regularity term with respect to individual parameters. Tensors have shape
(n_individuals, n_dims_param)
.
- regularity
- compute_regularity_individual_realization(realization: IndividualRealization) Tensor
Compute regularity term for
IndividualRealization
.- Parameters:
- realization
IndividualRealization
- realization
- Returns:
torch.Tensor
of the same shape asIndividualRealization.tensor
- compute_regularity_population_realization(realization: PopulationRealization) Tensor
Compute regularity term for
PopulationRealization
.- Parameters:
- realization
PopulationRealization
- realization
- Returns:
torch.Tensor
of the same shape asPopulationRealization.tensor
- compute_regularity_realization(realization: AbstractRealization) Tensor
Compute regularity term for a
AbstractRealization
instance.- Parameters:
- realization
AbstractRealization
- realization
- Returns:
torch.Tensor
of the same shape asAbstractRealization.tensor
- compute_regularity_variable(value: Tensor, mean: Tensor, std: Tensor, *, include_constant: bool = True, with_gradient: bool = False) Tensor | Tuple[Tensor, Tensor]
Compute regularity term (Gaussian distribution) and optionally its gradient wrt value.
Note
TODO: should be encapsulated in a
RandomVariableSpecification
class together with other specs of RV.- Parameters:
- value, mean, std
torch.Tensor
of same shapes - include_constant
bool
(defaultTrue
) Whether we include or not additional terms constant with respect to value.
- with_gradient
bool
(defaultFalse
) Whether we also return the gradient of regularity term with respect to value.
- value, mean, std
- Returns:
torch.Tensor
of same shape than input
- compute_sufficient_statistics(data: Dataset, realizations: CollectionRealization) Dict[str, Tensor]
Compute sufficient statistics from realizations.
- Parameters:
- data
Dataset
- realizations
CollectionRealization
- data
- Returns:
dict
[ suff_stat:str
,torch.Tensor
]
- property dimension: int | None
The dimension of the model. If the private attribute is defined, then it takes precedence over the feature length. The associated setters are responsible for their coherence.
- abstract get_individual_random_variable_information() Dict[str, Any]
Return the information on individual random variables relative to the model.
- Returns:
- DictParams
The information on the individual random variables.
- abstract get_population_random_variable_information() Dict[str, Any]
Return the information on population random variables relative to the model.
- Returns:
- DictParams
The information on the population random variables.
- initialize(dataset: Dataset, method: str = 'default') None
Initialize the model given a
Dataset
and an initialization method.After calling this method
is_initialized
should beTrue
and model should be ready for use.
- abstract load_hyperparameters(hyperparameters: Dict[str, Any]) None
Load model’s hyperparameters.
- Parameters:
- Raises:
LeaspyModelInputError
If any of the consistency checks fail.
- move_to_device(device: device) None
Move a model and its relevant attributes to the specified
torch.device
.- Parameters:
- device
torch.device
- device
- property noise_model: BaseNoiseModel
- save(path: str, **kwargs) None
Save
Leaspy
object as json model parameter file.TODO move logic upstream?
- Parameters:
- path
str
Path to store the model’s parameters.
- **kwargs
Keyword arguments for
AbstractModel.to_dict()
child method andjson.dump
function (default to indent=2).
- path
- static time_reparametrization(timepoints: Tensor, xi: Tensor, tau: Tensor) Tensor
Tensorized time reparametrization formula.
Warning
Shapes of tensors must be compatible between them.
- Parameters:
- timepoints
torch.Tensor
Timepoints to reparametrize.
- xi
torch.Tensor
Log-acceleration of individual(s).
- tau
torch.Tensor
Time-shift(s).
- timepoints
- Returns:
torch.Tensor
of same shape as timepoints
- abstract to_dict() Dict[str, Any]
Export model as a dictionary ready for export.
- Returns:
- KwargsType
The model instance serialized as a dictionary.
- abstract update_model_parameters_burn_in(data: Dataset, sufficient_statistics: Dict[str, Tensor]) None
Update model parameters (burn-in phase).
- Parameters:
- data
Dataset
- sufficient_statistics
dict
[ suff_stat:str
,torch.Tensor
]
- data
- abstract update_model_parameters_normal(data: Dataset, sufficient_statistics: Dict[str, Tensor]) None
Update model parameters (after burn-in phase).
- Parameters:
- data
Dataset
- sufficient_statistics
dict
[ suff_stat:str
,torch.Tensor
]
- data
- update_parameters_burn_in(data: Dataset, sufficient_statistics: Dict[str, Tensor]) None
Update model parameters (burn-in phase).
- Parameters:
- data
Dataset
- sufficient_statistics
dict
[ suff_stat:str
,torch.Tensor
]
- data
- update_parameters_normal(data: Dataset, sufficient_statistics: Dict[str, Tensor]) None
Update model parameters (after burn-in phase).
- Parameters:
- data
Dataset
- sufficient_statistics
dict
[ suff_stat:str
,torch.Tensor
]
- data