Main Content

BayesianOptimization

Bayesian optimization results

Description

A BayesianOptimization object contains the results of a Bayesian optimization. It is the output of bayesopt or a fit function that accepts the OptimizeHyperparameters name-value pair such as fitcdiscr. In addition, a BayesianOptimization object contains data for each iteration of bayesopt that can be accessed by a plot function or an output function.

Creation

Create a BayesianOptimization object by using the bayesopt function or one of the following fit functions with the OptimizeHyperparameters name-value argument.

Properties

expand all

Problem Definition Properties

This property is read-only.

ObjectiveFcn argument used by bayesopt, specified as a function handle.

  • If you call bayesopt directly, ObjectiveFcn is the bayesopt objective function argument.

  • If you call a fit function containing the 'OptimizeHyperparameters' name-value pair argument, ObjectiveFcn is a function handle that returns the misclassification rate for classification or returns the logarithm of one plus the cross-validation loss for regression, measured by five-fold cross-validation.

Data Types: function_handle

This property is read-only.

VariableDescriptions argument that bayesopt used, specified as a vector of optimizableVariable objects.

  • If you called bayesopt directly, VariableDescriptions is the bayesopt variable description argument.

  • If you called a fit function with the OptimizeHyperparameters name-value pair, VariableDescriptions is the vector of hyperparameters.

This property is read-only.

Options that bayesopt used, specified as a structure.

  • If you called bayesopt directly, Options is the options used in bayesopt, which are the name-value pairs See bayesopt Input Arguments.

  • If you called a fit function with the OptimizeHyperparameters name-value pair, Options are the default bayesopt options, modified by the HyperparameterOptimizationOptions name-value pair.

Options is a read-only structure containing the following fields.

Option NameMeaning
AcquisitionFunctionNameAcquisition function name. See Acquisition Function Types.
IsObjectiveDeterministictrue means the objective function is deterministic, false otherwise.
ExplorationRatioUsed only when AcquisitionFunctionName is 'expected-improvement-plus' or 'expected-improvement-per-second-plus'. See Plus.
  
MaxObjectiveEvaluationsObjective function evaluation limit.
MaxTimeTime limit.
  
XConstraintFcnDeterministic constraints on variables. See Deterministic Constraints — XConstraintFcn.
ConditionalVariableFcnConditional variable constraints. See Conditional Constraints — ConditionalVariableFcn.
NumCoupledConstraintsNumber of coupled constraints. See Coupled Constraints.
CoupledConstraintTolerancesCoupled constraint tolerances. See Coupled Constraints.
AreCoupledConstraintsDeterministicLogical vector specifying whether each coupled constraint is deterministic.
  
VerboseCommand-line display level.
OutputFcnFunction called after each iteration. See Bayesian Optimization Output Functions.
SaveVariableNameVariable name for the @assignInBase output function.
SaveFileNameFile name for the @saveToFile output function.
PlotFcnPlot function called after each iteration. See Bayesian Optimization Plot Functions
  
InitialXPoints where bayesopt evaluated the objective function.
InitialObjectiveObjective function values at InitialX.
InitialConstraintViolationsCoupled constraint function values at InitialX.
InitialErrorValuesError values at InitialX.
InitialObjectiveEvaluationTimesObjective function evaluation times at InitialX.
InitialIterationTimesTime for each iteration, including objective function evaluation and other computations.

Data Types: struct

Solution Properties

This property is read-only.

Minimum observed value of objective function, specified as a real scalar. When there are coupled constraints or evaluation errors, this value is the minimum over all observed points that are feasible according to the final constraint and Error models.

Data Types: double

This property is read-only.

Observed point with minimum objective function value, specified as a 1-by-D table, where D is the number of variables.

Data Types: table

This property is read-only.

Estimated objective function value at XAtMinEstimatedObjective, specified as a real scalar.

MinEstimatedObjective is the mean value of the posterior distribution of the final objective model. The software estimates the MinEstimatedObjective value by passing XAtMinEstimatedObjective to the object function predictObjective.

Data Types: double

This property is read-only.

Point with the minimum upper confidence bound of the objective function value among the visited points, specified as a 1-by-D table, where D is the number of variables. The software uses the final objective model to find the upper confidence bounds of the visited points.

XAtMinEstimatedObjective is the same as the best point returned by the bestPoint function with the default criterion ('min-visited-upper-confidence-interval').

Data Types: table

This property is read-only.

Number of objective function evaluations, specified as a positive integer. This includes the initial evaluations to form a posterior model as well as evaluation during the optimization iterations.

Data Types: double

This property is read-only.

Total elapsed time of optimization in seconds, specified as a positive scalar.

Data Types: double

This property is read-only.

Next point to evaluate if optimization continues, specified as a 1-by-D table, where D is the number of variables.

Data Types: table

Trace Properties

This property is read-only.

Points where the objective function was evaluated, specified as a T-by-D table, where T is the number of evaluation points and D is the number of variables.

Data Types: table

This property is read-only.

Objective function values, specified as a column vector of length T, where T is the number of evaluation points. ObjectiveTrace contains the history of objective function evaluations.

Data Types: double

This property is read-only.

Objective function evaluation times, specified as a column vector of length T, where T is the number of evaluation points. ObjectiveEvaluationTimeTrace includes the time in evaluating coupled constraints, because the objective function computes these constraints.

Data Types: double

This property is read-only.

Iteration times, specified as a column vector of length T, where T is the number of evaluation points. IterationTimeTrace includes both objective function evaluation time and other overhead.

Data Types: double

This property is read-only.

Coupled constraint values, specified as a T-by-K array, where T is the number of evaluation points and K is the number of coupled constraints.

Data Types: double

This property is read-only.

Error indications, specified as a column vector of length T of -1 or 1 entries, where T is the number of evaluation points. Each 1 entry indicates that the objective function errored or returned NaN on the corresponding point in XTrace. Each -1 entry indicates that the objective function value was computed.

Data Types: double

This property is read-only.

Feasibility indications, specified as a logical column vector of length T, where T is the number of evaluation points. Each 1 entry indicates that the final constraint model predicts feasibility at the corresponding point in XTrace.

Data Types: logical

This property is read-only.

Probability that evaluation point is feasible, specified as a column vector of length T, where T is the number of evaluation points. The probabilities come from the final constraint model, including the error constraint model, on the corresponding points in XTrace.

Data Types: double

This property is read-only.

Which evaluation gave minimum feasible objective, specified as a column vector of integer indices of length T, where T is the number of evaluation points. Feasibility is determined with respect to the constraint models that existed at each iteration, including the error constraint model.

Data Types: double

This property is read-only.

Minimum observed objective, specified as a column vector of length T, where T is the number of evaluation points.

Data Types: double

This property is read-only.

Estimated objective, specified as a column vector of length T, where T is the number of evaluation points. The estimated objective at each iteration is determined with respect to the objective model at that iteration. At each iteration, the software uses the object function predictObjective to estimate the objective function value at the point with the minimum upper confidence bound of the objective function among the visited points.

Data Types: double

This property is read-only.

Auxiliary data from the objective function, specified as a cell array of length T, where T is the number of evaluation points. Each entry in the cell array is the UserData returned in the third output of the objective function.

Data Types: cell

Object Functions

bestPointBest point in a Bayesian optimization according to a criterion
plotPlot Bayesian optimization results
predictConstraintsPredict coupled constraint violations at a set of points
predictErrorPredict error value at a set of points
predictObjectivePredict objective function at a set of points
predictObjectiveEvaluationTimePredict objective function run times at a set of points
resumeResume a Bayesian optimization

Examples

collapse all

This example shows how to create a BayesianOptimization object by using bayesopt to minimize cross-validation loss.

Optimize hyperparameters of a KNN classifier for the ionosphere data, that is, find KNN hyperparameters that minimize the cross-validation loss. Have bayesopt minimize over the following hyperparameters:

  • Nearest-neighborhood sizes from 1 to 30

  • Distance functions 'chebychev', 'euclidean', and 'minkowski'.

For reproducibility, set the random seed, set the partition, and set the AcquisitionFunctionName option to 'expected-improvement-plus'. To suppress iterative display, set 'Verbose' to 0. Pass the partition c and fitting data X and Y to the objective function fun by creating fun as an anonymous function that incorporates this data. See Parameterizing Functions.

load ionosphere
rng default
num = optimizableVariable('n',[1,30],'Type','integer');
dst = optimizableVariable('dst',{'chebychev','euclidean','minkowski'},'Type','categorical');
c = cvpartition(351,'Kfold',5);
fun = @(x)kfoldLoss(fitcknn(X,Y,'CVPartition',c,'NumNeighbors',x.n,...
    'Distance',char(x.dst),'NSMethod','exhaustive'));
results = bayesopt(fun,[num,dst],'Verbose',0,...
    'AcquisitionFunctionName','expected-improvement-plus')

Figure contains an axes object. The axes object with title Objective function model, xlabel n, ylabel dst contains 5 objects of type line, surface, contour. One or more of the lines displays its values using only markers These objects represent Observed points, Model mean, Next point, Model minimum feasible.

Figure contains an axes object. The axes object with title Min objective vs. Number of function evaluations, xlabel Function evaluations, ylabel Min objective contains 2 objects of type line. These objects represent Min observed objective, Estimated min objective.

results = 
  BayesianOptimization with properties:

                      ObjectiveFcn: @(x)kfoldLoss(fitcknn(X,Y,'CVPartition',c,'NumNeighbors',x.n,'Distance',char(x.dst),'NSMethod','exhaustive'))
              VariableDescriptions: [1x2 optimizableVariable]
                           Options: [1x1 struct]
                      MinObjective: 0.1197
                   XAtMinObjective: [1x2 table]
             MinEstimatedObjective: 0.1213
          XAtMinEstimatedObjective: [1x2 table]
           NumObjectiveEvaluations: 30
                  TotalElapsedTime: 56.0618
                         NextPoint: [1x2 table]
                            XTrace: [30x2 table]
                    ObjectiveTrace: [30x1 double]
                  ConstraintsTrace: []
                     UserDataTrace: {30x1 cell}
      ObjectiveEvaluationTimeTrace: [30x1 double]
                IterationTimeTrace: [30x1 double]
                        ErrorTrace: [30x1 double]
                  FeasibilityTrace: [30x1 logical]
       FeasibilityProbabilityTrace: [30x1 double]
               IndexOfMinimumTrace: [30x1 double]
             ObjectiveMinimumTrace: [30x1 double]
    EstimatedObjectiveMinimumTrace: [30x1 double]

This example shows how to minimize the cross-validation loss in the ionosphere data using Bayesian optimization of an SVM classifier.

Load the data.

load ionosphere

Optimize the classification using the 'auto' parameters.

rng default % For reproducibility
Mdl = fitcsvm(X,Y,'OptimizeHyperparameters','auto')
|====================================================================================================================|
| Iter | Eval   | Objective   | Objective   | BestSoFar   | BestSoFar   | BoxConstraint|  KernelScale |  Standardize |
|      | result |             | runtime     | (observed)  | (estim.)    |              |              |              |
|====================================================================================================================|
|    1 | Best   |     0.35897 |      0.8329 |     0.35897 |     0.35897 |       3.8653 |       961.53 |         true |
|    2 | Best   |      0.1339 |      15.101 |      0.1339 |     0.16146 |       429.99 |       0.2378 |        false |
|    3 | Accept |     0.35897 |     0.33327 |      0.1339 |     0.13712 |      0.11801 |       8.9479 |        false |
|    4 | Accept |      0.1339 |      7.9736 |      0.1339 |     0.13515 |    0.0010694 |    0.0032063 |         true |
|    5 | Best   |     0.13105 |      1.2251 |     0.13105 |     0.13108 |       568.72 |       2.2544 |        false |
|    6 | Best   |     0.12821 |      14.319 |     0.12821 |     0.12823 |    0.0067651 |    0.0016188 |         true |
|    7 | Accept |     0.35897 |     0.17101 |     0.12821 |     0.12822 |    0.0031596 |       868.28 |         true |
|    8 | Best   |     0.12536 |     0.20432 |     0.12536 |     0.12539 |       946.95 |       35.907 |        false |
|    9 | Accept |     0.17379 |      18.665 |     0.12536 |     0.12542 |       997.11 |    0.0011323 |        false |
|   10 | Accept |     0.35897 |     0.29171 |     0.12536 |     0.12539 |       999.23 |       895.01 |        false |
|   11 | Accept |     0.12536 |      0.5497 |     0.12536 |     0.12531 |       998.79 |       13.208 |        false |
|   12 | Accept |     0.12821 |     0.14558 |     0.12536 |      0.1253 |       169.44 |       27.003 |        false |
|   13 | Accept |      0.1339 |      0.2999 |     0.12536 |      0.1257 |       485.88 |       22.885 |        false |
|   14 | Best   |     0.12251 |      0.3963 |     0.12251 |     0.12423 |       955.38 |        19.18 |        false |
|   15 | Accept |     0.16524 |     0.15766 |     0.12251 |     0.12441 |       43.535 |       68.071 |        false |
|   16 | Accept |     0.35897 |     0.20426 |     0.12251 |     0.12442 |    0.0010198 |       2.2585 |         true |
|   17 | Best   |     0.11681 |     0.20356 |     0.11681 |     0.12223 |       983.14 |       24.795 |        false |
|   18 | Accept |     0.12251 |     0.46785 |     0.11681 |     0.12225 |       957.18 |       22.546 |        false |
|   19 | Accept |     0.35897 |     0.37749 |     0.11681 |     0.12228 |    0.0010248 |       989.08 |        false |
|   20 | Accept |     0.12536 |     0.45778 |     0.11681 |     0.12272 |       970.67 |       27.831 |        false |
|====================================================================================================================|
| Iter | Eval   | Objective   | Objective   | BestSoFar   | BestSoFar   | BoxConstraint|  KernelScale |  Standardize |
|      | result |             | runtime     | (observed)  | (estim.)    |              |              |              |
|====================================================================================================================|
|   21 | Accept |      0.1339 |      15.013 |     0.11681 |      0.1227 |       584.46 |      0.68436 |         true |
|   22 | Accept |     0.35897 |     0.19457 |     0.11681 |      0.1227 |    0.0010082 |       49.656 |         true |
|   23 | Accept |     0.35897 |     0.17123 |     0.11681 |      0.1228 |       0.5453 |       358.77 |        false |
|   24 | Accept |     0.13105 |      5.1692 |     0.11681 |     0.12282 |      0.12429 |     0.041456 |         true |
|   25 | Accept |     0.13105 |      20.393 |     0.11681 |     0.12283 |       8.0927 |     0.047486 |         true |
|   26 | Accept |     0.13675 |      12.147 |     0.11681 |     0.12283 |     0.034533 |    0.0093727 |         true |
|   27 | Accept |     0.35897 |     0.22858 |     0.11681 |     0.12282 |    0.0018006 |       66.321 |        false |
|   28 | Accept |     0.35897 |     0.16496 |     0.11681 |     0.12263 |      0.55317 |       56.345 |        false |
|   29 | Accept |      0.1339 |     0.13092 |     0.11681 |      0.1225 |        68.17 |       8.5097 |        false |
|   30 | Accept |     0.14245 |     0.36211 |     0.11681 |     0.12256 |       47.617 |       1.5789 |        false |

__________________________________________________________
Optimization completed.
MaxObjectiveEvaluations of 30 reached.
Total function evaluations: 30
Total elapsed time: 147.0058 seconds
Total objective function evaluation time: 116.3521

Best observed feasible point:
    BoxConstraint    KernelScale    Standardize
    _____________    ___________    ___________

       983.14          24.795          false   

Observed objective function value = 0.11681
Estimated objective function value = 0.12259
Function evaluation time = 0.20356

Best estimated feasible point (according to models):
    BoxConstraint    KernelScale    Standardize
    _____________    ___________    ___________

       957.18          22.546          false   

Estimated objective function value = 0.12256
Estimated function evaluation time = 0.34934

Figure contains an axes object. The axes object with title Min objective vs. Number of function evaluations, xlabel Function evaluations, ylabel Min objective contains 2 objects of type line. These objects represent Min observed objective, Estimated min objective.

Mdl = 
  ClassificationSVM
                         ResponseName: 'Y'
                CategoricalPredictors: []
                           ClassNames: {'b'  'g'}
                       ScoreTransform: 'none'
                      NumObservations: 351
    HyperparameterOptimizationResults: [1x1 BayesianOptimization]
                                Alpha: [96x1 double]
                                 Bias: -4.9622
                     KernelParameters: [1x1 struct]
                       BoxConstraints: [351x1 double]
                      ConvergenceInfo: [1x1 struct]
                      IsSupportVector: [351x1 logical]
                               Solver: 'SMO'


The fit achieved about 12% loss for the default 5-fold cross validation.

Examine the BayesianOptimization object that is returned in the HyperparameterOptimizationResults property of the returned model.

disp(Mdl.HyperparameterOptimizationResults)
  BayesianOptimization with properties:

                      ObjectiveFcn: @createObjFcn/inMemoryObjFcn
              VariableDescriptions: [5x1 optimizableVariable]
                           Options: [1x1 struct]
                      MinObjective: 0.1168
                   XAtMinObjective: [1x3 table]
             MinEstimatedObjective: 0.1226
          XAtMinEstimatedObjective: [1x3 table]
           NumObjectiveEvaluations: 30
                  TotalElapsedTime: 147.0058
                         NextPoint: [1x3 table]
                            XTrace: [30x3 table]
                    ObjectiveTrace: [30x1 double]
                  ConstraintsTrace: []
                     UserDataTrace: {30x1 cell}
      ObjectiveEvaluationTimeTrace: [30x1 double]
                IterationTimeTrace: [30x1 double]
                        ErrorTrace: [30x1 double]
                  FeasibilityTrace: [30x1 logical]
       FeasibilityProbabilityTrace: [30x1 double]
               IndexOfMinimumTrace: [30x1 double]
             ObjectiveMinimumTrace: [30x1 double]
    EstimatedObjectiveMinimumTrace: [30x1 double]

Version History

Introduced in R2016b