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 dim: int
posterior(x)[source]
Parameters

x (Tensor) –

Return type

botorch.posteriors.GPyTorchPosterior

predict(x, **kwargs)[source]
Parameters

x (Tensor) –

Return type

Tensor

property stimuli_per_trial: int
property likelihood: Likelihood
sample(x, num_samples)[source]
Parameters
  • x (Tensor) –

  • num_samples (int) –

Return type

Tensor

dim_grid(gridsize=30)[source]
Parameters

gridsize (int) –

Return type

Tensor

fit(train_x, train_y, **kwargs)[source]
Parameters
  • train_x (Tensor) –

  • train_y (Tensor) –

  • kwargs (Any) –

Return type

None

update(train_x, train_y, **kwargs)[source]
Parameters
  • train_x (Tensor) –

  • train_y (Tensor) –

  • kwargs (Any) –

Return type

None

p_below_threshold(x, f_thresh)[source]
Return type

ndarray

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] = []
get_max(locked_dims=None)[source]

Return the maximum of the modeled function, subject to constraints :returns: Tuple containing the max and its location (argmax).

locked_dims (Mapping[int, List[float]]): Dimensions to fix, so that the

inverse is along a slice of the full surface.

Return type

Tuple[float, np.ndarray]

Parameters
  • self (ModelProtocol) –

  • locked_dims (Optional[Mapping[int, List[float]]]) –

get_min(locked_dims=None)[source]

Return the minimum of the modeled function, subject to constraints :returns: Tuple containing the min and its location (argmin).

locked_dims (Mapping[int, List[float]]): Dimensions to fix, so that the

inverse is along a slice of the full surface.

Return type

Tuple[float, np.ndarray]

Parameters
  • self (ModelProtocol) –

  • locked_dims (Optional[Mapping[int, List[float]]]) –

inv_query(y, locked_dims=None, probability_space=False, n_samples=1000)[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]]) – Dimensions to fix, so that the inverse is along a slice of the full surface.

  • probability_space (bool, optional) – Is y (and therefore the returned nearest_y) in probability space instead of latent function space? Defaults to False.

  • self (ModelProtocol) –

  • n_samples (int) –

Returns

Tuple containing the value of f

nearest to queried y and the x position of this value.

Return type

Tuple[float, np.ndarray]

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 (Optional[np.ndarray], 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, optional) – Dimension over which to compute the JND. Defaults to -1.

  • confsamps (int, optional) – Number of posterior samples to use for computing the credible interval. Defaults to 500.

  • method (str, optional) – “taylor” or “step” method (see docstring). Defaults to “step”.

  • self (ModelProtocol) –

Raises

RuntimeError – for passing an unknown method.

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]
Parameters
  • self (ModelProtocol) –

  • gridsize (int) –

  • slice_dims (Optional[Mapping[int, float]]) –

Return type

Tensor

set_train_data(inputs=None, targets=None, strict=False)[source]
Parameters
  • inputs (torch.Tensor) – The new training inputs.

  • targets (torch.Tensor) – The new training targets.

  • strict (bool) – (default False, ignored). Here for compatibility with

input transformers. TODO: actually use this arg or change input transforms to not require it.

normalize_inputs(x)[source]
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]
Return type

ndarray

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], optional) – 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.

forward(x)[source]

Evaluate the model

Parameters

x (torch.Tensor) – Points at which to evaluate.

Returns

Object containig mean and covariance

of GP at these points.

Return type

MultivariateNormal

aepsych.models.gp_classification module

class aepsych.models.gp_classification.GPClassificationModel(*args, **kwargs)[source]

Bases: AEPsychMixin, 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 (Union[numpy.ndarray, torch.Tensor]) – Lower bounds of the parameters.

  • ub (Union[numpy.ndarray, 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) – 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.

  • 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.

  • args (Any) –

  • kwargs (Any) –

Return type

Any

stimuli_per_trial = 1
outcome_type = 'binary'
classmethod from_config(config)[source]

Alternate constructor for GPClassification 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

GPClassificationModel

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, optional) – Number of samples to return. Defaults to None.

  • 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, optional) – 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[np.ndarray, np.ndarray]

update(train_x, train_y)[source]

Perform a warm-start update of the model from previous fit.

Parameters
  • train_x (Tensor) –

  • train_y (Tensor) –

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
  • likelihood (str) – Link function and likelihood. Can be ‘probit-bernoulli’ or ‘identity-gaussian’.

  • monotonic_idxs (List[int]) – List of which columns of x should be given monotonicity

  • constraints.

  • fixed_prior_mean (Optional[float], optional) – Fixed prior mean. If classification, should be the prior

  • probability (classification) –

  • covar_module (Optional[Kernel], optional) – Covariance kernel to use (default: scaled RBF).

  • mean_module (Optional[Mean], optional) – Mean module to use (default: constant mean).

  • num_induc (int, optional) – Number of inducing points for variational GP.]. Defaults to 25.

  • num_samples (int, optional) – Number of samples for estimating posterior on preDict or

  • 250. (acquisition function evaluation. Defaults to) –

  • num_rejection_samples (int, optional) – Number of samples used for rejection sampling. Defaults to 4096.

  • acqf (MonotonicMCAcquisition, optional) – Acquisition function to use for querying points. Defaults to MonotonicMCLSE.

  • objective (Optional[MCAcquisitionObjective], optional) – Transformation of GP to apply before computing acquisition function. Defaults to identity transform for gaussian likelihood, probit transform for probit-bernoulli.

  • extra_acqf_args (Optional[Dict[str, object]], optional) – Additional arguments to pass into the acquisition function. Defaults to None.

  • args (Any) –

  • kwargs (Any) –

Return type

Any

stimuli_per_trial = 1
outcome_type = 'binary'
fit(train_x, train_y, **kwargs)[source]

Fit the model

Parameters
  • train_x (Tensor) – Training x points

  • train_y (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 (Tensor) – Train X.

  • train_y (Tensor) – Train Y. Should be (n x 1).

  • warmstart (bool) – If True, warm-start model fitting with current parameters.

Return type

None

sample(x, num_samples=None, num_rejection_samples=None)[source]

Sample from monotonic GP

Parameters
  • x (Tensor) – tensor of n points at which to sample

  • num_samples (int, optional) – how many points to sample (default: self.num_samples)

  • num_rejection_samples (Optional[int]) –

Return type

Tensor

Returns: a Tensor of shape [n_samp, n]

predict(x, probability_space=False)[source]

Predict

Parameters
  • x (Tensor) – tensor of n points at which to predict.

  • probability_space (bool) –

Return type

Tuple[Tensor, Tensor]

Returns: tuple (f, var) where f is (n,) and var is (n,)

classmethod from_config(config)[source]
Parameters

config (Config) –

Return type

MonotonicRejectionGP

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

Module contents

class aepsych.models.GPClassificationModel(*args, **kwargs)[source]

Bases: AEPsychMixin, 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 (Union[numpy.ndarray, torch.Tensor]) – Lower bounds of the parameters.

  • ub (Union[numpy.ndarray, 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) – 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.

  • 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.

  • args (Any) –

  • kwargs (Any) –

Return type

Any

stimuli_per_trial = 1
outcome_type = 'binary'
classmethod from_config(config)[source]

Alternate constructor for GPClassification 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

GPClassificationModel

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, optional) – Number of samples to return. Defaults to None.

  • 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, optional) – 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[np.ndarray, np.ndarray]

update(train_x, train_y)[source]

Perform a warm-start update of the model from previous fit.

Parameters
  • train_x (Tensor) –

  • train_y (Tensor) –

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
  • likelihood (str) – Link function and likelihood. Can be ‘probit-bernoulli’ or ‘identity-gaussian’.

  • monotonic_idxs (List[int]) – List of which columns of x should be given monotonicity

  • constraints.

  • fixed_prior_mean (Optional[float], optional) – Fixed prior mean. If classification, should be the prior

  • probability (classification) –

  • covar_module (Optional[Kernel], optional) – Covariance kernel to use (default: scaled RBF).

  • mean_module (Optional[Mean], optional) – Mean module to use (default: constant mean).

  • num_induc (int, optional) – Number of inducing points for variational GP.]. Defaults to 25.

  • num_samples (int, optional) – Number of samples for estimating posterior on preDict or

  • 250. (acquisition function evaluation. Defaults to) –

  • num_rejection_samples (int, optional) – Number of samples used for rejection sampling. Defaults to 4096.

  • acqf (MonotonicMCAcquisition, optional) – Acquisition function to use for querying points. Defaults to MonotonicMCLSE.

  • objective (Optional[MCAcquisitionObjective], optional) – Transformation of GP to apply before computing acquisition function. Defaults to identity transform for gaussian likelihood, probit transform for probit-bernoulli.

  • extra_acqf_args (Optional[Dict[str, object]], optional) – Additional arguments to pass into the acquisition function. Defaults to None.

  • args (Any) –

  • kwargs (Any) –

Return type

Any

stimuli_per_trial = 1
outcome_type = 'binary'
fit(train_x, train_y, **kwargs)[source]

Fit the model

Parameters
  • train_x (Tensor) – Training x points

  • train_y (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 (Tensor) – Train X.

  • train_y (Tensor) – Train Y. Should be (n x 1).

  • warmstart (bool) – If True, warm-start model fitting with current parameters.

Return type

None

sample(x, num_samples=None, num_rejection_samples=None)[source]

Sample from monotonic GP

Parameters
  • x (Tensor) – tensor of n points at which to sample

  • num_samples (int, optional) – how many points to sample (default: self.num_samples)

  • num_rejection_samples (Optional[int]) –

Return type

Tensor

Returns: a Tensor of shape [n_samp, n]

predict(x, probability_space=False)[source]

Predict

Parameters
  • x (Tensor) – tensor of n points at which to predict.

  • probability_space (bool) –

Return type

Tuple[Tensor, Tensor]

Returns: tuple (f, var) where f is (n,) and var is (n,)

classmethod from_config(config)[source]
Parameters

config (Config) –

Return type

MonotonicRejectionGP

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

training: bool
class aepsych.models.GPRegressionModel(*args, **kwargs)[source]

Bases: AEPsychMixin, ExactGP

GP Regression model for continuous outcomes, using exact inference.

Initialize the GP regression model

Parameters
  • lb (Union[numpy.ndarray, torch.Tensor]) – Lower bounds of the parameters.

  • ub (Union[numpy.ndarray, 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.

  • args (Any) –

  • kwargs (Any) –

Return type

Any

stimuli_per_trial = 1
outcome_type = 'continuous'
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

GPRegressionModel

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, optional) – Number of samples to return. Defaults to None.

  • ignored (kwargs are) –

Returns

Posterior samples [num_samples x dim]

Return type

torch.Tensor

update(train_x, train_y)[source]

Perform a warm-start update of the model from previous fit.

Parameters
  • train_x (Tensor) –

  • train_y (Tensor) –

predict(x, **kwargs)[source]

Query the model for posterior mean and variance.

Parameters
  • x (torch.Tensor) – Points at which to predict from the model.

  • probability_space (bool, optional) – 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[np.ndarray, np.ndarray]

class aepsych.models.PairwiseProbitModel(*args, **kwargs)[source]

Bases: PairwiseGP, AEPsychMixin

Parameters
  • args (Any) –

  • kwargs (Any) –

Return type

Any

stimuli_per_trial = 2
outcome_type = 'binary'
fit(train_x, train_y, optimizer_kwargs=None, **kwargs)[source]
Parameters
  • train_x (Tensor) –

  • train_y (Tensor) –

  • optimizer_kwargs (Optional[Dict[str, Any]]) –

update(train_x, train_y, warmstart=True)[source]

Perform a warm-start update of the model from previous fit.

Parameters
  • train_x (Tensor) –

  • train_y (Tensor) –

  • warmstart (bool) –

predict(x, probability_space=False, num_samples=1000, rereference='x_min')[source]
sample(x, num_samples, rereference='x_min')[source]
classmethod from_config(config)[source]
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 GP Classification model

Parameters
  • lb (Union[numpy.ndarray, torch.Tensor]) – Lower bounds of the parameters.

  • ub (Union[numpy.ndarray, 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) – 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.

  • 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.

  • args (Any) –

  • kwargs (Any) –

Return type

Any

outcome_type = 'ordinal'
predict_probs(xgrid)[source]
training: bool
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 – A list of the dimensions on which monotonicity should be enforced.

  • monotonic_grid_size – The size of the grid, s, in 1. above.

  • min_f_val – If provided, maintains this minimum in the projection in 5.

  • args (Any) –

  • kwargs (Any) –

Return type

Any

Initialize the GP Classification model

Parameters
  • lb (Union[numpy.ndarray, torch.Tensor]) – Lower bounds of the parameters.

  • ub (Union[numpy.ndarray, 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) – 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.

  • 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.

  • args (Any) –

  • kwargs (Any) –

Return type

Any

posterior(X, observation_noise=False, **kwargs)[source]
Parameters
  • X (Tensor) –

  • observation_noise (Union[bool, Tensor]) –

  • kwargs (Any) –

Return type

botorch.posteriors.gpytorch.GPyTorchPosterior

sample(x, num_samples)[source]

Sample from underlying model.

Parameters
  • x (torch.Tensor) – Points at which to sample.

  • num_samples (int, optional) – Number of samples to return. Defaults to None.

  • ignored (kwargs are) –

Returns

Posterior samples [num_samples x dim]

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

MonotonicProjectionGP

training: bool