aepsych.models¶
Submodules¶
aepsych.models.base module¶
- class aepsych.models.base.ModelProtocol(*args, **kwargs)[source]¶
Bases:
Protocol
- property outcome_type: str¶
- property extremum_solver: str¶
- property train_inputs: Tensor¶
- property lb: Tensor¶
- property ub: Tensor¶
- property bounds: Tensor¶
- property dim: int¶
- property device: device¶
- property stimuli_per_trial: int¶
- property likelihood: Likelihood¶
- fit(train_x, train_y, **kwargs)[source]¶
- Parameters:
train_x (Tensor) –
train_y (Tensor) –
kwargs (Any) –
- Return type:
None
- class aepsych.models.base.AEPsychMixin(*args, **kwargs)[source]¶
Bases:
GPyTorchModel
Mixin class that provides AEPsych-specific utility methods.
- Parameters:
args (Any) –
kwargs (Any) –
- Return type:
Any
- extremum_solver = 'Nelder-Mead'¶
- outcome_types: List[str] = []¶
- train_inputs: Optional[Tuple[Tensor]]¶
- train_targets: Optional[Tensor]¶
- property bounds: Tensor¶
- get_max(locked_dims=None, probability_space=False, n_samples=1000, max_time=None)[source]¶
Return the maximum of the modeled function, subject to constraints
- Parameters:
locked_dims (Mapping[int, List[float]], optional) – Dimensions to fix, so that the inverse is along a slice of the full surface. Defaults to None.
probability_space (bool) – Is y (and therefore the returned nearest_y) in probability space instead of latent function space? Defaults to False.
n_samples (int) – number of coarse grid points to sample for optimization estimate.
max_time (float, optional) – Maximum time to spend optimizing. Defaults to None.
self (ModelProtocol) –
- Returns:
Tuple containing the max and its location (argmax).
- Return type:
Tuple[float, torch.Tensor]
- get_min(locked_dims=None, probability_space=False, n_samples=1000, max_time=None)[source]¶
Return the minimum of the modeled function, subject to constraints :param locked_dims: Dimensions to fix, so that the
inverse is along a slice of the full surface.
- Parameters:
probability_space (bool) – Is y (and therefore the returned nearest_y) in probability space instead of latent function space? Defaults to False.
n_samples (int) – number of coarse grid points to sample for optimization estimate.
max_time (float, optional) – Maximum time to spend optimizing. Defaults to None.
self (ModelProtocol) –
locked_dims (Mapping[int, List[float]], optional) –
- Returns:
Tuple containing the min and its location (argmin).
- Return type:
Tuple[float, torch.Tensor]
- inv_query(y, locked_dims=None, probability_space=False, n_samples=1000, max_time=None, weights=None)[source]¶
Query the model inverse. Return nearest x such that f(x) = queried y, and also return the
value of f at that point.
- Parameters:
y (float) – Points at which to find the inverse.
locked_dims (Mapping[int, List[float]], optional) – Dimensions to fix, so that the inverse is along a slice of the full surface.
probability_space (bool) – Is y (and therefore the returned nearest_y) in probability space instead of latent function space? Defaults to False.
n_samples (int) – number of coarse grid points to sample for optimization estimate. Defaults to 1000.
max_time (float, optional) – Maximum time to spend optimizing. Defaults to None.
weights (torch.Tensor, optional) – Weights for the optimization. Defaults to None.
- Returns:
- Tuple containing the value of f
nearest to queried y and the x position of this value.
- Return type:
Tuple[float, torch.Tensor]
- get_jnd(grid=None, cred_level=None, intensity_dim=- 1, confsamps=500, method='step')[source]¶
Calculate the JND.
Note that JND can have multiple plausible definitions outside of the linear case, so we provide options for how to compute it. For method=”step”, we report how far one needs to go over in stimulus space to move 1 unit up in latent space (this is a lot of people’s conventional understanding of the JND). For method=”taylor”, we report the local derivative, which also maps to a 1st-order Taylor expansion of the latent function. This is a formal generalization of JND as defined in Weber’s law. Both definitions are equivalent for linear psychometric functions.
- Parameters:
grid (torch.Tensor, optional) – Mesh grid over which to find the JND. Defaults to a square grid of size as determined by aepsych.utils.dim_grid.
cred_level (float, optional) – Credible level for computing an interval. Defaults to None, computing no interval.
intensity_dim (int) – Dimension over which to compute the JND. Defaults to -1.
confsamps (int) – Number of posterior samples to use for computing the credible interval. Defaults to 500.
method (str) – “taylor” or “step” method (see docstring). Defaults to “step”.
self (ModelProtocol) –
- Returns:
- either the
mean JND, or a median, lower, upper tuple of the JND posterior.
- Return type:
Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor, torch.Tensor]]
- dim_grid(gridsize=30, slice_dims=None)[source]¶
Generate a grid based on lower, upper, and dim.
- Parameters:
gridsize (int) – Number of points in each dimension. Defaults to 30.
slice_dims (Mapping[int, float], optional) – Dimensions to fix at a certain value. Defaults to None.
self (ModelProtocol) –
- Return type:
Tensor
- set_train_data(inputs=None, targets=None, strict=False)[source]¶
Set the training data for the model.
- Parameters:
inputs (torch.Tensor, optional) – The new training inputs.
targets (torch.Tensor, optional) – The new training targets.
strict (bool) – Default is False. Ignored, just for compatibility.
input transformers. TODO: actually use this arg or change input transforms to not require it.
- forward(x)[source]¶
Evaluate GP
- Parameters:
x (torch.Tensor) – Tensor of points at which GP should be evaluated.
- Returns:
- Distribution object
holding mean and covariance at x.
- Return type:
gpytorch.distributions.MultivariateNormal
- p_below_threshold(x, f_thresh)[source]¶
Compute the probability that the latent function is below a threshold.
- Parameters:
x (torch.Tensor) – Points at which to evaluate the probability.
f_thresh (torch.Tensor) – Threshold value.
- Returns:
Probability that the latent function is below the threshold.
- Return type:
torch.Tensor
- class aepsych.models.base.AEPsychModelDeviceMixin(*args, **kwargs)[source]¶
Bases:
AEPsychMixin
- Parameters:
args (Any) –
kwargs (Any) –
- Return type:
Any
- set_train_data(inputs=None, targets=None, strict=False)[source]¶
Set the training data for the model.
- Parameters:
inputs (torch.Tensor, optional) – The new training inputs X.
targets (torch.Tensor, optional) – The new training targets Y.
strict (bool) – Whether to strictly enforce the device of the inputs and targets.
- Return type:
None
input transformers. TODO: actually use this arg or change input transforms to not require it.
- property device: device¶
Get the device of the model.
- Returns:
Device of the model.
- Return type:
torch.device
- property train_inputs: Optional[Tuple[Tensor]]¶
Get the training inputs.
- Returns:
Training inputs.
- Return type:
Optional[Tuple[torch.Tensor]]
- property train_targets: Optional[Tensor]¶
Get the training targets.
- Returns:
Training targets.
- Return type:
Optional[torch.Tensor]
aepsych.models.derivative_gp module¶
- class aepsych.models.derivative_gp.MixedDerivativeVariationalGP(train_x, train_y, inducing_points, scales=1.0, mean_module=None, covar_module=None, fixed_prior_mean=None)[source]¶
Bases:
ApproximateGP
,GPyTorchModel
A variational GP with mixed derivative observations.
For more on GPs with derivative observations, see e.g. Riihimaki & Vehtari 2010.
References
- Riihimäki, J., & Vehtari, A. (2010). Gaussian processes with
monotonicity information. Journal of Machine Learning Research, 9, 645–652.
Initialize MixedDerivativeVariationalGP
- Parameters:
train_x (torch.Tensor) – Training x points. The last column of x is the derivative indiciator: 0 if it is an observation of f(x), and i if it is an observation of df/dx_i.
train_y (torch.Tensor) – Training y points
inducing_points (torch.Tensor) – Inducing points to use
scales (Union[torch.Tensor, float]) – Typical scale of each dimension of input space (this is used to set the lengthscale prior). Defaults to 1.0.
mean_module (Mean, optional) – A mean class that supports derivative indexes as the final dim. Defaults to a constant mean.
covar_module (Kernel, optional) – A covariance kernel class that supports derivative indexes as the final dim. Defaults to RBF kernel.
fixed_prior_mean (float, optional) – A prior mean value to use with the constant mean. Often setting this to the target threshold speeds up experiments. Defaults to None, in which case the mean will be inferred.
aepsych.models.gp_classification module¶
- class aepsych.models.gp_classification.GPClassificationModel(*args, **kwargs)[source]¶
Bases:
AEPsychModelDeviceMixin
,ApproximateGP
Probit-GP model with variational inference.
From a conventional ML perspective this is a GP Classification model, though in the psychophysics context it can also be thought of as a nonlinear generalization of the standard linear model for 1AFC or yes/no trials.
For more on variational inference, see e.g. https://docs.gpytorch.ai/en/v1.1.1/examples/04_Variational_and_Approximate_GPs/
Initialize the GP Classification model
- Parameters:
lb (torch.Tensor) – Lower bounds of the parameters.
ub (torch.Tensor) – Upper bounds of the parameters.
dim (int, optional) – The number of dimensions in the parameter space. If None, it is inferred from the size of lb and ub.
mean_module (gpytorch.means.Mean, optional) – GP mean class. Defaults to a constant with a normal prior.
covar_module (gpytorch.kernels.Kernel, optional) – GP covariance kernel class. Defaults to scaled RBF with a gamma prior.
likelihood (gpytorch.likelihood.Likelihood, optional) – The likelihood function to use. If None defaults to Bernouli likelihood.
inducing_size (int, optional) – Number of inducing points. Defaults to 99.
max_fit_time (float, optional) – The maximum amount of time, in seconds, to spend fitting the model. If None, there is no limit to the fitting time.
inducing_point_method (string) – The method to use to select the inducing points. Defaults to “auto”. If “sobol”, a number of Sobol points equal to inducing_size will be selected. If “pivoted_chol”, selects points based on the pivoted Cholesky heuristic. If “kmeans++”, selects points by performing kmeans++ clustering on the training data. If “auto”, tries to determine the best method automatically.
optimizer_options (Dict[str, Any], optional) – Optimizer options to pass to the SciPy optimizer during fitting. Assumes we are using L-BFGS-B.
- stimuli_per_trial = 1¶
- outcome_type = 'binary'¶
- classmethod from_config(config)[source]¶
Alternate constructor for GPClassification model from a configuration.
This is used when we recursively build a full sampling strategy from a configuration. TODO: document how this works in some tutorial.
- Parameters:
config (Config) – A configuration containing keys/values matching this class
- Returns:
Configured class instance.
- Return type:
- fit(train_x, train_y, warmstart_hyperparams=False, warmstart_induc=False, **kwargs)[source]¶
Fit underlying model.
- Parameters:
train_x (torch.Tensor) – Inputs.
train_y (torch.LongTensor) – Responses.
warmstart_hyperparams (bool) – Whether to reuse the previous hyperparameters (True) or fit from scratch (False). Defaults to False.
warmstart_induc (bool) – Whether to reuse the previous inducing points or fit from scratch (False). Defaults to False.
- Return type:
None
- sample(x, num_samples)[source]¶
Sample from underlying model.
- Parameters:
x (torch.Tensor) – Points at which to sample.
num_samples (int) – Number of samples to return.
ignored (kwargs are) –
- Returns:
Posterior samples [num_samples x dim]
- Return type:
torch.Tensor
- predict(x, probability_space=False)[source]¶
Query the model for posterior mean and variance.
- Parameters:
x (torch.Tensor) – Points at which to predict from the model.
probability_space (bool) – Return outputs in units of response probability instead of latent function value. Defaults to False.
- Returns:
Posterior mean and variance at queries points.
- Return type:
Tuple[torch.Tensor, torch.Tensor]
- class aepsych.models.gp_classification.GPBetaRegressionModel(*args, **kwargs)[source]¶
Bases:
GPClassificationModel
Initialize the GP Beta Regression model
- Parameters:
lb (torch.Tensor) – Lower bounds of the parameters.
ub (torch.Tensor) – Upper bounds of the parameters.
dim (int, optional) – The number of dimensions in the parameter space. If None, it is inferred from the size of lb and ub. Defaults to None.
mean_module (gpytorch.means.Mean, optional) – GP mean class. Defaults to a constant with a normal prior. Defaults to None.
covar_module (gpytorch.kernels.Kernel, optional) – GP covariance kernel class. Defaults to scaled RBF with a gamma prior.
likelihood (gpytorch.likelihood.Likelihood, optional) – The likelihood function to use. If None defaults to Beta likelihood.
inducing_size (int, optional) – Number of inducing points. Defaults to 100.
max_fit_time (float, optional) – The maximum amount of time, in seconds, to spend fitting the model. If None, there is no limit to the fitting time. Defaults to None.
inducing_point_method (string) – The method to use to select the inducing points. Defaults to “auto”.
optimizer_options (Optional[Dict[str, Any]]) –
- outcome_type = 'percentage'¶
aepsych.models.monotonic_rejection_gp module¶
- class aepsych.models.monotonic_rejection_gp.MonotonicRejectionGP(*args, **kwargs)[source]¶
Bases:
AEPsychMixin
,ApproximateGP
A monotonic GP using rejection sampling.
This takes the same insight as in e.g. Riihimäki & Vehtari 2010 (that the derivative of a GP is likewise a GP) but instead of approximately optimizing the likelihood of the model using EP, we optimize an unconstrained model by VI and then draw monotonic samples by rejection sampling.
References
- Riihimäki, J., & Vehtari, A. (2010). Gaussian processes with monotonicity information.
Journal of Machine Learning Research, 9, 645–652.
Initialize MonotonicRejectionGP.
- Parameters:
monotonic_idxs (Sequence[int]) – List of which columns of x should be given monotonicity
constraints. –
lb (torch.Tensor) – Lower bounds of the parameters.
ub (torch.Tensor) – Upper bounds of the parameters.
dim (int, optional) – The number of dimensions in the parameter space. If None, it is inferred from the size.
covar_module (Kernel, optional) – Covariance kernel to use. Default is scaled RBF.
mean_module (Mean, optional) – Mean module to use. Default is constant mean.
likelihood (str, optional) – Link function and likelihood. Can be ‘probit-bernoulli’ or ‘identity-gaussian’.
fixed_prior_mean (float, optional) – Fixed prior mean. If classification, should be the prior
probability (classification) –
num_induc (int) – Number of inducing points for variational GP.]. Defaults to 25.
num_samples (int) – Number of samples for estimating posterior on preDict or
250. (acquisition function evaluation. Defaults to) –
num_rejection_samples (int) – Number of samples used for rejection sampling. Defaults to 4096.
inducing_point_method (str) – Method for selecting inducing points. Defaults to “auto”.
optimizer_options (Dict[str, Any], optional) – Optimizer options to pass to the SciPy optimizer during fitting. Assumes we are using L-BFGS-B.
- stimuli_per_trial = 1¶
- outcome_type = 'binary'¶
- fit(train_x, train_y, **kwargs)[source]¶
Fit the model
- Parameters:
train_x (torch.Tensor) – Training x points
train_y (torch.Tensor) – Training y points. Should be (n x 1).
- Return type:
None
- update(train_x, train_y, warmstart=True)[source]¶
Update the model with new data.
Expects the full set of data, not the incremental new data.
- Parameters:
train_x (torch.Tensor) – Train X.
train_y (torch.Tensor) – Train Y. Should be (n x 1).
warmstart (bool) – If True, warm-start model fitting with current parameters. Defaults to True.
- Return type:
None
- sample(x, num_samples=None, num_rejection_samples=None)[source]¶
Sample from monotonic GP
- Parameters:
x (torch.Tensor) – tensor of n points at which to sample
num_samples (int, optional) – how many points to sample. Default is self.num_samples.
num_rejection_samples (int) – how many samples to use for rejection sampling. Default is self.num_rejection_samples.
- Return type:
Tensor
Returns: a Tensor of shape [n_samp, n]
- predict(x, probability_space=False)[source]¶
Predict
- Parameters:
x (torch.Tensor) – tensor of n points at which to predict.
probability_space (bool) – whether to return in probability space. Defaults to False.
- Returns:
Posterior mean and variance at query points.
- Return type:
Tuple[torch.Tensor, torch.Tensor]
- predict_probability(x)[source]¶
Predict in probability space
- Parameters:
x (torch.Tensor) – Points at which to predict.
- Returns:
Posterior mean and variance at query points.
- Return type:
Tuple[torch.Tensor, torch.Tensor]
Module contents¶
- class aepsych.models.GPClassificationModel(*args, **kwargs)[source]¶
Bases:
AEPsychModelDeviceMixin
,ApproximateGP
Probit-GP model with variational inference.
From a conventional ML perspective this is a GP Classification model, though in the psychophysics context it can also be thought of as a nonlinear generalization of the standard linear model for 1AFC or yes/no trials.
For more on variational inference, see e.g. https://docs.gpytorch.ai/en/v1.1.1/examples/04_Variational_and_Approximate_GPs/
Initialize the GP Classification model
- Parameters:
lb (torch.Tensor) – Lower bounds of the parameters.
ub (torch.Tensor) – Upper bounds of the parameters.
dim (int, optional) – The number of dimensions in the parameter space. If None, it is inferred from the size of lb and ub.
mean_module (gpytorch.means.Mean, optional) – GP mean class. Defaults to a constant with a normal prior.
covar_module (gpytorch.kernels.Kernel, optional) – GP covariance kernel class. Defaults to scaled RBF with a gamma prior.
likelihood (gpytorch.likelihood.Likelihood, optional) – The likelihood function to use. If None defaults to Bernouli likelihood.
inducing_size (int, optional) – Number of inducing points. Defaults to 99.
max_fit_time (float, optional) – The maximum amount of time, in seconds, to spend fitting the model. If None, there is no limit to the fitting time.
inducing_point_method (string) – The method to use to select the inducing points. Defaults to “auto”. If “sobol”, a number of Sobol points equal to inducing_size will be selected. If “pivoted_chol”, selects points based on the pivoted Cholesky heuristic. If “kmeans++”, selects points by performing kmeans++ clustering on the training data. If “auto”, tries to determine the best method automatically.
optimizer_options (Dict[str, Any], optional) – Optimizer options to pass to the SciPy optimizer during fitting. Assumes we are using L-BFGS-B.
- stimuli_per_trial = 1¶
- outcome_type = 'binary'¶
- likelihood: Likelihood¶
- classmethod from_config(config)[source]¶
Alternate constructor for GPClassification model from a configuration.
This is used when we recursively build a full sampling strategy from a configuration. TODO: document how this works in some tutorial.
- Parameters:
config (Config) – A configuration containing keys/values matching this class
- Returns:
Configured class instance.
- Return type:
- fit(train_x, train_y, warmstart_hyperparams=False, warmstart_induc=False, **kwargs)[source]¶
Fit underlying model.
- Parameters:
train_x (torch.Tensor) – Inputs.
train_y (torch.LongTensor) – Responses.
warmstart_hyperparams (bool) – Whether to reuse the previous hyperparameters (True) or fit from scratch (False). Defaults to False.
warmstart_induc (bool) – Whether to reuse the previous inducing points or fit from scratch (False). Defaults to False.
- Return type:
None
- sample(x, num_samples)[source]¶
Sample from underlying model.
- Parameters:
x (torch.Tensor) – Points at which to sample.
num_samples (int) – Number of samples to return.
ignored (kwargs are) –
- Returns:
Posterior samples [num_samples x dim]
- Return type:
torch.Tensor
- predict(x, probability_space=False)[source]¶
Query the model for posterior mean and variance.
- Parameters:
x (torch.Tensor) – Points at which to predict from the model.
probability_space (bool) – Return outputs in units of response probability instead of latent function value. Defaults to False.
- Returns:
Posterior mean and variance at queries points.
- Return type:
Tuple[torch.Tensor, torch.Tensor]
- predict_probability(x)[source]¶
Query the model for posterior mean and variance in probability space.
- Parameters:
x (torch.Tensor) – Points at which to predict from the model.
- Returns:
Posterior mean and variance at queries points.
- Return type:
Tuple[torch.Tensor, torch.Tensor]
- update(train_x, train_y, **kwargs)[source]¶
Perform a warm-start update of the model from previous fit.
- Parameters:
train_x (torch.Tensor) – Inputs.
train_y (torch.Tensor) – Responses.
- training: bool¶
- class aepsych.models.MonotonicRejectionGP(*args, **kwargs)[source]¶
Bases:
AEPsychMixin
,ApproximateGP
A monotonic GP using rejection sampling.
This takes the same insight as in e.g. Riihimäki & Vehtari 2010 (that the derivative of a GP is likewise a GP) but instead of approximately optimizing the likelihood of the model using EP, we optimize an unconstrained model by VI and then draw monotonic samples by rejection sampling.
References
- Riihimäki, J., & Vehtari, A. (2010). Gaussian processes with monotonicity information.
Journal of Machine Learning Research, 9, 645–652.
Initialize MonotonicRejectionGP.
- Parameters:
monotonic_idxs (Sequence[int]) – List of which columns of x should be given monotonicity
constraints. –
lb (torch.Tensor) – Lower bounds of the parameters.
ub (torch.Tensor) – Upper bounds of the parameters.
dim (int, optional) – The number of dimensions in the parameter space. If None, it is inferred from the size.
covar_module (Kernel, optional) – Covariance kernel to use. Default is scaled RBF.
mean_module (Mean, optional) – Mean module to use. Default is constant mean.
likelihood (str, optional) – Link function and likelihood. Can be ‘probit-bernoulli’ or ‘identity-gaussian’.
fixed_prior_mean (float, optional) – Fixed prior mean. If classification, should be the prior
probability (classification) –
num_induc (int) – Number of inducing points for variational GP.]. Defaults to 25.
num_samples (int) – Number of samples for estimating posterior on preDict or
250. (acquisition function evaluation. Defaults to) –
num_rejection_samples (int) – Number of samples used for rejection sampling. Defaults to 4096.
inducing_point_method (str) – Method for selecting inducing points. Defaults to “auto”.
optimizer_options (Dict[str, Any], optional) – Optimizer options to pass to the SciPy optimizer during fitting. Assumes we are using L-BFGS-B.
- stimuli_per_trial = 1¶
- outcome_type = 'binary'¶
- likelihood: Likelihood¶
- fit(train_x, train_y, **kwargs)[source]¶
Fit the model
- Parameters:
train_x (torch.Tensor) – Training x points
train_y (torch.Tensor) – Training y points. Should be (n x 1).
- Return type:
None
- update(train_x, train_y, warmstart=True)[source]¶
Update the model with new data.
Expects the full set of data, not the incremental new data.
- Parameters:
train_x (torch.Tensor) – Train X.
train_y (torch.Tensor) – Train Y. Should be (n x 1).
warmstart (bool) – If True, warm-start model fitting with current parameters. Defaults to True.
- Return type:
None
- sample(x, num_samples=None, num_rejection_samples=None)[source]¶
Sample from monotonic GP
- Parameters:
x (torch.Tensor) – tensor of n points at which to sample
num_samples (int, optional) – how many points to sample. Default is self.num_samples.
num_rejection_samples (int) – how many samples to use for rejection sampling. Default is self.num_rejection_samples.
- Return type:
Tensor
Returns: a Tensor of shape [n_samp, n]
- predict(x, probability_space=False)[source]¶
Predict
- Parameters:
x (torch.Tensor) – tensor of n points at which to predict.
probability_space (bool) – whether to return in probability space. Defaults to False.
- Returns:
Posterior mean and variance at query points.
- Return type:
Tuple[torch.Tensor, torch.Tensor]
- predict_probability(x)[source]¶
Predict in probability space
- Parameters:
x (torch.Tensor) – Points at which to predict.
- Returns:
Posterior mean and variance at query points.
- Return type:
Tuple[torch.Tensor, torch.Tensor]
- classmethod from_config(config)[source]¶
Alternate constructor for MonotonicRejectionGP
- Parameters:
config (Config) – a configuration containing keys/values matching this class
- Returns:
configured class instance
- Return type:
- forward(x)[source]¶
Evaluate GP
- Parameters:
x (torch.Tensor) – Tensor of points at which GP should be evaluated.
- Returns:
- Distribution object
holding mean and covariance at x.
- Return type:
gpytorch.distributions.MultivariateNormal
- train_inputs: Optional[Tuple[torch.Tensor]]¶
- train_targets: Optional[torch.Tensor]¶
- training: bool¶
- class aepsych.models.GPRegressionModel(*args, **kwargs)[source]¶
Bases:
AEPsychModelDeviceMixin
,ExactGP
GP Regression model for continuous outcomes, using exact inference.
Initialize the GP regression model
- Parameters:
lb (torch.Tensor) – Lower bounds of the parameters.
ub (torch.Tensor) – Upper bounds of the parameters.
dim (int, optional) – The number of dimensions in the parameter space. If None, it is inferred from the size of lb and ub.
mean_module (gpytorch.means.Mean, optional) – GP mean class. Defaults to a constant with a normal prior.
covar_module (gpytorch.kernels.Kernel, optional) – GP covariance kernel class. Defaults to scaled RBF with a gamma prior.
likelihood (gpytorch.likelihood.Likelihood, optional) – The likelihood function to use. If None defaults to Gaussian likelihood.
max_fit_time (float, optional) – The maximum amount of time, in seconds, to spend fitting the model. If None, there is no limit to the fitting time.
optimizer_options (Dict[str, Any], optional) – Optimizer options to pass to the SciPy optimizer during fitting. Assumes we are using L-BFGS-B.
- stimuli_per_trial = 1¶
- outcome_type = 'continuous'¶
- classmethod construct_inputs(config)[source]¶
Construct inputs for the GP regression model from configuration.
- Parameters:
config (Config) – A configuration containing keys/values matching this class.
- Returns:
Dictionary of inputs for the GP regression model.
- Return type:
Dict
- classmethod from_config(config)[source]¶
Alternate constructor for GP regression model.
This is used when we recursively build a full sampling strategy from a configuration. TODO: document how this works in some tutorial.
- Parameters:
config (Config) – A configuration containing keys/values matching this class.
- Returns:
Configured class instance.
- Return type:
- fit(train_x, train_y, **kwargs)[source]¶
Fit underlying model.
- Parameters:
train_x (torch.Tensor) – Inputs.
train_y (torch.LongTensor) – Responses.
- Return type:
None
- sample(x, num_samples)[source]¶
Sample from underlying model.
- Parameters:
x (torch.Tensor) – Points at which to sample.
num_samples (int) – Number of samples to return.
- Returns:
Posterior samples [num_samples x dim]
- Return type:
torch.Tensor
- class aepsych.models.OrdinalGPModel(*args, **kwargs)[source]¶
Bases:
GPClassificationModel
Convenience wrapper for GPClassificationModel that hardcodes an ordinal likelihood, better priors for this setting, and adds a convenience method for computing outcome probabilities.
TODO: at some point we should refactor posteriors so that things like OrdinalPosterior and MonotonicPosterior don’t have to have their own model classes.
Initialize the OrdinalGPModel
- Parameters:
likelihood (Likelihood) – The likelihood function to use. If None defaults to Ordinal likelihood.
- outcome_type = 'ordinal'¶
- predict_probs(xgrid)[source]¶
Predict probabilities of each ordinal level at xgrid
- Parameters:
xgrid (torch.Tensor) – Tensor of input points to predict at
- Returns:
Tensor of probabilities of each ordinal level at xgrid
- Return type:
torch.Tensor
- calculate_probs(fmean, fvar)[source]¶
Calculate probabilities of each ordinal level given a mean and variance
- Parameters:
fmean (torch.Tensor) – Mean of the latent function
fvar (torch.Tensor) – Variance of the latent function
- Returns:
Tensor of probabilities of each ordinal level
- Return type:
torch.Tensor
- class aepsych.models.MonotonicProjectionGP(*args, **kwargs)[source]¶
Bases:
GPClassificationModel
A monotonic GP based on posterior projection
NOTE: This model does not currently support backprop and so cannot be used with gradient optimization for active learning.
This model produces predictions that are monotonic in any number of specified monotonic dimensions. It follows the intuition of the paper
Lin L, Dunson DB (2014) Bayesian monotone regression using Gaussian process projection, Biometrika 101(2): 303-317.
but makes significant departures by using heuristics for a lot of what is done in a more principled way in the paper. The reason for the move to heuristics is to improve scaling, especially with multiple monotonic dimensions.
The method in the paper applies PAVA projection at the sample level, which requires a significant amount of costly GP posterior sampling. The approach taken here applies rolling-max projection to quantiles of the distribution, and so requires only marginal posterior evaluation. There is also a significant departure in the way multiple monotonic dimensions are handled, since in the paper computation scales exponentially with the number of monotonic dimensions and the heuristic approach taken here scales linearly in the number of dimensions.
The cost of these changes is that the convergence guarantees proven in the paper no longer hold. The method implemented here is a heuristic, and it may be useful in some problems.
The principle behind the method given here is that sample-level monotonicity implies monotonicity in the quantiles. We enforce monotonicity in several quantiles, and use that as an approximation for the true projected posterior distribution.
The approach here also supports specifying a minimum value of f. That minimum will be enforced on mu, but not necessarily on the lower bound of the projected posterior since we keep the projected posterior normal. The min f value will also be enforced on samples drawn from the model, while monotonicity will not be enforced at the sample level.
The procedure for computing the monotonic projected posterior at x is: 1. Separately for each monotonic dimension, create a grid of s points that differ only in that dimension, and sweep from the lower bound up to x. 2. Evaluate the marginal distribution, mu and sigma, on the full set of points (x and the s grid points for each monotonic dimension). 3. Compute the mu +/- 2 * sigma quantiles. 4. Enforce monotonicity in the quantiles by taking mu_proj as the maximum mu across the set, and lb_proj as the maximum of mu - 2 * sigma across the set. ub_proj is left as mu(x) + 2 * sigma(x), but is clamped to mu_proj in case that project put it above the original ub. 5. Clamp mu and lb to the minimum value for f, if one was set. 6. Construct a new normal posterior given the projected quantiles by taking mu_proj as the mean, and (ub - lb) / 4 as the standard deviation. Adjust the covariance matrix to account for the change in the marginal variances.
The process above requires only marginal posterior evaluation on the grid of points used for the posterior projection, and the size of that grid scales linearly with the number of monotonic dimensions, not exponentially.
The args here are the same as for GPClassificationModel with the addition of:
- Parameters:
monotonic_dims (List[int]) – A list of the dimensions on which monotonicity should be enforced.
monotonic_grid_size (int) – The size of the grid, s, in 1. above.
min_f_val (Optional[float]) – If provided, maintains this minimum in the projection in 5.
lb (torch.Tensor) –
ub (torch.Tensor) –
dim (Optional[int]) –
mean_module (Optional[gpytorch.means.Mean]) –
covar_module (Optional[gpytorch.kernels.Kernel]) –
likelihood (Optional[Likelihood]) –
inducing_size (Optional[int]) –
max_fit_time (Optional[float]) –
inducing_point_method (str) –
optimizer_options (Optional[Dict[str, Any]]) –
Initialize the MonotonicProjectionGP model.
- Parameters:
lb (torch.Tensor) – Lower bounds of the parameters.
ub (torch.Tensor) – Upper bounds of the parameters.
monotonic_dims (List[int]) – A list of the dimensions on which monotonicity should be enforced.
monotonic_grid_size (int) – The size of the grid, s, in 1. above. Defaults to 20.
min_f_val (float, optional) – If provided, maintains this minimum in the projection in 5. Defaults to None.
dim (int, optional) – The number of dimensions in the parameter space. If None, it is inferred from the size of lb and ub. Defaults to None.
mean_module (gpytorch.means.Mean, optional) – GP mean class. Defaults to a constant with a normal prior. Defaults to None.
covar_module (gpytorch.kernels.Kernel, optional) – GP covariance kernel class. Defaults to scaled RBF with a gamma prior. Defaults to None.
likelihood (Likelihood, optional) – The likelihood function to use. If None defaults to Gaussian likelihood. Defaults to None.
inducing_size (int, optional) – The number of inducing points to use. Defaults to None.
max_fit_time (float, optional) – The maximum amount of time, in seconds, to spend fitting the model. If None, there is no limit to the fitting time. Defaults to None.
inducing_point_method (string) – The method to use to select the inducing points. Defaults to “auto”.
optimizer_options (Optional[Dict[str, Any]]) –
- posterior(X, observation_noise=False, **kwargs)[source]¶
Compute the posterior at X, projecting to enforce monotonicity.
- Parameters:
X (torch.Tensor) – The input points at which to compute the posterior.
observation_noise (Union[bool, torch.Tensor]) – Whether or not to include the observation noise in the posterior. Defaults to False.
kwargs (Any) –
- Returns:
The posterior at X.
- Return type:
GPyTorchPosterior
- sample(x, num_samples)[source]¶
Sample from the model.
- Parameters:
x (torch.Tensor) – The input points at which to sample.
num_samples (int) – The number of samples to draw.
- Returns:
The samples at x.
- Return type:
torch.Tensor
- classmethod from_config(config)[source]¶
Alternate constructor for MonotonicProjectionGP model.
This is used when we recursively build a full sampling strategy from a configuration. TODO: document how this works in some tutorial.
- Parameters:
config (Config) – A configuration containing keys/values matching this class
- Returns:
Configured class instance.
- Return type:
- class aepsych.models.MultitaskGPRModel(*args, **kwargs)[source]¶
Bases:
GPRegressionModel
Multitask (multi-output) GP regression, using a kronecker-separable model where [a] each output is observed at each input, and [b] the kernel between two outputs at two points is given by k_x(x, x’) * k_t[i, j] where k(x, x’) is the usual GP kernel and k_t[i, j] is indexing into a freeform covariance of potentially low rank.
This essentially implements / wraps the GPyTorch multitask GPR tutorial in https://docs.gpytorch.ai/en/stable/examples/03_Multitask_Exact_GPs/Multitask_GP_Regression.html with AEPsych API and convenience fitting / prediction methods.
Initialize multitask GPR model.
- Parameters:
num_outputs (int) – Number of tasks (outputs). Defaults to 2.
rank (int) – Rank of cross-task covariance. Lower rank is a simpler model. Should be less than or equal to num_outputs. Defaults to 1.
mean_module (gpytorch.means.Mean, optional) – GP mean. Defaults to a constant mean.
covar_module (gpytorch.kernels.Kernel, optional) – GP kernel module. Defaults to scaled RBF kernel.
likelihood (gpytorch.likelihoods.Likelihood, optional) – Likelihood (should be a multitask-compatible likelihood). Defaults to multitask Gaussian likelihood.
- stimuli_per_trial = 1¶
- outcome_type = 'continuous'¶
- class aepsych.models.IndependentMultitaskGPRModel(*args, **kwargs)[source]¶
Bases:
GPRegressionModel
Independent multitask GP regression. This is a convenience wrapper for fitting a batch of independent GPRegression models. It wraps the GPyTorch tutorial here https://docs.gpytorch.ai/en/stable/examples/03_Multitask_Exact_GPs/Batch_Independent_Multioutput_GP.html with AEPsych API and convenience fitting / prediction methods.
Initialize independent multitask GPR model.
- Parameters:
num_outputs (int) – Number of tasks (outputs). Defaults to 2.
mean_module (gpytorch.means.Mean, optional) – GP mean. Defaults to a constant mean.
covar_module (gpytorch.kernels.Kernel, optional) – GP kernel module. Defaults to scaled RBF kernel.
likelihood (gpytorch.likelihoods.Likelihood, optional) – Likelihood (should be a multitask-compatible likelihood). Defaults to multitask Gaussian likelihood.
- stimuli_per_trial = 1¶
- outcome_type = 'continuous'¶
- class aepsych.models.HadamardSemiPModel(*args, **kwargs)[source]¶
Bases:
GPClassificationModel
Semiparametric GP model for psychophysics, with a MVN approximation to the elementwise product of GPs.
Implements a semi-parametric model with a functional form like \(k(x_c()x_i + c(x_c))\), for scalar intensity dimension \(x_i\) and vector-valued context dimensions \(x_c\), with k and c having a GP prior. In contrast to SemiParametricGPModel, this version approximates the product as a single multivariate normal, which should be faster (the approximation is exact if one of the GP’s variance goes to zero). Intended for use with a BernoulliObjectiveLikelihood with flexible link function such as Logistic or Gumbel nonlinearity with a floor.
Initialize HadamardSemiPModel. :param lb: Lower bounds of the parameters. :type lb: torch.Tensor :param ub: Upper bounds of the parameters. :type ub: torch.Tensor :param dim: The number of dimensions in the parameter space. If None, it is inferred from the size
of lb and ub.
- Parameters:
stim_dim (int) – Index of the intensity (monotonic) dimension. Defaults to 0.
slope_mean_module (gpytorch.means.Mean, optional) – Mean module to use (default: constant mean) for slope.
slope_covar_module (gpytorch.kernels.Kernel, optional) – Covariance kernel to use (default: scaled RBF) for slope.
offset_mean_module (gpytorch.means.Mean, optional) – Mean module to use (default: constant mean) for offset.
offset_covar_module (gpytorch.kernels.Kernel, optional) – Covariance kernel to use (default: scaled RBF) for offset.
likelihood (gpytorch.likelihood.Likelihood, optional)) – defaults to bernoulli with logistic input and a floor of .5
slope_mean (float) – The mean of the slope. Defaults to 2.
inducing_size (int, optional) – Number of inducing points. Defaults to 99.
max_fit_time (float, optional) – The maximum amount of time, in seconds, to spend fitting the model. If None, there is no limit to the fitting time.
inducing_point_method (string) – The method to use to select the inducing points. Defaults to “auto”. If “sobol”, a number of Sobol points equal to inducing_size will be selected. If “pivoted_chol”, selects points based on the pivoted Cholesky heuristic. If “kmeans++”, selects points by performing kmeans++ clustering on the training data. If “auto”, tries to determine the best method automatically.
optimizer_options (Dict[str, Any], optional) – Optimizer options to pass to the SciPy optimizer during fitting. Assumes we are using L-BFGS-B.
lb (torch.Tensor) –
ub (torch.Tensor) –
dim (int, optional) –
- stimuli_per_trial = 1¶
- outcome_type = 'binary'¶
- forward(x)[source]¶
Forward pass for HadamardSemiPModel GP.
generates a k(c + x[:,stim_dim]) = kc + kx[:,stim_dim] mvn object where k and c are slope and offset GPs and x[:,stim_dim] are the intensity stimulus (x) locations and thus acts as a constant offset to the k mvn. :param x: Points at which to sample. :type x: torch.Tensor
- Returns:
MVN object evaluated at samples
- Parameters:
x (Tensor) –
- Return type:
MultivariateNormal
- classmethod from_config(config)[source]¶
Alternate constructor for HadamardSemiPModel model.
This is used when we recursively build a full sampling strategy from a configuration.
- Parameters:
config (Config) – A configuration containing keys/values matching this class
- Returns:
Configured class instance.
- Return type:
- predict(x, probability_space=False)[source]¶
Query the model for posterior mean and variance.
- Parameters:
x (torch.Tensor) – Points at which to predict from the model.
probability_space (bool) – Return outputs in units of response probability instead of latent function value. Defaults to False.
- Returns:
Posterior mean and variance at queries points.
- Return type:
Tuple[torch.Tensor, torch.Tensor]
- class aepsych.models.SemiParametricGPModel(*args, **kwargs)[source]¶
Bases:
GPClassificationModel
Semiparametric GP model for psychophysics.
Implements a semi-parametric model with a functional form like \(k(x_c()x_i + c(x_c))\), for scalar intensity dimension \(x_i\) and vector-valued context dimensions \(x_c\), with k and c having a GP prior. In contrast to HadamardSemiPModel, this version uses a batched GP directly, which is about 2-3x slower but does not use the MVN approximation.
Intended for use with a BernoulliObjectiveLikelihood with flexible link function such as Logistic or Gumbel nonlinearity with a floor.
Initialize SemiParametricGP. :param lb: Lower bounds of the parameters. :type lb: torch.Tensor :param ub: Upper bounds of the parameters. :type ub: torch.Tensor :param dim: The number of dimensions in the parameter space. If None, it is inferred from the size
of lb and ub. Defaults to None.
- Parameters:
stim_dim (int) – Index of the intensity (monotonic) dimension. Defaults to 0.
mean_module (gpytorch.means.Mean, optional) – GP mean class. Defaults to a constant with a normal prior.
covar_module (gpytorch.kernels.Kernel, optional) – GP covariance kernel class. Defaults to scaled RBF with a gamma prior.
likelihood (gpytorch.likelihood.Likelihood, optional) – The likelihood function to use. If None defaults to linear-Bernouli likelihood with probit link.
slope_mean (float) – The mean of the slope. Defaults to 2.
inducing_size (int, optional) – Number of inducing points. Defaults to 99.
max_fit_time (float, optional) – The maximum amount of time, in seconds, to spend fitting the model. If None, there is no limit to the fitting time.
inducing_point_method (string) – The method to use to select the inducing points. Defaults to “auto”. If “sobol”, a number of Sobol points equal to inducing_size will be selected. If “pivoted_chol”, selects points based on the pivoted Cholesky heuristic. If “kmeans++”, selects points by performing kmeans++ clustering on the training data. If “auto”, tries to determine the best method automatically.
optimizer_options (Dict[str, Any], optional) – Optimizer options to pass to the SciPy optimizer during fitting. Assumes we are using L-BFGS-B.
lb (torch.Tensor) –
ub (torch.Tensor) –
dim (int, optional) –
- stimuli_per_trial = 1¶
- outcome_type = 'binary'¶
- classmethod from_config(config)[source]¶
Alternate constructor for SemiParametricGPModel model.
This is used when we recursively build a full sampling strategy from a configuration.
- Parameters:
config (Config) – A configuration containing keys/values matching this class
- Returns:
Configured class instance.
- Return type:
- fit(train_x, train_y, warmstart_hyperparams=False, warmstart_induc=False, **kwargs)[source]¶
Fit underlying model.
- Parameters:
train_x (torch.Tensor) – Inputs.
train_y (torch.LongTensor) – Responses.
warmstart_hyperparams (bool) – Whether to reuse the previous hyperparameters (True) or fit from scratch (False). Defaults to False.
warmstart_induc (bool) – Whether to reuse the previous inducing points or fit from scratch (False). Defaults to False.
kwargs – Keyword arguments passed to optimizer=fit_gpytorch_mll_scipy.
- Return type:
None
- sample(x, num_samples, probability_space=False)[source]¶
Sample from underlying model.
- Parameters:
x (torch.Tensor) – n x d Points at which to sample.
num_samples (int) – Number of samples to return. Defaults to None.
probability_space (bool) – Whether to sample from the probability space (True) or the latent function. Defaults to False.
ignored (kwargs are) –
- Returns:
Posterior samples
- Return type:
(num_samples x n) torch.Tensor
- predict(x, probability_space=False)[source]¶
Query the model for posterior mean and variance.
- Parameters:
x (torch.Tensor) – Points at which to predict from the model.
probability_space (bool) – Return outputs in units of response probability instead of latent function value. Defaults to False.
- Returns:
Posterior mean and variance at query points.
- Return type:
Tuple[torch.Tensor, torch.Tensor]
- posterior(X, posterior_transform=None)[source]¶
Get the posterior distribution at the given points.
- Parameters:
X (torch.Tensor) – Points at which to evaluate the posterior.
posterior_transform (PosteriorTransform, optional) – A transform to apply to the posterior. Defaults to None.
- Returns:
The posterior distribution at the given points.
- Return type:
SemiPPosterior
- aepsych.models.semi_p_posterior_transform(posterior)[source]¶
Transform a posterior from a SemiP model to a Hadamard model.
- Parameters:
posterior (GPyTorchPosterior) – The posterior to transform
- Returns:
The transformed posterior.
- Return type:
GPyTorchPosterior
- class aepsych.models.GPBetaRegressionModel(*args, **kwargs)[source]¶
Bases:
GPClassificationModel
Initialize the GP Beta Regression model
- Parameters:
lb (torch.Tensor) – Lower bounds of the parameters.
ub (torch.Tensor) – Upper bounds of the parameters.
dim (int, optional) – The number of dimensions in the parameter space. If None, it is inferred from the size of lb and ub. Defaults to None.
mean_module (gpytorch.means.Mean, optional) – GP mean class. Defaults to a constant with a normal prior. Defaults to None.
covar_module (gpytorch.kernels.Kernel, optional) – GP covariance kernel class. Defaults to scaled RBF with a gamma prior.
likelihood (gpytorch.likelihood.Likelihood, optional) – The likelihood function to use. If None defaults to Beta likelihood.
inducing_size (int, optional) – Number of inducing points. Defaults to 100.
max_fit_time (float, optional) – The maximum amount of time, in seconds, to spend fitting the model. If None, there is no limit to the fitting time. Defaults to None.
inducing_point_method (string) – The method to use to select the inducing points. Defaults to “auto”.
optimizer_options (Optional[Dict[str, Any]]) –
- outcome_type = 'percentage'¶
- likelihood: Likelihood¶
- training: bool¶
- class aepsych.models.PairwiseProbitModel(*args, **kwargs)[source]¶
Bases:
PairwiseGP
,AEPsychMixin
Initialize the PairwiseProbitModel
- Parameters:
lb (torch.Tensor) – Lower bounds of the parameters.
ub (torch.Tensor) – Upper bounds of the parameters.
dim (int, optional) – The number of dimensions in the parameter space. If None, it is inferred from the size of lb and ub. Defaults to None.
covar_module (gpytorch.kernels.Kernel, optional) – GP covariance kernel class. Defaults to scaled RBF with a gamma prior. Defaults to None.
max_fit_time (float, optional) – The maximum amount of time, in seconds, to spend fitting the model. Defaults to None.
optimizer_options (Optional[Dict[str, Any]]) –
- stimuli_per_trial = 2¶
- outcome_type = 'binary'¶
- fit(train_x, train_y, optimizer_kwargs=None, **kwargs)[source]¶
Fit the model to the training data.
- Parameters:
train_x (torch.Tensor) – Trainin x points.
train_y (torch.Tensor) – Training y points.
optimizer_kwargs (Dict[str, Any], optional) – Keyword arguments to pass to the optimizer. Defaults to None.
- Return type:
None
- update(train_x, train_y, warmstart=True)[source]¶
Perform a warm-start update of the model from previous fit.
- Parameters:
train_x (torch.Tensor) – Train X.
train_y (torch.Tensor) – Train Y.
warmstart (bool) – If True, warm-start model fitting with current parameters. Defaults to True.
- Return type:
None
- predict(x, probability_space=False, num_samples=1000, rereference='x_min')[source]¶
Query the model for posterior mean and variance.
- Parameters:
x (torch.Tensor) – Points at which to predict from the model.
probability_space (bool) – Return outputs in units of response probability instead of latent function value. Defaults to False.
num_samples (int) – Number of samples to return. Defaults to 1000.
rereference (str) – How to sample. Options are “x_min”, “x_max”, “f_min”, “f_max”. Defaults to “x_min”.
- Returns:
Posterior mean and variance at queries points.
- Return type:
Tuple[torch.Tensor, torch.Tensor]
- predict_probability(x, probability_space=False, num_samples=1000, rereference='x_min')[source]¶
Query the model for posterior mean and variance in probability space.
- Parameters:
x (torch.Tensor) – Points at which to predict from the model.
probability_space (bool) – Return outputs in units of response probability instead of latent function value. Defaults to False.
num_samples (int) – Number of samples to return. Defaults to 1000.
rereference (str) – How to sample. Options are “x_min”, “x_max”, “f_min”, “f_max”. Defaults to “x_min”.
- Returns:
Posterior mean and variance at queries points.
- Return type:
Tuple[torch.Tensor, torch.Tensor]
- sample(x, num_samples, rereference='x_min')[source]¶
Sample from the model model posterior.
- Parameters:
x (torch.Tensor) – Points at which to sample.
num_samples (int) – Number of samples to return.
rereference (str) – How to sample. Options are “x_min”, “x_max”, “f_min”, “f_max”. Defaults to “x_min”.
- Returns:
Posterior samples [num_samples x dim]
- Return type:
torch.Tensor