leaspy.models¶
Submodules¶
- leaspy.models.base
- leaspy.models.constant
- leaspy.models.factory
- leaspy.models.joint
- leaspy.models.linear
- leaspy.models.lme
- leaspy.models.logistic
- leaspy.models.mcmc_saem_compatible
- leaspy.models.mixture
- leaspy.models.obs_models
- leaspy.models.riemanian_manifold
- leaspy.models.settings
- leaspy.models.shared_speed_logistic
- leaspy.models.stateful
- leaspy.models.stateless
- leaspy.models.time_reparametrized
- leaspy.models.utilities
- leaspy.models.utils
Classes¶
Base model class from which all |
|
This is the public interface for Leaspy models. |
|
ConstantModel` is a benchmark model that predicts constant values (no matter what the patient's ages are). |
|
The available models that users can instantiate in Leaspy. |
|
Joint model for multiple repeated measures (logistic) and multiple competing events. |
|
Manifold model for multiple variables of interest (linear formulation). |
|
LMEModel is a benchmark model that fits and personalize a linear mixed-effects model. |
|
Manifold model for multiple variables of interest (logistic formulation). |
|
Defines probabilistic models compatible with an MCMC SAEM estimation. |
|
Manifold model for multiple variables of interest (logistic or linear formulation). |
|
Used in models.base.load to create a model class object from a json file. |
|
Logistic model for multiple variables of interest, imposing same average |
|
Stateful models have an internal |
|
Stateless model do not use an internal state to keep track of variables. |
|
Contains the common attributes & methods of the multivariate time-reparametrized models. |
|
Mixture Manifold model for multiple variables of interest (logistic formulation). |
Functions¶
|
Return the model object corresponding to |
Package Contents¶
- class BaseModel(name, **kwargs)[source]¶
Bases:
ModelInterfaceBase model class from which all
Leaspymodels should inherit.It implements the
ModelInterface.- Parameters:
name (str)
- dataset_info¶
- training_info¶
- initialization_method: InitializationMethod¶
- property features: list[FeatureType] | None¶
List of model features (None if not initialization).
- Returns:
- :
list[FeatureType], optional The features of the model, or None if not initialized.
- :
- Return type:
Optional[list[FeatureType]]
- initialize(dataset=None)[source]¶
Initialize the model given a
Datasetand an initialization method.After calling this method
is_initializedshould beTrueand model should be ready for use.
- save(path, **kwargs)[source]¶
Save model as json model parameter file.
- Parameters:
- Raises:
LeaspyModelInputErrorIf the model is not initialized.
- Parameters:
- Return type:
None
- to_dict(**kwargs)[source]¶
Export model as a dictionary ready for export.
- Returns:
KwargsTypeThe model instance serialized as a dictionary.
- Return type:
- classmethod load(path_to_model_settings)[source]¶
Load a model from a json model parameter file.
- Parameters:
- path_to_model_settings
strorPath The path to the model’s parameters file.
- path_to_model_settings
- Returns:
BaseModelAn instance of the model loaded from the file.
- Raises:
LeaspyModelInputErrorIf the model settings file is not found or cannot be read.
- Parameters:
- abstractmethod load_parameters(parameters)[source]¶
Load model parameters from a dictionary.
- Parameters:
- parameters
KwargsType The parameters to load into the model.
- parameters
- Raises:
- NotImplementedError
- Parameters:
parameters (KwargsType)
- Return type:
None
- fit(data=None, algorithm=None, algorithm_settings=None, algorithm_settings_path=None, **kwargs)[source]¶
Estimate the model’s parameters for a given dataset and a given algorithm. These model’s parameters correspond to the fixed-effects of the mixed-effects model.
- Parameters:
- data
pd.DataFrameorDataorDataset, optional Contains the information of the individuals, in particular the time-points \((t_{i,j})\) and the observations \((y_{i,j})\).
- algorithm
strorAlgorithmName, optional The name of the algorithm to use. Use this if you want to provide algorithm settings through kwargs.
- algorithm_settings
AlgorithmSettings, optional The algorithm settings to use. Use this if you want to customize algorithm settings through the
AlgorithmSettingsclass. If provided, the fit will rely on these settings.- algorithm_settings_path
strorPath, optional The path to the algorithm settings file. If provided, the settings from the file will be used instead of the settings provided.
- **kwargs
dict Contains the algorithm’s settings.
- data
- Parameters:
data (Optional[Union[DataFrame, leaspy.io.data.dataset.Data, Dataset]])
algorithm (Optional[Union[str, AlgorithmName]])
algorithm_settings (Optional[AlgorithmSettings])
- info()[source]¶
Print detailed information about the model configuration and training dataset.
- Return type:
None
- summary()[source]¶
Generate a structured summary of the model.
When called directly (e.g., model.summary()), prints a formatted summary. When stored in a variable, provides programmatic access to model attributes.
- Returns:
SummaryA structured summary object.
- Raises:
LeaspyModelInputErrorIf the model is not initialized or has no parameters.
- Return type:
Examples
>>> model.summary() # Prints the summary >>> s = model.summary() # Store to access attributes >>> s.nll # Get specific value >>> s.help() # Show available attributes
- personalize(data=None, algorithm=None, algorithm_settings=None, algorithm_settings_path=None, **kwargs)[source]¶
Estimate individual parameters for each ID of a given dataset. These individual parameters correspond to the random-effects \((z_{i,j})\) of the mixed-effects model.
- Parameters:
- data
pd.DataFrameorDataorDataset, optional Contains the information of the individuals, in particular the time-points \((t_{i,j})\) and the observations \((y_{i,j})\).
- algorithm
strorAlgorithmName, optional The name of the algorithm to use.
- algorithm_settings
AlgorithmSettings, optional The algorithm settings to use. Use this if you want to customize algorithm settings through the
AlgorithmSettingsclass. If provided, the fit will rely on these settings.- algorithm_settings_path
strorPath, optional The path to the algorithm settings file. If provided, the settings from the file will be used instead of the settings provided.
- **kwargs
dict Contains the algorithm’s settings.
- data
- Returns:
IndividualParametersIndividual parameters computed.
- Parameters:
data (Optional[Union[DataFrame, leaspy.io.data.dataset.Data, Dataset]])
algorithm (Optional[Union[str, AlgorithmName]])
algorithm_settings (Optional[AlgorithmSettings])
- Return type:
- estimate(timepoints, individual_parameters, *, to_dataframe=None)[source]¶
Return the model values for individuals characterized by their individual parameters \(z_i\) at time-points \((t_{i,j})_j\).
- Parameters:
- timepoints
pd.MultiIndexordict[IDType,list[float]] Contains, for each individual, the time-points to estimate. It can be a unique time-point or a list of time-points.
- individual_parameters
IndividualParameters Corresponds to the individual parameters of individuals.
- to_dataframe
bool, optional Whether to output a dataframe of estimations? If None: default is to be True if and only if timepoints is a pandas.MultiIndex
- timepoints
- Returns:
- individual_trajectory
pd.DataFrameordict[IDType,np.ndarray] Key: patient indices. Value:
numpy.ndarrayof the estimated value, in the shape (number of timepoints, number of features)
- individual_trajectory
- Parameters:
timepoints (Union[MultiIndex, dict[IDType, list[float]]])
individual_parameters (IndividualParameters)
to_dataframe (Optional[bool])
- Return type:
- abstractmethod compute_individual_trajectory(timepoints, individual_parameters)[source]¶
Compute the model values for an individual characterized by their individual parameters at given time-points. Parameters ———- timepoints :
list[float]The time-points at which to compute the model values.
- individual_parameters
IndividualParameters The individual parameters of the individual.
- Returns:
torch.TensorThe computed model values for the individual at the given time-points.
- Raises:
- NotImplementedError
If the method is not implemented in the subclass.
- Parameters:
individual_parameters (IndividualParameters)
- Return type:
- individual_parameters
- simulate(algorithm=None, algorithm_settings=None, algorithm_settings_path=None, **kwargs)[source]¶
Run the simulation pipeline using a leaspy model.
This method simulates longitudinal data using the given leaspy model. It performs the following steps: - Retrieves individual parameters (IP) from fixed effects of the model. - Loads the specified Leaspy model. - Generates visit ages (timepoints) for each individual (based on specifications in visits_type) - Simulates observations at those visit ages. - Packages the result into a Result object, including simulated data, individual parameters, and the model’s noise standard deviation.
- Parameters:
- algorithm
strorAlgorithmName, optional The name of the algorithm to use. Use this if you want to provide algorithm settings through kwargs.
- algorithm_settings
AlgorithmSettings, optional The algorithm settings to use. Use this if you want to customize algorithm settings through the
AlgorithmSettingsclass. If provided, the fit will rely on these settings.- algorithm_settings_path
strorPath, optional The path to the algorithm settings file. If provided, the settings from the file will be used instead of the settings provided.
- **kwargs
dict Contains the algorithm’s settings.
- algorithm
- Returns:
- simulated_data
Result Contains the generated individual parameters & the corresponding generated scores. Returns empty Result if any required input is None.
- simulated_data
- Parameters:
algorithm (Optional[Union[str, AlgorithmName]])
algorithm_settings (Optional[AlgorithmSettings])
Notes
To generate a new subject, first we estimate the joined distribution of the individual parameters and the reparametrized baseline ages. Then, we randomly pick a new point from this distribution, which define the individual parameters & baseline age of our new subjects. Then, we generate the timepoints following the baseline age. Then, from the model and the generated timepoints and individual parameters, we compute the corresponding values estimations. Then, we add some noise to these estimations, which is the same noise-model as the one from your model by default. But, you may customize it by setting the noise keyword.
Examples
Use a calibrated model & individual parameters to simulate new subjects similar to the ones you have:
>>> from leaspy.models import LogisticModel >>> from leaspy.io.data import Data >>> from leaspy.datasets import load_dataset, load_leaspy_instance, load_individual_parameters >>> putamen_df = load_dataset("parkinson-putamen-train_and_test") >>> data = Data.from_dataframe(putamen_df.xs('train', level='SPLIT')) >>> leaspy_logistic = load_leaspy_instance("parkinson-putamen-train") >>> visits_params = {'patient_number':200, 'visit_type': "random", 'first_visit_mean' : 0., 'first_visit_std' : 0.4, 'time_follow_up_mean' : 11, 'time_follow_up_std' : 0.5, 'distance_visit_mean' : 2/12, 'distance_visit_std' : 0.75/12, 'min_spacing_between_visits': 1/365 } >>> simulated_data = model.simulate( algorithm="simulate", features=["MDS1_total", "MDS2_total", "MDS3_off_total", 'SCOPA_total','MOCA_total','REM_total','PUTAMEN_R','PUTAMEN_L','CAUDATE_R','CAUDATE_L'],visit_parameters= visits_params )
- class ModelInterface[source]¶
Bases:
abc.ABCThis is the public interface for Leaspy models. It defines the methods and properties that all models should implement. It is not meant to be instantiated directly, but rather to be inherited by concrete model classes.
- property is_initialized: bool¶
- Abstractmethod:
- Return type:
True if the model is initialized, False otherwise.
- property features: list[FeatureType]¶
- Abstractmethod:
- Return type:
List of model features (None if not initialization).
- Raises:
- NotImplementedError
- Return type:
- property parameters: DictParamsTorch¶
- Abstractmethod:
- Return type:
Dictionary of values for model parameters.
- Returns:
- Raises:
- NotImplementedError
- Return type:
- property hyperparameters: DictParamsTorch¶
- Abstractmethod:
- Return type:
Dictionary of values for model hyperparameters.
- Returns:
- Raises:
- NotImplementedError
- Return type:
- abstractmethod fit(data=None, algorithm=None, algorithm_settings=None, algorithm_settings_path=None, **kwargs)[source]¶
Estimate the model’s parameters \(\theta\) for a given dataset and a given algorithm.
These model’s parameters correspond to the fixed-effects of the mixed-effects model.
There are three ways to provide parameters to the fitting algorithm:
By providing an instance of
AlgorithmSettingsBy providing a path to a serialized
AlgorithmSettingsBy providing the algorithm name and parameters directly
If settings are provided in multiple ways, the order above will prevail.
- Parameters:
- data
pd.DataFrameorDataorDataset, optional Contains the information of the individuals, in particular the time-points \((t_{i,j})\) and the observations \((y_{i,j})\).
- algorithm
strorAlgorithmName,optional The name of the algorithm to use.
Note
Use this if you want to provide algorithm settings through kwargs.
- algorithm_settings
AlgorithmSettings, optional The algorithm settings to use.
Note
Use this if you want to customize algorithm settings through the
AlgorithmSettingsclass. If provided, the fit will rely on these settings.- algorithm_settings_path
strorPath, optional The path to the algorithm settings file.
Note
If provided, the settings from the file will be used instead of the settings provided through kwarsg.
- **kwargs
dict Contains the algorithm’s settings.
- data
- Raises:
- NotImplementedError
- Parameters:
data (Optional[Union[DataFrame, leaspy.io.data.dataset.Data, Dataset]])
algorithm (Optional[Union[str, AlgorithmName]])
algorithm_settings (Optional[AlgorithmSettings])
Examples
Fit a logistic model on a longitudinal dataset, display the group parameters
>>> from leaspy.models import LogisticModel >>> from leaspy.datasets import load_dataset >>> putamen_df = load_dataset("parkinson-putamen") >>> model = LogisticModel(name="test-model-logistic") >>> model.fit(putamen_df, "mcmc_saem", seed=0, print_periodicity=50) >>> print(model) === MODEL === betas_mean : [] log_g_mean : [-0.8394] log_v0_mean : [-3.7930] noise_std : 0.021183 tau_mean : [64.6920] tau_std : [10.0864] xi_std : [0.5232]
- abstractmethod personalize(data=None, algorithm=None, algorithm_settings=None, algorithm_settings_path=None, **kwargs)[source]¶
Estimate individual parameters for each ID of a given dataset.
These individual parameters correspond to the random-effects \((z_{i,j})\) of the mixed-effects model.
- Parameters:
- data
pd.DataFrameorDataorDataset, optional Contains the information of the individuals, in particular the time-points \((t_{i,j})\) and the observations \((y_{i,j})\).
- algorithm
strorAlgorithmName, optional The name of the algorithm to use.
- algorithm_settings
AlgorithmSettings, optional The algorithm settings to use.
Note
Use this if you want to customize algorithm settings through the
AlgorithmSettingsclass. If provided, the fit will rely on these settings.- algorithm_settings_path
strorPath, optional The path to the algorithm settings file.
Note
If provided, the settings from the file will be used instead of the settings provided.
- **kwargs
dict Contains the algorithm’s settings.
- data
- Returns:
- ips
IndividualParameters Individual parameters computed.
- ips
- Raises:
- NotImplementedError
- Parameters:
data (Optional[Union[DataFrame, leaspy.io.data.dataset.Data, Dataset]])
algorithm (Optional[Union[str, AlgorithmName]])
algorithm_settings (Optional[AlgorithmSettings])
- Return type:
Examples
Compute the individual parameters for a given longitudinal dataset and calibrated model, then display the histogram of the log-acceleration:
>>> from leaspy.datasets import load_model, load_dataset >>> model = load_model("parkinson-putamen") >>> putamen_df = load_dataset("parkinson-putamen") >>> individual_parameters = model.personalize(putamen_df, "scipy_minimize", seed=0)
- abstractmethod estimate(timepoints, individual_parameters, *, to_dataframe=None)[source]¶
Return the model values for individuals characterized by their individual parameters \(z_i\) at time-points \((t_{i,j})_j\).
- Parameters:
- timepoints
pd.MultiIndexordict[IDType,list[float] ] Contains, for each individual, the time-points to estimate. It can be a unique time-point or a list of time-points.
- individual_parameters
IndividualParameters Corresponds to the individual parameters of individuals.
- to_dataframe
bool, optional Whether to output a dataframe of estimations? If None: default is to be True if and only if timepoints is a pandas.MultiIndex
- timepoints
- Returns:
- individual_trajectory
pd.MultiIndexordict[IDType,list[float]] Key: patient indices. Value:
numpy.ndarrayof the estimated value, in the shape (number of timepoints, number of features)
- individual_trajectory
- Raises:
- NotImplementedError
- Parameters:
timepoints (Union[MultiIndex, dict[IDType, list[float]]])
individual_parameters (IndividualParameters)
to_dataframe (Optional[bool])
- Return type:
Examples
Given the individual parameters of two subjects, estimate the features of the first at 70, 74 and 80 years old and at 71 and 72 years old for the second.
>>> from leaspy.datasets import load_model, load_individual_parameters, load_dataset >>> model = load_model("parkinson-putamen") >>> individual_parameters = load_individual_parameters("parkinson-putamen") >>> df_train = load_dataset("parkinson-putamen-train_and_test").xs("train", level="SPLIT") >>> timepoints = {'GS-001': (70, 74, 80), 'GS-002': (71, 72)} >>> estimations = model.estimate(timepoints, individual_parameters)
- abstractmethod simulate(individual_parameters, data=None, **kwargs)[source]¶
- Run the simulation pipeline using a leaspy model.
This method simulates longitudinal data using the given leaspy model. It performs the following steps: - Retrieves individual parameters (IP) from fixed effects of the model. - Loads the specified Leaspy model. - Generates visit ages (timepoints) for each individual (based on specifications
in visits_type).
Simulates observations at those visit ages.
Packages the result into a Result object, including simulated data, individual parameters, and the model’s noise standard deviation.
- Parameters:
- Returns:
- simulated_data
Result Contains the generated individual parameters & the corresponding generated scores. Returns empty Result if any required input is None.
- simulated_data
- Raises:
- NotImplementedError
- Parameters:
individual_parameters (IndividualParameters)
data (Optional[Union[DataFrame, leaspy.io.data.dataset.Data, Dataset]])
- class ConstantModel(name, **kwargs)[source]¶
Bases:
leaspy.models.stateless.StatelessModelConstantModel` is a benchmark model that predicts constant values (no matter what the patient’s ages are).
These constant values depend on the algorithm setting and the patient’s values provided during calibration.
- It could predict:
last: last value seen during calibration (even ifNaN).last_known: last nonNaNvalue seen during calibration.max: maximum (=worst) value seen during calibration.mean: average of values seen during calibration.
Warning
Depending on
features, thelast_known/maxvalue may correspond to different visits.Warning
For a given feature, value will be
NaNif and only if all values for this feature wereNaN.See also
- property hyperparameters: DictParamsTorch¶
Dictionary of values for model hyperparameters.
- Returns:
DictParamsTorchDictionary of hyperparameters.
- Return type:
- compute_individual_trajectory(timepoints, individual_parameters)[source]¶
Compute the individual trajectory based on the model’s features and parameters.
- Parameters:
- timepoints
torch.Tensor The time points at which to compute the trajectory.
- individual_parameters
dict Dictionary containing the individual’s parameters, where keys are feature names.
- timepoints
- Returns:
torch.TensorA tensor containing the computed trajectory for the individual.
- Raises:
LeaspyModelInputErrorIf the model was not properly initialized or if features are not set.
- Parameters:
- Return type:
- class ModelName[source]¶
-
The available models that users can instantiate in Leaspy.
- JOINT = 'joint'¶
- LOGISTIC = 'logistic'¶
- LINEAR = 'linear'¶
- SHARED_SPEED_LOGISTIC = 'shared_speed_logistic'¶
- LME = 'lme'¶
- CONSTANT = 'constant'¶
- MIXTURE_LOGISTIC = 'mixture_logistic'¶
- model_factory(name, instance_name=None, **kwargs)[source]¶
Return the model object corresponding to
namearg with possiblekwargs.- Parameters:
- name
stror ModelName - The name of the model class to be instantiated. Valid options include:
"joint""logistic""linear""shared_speed_logistic""lme""constant""mixture_logistic"
- instance_name
str, optional A custom name for the model instance. If not provided, the model’s name will be used as the instance name.
- **kwargs
Additional keyword arguments corresponding to the model’s hyperparameters. These must be valid for the specified model, or an error will be raised.
- name
- Returns:
BaseModelA child class object of
models.BaseModelclass object determined byname.
- Raises:
- ValueError
If an invalid model name is provided or the model cannot be instantiated with the provided arguments.
- Parameters:
- Return type:
- class JointModel(name, **kwargs)[source]¶
Bases:
leaspy.models.logistic.LogisticModelJoint model for multiple repeated measures (logistic) and multiple competing events. The model implemented is associated to this [publication](https://arxiv.org/abs/2501.08960) on arxiv.
- Parameters:
- name
str The name of the model.
- **kwargs
Hyperparameters of the model (including noise_model)
- name
- Raises:
LeaspyModelInputErrorIf name is not one of allowed sub-type: ‘univariate_linear’ or ‘univariate_logistic’
If hyperparameters are inconsistent
- Parameters:
name (str)
- get_variables_specs()[source]¶
Return the specifications of the variables (latent variables, derived variables, model ‘parameters’) that are part of the model.
- Returns:
- NamedVariables
The specifications of the model’s variables.
- Return type:
- to_dict(*, with_mixing_matrix=True)[source]¶
Export model as a dictionary ready for export. Add the number of events compare to the multivariate output
- put_individual_parameters(state, dataset)[source]¶
Initialise the individual parameters of the state thanks to the dataset.
- compute_individual_trajectory(timepoints, individual_parameters, *, skip_ips_checks=False)[source]¶
This method computes the individual trajectory of a patient for given timepoint(s) using his/her individual parameters (random effects). For the longitudinal sub-model:
Compute longitudinal values
- For the event sub-model:
only one event: return the survival rate corrected by the probability of the first time point of the prediction assuming that the patient was alive,
more than one event: return the Cumulative Incidence function corrected by the probability of the first time point of the prediction assuming that the patient was alive.
Nota: model uses its current internal state.
- 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_parameterswhen it was done earlier (speed-up).
- timepointsscalar or array_like[scalar] (
- Returns:
torch.TensorContains the subject’s scores computed at the given age(s) Shape of tensor is
(1, n_tpts, n_features).
- Raises:
LeaspyModelInputErrorIf computation is tried on more than 1 individual.
LeaspyIndividualParamsInputErrorif invalid individual parameters.
- Parameters:
individual_parameters (DictParams)
skip_ips_checks (bool)
- Return type:
- class LinearModel(name, **kwargs)[source]¶
Bases:
LinearInitializationMixin,leaspy.models.riemanian_manifold.RiemanianManifoldModelManifold model for multiple variables of interest (linear formulation).
- Parameters:
name (str)
- get_variables_specs()[source]¶
Return the specifications of the variables (latent variables, derived variables, model ‘parameters’) that are part of the model.
- Returns:
- :class:`~leaspy.variables.specs.NamedVariables
A dictionary-like object mapping variable names to their specifications.
- Return type:
- static metric(*, g)[source]¶
Compute the metric tensor for the model.
- Parameters:
- g
torch.Tensor Input tensor with values of the population parameter g for each feature.
- g
- Returns:
torch.TensorA tensor of ones with the same shape as g.
- Parameters:
g (Tensor)
- Return type:
- classmethod model_with_sources(*, rt, space_shifts, metric, v0, g)[source]¶
Return the model output when sources(spatial components) are present.
- Parameters:
- rt
torch.Tensor The reparametrized time.
- space_shifts
torch.Tensor The values of the space-shifts
- metricAny
The metric tensor used for computing the spatial/temporal influence.
- v0Any
The values of the population parameter v0 for each feature.
- gAny
The values of the population parameter g for each feature.
- rt
- Returns:
torch.TensorThe model output with contribution from sources.
- Parameters:
- Return type:
- class LMEModel(name, with_random_slope_age=True, **kwargs)[source]¶
Bases:
leaspy.models.stateless.StatelessModelLMEModel is a benchmark model that fits and personalize a linear mixed-effects model.
The model specification is the following:
\[y_{ij} = fixed_{intercept} + random_{intercept_i} + (fixed_{slopeAge} + random_{slopeAge_i}) * age_{ij} + \epsilon_{ij}\]- with:
\(y_{ij}\): value of the feature of the i-th subject at his j-th visit,
\(age_{ij}\): age of the i-th subject at his j-th visit.
\(\epsilon_{ij}\): residual Gaussian noise (independent between visits)
Warning
This model must be fitted on one feature only (univariate model).
TODO? add some covariates in this very simple model.
- Parameters:
- Attributes:
- name
str The model’s name.
- is_initialized
bool Trueif the model is initialized,Falseotherwise.- with_random_slope_age
bool(defaultTrue) Has the LME a random slope for subject’s age? Otherwise it only has a random intercept per subject.
- features
listofstr List of the model features.
Warning
LME has only one feature.
- dimension
int Will always be 1 (univariate).
- parameters
dict - Contains the model parameters. In particular:
ages_meanfloatMean of ages (for normalization).
ages_stdfloatStd-dev of ages (for normalization).
fe_paramsnp.ndarrayoffloatFixed effects.
cov_renp.ndarrayVariance-covariance matrix of random-effects.
cov_re_unscaled_invnp.ndarrayInverse of unscaled (= divided by variance of noise) variance-covariance matrix of random-effects. This matrix is used for personalization to new subjects.
noise_stdfloatStd-dev of Gaussian noise.
bse_fe,bse_renp.ndarrayoffloatStandard errors on fixed-effects and random-effects respectively (not used in
Leaspy).
- name
- Parameters:
See also
LMEFitAlgorithmLMEPersonalizeAlgorithm
- with_random_slope_age = True¶
- dimension = 1¶
Number of features.
- Returns:
int, optionalThe dimension of the model, or None if not initialized.
- property hyperparameters: DictParamsTorch¶
Dictionary of values for model hyperparameters.
- Return type:
- compute_individual_trajectory(timepoints, individual_parameters)[source]¶
Compute scores values at the given time-point(s) given a subject’s individual parameters.
- Parameters:
- timepointsarray-like of ages (not normalized)
Timepoints to compute individual trajectory at.
- individual_parameters
dict - Individual parameters:
random_intercept
random_slope_age (if
with_random_slope_age == True)
- Returns:
torch.TensoroffloatThe individual trajectories. The shape of the tensor is
(n_individuals == 1, n_tpts == len(timepoints), n_features == 1).
- Parameters:
individual_parameters (IndividualParameters)
- Return type:
- class LogisticModel(name, **kwargs)[source]¶
Bases:
LogisticInitializationMixin,leaspy.models.riemanian_manifold.RiemanianManifoldModelManifold model for multiple variables of interest (logistic formulation).
- Parameters:
name (str)
- get_variables_specs()[source]¶
Return the specifications of the variables (latent variables, derived variables, model ‘parameters’) that are part of the model.
- Returns:
- NamedVariables
A dictionary-like object mapping variable names to their specifications.
- Return type:
- static metric(*, g)[source]¶
Compute the metric tensor from input tensor g. This function calculates the metric as ((g + 1)^2 / g) element-wise.
- Parameters:
- gt
torch.Tensor Input tensor with values of the population parameter g for each feature.
- gt
- Returns:
torch.TensorThe computed metric tensor, same shape as g(number of features)
- Parameters:
g (Tensor)
- Return type:
- classmethod model_with_sources(*, rt, space_shifts, metric, v0, g)[source]¶
Return the model output when sources(spatial components) are present.
- Parameters:
- rtTensorOrWeightedTensor[float]
Tensor containing the reparametrized time.
- space_shiftsTensorOrWeightedTensor[float]
Tensor containing the values of the space-shifts
- metricTensorOrWeightedTensor[float]
Tensor containing the metric tensor used for computing the spatial/temporal influence.
- v0TensorOrWeightedTensor[float]
Tensor containing the values of the population parameter v0 for each feature.
- gTensorOrWeightedTensor[float]
Tensor containing the values of the population parameter g for each feature.
- Returns:
torch.TensorWeighted value tensor after applying sigmoid transformation, representing the model output with sources.
- Parameters:
rt (TensorOrWeightedTensor[float])
space_shifts (TensorOrWeightedTensor[float])
metric (TensorOrWeightedTensor[float])
v0 (TensorOrWeightedTensor[float])
- Return type:
- class McmcSaemCompatibleModel(name, *, obs_models, fit_metrics=None, **kwargs)[source]¶
Bases:
leaspy.models.stateful.StatefulModelDefines probabilistic models compatible with an MCMC SAEM estimation.
- Parameters:
- name
str The name of the model.
- obs_models
obs_modelsorIterable[obs_models] 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[str] Names of the model features.
- parameters
dict Contains the model’s parameters
- obs_models
tuple[obs_models, …] The observation model(s) associated to the model.
- fit_metrics
dict Contains the metrics that are measured during the fit of the model and reported to the user.
- _state
State Private instance holding all values for model variables and their derived variables.
- is_initialized
- Parameters:
name (str)
obs_models (Union[ObservationModel, Iterable[ObservationModel]])
- obs_models¶
- fit_metrics = None¶
- has_observation_model_with_name(name)[source]¶
Check if the model has an observation model with the given name. Parameters ———- name :
strThe name of the observation model to check.
- to_dict(**kwargs)[source]¶
Export model as a dictionary ready for export.
- Returns:
KwargsTypeThe model instance serialized as a dictionary.
- Return type:
- compute_individual_trajectory(timepoints, individual_parameters, *, skip_ips_checks=False)[source]¶
Compute scores values at the given time-point(s) given a subject’s individual parameters.
Note
The model uses its current internal state.
- Parameters:
- timepoints
scalarorarray_like[scalar] (list,tuple,numpy.ndarray) Contains the age(s) of the subject.
- individual_parameters
DictParams 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_parameterswhen it was done earlier (speed-up).
- timepoints
- Returns:
torch.TensorContains the subject’s scores computed at the given age(s) Shape of tensor is
(1, n_tpts, n_features).
- Parameters:
individual_parameters (DictParams)
skip_ips_checks (bool)
- Return type:
- compute_prior_trajectory(timepoints, prior_type, *, n_individuals=None)[source]¶
Compute trajectory of the model for prior mode or mean of individual parameters.
- Parameters:
- timepoints
torch.Tensor[1, n_timepoints] Contains the timepoints (age(s) of the subject).
- prior_type
LatentVariableInitType The type of prior to use for the individual parameters.
- n_individuals
int, optional The number of individuals.
- timepoints
- Returns:
torch.Tensor[1, n_timepoints, dimension]The group-average values at given timepoints.
- Raises:
LeaspyModelInputErrorIf n_individuals is provided but not a positive integer, or if it is provided while prior_type is not LatentVariableInitType.PRIOR_SAMPLES.
- Parameters:
timepoints (Tensor)
prior_type (LatentVariableInitType)
n_individuals (Optional[int])
- Return type:
- compute_mean_traj(timepoints)[source]¶
Trajectory for average of individual parameters (not really meaningful for non-linear models).
- Parameters:
- timepoints
torch.Tensor[1, n_timepoints]
- timepoints
- Returns:
torch.Tensor[1, n_timepoints, dimension]The group-average values at given timepoints.
- Parameters:
timepoints (Tensor)
- Return type:
- compute_mode_traj(timepoints)[source]¶
Most typical individual trajectory.
- Parameters:
- timepoints
torch.Tensor[1, n_timepoints]
- timepoints
- Returns:
torch.Tensor[1, n_timepoints, dimension]The group-average values at given timepoints.
- Parameters:
timepoints (Tensor)
- Return type:
- abstractmethod compute_jacobian_tensorized(state)[source]¶
Compute the jacobian of the model w.r.t. each individual parameter, given the input state.
This function aims to be used in
ScipyMinimizeto speed up optimization.- Parameters:
- state
State Instance holding values for all model variables (including latent individual variables)
- state
- Returns:
DictParamsTorchTensors are of shape
(n_individuals, n_timepoints, n_features, n_dims_param).
- Raises:
- Parameters:
state (State)
- Return type:
- classmethod compute_sufficient_statistics(state)[source]¶
Compute sufficient statistics from state.
- Parameters:
- state
State
- state
- Returns:
SuffStatsRWContains the sufficient statistics computed from the state.
- Parameters:
state (State)
- Return type:
- classmethod update_parameters(state, sufficient_statistics, *, burn_in)[source]¶
Update model parameters of the provided state.
- Parameters:
- cls
McmcSaemCompatibleModel Model class to which the parameters belong.
- state
State Instance holding values for all model variables (including latent individual variables)
- sufficient_statistics
SuffStatsRO Contains the sufficient statistics computed from the state.
- burn_in
bool If True, the parameters are updated in a burn-in phase.
- cls
- Parameters:
state (State)
sufficient_statistics (SuffStatsRO)
burn_in (bool)
- Return type:
None
- get_variables_specs()[source]¶
Get the specifications of the variables used in the model.
- Returns:
NamedVariablesSpecifications of the variables used in the model, including timepoints and observation models.
- Return type:
- abstractmethod put_individual_parameters(state, dataset)[source]¶
Put the individual parameters inside the provided state (in-place).
- Raises:
- Parameters:
- put_data_variables(state, dataset)[source]¶
Put all the needed data variables inside the provided state (in-place).
- Parameters:
- state
State Instance holding values for all model variables (including latent individual variables), as well as: - timepoints :
torch.Tensorof shape (n_individuals, n_timepoints)- dataset
Dataset The dataset containing the data to be put in the state.
- state
- Parameters:
- Return type:
None
- reset_data_variables(state)[source]¶
Reset all data variables inside the provided state (in-place).
- Parameters:
- state
State Instance holding values for all model variables (including latent individual variables), as well as: - timepoints :
torch.Tensorof shape (n_individuals, n_timepoints)
- state
- Parameters:
state (State)
- Return type:
None
- class RiemanianManifoldModel(name, variables_to_track=None, **kwargs)[source]¶
Bases:
leaspy.models.time_reparametrized.TimeReparametrizedModelManifold model for multiple variables of interest (logistic or linear formulation).
- Parameters:
- name
str The name of the model.
- **kwargs
Hyperparameters of the model (including noise_model)
- name
- Raises:
LeaspyModelInputErrorIf hyperparameters are inconsistent
- Parameters:
name (str)
variables_to_track (Optional[Iterable[VariableName]])
- classmethod compute_sufficient_statistics(state)[source]¶
Compute the model’s sufficient statistics.
- get_variables_specs()[source]¶
Return the specifications of the variables (latent variables, derived variables, model ‘parameters’) that are part of the model.
- Returns:
- NamedVariables
A dictionary-like object mapping variable names to their specifications. These include ModelParameter, Hyperparameter, PopulationLatentVariable, and LinkedVariable instances.
- Return type:
- classmethod model_no_sources(*, rt, metric, v0, g)[source]¶
Return the model output when sources(spatial components) are not present.
- Parameters:
- rt
torch.Tensor The reparametrized time.
- metricAny
The metric tensor used for computing the spatial/temporal influence.
- v0Any
The values of the population parameter v0 for each feature.
- gAny
The values of the population parameter g for each feature.
- rt
- Returns:
torch.TensorThe model output without contribution from source shifts.
- Parameters:
rt (Tensor)
- Return type:
Notes
This implementation delegates to model_with_sources with space_shifts set to a zero tensor of shape (1, 1), effectively removing source effects.
- class ModelSettings(path_to_model_settings_or_dict)[source]¶
Used in models.base.load to create a model class object from a json file.
- Parameters:
- Attributes:
- name
str The model’s name.
- parameters
KwargsType The model’s parameters.
- hyperparameters
KwargsType The model’s hyperparameters.
- name
- Raises:
LeaspyModelInputErrorIf the provided settings are not valid or if the file cannot be read.
- Parameters:
- parameters: KwargsType¶
- hyperparameters: KwargsType¶
Bases:
leaspy.models.logistic.LogisticInitializationMixin,leaspy.models.time_reparametrized.TimeReparametrizedModelLogistic model for multiple variables of interest, imposing same average evolution pace for all variables (logistic curves are only time-shifted).
- Parameters:
- name
str The name of the model.
- **kwargs
Hyperparameters of the model.
- name
- Parameters:
name (str)
Compute the metric term for the logistic model.
This scaling term modulates the curvature of the logistic trajectory.
- Parameters:
- g_deltas_exp
torch.Tensor Product of slope and exp(-deltas).
- g_deltas_exp
- Returns:
torch.Tensor- Metric value, computed as:
- \[\frac{(g \cdot e^{-\delta} + 1)^2}{g \cdot e^{-\delta}}\]
- Parameters:
g_deltas_exp (Tensor)
- Return type:
Compute the exponential of the negative deltas.
- Parameters:
deltas_padded (
torch.Tensor): Padded deltas.- Returns:
torch.Tensor: Exponential of the negative deltas.
Prepend deltas with a zero as delta_1 is set to zero in the equations. .
- Parameters:
deltas (
torch.Tensor): Deltas tensor.- Returns:
torch.Tensor: Padded deltas tensor.
Compute the denominator for the \(\gamma_{t_0}\) calculation.
Compute the \(\gamma_{t_0}\) value, which is the inverse of the denominator.
- Parameters:
- denom
torch.Tensor Denominator term.
- denom
- Returns:
torch.Tensor\(\gamma_{t_0}\) value.
- Parameters:
denom (Tensor)
- Return type:
Compute the g_metric value, which is the square of gamma_t0.
- Parameters:
- gamma_t0
torch.Tensor \(\gamma_{t_0}\) value.
- gamma_t0
- Returns:
torch.Tensor- \(g_{metric}\) value, computed as:
- \[g\_metric = \frac{1}{(\gamma_{t0} \cdot (1 - \gamma_{t0}))^2}\]
- Parameters:
gamma_t0 (Tensor)
- Return type:
Compute the collinear term to d_gamma_t0.
- Parameters:
- deltas_exp
torch.Tensor Exponential of the negative deltas.
- denom
torch.Tensor Denominator term.
- deltas_exp
- Returns:
torch.TensorCollinear term to d_gamma_t0
- Parameters:
- Return type:
Returns a model with sources.
- Parameters:
rt (TensorOrWeightedTensor[float])
space_shifts (TensorOrWeightedTensor[float])
metric (TensorOrWeightedTensor[float])
deltas_padded (TensorOrWeightedTensor[float])
log_g (TensorOrWeightedTensor[float])
- Return type:
Returns a model without sources.
- Parameters:
rt (TensorOrWeightedTensor[float])
metric (TensorOrWeightedTensor[float])
deltas_padded (TensorOrWeightedTensor[float])
log_g (TensorOrWeightedTensor[float])
- Return type:
Get the specifications of the variables used in the model.
- Return type:
- class StatefulModel(name, **kwargs)[source]¶
Bases:
leaspy.models.base.BaseModelStateful models have an internal
Stateto handle parameters and variables.- Parameters:
- name
str The name of the model.
- name
- Attributes:
- state
State The internal state of the model, which contains the variables and their values.
- tracked_variables
set[str] Set of variable names that are tracked by the model. These variables are not necessarily part of the model’s state but are monitored for changes or updates. This can include variables that are relevant for the model’s operation but not directly stored in the state.
- state
- Parameters:
name (str)
- track_variable(variable)[source]¶
Track a variable by its name.
Parameters¶
- variable
VariableName The name of the variable to track. This variable will be monitored for changes or updates.
- Parameters:
variable (VariableName)
- Return type:
None
- variable
- track_variables(variables)[source]¶
Track multiple variables by their names.
- Parameters:
- variables
Iterable[VariableName] An iterable containing the names of the variables to track. Each variable will be monitored for changes or updates.
- variables
- Parameters:
variables (Iterable[VariableName])
- Return type:
None
- untrack_variable(variable)[source]¶
Untrack a variable by its name.
Parameters¶
- variable
VariableName The name of the variable to untrack. This variable will no longer be monitored for changes or updates.
- Parameters:
variable (VariableName)
- Return type:
None
- variable
- untrack_variables(variables)[source]¶
Untrack multiple variables by their names.
- Parameters:
- variables
Iterable[VariableName] An iterable containing the names of the variables to untrack. Each variable will no longer be monitored for changes or updates.
- variables
- Parameters:
variables (Iterable[VariableName])
- Return type:
None
- property state: State¶
Get the internal state of the model.
- Returns:
- State
State The internal state of the model, which contains the variables and their values.
- State
- Raises:
LeaspyModelInputErrorIf the model’s state is not initialized yet.
- Return type:
- property dag: VariablesDAG¶
Get the underlying DAG of the model’s state.
- Returns:
- :
VariablesDAG The directed acyclic graph (DAG) representing the model’s variables and their relationships
- :
- Return type:
- property hyperparameters_names: tuple[VariableName, Ellipsis]¶
Get the names of the model’s hyperparameters.
- Returns:
- :
tuple[VariableName, others…] A tuple containing the names of the model’s hyperparameters.
- :
- Return type:
tuple[VariableName, Ellipsis]
- property parameters_names: tuple[VariableName, Ellipsis]¶
Get the names of the model’s parameters.
- Returns:
- :
tuple[VariableName, others…] A tuple containing the names of the model’s parameters.
- :
- Return type:
tuple[VariableName, Ellipsis]
- property population_variables_names: tuple[VariableName, Ellipsis]¶
Get the names of the population latent variables.
- Returns:
- :
tuple[VariableName, …] A tuple containing the names of the population latent variables.
- :
- Return type:
tuple[VariableName, Ellipsis]
- property individual_variables_names: tuple[VariableName, Ellipsis]¶
Get the names of the individual latent variables.
- Returns:
- :
tuple[VariableName, …] A tuple containing the names of the individual latent variables.
- :
- Return type:
tuple[VariableName, Ellipsis]
- property parameters: DictParamsTorch¶
Dictionary of values for model parameters.
- Returns:
- :
DictParamsTorch A dictionary mapping parameter names to their values (as tensors).
- :
- Return type:
- property hyperparameters: DictParamsTorch¶
Dictionary of values for model hyperparameters.
- Returns:
- :
DictParamsTorch A dictionary mapping hyperparameter names to their values (as tensors).
- :
- Return type:
- initialize(dataset=None)[source]¶
Overloads base model initialization (in particular to handle internal model State).
<!> We do not put data variables in internal model state at this stage (done in algorithm)
- load_parameters(parameters)[source]¶
Instantiate or update the model’s parameters.
It assumes that all model hyperparameters are defined.
- Parameters:
- parameters
KwargsType] Contains the model’s parameters.
- parameters
- Parameters:
parameters (KwargsType)
- Return type:
None
- abstractmethod get_variables_specs()[source]¶
Return the specifications of the variables (latent variables, derived variables, model ‘parameters’) that are part of the model.
- Returns:
- NamedVariables
NamedVariables The specifications of the model’s variables.
- NamedVariables
- Return type:
- move_to_device(device)[source]¶
Move a model and its relevant attributes to the specified
torch.device.- Parameters:
- device
torch.device The device to which the model and its attributes should be moved.
- device
- Parameters:
device (device)
- Return type:
None
- class StatelessModel(name, **kwargs)[source]¶
Bases:
leaspy.models.base.BaseModelStateless model do not use an internal state to keep track of variables.
Parameters are stored in an internal dictionary.
- property parameters¶
Dictionary of values for model parameters.
- Returns:
- Raises:
- NotImplementedError
- load_parameters(parameters)[source]¶
Instantiate or update the model’s parameters.
- Parameters:
- parameters
dict Contains the model’s parameters.
- parameters
- Parameters:
parameters (KwargsType)
- Return type:
None
- class TimeReparametrizedModel(name, source_dimension=None, **kwargs)[source]¶
Bases:
leaspy.models.mcmc_saem_compatible.McmcSaemCompatibleModelContains the common attributes & methods of the multivariate time-reparametrized models.
- Parameters:
- Raises:
LeaspyModelInputErrorIf inconsistent hyperparameters.
- Parameters:
- static time_reparametrization(*, t, alpha, tau)[source]¶
Tensorized time reparametrization formula.
Warning
Shapes of tensors must be compatible between them.
- Parameters:
- t
torch.Tensor Timepoints to reparametrize
- alpha
torch.Tensor Acceleration factors of individual(s)
- tau
torch.Tensor Time-shift(s) of individual(s)
- t
- Returns:
torch.TensorReparametrized time of same shape as timepoints
- Parameters:
- Return type:
- get_variables_specs()[source]¶
Return the specifications of the variables (latent variables, derived variables, model ‘parameters’) that are part of the model.
- Returns:
- NamedVariables
A dictionary-like object containing specifications for the variables
- Return type:
- put_individual_parameters(state, dataset)[source]¶
Initialize individual latent parameters in the given state if not already set.
- to_dict(*, with_mixing_matrix=True)[source]¶
Export model object as dictionary ready for JSON saving.
- Parameters:
- with_mixing_matrix
bool(defaultTrue) Save the mixing matrix in the exported file in its ‘parameters’ section.
Warning
It is not a real parameter and its value will be overwritten at model loading (orthonormal basis is recomputed from other “true” parameters and mixing matrix is then deduced from this orthonormal basis and the betas)! It was integrated historically because it is used for convenience in browser webtool and only there…
- with_mixing_matrix
- Returns:
- KwargsType
The object as a dictionary.
- Parameters:
with_mixing_matrix (bool)
- Return type:
- abstractmethod compute_individual_ages_from_biomarker_values(value, individual_parameters, feature=None)[source]¶
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.TensorContains the subject’s ages computed at the given values(s). Shape of tensor is
(1, n_values).
- Raises:
LeaspyModelInputErrorIf computation is tried on more than 1 individual.
- Parameters:
individual_parameters (DictParams)
feature (Optional[FeatureType])
- Return type:
- abstractmethod compute_individual_ages_from_biomarker_values_tensorized(value, individual_parameters, feature)[source]¶
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.Tensorof 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.TensorContains the subject’s ages computed at the given values(s). Shape of tensor is
(n_values, 1).
- Parameters:
value (Tensor)
individual_parameters (DictParamsTorch)
feature (Optional[FeatureType])
- Return type:
- class LogisticMultivariateMixtureModel(name, **kwargs)[source]¶
Bases:
LogisticMixtureInitializationMixin,RiemanianManifoldMixtureModelMixture Manifold model for multiple variables of interest (logistic formulation).
- Parameters:
name (str)
- get_variables_specs()[source]¶
Return the specifications of the variables (latent variables, derived variables, model ‘parameters’) that are part of the model.
- Returns:
NamedVariablesA dictionary-like object mapping variable names to their specifications. These include ModelParameter, Hyperparameter, PopulationLatentVariable, and LinkedVariable instances.
- Return type:
- static metric(*, g)[source]¶
Compute the metric tensor from input tensor g. This function calculates the metric as ((g + 1)^2 / g) element-wise.
- Parameters:
- gt
torch.Tensor Input tensor with values of the population parameter g for each feature.
- gt
- Returns:
torch.TensorThe computed metric tensor, same shape as g(number of features)
- Parameters:
g (Tensor)
- Return type:
- classmethod model_with_sources(*, rt, space_shifts, metric, v0, g)[source]¶
Return the model output when sources(spatial components) are present.
- Parameters:
- rt
TensorOrWeightedTensor`[:obj:`float] Tensor containing the reparametrized time.
- space_shifts~leaspy.uitls.weighted_tensor._weighted_tensor.TensorOrWeightedTensor`[:obj:`float]
Tensor containing the values of the space-shifts
- metric :`~leaspy.uitls.weighted_tensor._weighted_tensor.TensorOrWeightedTensor`[:obj:`float`]
Tensor containing the metric tensor used for computing the spatial/temporal influence.
- v0~leaspy.uitls.weighted_tensor._weighted_tensor.TensorOrWeightedTensor`[:obj:`float]
Tensor containing the values of the population parameter v0 for each feature.
- g~leaspy.uitls.weighted_tensor._weighted_tensor.TensorOrWeightedTensor`[:obj:`float]
Tensor containing the values of the population parameter g for each feature.
- rt
- Returns:
torch.TensorWeighted value tensor after applying sigmoid transformation, representing the model output with sources.
- Parameters:
rt (TensorOrWeightedTensor[float])
space_shifts (TensorOrWeightedTensor[float])
metric (TensorOrWeightedTensor[float])
v0 (TensorOrWeightedTensor[float])
- Return type: