This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English version of the page.

Note: This page has been translated by MathWorks. Click here to see
To view all translated materials including this page, select Country from the country navigator on the bottom of this page.

fitcensemble

Fit ensemble of learners for classification

Syntax

Mdl = fitcensemble(Tbl,ResponseVarName)
Mdl = fitcensemble(Tbl,formula)
Mdl = fitcensemble(Tbl,Y)
Mdl = fitcensemble(X,Y)
Mdl = fitcensemble(___,Name,Value)

Description

example

Mdl = fitcensemble(Tbl,ResponseVarName) returns the trained classification ensemble model object (Mdl) that contains the results of boosting 100 classification trees and the predictor and response data in the table Tbl. ResponseVarName is the name of the response variable in Tbl. By default, fitcensemble uses LogitBoost for binary classification and AdaBoostM2 for multiclass classification.

example

Mdl = fitcensemble(Tbl,formula) applies formula to fit the model to the predictor and response data in the table Tbl. formula is an explanatory model of the response and a subset of predictor variables in Tbl used to fit Mdl. For example, 'Y~X1+X2+X3' fits the response variable Tbl.Y as a function of the predictor variables Tbl.X1, Tbl.X2, and Tbl.X3.

example

Mdl = fitcensemble(Tbl,Y) treats all variables in the table Tbl as predictor variables. Y is the array of class labels that is not in Tbl.

example

Mdl = fitcensemble(X,Y) uses the predictor data in the matrix X and the array of class labels in Y.

example

Mdl = fitcensemble(___,Name,Value) uses additional options specified by one or more Name,Value pair arguments and any of the input arguments in the previous syntaxes. For example, you can specify the number of learning cycles, the ensemble aggregation method, or to implement 10-fold cross-validation.

Examples

collapse all

Create a predictive classification ensemble using all available predictor variables in the data. Then, train another ensemble using fewer predictors. Compare the in-sample predictive accuracies of the ensembles.

Load the census1994 data set.

load census1994

Train an ensemble of classification models using the entire data set and default options.

Mdl1 = fitcensemble(adultdata,'salary')
Mdl1 = 
  classreg.learning.classif.ClassificationEnsemble
           PredictorNames: {1x14 cell}
             ResponseName: 'salary'
    CategoricalPredictors: [2 4 6 7 8 9 10 14]
               ClassNames: [<=50K    >50K]
           ScoreTransform: 'none'
          NumObservations: 32561
               NumTrained: 100
                   Method: 'LogitBoost'
             LearnerNames: {'Tree'}
     ReasonForTermination: 'Terminated normally after completing the requested number of training cycles.'
                  FitInfo: [100x1 double]
       FitInfoDescription: {2x1 cell}


  Properties, Methods

Mdl is a ClassificationEnsemble model. Some notable characteristics of Mdl are:

  • Because two classes are represented in the data, LogitBoost is the ensemble aggregation algorithm.

  • Because the ensemble aggregation method is a boosting algorithm, classification trees that allow a maximum of 10 splits compose the ensemble.

  • One hundred trees compose the ensemble.

Use the classification ensemble to predict the labels of a random set of five observations from the data. Compare the predicted labels with their true values.

rng(1) % For reproducibility
[pX,pIdx] = datasample(adultdata,5);
label = predict(Mdl1,pX);
table(label,adultdata.salary(pIdx),'VariableNames',{'Predicted','Truth'})
ans=5×2 table
    Predicted    Truth
    _________    _____

      <=50K      <=50K
      <=50K      <=50K
      <=50K      <=50K
      <=50K      <=50K
      <=50K      <=50K

Train a new ensemble using age and education only.

Mdl2 = fitcensemble(adultdata,'salary ~ age + education');

Compare the resubstitution losses between Mdl1 and Mdl2.

rsLoss1 = resubLoss(Mdl1)
rsLoss1 = 0.1058
rsLoss2 = resubLoss(Mdl2)
rsLoss2 = 0.2037

The in-sample misclassification rate for the ensemble that uses all predictors is lower.

Train an ensemble of boosted classification trees by using fitcensemble. Reduce training time by specifying the 'NumBins' name-value pair argument to bin numeric predictors. This argument is valid only when fitcensemble uses a tree learner. After training, you can reproduce binned predictor data by using the BinEdges property of the trained model and the discretize function.

Generate a sample data set.

rng('default') % For reproducibility
N = 1e6;
X = [mvnrnd([-1 -1],eye(2),N); mvnrnd([1 1],eye(2),N)];
y = [zeros(N,1); ones(N,1)];

Visualize the data set.

figure
scatter(X(1:N,1),X(1:N,2),'Marker','.','MarkerEdgeAlpha',0.01)
hold on
scatter(X(N+1:2*N,1),X(N+1:2*N,2),'Marker','.','MarkerEdgeAlpha',0.01)

Train an ensemble of boosted classification trees using adaptive logistic regression (LogitBoost, the default for binary classification). Time the function for comparison purposes.

tic
Mdl1 = fitcensemble(X,y);
toc
Elapsed time is 478.988422 seconds.

Speed up training by using the 'NumBins' name-value pair argument. If you specify the 'NumBins' value as a positive integer scalar, then the software bins every numeric predictor into a specified number of equiprobable bins, and then grows trees on the bin indices instead of the original data. The software does not bin categorical predictors.

tic
Mdl2 = fitcensemble(X,y,'NumBins',50);
toc
Elapsed time is 165.598434 seconds.

The process is about three times faster when you use binned data instead of the original data. Note that the elapsed time can vary depending on your operating system.

Compare the classification errors by resubstitution.

rsLoss1 = resubLoss(Mdl1)
rsLoss1 = 0.0788
rsLoss2 = resubLoss(Mdl2)
rsLoss2 = 0.0788

In this example, binning predictor values reduces training time without loss of accuracy. In general, when you have a large data set like the one in this example, using the binning option speeds up training but causes a potential decrease in accuracy. If you want to reduce training time further, specify a smaller number of bins.

Reproduce binned predictor data by using the BinEdges property of the trained model and the discretize function.

X = Mdl2.X; % Predictor data
Xbinned = zeros(size(X));
edges = Mdl2.BinEdges;
% Find indices of binned predictors.
idxNumeric = find(~cellfun(@isempty,edges));
if iscolumn(idxNumeric)
    idxNumeric = idxNumeric';
end
for j = idxNumeric 
    x = X(:,j);
    % Convert x to array if x is a table.
    if istable(x)
        x = table2array(x);
    end
    % Group x into bins by using the discretize function.
    xbinned = discretize(x,[-inf; edges{j}; inf]);
    Xbinned(:,j) = xbinned;
end

Xbinned contains the bin indices, ranging from 1 to the number of bins, for numeric predictors. Xbinned values are 0 for categorical predictors. If X contains NaNs, then the corresponding Xbinned values are NaNs.

Estimate the generalization error of ensemble of boosted classification trees.

Load the ionosphere data set.

load ionosphere

Cross-validate an ensemble of classification trees using AdaBoostM1 and 10-fold cross-validation. Specify that each tree should be split a maximum of five times using a decision tree template.

rng(5); % For reproducibility
t = templateTree('MaxNumSplits',5);
Mdl = fitcensemble(X,Y,'Method','AdaBoostM1','Learners',t,'CrossVal','on');

Mdl is a ClassificationPartitionedEnsemble model.

Plot the cumulative, 10-fold cross-validated, misclassification rate. Display the estimated generalization error of the ensemble.

kflc = kfoldLoss(Mdl,'Mode','cumulative');
figure;
plot(kflc);
ylabel('10-fold Misclassification rate');
xlabel('Learning cycle');

estGenError = kflc(end)
estGenError = 0.0712

kfoldLoss returns the generalization error by default. However, plotting the cumulative loss allows you to monitor how the loss changes as weak learners accumulate in the ensemble.

The ensemble achieves a misclassification rate of around 0.06 after accumulating about 50 weak learners. Then, the misclassification rate increase slightly as more weak learners enter the ensemble.

If you are satisfied with the generalization error of the ensemble, then, to create a predictive model, train the ensemble again using all of the settings except cross-validation. However, it is good practice to tune hyperparameters, such as the maximum number of decision splits per tree and the number of learning cycles.

Optimize hyperparameters automatically using fitcensemble.

Load the ionosphere data set.

load ionosphere

You can find hyperparameters that minimize five-fold cross-validation loss by using automatic hyperparameter optimization.

Mdl = fitcensemble(X,Y,'OptimizeHyperparameters','auto')

In this example, for reproducibility, set the random seed and use the 'expected-improvement-plus' acquisition function. Also, for reproducibility of random forest algorithm, specify the 'Reproducible' name-value pair argument as true for tree learners.

rng('default')
t = templateTree('Reproducible',true);
Mdl = fitcensemble(X,Y,'OptimizeHyperparameters','auto','Learners',t, ...
    'HyperparameterOptimizationOptions',struct('AcquisitionFunctionName','expected-improvement-plus'))

|===================================================================================================================================|
| Iter | Eval   | Objective   | Objective   | BestSoFar   | BestSoFar   |       Method | NumLearningC-|    LearnRate |  MinLeafSize |
|      | result |             | runtime     | (observed)  | (estim.)    |              | ycles        |              |              |
|===================================================================================================================================|
|    1 | Best   |     0.10256 |      3.3624 |     0.10256 |     0.10256 |     RUSBoost |           11 |     0.010199 |           17 |
|    2 | Best   |    0.062678 |      9.6203 |    0.062678 |    0.064264 |   LogitBoost |          206 |      0.96537 |           33 |
|    3 | Accept |    0.099715 |      8.0898 |    0.062678 |    0.062688 |   AdaBoostM1 |          130 |    0.0072814 |            2 |
|    4 | Accept |    0.065527 |      1.6408 |    0.062678 |    0.062681 |          Bag |           25 |            - |            5 |
|    5 | Accept |    0.065527 |      7.7597 |    0.062678 |    0.062695 |   LogitBoost |          178 |      0.52008 |           40 |
|    6 | Accept |    0.068376 |      5.9989 |    0.062678 |    0.062693 |  GentleBoost |          146 |      0.46233 |            8 |
|    7 | Accept |    0.076923 |      18.779 |    0.062678 |    0.063613 |  GentleBoost |          456 |    0.0018323 |            3 |
|    8 | Accept |    0.068376 |      22.404 |    0.062678 |    0.063878 |   LogitBoost |          479 |     0.036176 |            7 |
|    9 | Accept |    0.068376 |      11.182 |    0.062678 |    0.065468 |   LogitBoost |          277 |      0.99964 |           42 |
|   10 | Accept |     0.17379 |     0.56157 |    0.062678 |    0.064692 |   LogitBoost |           11 |    0.0012008 |            1 |
|   11 | Accept |    0.065527 |      5.5375 |    0.062678 |    0.064854 |          Bag |          100 |            - |            1 |
|   12 | Accept |    0.076923 |      1.0801 |    0.062678 |    0.062571 |  GentleBoost |           23 |    0.0096328 |            2 |
|   13 | Accept |    0.082621 |     0.80043 |    0.062678 |    0.064919 |  GentleBoost |           18 |    0.0078878 |           61 |
|   14 | Accept |    0.065527 |      27.031 |    0.062678 |     0.06557 |          Bag |          499 |            - |            7 |
|   15 | Accept |    0.079772 |      15.974 |    0.062678 |    0.064962 |  GentleBoost |          359 |     0.080649 |            1 |
|   16 | Accept |     0.35897 |     0.59864 |    0.062678 |    0.062491 |          Bag |           10 |            - |          171 |
|   17 | Accept |     0.35897 |     0.76429 |    0.062678 |    0.062483 |   AdaBoostM1 |           14 |    0.0029975 |          174 |
|   18 | Accept |     0.10826 |       33.38 |    0.062678 |    0.062484 |     RUSBoost |          498 |      0.35355 |            1 |
|   19 | Accept |     0.64103 |      1.3341 |    0.062678 |    0.062469 |     RUSBoost |           20 |      0.11564 |          175 |
|   20 | Accept |    0.091168 |       12.13 |    0.062678 |    0.062474 |     RUSBoost |          187 |    0.0010337 |            5 |
|===================================================================================================================================|
| Iter | Eval   | Objective   | Objective   | BestSoFar   | BestSoFar   |       Method | NumLearningC-|    LearnRate |  MinLeafSize |
|      | result |             | runtime     | (observed)  | (estim.)    |              | ycles        |              |              |
|===================================================================================================================================|
|   21 | Accept |    0.076923 |      14.191 |    0.062678 |    0.062473 |  GentleBoost |          322 |     0.020651 |          174 |
|   22 | Accept |    0.065527 |      3.9125 |    0.062678 |    0.062473 |   AdaBoostM1 |           63 |      0.94968 |            1 |
|   23 | Accept |     0.17379 |      7.1762 |    0.062678 |    0.062356 |   LogitBoost |          166 |    0.0011034 |          175 |
|   24 | Accept |     0.17379 |     0.93764 |    0.062678 |    0.062611 |   LogitBoost |           20 |    0.0011381 |           15 |
|   25 | Accept |    0.062678 |      5.5353 |    0.062678 |    0.062619 |   LogitBoost |          125 |       0.9709 |            4 |
|   26 | Accept |     0.11681 |      0.7908 |    0.062678 |    0.062621 |     RUSBoost |           10 |      0.93628 |            6 |
|   27 | Accept |    0.082621 |      1.0245 |    0.062678 |    0.062716 |  GentleBoost |           19 |      0.94744 |           75 |
|   28 | Accept |    0.065527 |      6.1532 |    0.062678 |    0.064168 |   LogitBoost |          131 |      0.99024 |            9 |
|   29 | Accept |    0.068376 |      26.654 |    0.062678 |    0.064254 |          Bag |          489 |            - |            2 |
|   30 | Accept |    0.076923 |       19.52 |    0.062678 |    0.063851 |  GentleBoost |          458 |    0.0010094 |           16 |

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

Best observed feasible point:
      Method      NumLearningCycles    LearnRate    MinLeafSize
    __________    _________________    _________    ___________

    LogitBoost           206            0.96537         33     

Observed objective function value = 0.062678
Estimated objective function value = 0.063851
Function evaluation time = 9.6203

Best estimated feasible point (according to models):
      Method      NumLearningCycles    LearnRate    MinLeafSize
    __________    _________________    _________    ___________

    LogitBoost           277            0.99964         42     

Estimated objective function value = 0.063851
Estimated function evaluation time = 11.6541
Mdl = 
  classreg.learning.classif.ClassificationEnsemble
                         ResponseName: 'Y'
                CategoricalPredictors: []
                           ClassNames: {'b'  'g'}
                       ScoreTransform: 'none'
                      NumObservations: 351
    HyperparameterOptimizationResults: [1×1 BayesianOptimization]
                           NumTrained: 277
                               Method: 'LogitBoost'
                         LearnerNames: {'Tree'}
                 ReasonForTermination: 'Terminated normally after completing the requested number of training cycles.'
                              FitInfo: [277×1 double]
                   FitInfoDescription: {2×1 cell}


  Properties, Methods

The optimization searched over the ensemble aggregation methods for binary classification, over NumLearningCycles, over the LearnRate for applicable methods, and over the tree learner MinLeafSize. The output is the ensemble classifier with the minimum estimated cross-validation loss.

One way to create an ensemble of boosted classification trees that has satisfactory predictive performance is by tuning the decision tree complexity level using cross-validation. While searching for an optimal complexity level, tune the learning rate to minimize the number of learning cycles.

This example manually finds optimal parameters by using the cross-validation option (the 'KFold' name-value pair argument) and the kfoldLoss function. Alternatively, you can use the 'OptimizeHyperparameters' name-value pair argument to optimize hyperparameters automatically. See Optimize Classification Ensemble.

Load the ionosphere data set.

load ionosphere

To search for the optimal tree-complexity level:

  1. Cross-validate a set of ensembles. Exponentially increase the tree-complexity level for subsequent ensembles from decision stump (one split) to at most n - 1 splits. n is the sample size. Also, vary the learning rate for each ensemble between 0.1 to 1.

  2. Estimate the cross-validated misclassification rate of each ensemble.

  3. For tree-complexity level j, j=1...J, compare the cumulative, cross-validated misclassification rate of the ensembles by plotting them against number of learning cycles. Plot separate curves for each learning rate on the same figure.

  4. Choose the curve that achieves the minimal misclassification rate, and note the corresponding learning cycle and learning rate.

Cross-validate a deep classification tree and a stump. These classification trees serve as benchmarks.

rng(1) % For reproducibility
MdlDeep = fitctree(X,Y,'CrossVal','on','MergeLeaves','off', ...
    'MinParentSize',1);
MdlStump = fitctree(X,Y,'MaxNumSplits',1,'CrossVal','on');

Cross-validate an ensemble of 150 boosted classification trees using 5-fold cross-validation. Using a tree template, vary the maximum number of splits using the values in the sequence {30,31,...,3m}. m is such that 3m is no greater than n - 1. For each variant, adjust the learning rate using each value in the set {0.1, 0.25, 0.5, 1};

n = size(X,1);
m = floor(log(n - 1)/log(3));
learnRate = [0.1 0.25 0.5 1];
numLR = numel(learnRate);
maxNumSplits = 3.^(0:m);
numMNS = numel(maxNumSplits);
numTrees = 150;
Mdl = cell(numMNS,numLR);

for k = 1:numLR
    for j = 1:numMNS
        t = templateTree('MaxNumSplits',maxNumSplits(j));
        Mdl{j,k} = fitcensemble(X,Y,'NumLearningCycles',numTrees,...
            'Learners',t,'KFold',5,'LearnRate',learnRate(k));
    end
end

Estimate the cumulative, cross-validated misclassification rate for each ensemble and the classification trees serving as benchmarks.

kflAll = @(x)kfoldLoss(x,'Mode','cumulative');
errorCell = cellfun(kflAll,Mdl,'Uniform',false);
error = reshape(cell2mat(errorCell),[numTrees numel(maxNumSplits) numel(learnRate)]);
errorDeep = kfoldLoss(MdlDeep);
errorStump = kfoldLoss(MdlStump);

Plot how the cross-validated misclassification rate behaves as the number of trees in the ensemble increases. Plot the curves with respect to learning rate on the same plot, and plot separate plots for varying tree-complexity levels. Choose a subset of tree complexity levels to plot.

mnsPlot = [1 round(numel(maxNumSplits)/2) numel(maxNumSplits)];
figure
for k = 1:3
    subplot(2,2,k)
    plot(squeeze(error(:,mnsPlot(k),:)),'LineWidth',2)
    axis tight
    hold on
    h = gca;
    plot(h.XLim,[errorDeep errorDeep],'-.b','LineWidth',2)
    plot(h.XLim,[errorStump errorStump],'-.r','LineWidth',2)
    plot(h.XLim,min(min(error(:,mnsPlot(k),:))).*[1 1],'--k')
    h.YLim = [0 0.2];    
    xlabel('Number of trees')
    ylabel('Cross-validated misclass. rate')
    title(sprintf('MaxNumSplits = %0.3g', maxNumSplits(mnsPlot(k))))
    hold off
end
hL = legend([cellstr(num2str(learnRate','Learning Rate = %0.2f')); ...
        'Deep Tree';'Stump';'Min. misclass. rate']);
hL.Position(1) = 0.6;

Each curve contains a minimum cross-validated misclassification rate occurring at the optimal number of trees in the ensemble.

Identify the maximum number of splits, number of trees, and learning rate that yields the lowest misclassification rate overall.

[minErr,minErrIdxLin] = min(error(:));
[idxNumTrees,idxMNS,idxLR] = ind2sub(size(error),minErrIdxLin);

fprintf('\nMin. misclass. rate = %0.5f',minErr)
Min. misclass. rate = 0.05413
fprintf('\nOptimal Parameter Values:\nNum. Trees = %d',idxNumTrees);
Optimal Parameter Values:
Num. Trees = 47
fprintf('\nMaxNumSplits = %d\nLearning Rate = %0.2f\n',...
    maxNumSplits(idxMNS),learnRate(idxLR))
MaxNumSplits = 3
Learning Rate = 0.25

Create a predictive ensemble based on the optimal hyperparameters and the entire training set.

tFinal = templateTree('MaxNumSplits',maxNumSplits(idxMNS));
MdlFinal = fitcensemble(X,Y,'NumLearningCycles',idxNumTrees,...
    'Learners',tFinal,'LearnRate',learnRate(idxLR))
MdlFinal = 
  classreg.learning.classif.ClassificationEnsemble
             ResponseName: 'Y'
    CategoricalPredictors: []
               ClassNames: {'b'  'g'}
           ScoreTransform: 'none'
          NumObservations: 351
               NumTrained: 47
                   Method: 'LogitBoost'
             LearnerNames: {'Tree'}
     ReasonForTermination: 'Terminated normally after completing the requested number of training cycles.'
                  FitInfo: [47×1 double]
       FitInfoDescription: {2×1 cell}


  Properties, Methods

MdlFinal is a ClassificationEnsemble. To predict whether a radar return is good given predictor data, you can pass the predictor data and MdlFinal to predict.

Instead of searching optimal values manually by using the cross-validation option ('KFold') and the kfoldLoss function, you can use the 'OptimizeHyperparameters' name-value pair argument. When you specify 'OptimizeHyperparameters', the software finds optimal parameters automatically using Bayesian optimization. The optimal values obtained by using 'OptimizeHyperparameters' can be different from those obtained using manual search.

mdl = fitcensemble(X,Y,'OptimizeHyperparameters',{'NumLearningCycles','LearnRate','MaxNumSplits'})

|====================================================================================================================|
| Iter | Eval   | Objective   | Objective   | BestSoFar   | BestSoFar   | NumLearningC-|    LearnRate | MaxNumSplits |
|      | result |             | runtime     | (observed)  | (estim.)    | ycles        |              |              |
|====================================================================================================================|
|    1 | Best   |     0.17379 |      6.5879 |     0.17379 |     0.17379 |          137 |     0.001364 |            3 |
|    2 | Accept |     0.17379 |     0.86125 |     0.17379 |     0.17379 |           15 |     0.013089 |          144 |
|    3 | Best   |    0.065527 |      1.5839 |    0.065527 |    0.065538 |           31 |      0.47201 |            2 |
|    4 | Accept |    0.074074 |      16.044 |    0.065527 |    0.065549 |          340 |      0.92167 |            7 |
|    5 | Accept |    0.088319 |      1.1615 |    0.065527 |    0.065562 |           20 |      0.24336 |           55 |
|    6 | Accept |    0.076923 |     0.65064 |    0.065527 |    0.072693 |           11 |      0.64021 |            1 |
|    7 | Accept |    0.071225 |     0.58602 |    0.065527 |    0.072095 |           10 |      0.99816 |            5 |
|    8 | Accept |    0.076923 |     0.60015 |    0.065527 |    0.072986 |           10 |      0.75338 |           90 |
|    9 | Accept |    0.096866 |     0.59733 |    0.065527 |     0.06506 |           10 |      0.42369 |            2 |
|   10 | Best   |    0.062678 |      1.8773 |    0.062678 |    0.062667 |           37 |      0.99202 |           63 |
|   11 | Accept |    0.065527 |      1.0259 |    0.062678 |    0.062575 |           19 |      0.97944 |            1 |
|   12 | Best   |    0.059829 |      4.2008 |    0.059829 |    0.059766 |           86 |      0.40411 |            1 |
|   13 | Best   |     0.05698 |      3.0948 |     0.05698 |    0.057382 |           63 |      0.60537 |            1 |
|   14 | Accept |    0.062678 |      3.2667 |     0.05698 |    0.059783 |           69 |       0.6167 |            4 |
|   15 | Accept |    0.065527 |      3.5624 |     0.05698 |    0.060842 |           76 |      0.49778 |            2 |
|   16 | Accept |    0.065527 |      2.1858 |     0.05698 |    0.061283 |           44 |      0.99938 |            4 |
|   17 | Accept |    0.065527 |      2.6444 |     0.05698 |    0.062047 |           55 |      0.59384 |           46 |
|   18 | Accept |    0.059829 |      6.0262 |     0.05698 |    0.061494 |          128 |      0.29635 |           48 |
|   19 | Accept |    0.062678 |       8.417 |     0.05698 |    0.061481 |          182 |      0.25896 |            9 |
|   20 | Accept |    0.062678 |      4.8812 |     0.05698 |    0.061248 |          107 |      0.38775 |            2 |
|====================================================================================================================|
| Iter | Eval   | Objective   | Objective   | BestSoFar   | BestSoFar   | NumLearningC-|    LearnRate | MaxNumSplits |
|      | result |             | runtime     | (observed)  | (estim.)    | ycles        |              |              |
|====================================================================================================================|
|   21 | Accept |     0.17379 |     0.53809 |     0.05698 |      0.0612 |           10 |    0.0010009 |           53 |
|   22 | Accept |     0.17379 |     0.56404 |     0.05698 |    0.061382 |           10 |     0.051241 |            2 |
|   23 | Best   |     0.05698 |      4.1022 |     0.05698 |    0.060531 |           87 |       0.3124 |            1 |
|   24 | Accept |     0.05698 |      4.1749 |     0.05698 |    0.058776 |           85 |        0.259 |            5 |
|   25 | Accept |    0.065527 |      4.5086 |     0.05698 |    0.059405 |           93 |      0.20081 |            4 |
|   26 | Accept |     0.17379 |     0.53874 |     0.05698 |    0.059578 |           10 |    0.0035026 |            2 |
|   27 | Accept |     0.17379 |      1.4021 |     0.05698 |    0.059534 |           30 |    0.0036169 |            1 |
|   28 | Accept |       0.151 |      1.9551 |     0.05698 |    0.059446 |           41 |     0.028937 |            1 |
|   29 | Accept |     0.17379 |      1.4866 |     0.05698 |    0.059485 |           29 |    0.0010049 |            2 |
|   30 | Accept |      0.1453 |     0.55298 |     0.05698 |    0.059371 |           10 |      0.13172 |            3 |

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

Best observed feasible point:
    NumLearningCycles    LearnRate    MaxNumSplits
    _________________    _________    ____________

           87             0.3124           1      

Observed objective function value = 0.05698
Estimated objective function value = 0.059371
Function evaluation time = 4.1022

Best estimated feasible point (according to models):
    NumLearningCycles    LearnRate    MaxNumSplits
    _________________    _________    ____________

           87             0.3124           1      

Estimated objective function value = 0.059371
Estimated function evaluation time = 4.1152
mdl = 
  classreg.learning.classif.ClassificationEnsemble
                         ResponseName: 'Y'
                CategoricalPredictors: []
                           ClassNames: {'b'  'g'}
                       ScoreTransform: 'none'
                      NumObservations: 351
    HyperparameterOptimizationResults: [1×1 BayesianOptimization]
                           NumTrained: 87
                               Method: 'LogitBoost'
                         LearnerNames: {'Tree'}
                 ReasonForTermination: 'Terminated normally after completing the requested number of training cycles.'
                              FitInfo: [87×1 double]
                   FitInfoDescription: {2×1 cell}


  Properties, Methods

Input Arguments

collapse all

Sample data used to train the model, specified as a table. Each row of Tbl corresponds to one observation, and each column corresponds to one predictor variable. Tbl can contain one additional column for the response variable. Multi-column variables and cell arrays other than cell arrays of character vectors are not allowed.

  • If Tbl contains the response variable and you want to use all remaining variables as predictors, then specify the response variable using ResponseVarName.

  • If Tbl contains the response variable, and you want to use a subset of the remaining variables only as predictors, then specify a formula using formula.

  • If Tbl does not contain the response variable, then specify the response data using Y. The length of response variable and the number of rows of Tbl must be equal.

Note

To save memory and execution time, supply X and Y instead of Tbl.

Data Types: table

Response variable name, specified as the name of the response variable in Tbl.

You must specify ResponseVarName as a character vector or string scalar. For example, if Tbl.Y is the response variable, then specify ResponseVarName as 'Y'. Otherwise, fitcensemble treats all columns of Tbl as predictor variables.

The response variable must be a categorical, character, or string array, logical or numeric vector, or cell array of character vectors. If the response variable is a character array, then each element must correspond to one row of the array.

For classification, you can specify the order of the classes using the ClassNames name-value pair argument. Otherwise, fitcensemble determines the class order, and stores it in the Mdl.ClassNames.

Data Types: char | string

Explanatory model of the response and a subset of the predictor variables, specified as a character vector or string scalar in the form 'Y~X1+X2+X3'. In this form, Y represents the response variable, and X1, X2, and X3 represent the predictor variables. The variables must be variable names in Tbl (Tbl.Properties.VariableNames).

To specify a subset of variables in Tbl as predictors for training the model, use a formula. If you specify a formula, then the software does not use any variables in Tbl that do not appear in formula.

Data Types: char | string

Predictor data, specified as numeric matrix.

Each row corresponds to one observation, and each column corresponds to one predictor variable.

The length of Y and the number of rows of X must be equal.

To specify the names of the predictors in the order of their appearance in X, use the PredictorNames name-value pair argument.

Data Types: single | double

Response data, specified as a categorical, character, or string array, logical or numeric vector, or cell array of character vectors. Each entry in Y is the response to or label for the observation in the corresponding row of X or Tbl. The length of Y and the number of rows of X or Tbl must be equal. If the response variable is a character array, then each element must correspond to one row of the array.

You can specify the order of the classes using the ClassNames name-value pair argument. Otherwise, fitcensemble determines the class order, and stores it in the Mdl.ClassNames.

Data Types: categorical | char | string | logical | single | double | cell

Name-Value Pair Arguments

Specify optional comma-separated pairs of Name,Value arguments. Name is the argument name and Value is the corresponding value. Name must appear inside quotes. You can specify several name and value pair arguments in any order as Name1,Value1,...,NameN,ValueN.

Example: 'CrossVal','on','LearnRate',0.05 specifies to implement 10-fold cross-validation and to use 0.05 as the learning rate.

Note

You cannot use any cross-validation name-value pair argument along with the 'OptimizeHyperparameters' name-value pair argument. You can modify the cross-validation for 'OptimizeHyperparameters' only by using the 'HyperparameterOptimizationOptions' name-value pair argument.

General Ensemble Options

collapse all

Ensemble aggregation method, specified as the comma-separated pair consisting of 'Method' and one of the following values.

ValueMethodClassification Problem SupportRelated Name-Value Pair Arguments
'Bag'Bootstrap aggregation (bagging, for example, random forest[2]) — If 'Method' is 'Bag', then fitcensemble uses bagging with random predictor selections at each split (random forest) by default. To use bagging without the random selections, use tree learners whose 'NumVariablesToSample' value is 'all' or use discriminant analysis classifier learners.Binary and multiclassN/A
'Subspace'Random subspaceBinary and multiclassNPredToSample
'AdaBoostM1'Adaptive boostingBinary onlyLearnRate
'AdaBoostM2'Adaptive boostingMulticlass onlyLearnRate
'GentleBoost'Gentle adaptive boostingBinary onlyLearnRate
'LogitBoost'Adaptive logistic regressionBinary onlyLearnRate
'LPBoost'Linear programming boosting — Requires Optimization Toolbox™Binary and multiclassMarginPrecision
'RobustBoost'Robust boosting — Requires Optimization ToolboxBinary onlyRobustErrorGoal, RobustMarginSigma, RobustMaxMargin
'RUSBoost'Random undersampling boostingBinary and multiclassLearnRate, RatioToSmallest
'TotalBoost'Totally corrective boosting — Requires Optimization ToolboxBinary and multiclassMarginPrecision

You can specify sampling options (FResample, Replace, Resample) for training data when you use bagging ('Bag') or boosting ('TotalBoost', 'RUSBoost', 'AdaBoostM1', 'AdaBoostM2', 'GentleBoost', 'LogitBoost', 'RobustBoost', or 'LPBoost').

The defaults are:

  • 'LogitBoost' for binary problems and 'AdaBoostM2' for multiclass problems if 'Learners' includes only tree learners

  • 'AdaBoostM1' for binary problems and 'AdaBoostM2' for multiclass problems if 'Learners' includes both tree and discriminant analysis learners

  • 'Subspace' if 'Learners' does not include tree learners

For details about ensemble aggregation algorithms and examples, see Algorithms, Tips, Ensemble Algorithms, and Choose an Applicable Ensemble Aggregation Method.

Example: 'Method','Bag'

Number of ensemble learning cycles, specified as the comma-separated pair consisting of 'NumLearningCycles' and a positive integer or 'AllPredictorCombinations'.

  • If you specify a positive integer, then, at every learning cycle, the software trains one weak learner for every template object in Learners. Consequently, the software trains NumLearningCycles*numel(Learners) learners.

  • If you specify 'AllPredictorCombinations', then set Method to 'Subspace' and specify one learner only for Learners. With these settings, the software trains learners for all possible combinations of predictors taken NPredToSample at a time. Consequently, the software trains nchoosek(size(X,2),NPredToSample) learners.

The software composes the ensemble using all trained learners and stores them in Mdl.Trained.

For more details, see Tips.

Example: 'NumLearningCycles',500

Data Types: single | double | char | string

Weak learners to use in the ensemble, specified as the comma-separated pair consisting of 'Learners' and a weak-learner name, weak-learner template object, or cell vector of weak-learner template objects.

Weak LearnerWeak-Learner NameTemplate Object Creation FunctionMethod Setting
Discriminant analysis'discriminant'templateDiscriminantRecommended for 'Subspace'
k-nearest neighbors'knn'templateKNNFor 'Subspace' only
Decision tree'tree'templateTreeAll methods except 'Subspace'

  • Weak-learner name ('discriminant', 'knn', or 'tree') — fitcensemble uses weak learners created by a template object creation function with default settings. For example, specifying 'Learner','discriminant' is the same as specifying 'Learner',templateDiscriminant(). See the template object creation function pages for the default settings of a weak learner.

  • Weak-learner template object — fitcensemble uses the weak learners created by a template object creation function. Use the name-value pair arguments of the template object creation function to specify the settings of the weak learners.

  • Cell vector of m weak-learner template objects — fitcensemble grows m learners per learning cycle (see NumLearningCycles). For example, for an ensemble composed of two types of classification trees, supply {t1 t2}, where t1 and t2 are classification tree template objects returned by templateTree.

The default 'Learners' value is 'knn' if 'Method' is 'Subspace'.

The default 'Learners' value is 'tree' if 'Method' is 'Bag' or any boosting method. The default values of templateTree() depend on the value of 'Method'.

  • For bagged decision trees, the maximum number of decision splits ('MaxNumSplits') is n–1, where n is the number of observations. The number of predictors to select at random for each split ('NumVariablesToSample') is the square root of the number of predictors. Therefore, fitcensemble grows deep decision trees. You can grow shallower trees to reduce model complexity or computation time.

  • For boosted decision trees, 'MaxNumSplits' is 10 and 'NumVariablesToSample' is 'all'. Therefore, fitcensemble grows shallow decision trees. You can grow deeper trees for better accuracy.

For details on the number of learners to train, see NumLearningCycles and Tips.

Example: 'Learners',templateTree('MaxNumSplits',5)

Printout frequency, specified as the comma-separated pair consisting of 'NPrint' and a positive integer or 'off'.

To track the number of weak learners or folds that fitcensemble trained so far, specify a positive integer. That is, if you specify the positive integer m:

  • Without also specifying any cross-validation option (for example, CrossVal), then fitcensemble displays a message to the command line every time it completes training m weak learners.

  • And a cross-validation option, then fitcensemble displays a message to the command line every time it finishes training m folds.

If you specify 'off', then fitcensemble does not display a message when it completes training weak learners.

Tip

When training an ensemble of many weak learners on a large data set, specify a positive integer for NPrint.

Example: 'NPrint',5

Data Types: single | double | char | string

Number of bins for numeric predictors, specified as the comma-separated pair consisting of 'NumBins' and a positive integer scalar. This argument is valid only when fitcensemble uses a tree learner, that is, 'Learner' is either 'tree' or a template object created by using templateTree.

  • If the 'NumBins' value is empty (default), then the software does not bin any predictors.

  • If you specify the 'NumBins' value as a positive integer scalar, then the software bins every numeric predictor into a specified number of equiprobable bins, and then grows trees on the bin indices instead of the original data.

    • If the 'NumBins' value exceeds the number (u) of unique values for a predictor, then fitcensemble bins the predictor into u bins.

    • fitcensemble does not bin categorical predictors.

When you use a large training data set, this binning option speeds up training but causes a potential decrease in accuracy. You can try 'NumBins',50 first, and then change the 'NumBins' value depending on the accuracy and training speed.

A trained model stores the bin edges in the BinEdges property.

Example: 'NumBins',50

Data Types: single | double

Categorical predictors list, specified as the comma-separated pair consisting of 'CategoricalPredictors' and one of the values in this table.

ValueDescription
Vector of positive integersAn entry in the vector is the index value corresponding to the column of the predictor data (X or Tbl) that contains a categorical variable.
Logical vectorA true entry means that the corresponding column of predictor data (X or Tbl) is a categorical variable.
Character matrixEach row of the matrix is the name of a predictor variable. The names must match the entries in PredictorNames. Pad the names with extra blanks so each row of the character matrix has the same length.
String array or cell array of character vectorsEach element in the array is the name of a predictor variable. The names must match the entries in PredictorNames.
'all'All predictors are categorical.

Specification of CategoricalPredictors is appropriate if:

  • 'Learners' is 'tree'.

  • 'Learners' is 'knn' when all predictors are categorical.

By default, if the predictor data is in a table (Tbl), fitcensemble assumes that a variable is categorical if it contains logical values, categorical values, a string array, or a cell array of character vectors. If the predictor data is a matrix (X), fitcensemble assumes all predictors are continuous. To identify any categorical predictors when the data is a matrix, use the 'CategoricalPredictors' name-value pair argument.

Example: 'CategoricalPredictors','all'

Data Types: single | double | logical | char | string | cell

Predictor variable names, specified as the comma-separated pair consisting of 'PredictorNames' and a string array of unique names or cell array of unique character vectors. The functionality of 'PredictorNames' depends on the way you supply the training data.

  • If you supply X and Y, then you can use 'PredictorNames' to give the predictor variables in X names.

    • The order of the names in PredictorNames must correspond to the column order of X. That is, PredictorNames{1} is the name of X(:,1), PredictorNames{2} is the name of X(:,2), and so on. Also, size(X,2) and numel(PredictorNames) must be equal.

    • By default, PredictorNames is {'x1','x2',...}.

  • If you supply Tbl, then you can use 'PredictorNames' to choose which predictor variables to use in training. That is, fitcensemble uses only the predictor variables in PredictorNames and the response variable in training.

    • PredictorNames must be a subset of Tbl.Properties.VariableNames and cannot include the name of the response variable.

    • By default, PredictorNames contains the names of all predictor variables.

    • It is a good practice to specify the predictors for training using either 'PredictorNames' or formula only.

Example: 'PredictorNames',{'SepalLength','SepalWidth','PetalLength','PetalWidth'}

Data Types: string | cell

Response variable name, specified as the comma-separated pair consisting of 'ResponseName' and a character vector or string scalar.

  • If you supply Y, then you can use 'ResponseName' to specify a name for the response variable.

  • If you supply ResponseVarName or formula, then you cannot use 'ResponseName'.

Example: 'ResponseName','response'

Data Types: char | string

Cross-Validation Options

collapse all

Cross-validation flag, specified as the comma-separated pair consisting of 'Crossval' and 'on' or 'off'.

If you specify 'on', then the software implements 10-fold cross-validation.

To override this cross-validation setting, use one of these name-value pair arguments: CVPartition, Holdout, KFold, or Leaveout. To create a cross-validated model, you can use one cross-validation name-value pair argument at a time only.

Alternatively, cross-validate later by passing Mdl to crossval or crossval.

Example: 'Crossval','on'

Cross-validation partition, specified as the comma-separated pair consisting of 'CVPartition' and a cvpartition partition object created by cvpartition. The partition object specifies the type of cross-validation and the indexing for the training and validation sets.

To create a cross-validated model, you can use one of these four name-value pair arguments only: CVPartition, Holdout, KFold, or Leaveout.

Example: Suppose you create a random partition for 5-fold cross-validation on 500 observations by using cvp = cvpartition(500,'KFold',5). Then, you can specify the cross-validated model by using 'CVPartition',cvp.

Fraction of the data used for holdout validation, specified as the comma-separated pair consisting of 'Holdout' and a scalar value in the range (0,1). If you specify 'Holdout',p, then the software completes these steps:

  1. Randomly select and reserve p*100% of the data as validation data, and train the model using the rest of the data.

  2. Store the compact, trained model in the Trained property of the cross-validated model.

To create a cross-validated model, you can use one of these four name-value pair arguments only: CVPartition, Holdout, KFold, or Leaveout.

Example: 'Holdout',0.1

Data Types: double | single

Number of folds to use in a cross-validated model, specified as the comma-separated pair consisting of 'KFold' and a positive integer value greater than 1. If you specify 'KFold',k, then the software completes these steps:

  1. Randomly partition the data into k sets.

  2. For each set, reserve the set as validation data, and train the model using the other k – 1 sets.

  3. Store the k compact, trained models in the cells of a k-by-1 cell vector in the Trained property of the cross-validated model.

To create a cross-validated model, you can use one of these four name-value pair arguments only: CVPartition, Holdout, KFold, or Leaveout.

Example: 'KFold',5

Data Types: single | double

Leave-one-out cross-validation flag, specified as the comma-separated pair consisting of 'Leaveout' and 'on' or 'off'. If you specify 'Leaveout','on', then, for each of the n observations (where n is the number of observations excluding missing observations, specified in the NumObservations property of the model), the software completes these steps:

  1. Reserve the observation as validation data, and train the model using the other n – 1 observations.

  2. Store the n compact, trained models in the cells of an n-by-1 cell vector in the Trained property of the cross-validated model.

To create a cross-validated model, you can use one of these four name-value pair arguments only: CVPartition, Holdout, KFold, or Leaveout.

Example: 'Leaveout','on'

Other Classification Options

collapse all

Names of classes to use for training, specified as the comma-separated pair consisting of 'ClassNames' and a categorical, character, or string array, a logical or numeric vector, or a cell array of character vectors. ClassNames must have the same data type as Y.

If ClassNames is a character array, then each element must correspond to one row of the array.

Use ClassNames to:

  • Order the classes during training.

  • Specify the order of any input or output argument dimension that corresponds to the class order. For example, use ClassNames to specify the order of the dimensions of Cost or the column order of classification scores returned by predict.

  • Select a subset of classes for training. For example, suppose that the set of all distinct class names in Y is {'a','b','c'}. To train the model using observations from classes 'a' and 'c' only, specify 'ClassNames',{'a','c'}.

The default value for ClassNames is the set of all distinct class names in Y.

Example: 'ClassNames',{'b','g'}

Data Types: categorical | char | string | logical | single | double | cell

Misclassification cost, specified as the comma-separated pair consisting of 'Cost' and a square matrix or structure. If you specify:

  • The square matrix Cost, then Cost(i,j) is the cost of classifying a point into class j if its true class is i. That is, the rows correspond to the true class and the columns correspond to the predicted class. To specify the class order for the corresponding rows and columns of Cost, also specify the ClassNames name-value pair argument.

  • The structure S, then it must have two fields:

    • S.ClassNames, which contains the class names as a variable of the same data type as Y

    • S.ClassificationCosts, which contains the cost matrix with rows and columns ordered as in S.ClassNames

The default is ones(K) - eye(K), where K is the number of distinct classes.

Note

fitcensemble uses Cost to adjust the prior class probabilities specified in Prior. Then, fitcensemble uses the adjusted prior probabilities for training and resets the cost matrix to its default.

Example: 'Cost',[0 1 2 ; 1 0 2; 2 2 0]

Data Types: double | single | struct

Prior probabilities for each class, specified as the comma-separated pair consisting of 'Prior' and a value in this table.

ValueDescription
'empirical'The class prior probabilities are the class relative frequencies in Y.
'uniform'All class prior probabilities are equal to 1/K, where K is the number of classes.
numeric vectorEach element is a class prior probability. Order the elements according to Mdl.ClassNames or specify the order using the ClassNames name-value pair argument. The software normalizes the elements such that they sum to 1.
structure array

A structure S with two fields:

  • S.ClassNames contains the class names as a variable of the same type as Y.

  • S.ClassProbs contains a vector of corresponding prior probabilities. The software normalizes the elements such that they sum to 1.

fitcensemble normalizes the prior probabilities in Prior to sum to 1.

Example: struct('ClassNames',{{'setosa','versicolor','virginica'}},'ClassProbs',1:3)

Data Types: char | string | double | single | struct

Score transformation, specified as the comma-separated pair consisting of 'ScoreTransform' and a character vector, string scalar, or function handle.

This table summarizes the available character vectors and string scalars.

ValueDescription
'doublelogit'1/(1 + e–2x)
'invlogit'log(x / (1 – x))
'ismax'Sets the score for the class with the largest score to 1, and sets the scores for all other classes to 0
'logit'1/(1 + ex)
'none' or 'identity'x (no transformation)
'sign'–1 for x < 0
0 for x = 0
1 for x > 0
'symmetric'2x – 1
'symmetricismax'Sets the score for the class with the largest score to 1, and sets the scores for all other classes to –1
'symmetriclogit'2/(1 + ex) – 1

For a MATLAB® function or a function you define, use its function handle for score transform. The function handle must accept a matrix (the original scores) and return a matrix of the same size (the transformed scores).

Example: 'ScoreTransform','logit'

Data Types: char | string | function_handle

Observation weights, specified as the comma-separated pair consisting of 'Weights' and a numeric vector of positive values or name of a variable in Tbl. The software weighs the observations in each row of X or Tbl with the corresponding value in Weights. The size of Weights must equal the number of rows of X or Tbl.

If you specify the input data as a table Tbl, then Weights can be the name of a variable in Tbl that contains a numeric vector. In this case, you must specify Weights as a character vector or string scalar. For example, if the weights vector W is stored as Tbl.W, then specify it as 'W'. Otherwise, the software treats all columns of Tbl, including W, as predictors or the response when training the model.

The software normalizes Weights to sum up to the value of the prior probability in the respective class.

By default, Weights is ones(n,1), where n is the number of observations in X or Tbl.

Data Types: double | single | char | string

Sampling Options for Boosting Methods and Bagging

collapse all

Fraction of the training set to resample for every weak learner, specified as the comma-separated pair consisting of 'FResample' and a positive scalar in (0,1].

To use 'FResample', specify 'bag' for Method or set Resample to 'on'.

Example: 'FResample',0.75

Data Types: single | double

Flag indicating sampling with replacement, specified as the comma-separated pair consisting of 'Replace' and 'off' or 'on'.

  • For 'on', the software samples the training observations with replacement.

  • For 'off', the software samples the training observations without replacement. If you set Resample to 'on', then the software samples training observations assuming uniform weights. If you also specify a boosting method, then the software boosts by reweighting observations.

Unless you set Method to 'bag' or set Resample to 'on', Replace has no effect.

Example: 'Replace','off'

Flag indicating to resample, specified as the comma-separated pair consisting of 'Resample' and 'off' or 'on'.

  • If Method is a boosting method, then:

    • 'Resample','on' specifies to sample training observations using updated weights as the multinomial sampling probabilities.

    • 'Resample','off'(default) specifies to reweight observations at every learning iteration.

  • If Method is 'bag', then 'Resample' must be 'on'. The software resamples a fraction of the training observations (see FResample) with or without replacement (see Replace).

If you specify to resample using Resample, then it is good practice to resample to entire data set. That is, use the default setting of 1 for FResample.

AdaBoostM1, AdaBoostM2, LogitBoost, and GentleBoost Method Options

collapse all

Learning rate for shrinkage, specified as the comma-separated pair consisting of a numeric scalar in the interval (0,1].

To train an ensemble using shrinkage, set LearnRate to a value less than 1, for example, 0.1 is a popular choice. Training an ensemble using shrinkage requires more learning iterations, but often achieves better accuracy.

Example: 'LearnRate',0.1

Data Types: single | double

RUSBoost Method Options

collapse all

Learning rate for shrinkage, specified as the comma-separated pair consisting of a numeric scalar in the interval (0,1].

To train an ensemble using shrinkage, set LearnRate to a value less than 1, for example, 0.1 is a popular choice. Training an ensemble using shrinkage requires more learning iterations, but often achieves better accuracy.

Example: 'LearnRate',0.1

Data Types: single | double

Sampling proportion with respect to the lowest-represented class, specified as the comma-separated pair consisting of 'RatioToSmallest' and a numeric scalar or numeric vector of positive values with length equal to the number of distinct classes in the training data.

Suppose that there are K classes in the training data and the lowest-represented class has m observations in the training data.

  • If you specify the positive numeric scalar s, then fitcensemble samples s*m observations from each class, that is, it uses the same sampling proportion for each class. For more details, see Algorithms.

  • If you specify the numeric vector [s1,s2,...,sK], then fitcensemble samples si*m observations from class i, i = 1,...,K. The elements of RatioToSmallest correspond to the order of the class names specified using ClassNames (see Tips).

The default value is ones(K,1), which specifies to sample m observations from each class.

Example: 'RatioToSmallest',[2,1]

Data Types: single | double

LPBoost and TotalBoost Method Options

collapse all

Margin precision to control convergence speed, specified as the comma-separated pair consisting of 'MarginPrecision' and a numeric scalar in the interval [0,1]. MarginPrecision affects the number of boosting iterations required for convergence.

Tip

To train an ensemble using many learners, specify a small value for MarginPrecision. For training using a few learners, specify a large value.

Example: 'MarginPrecision',0.5

Data Types: single | double

RobustBoost Method Options

collapse all

Target classification error, specified as the comma-separated pair consisting of 'RobustErrorGoal' and a nonnegative numeric scalar. The upper bound on possible values depends on the values of RobustMarginSigma and RobustMaxMargin. However, the upper bound cannot exceed 1.

Tip

For a particular training set, usually there is an optimal range for RobustErrorGoal. If you set it too low or too high, then the software can produce a model with poor classification accuracy. Try cross-validating to search for the appropriate value.

Example: 'RobustErrorGoal',0.05

Data Types: single | double

Classification margin distribution spread over the training data, specified as the comma-separated pair consisting of 'RobustMarginSigma' and a positive numeric scalar. Before specifying RobustMarginSigma, consult the literature on RobustBoost, for example, [19].

Example: 'RobustMarginSigma',0.5

Data Types: single | double

Maximal classification margin in the training data, specified as the comma-separated pair consisting of 'RobustMaxMargin' and a nonnegative numeric scalar. The software minimizes the number of observations in the training data having classification margins below RobustMaxMargin.

Example: 'RobustMaxMargin',1

Data Types: single | double

Random Subspace Method Options

collapse all

Number of predictors to sample for each random subspace learner, specified as the comma-separated pair consisting of 'NPredToSample' and a positive integer in the interval 1,...,p, where p is the number of predictor variables (size(X,2) or size(Tbl,2)).

Data Types: single | double

Hyperparameter Optimization

collapse all

Parameters to optimize, specified as the comma-separated pair consisting of 'OptimizeHyperparameters' and one of the following:

  • 'none' — Do not optimize.

  • 'auto' — Use {'Method','NumLearningCycles','LearnRate'} along with the default parameters for the specified Learners:

    • Learners = 'tree' (default) — {'MinLeafSize'}

    • Learners = 'discriminant'{'Delta','Gamma'}

    • Learners = 'knn'{'Distance','NumNeighbors'}

    Note

    For hyperparameter optimization, Learners must be a single argument, not a string array or cell array.

  • 'all' — Optimize all eligible parameters.

  • String array or cell array of eligible parameter names

  • Vector of optimizableVariable objects, typically the output of hyperparameters

The optimization attempts to minimize the cross-validation loss (error) for fitcensemble by varying the parameters. For information about cross-validation loss (albeit in a different context), see Classification Loss. To control the cross-validation type and other aspects of the optimization, use the HyperparameterOptimizationOptions name-value pair.

Note

'OptimizeHyperparameters' values override any values you set using other name-value pair arguments. For example, setting 'OptimizeHyperparameters' to 'auto' causes the 'auto' values to apply.

The eligible parameters for fitcensemble are:

  • Method — Depends on the number of classes.

    • Two classes — Eligible methods are 'Bag', 'GentleBoost', 'LogitBoost', 'AdaBoostM1', and 'RUSBoost'.

    • Three or more classes — Eligible methods are 'Bag', 'AdaBoostM2', and 'RUSBoost'.

  • NumLearningCyclesfitcensemble searches among positive integers, by default log-scaled with range [10,500].

  • LearnRatefitcensemble searches among positive reals, by default log-scaled with range [1e-3,1].

  • The eligible hyperparameters for the chosen Learners:

    LearnersEligible Hyperparameters
    Bold = Used By Default
    Default Range
    'discriminant'DeltaLog-scaled in the range [1e-6,1e3]
    DiscrimType'linear', 'quadratic', 'diagLinear', 'diagQuadratic', 'pseudoLinear', and 'pseudoQuadratic'
    GammaReal values in [0,1]
    'knn'Distance'cityblock', 'chebychev', 'correlation', 'cosine', 'euclidean', 'hamming', 'jaccard', 'mahalanobis', 'minkowski', 'seuclidean', and 'spearman'
    DistanceWeight'equal', 'inverse', and 'squaredinverse'
    ExponentPositive values in [0.5,3]
    NumNeighborsPositive integer values log-scaled in the range [1, max(2,round(NumObservations/2))]
    Standardize'true' and 'false'
    'tree'MaxNumSplitsIntegers log-scaled in the range [1,max(2,NumObservations-1)]
    MinLeafSizeIntegers log-scaled in the range [1,max(2,floor(NumObservations/2))]
    NumVariablesToSampleIntegers in the range [1,max(2,NumPredictors)]
    SplitCriterion'gdi', 'deviance', and 'twoing'

    Alternatively, use hyperparameters with your chosen Learners. Note that you must specify the predictor data and response when creating an optimizableVariable object.

    load fisheriris
    params = hyperparameters('fitcensemble',meas,species,'Tree');

    To see the eligible and default hyperparameters, examine params.

Set nondefault parameters by passing a vector of optimizableVariable objects that have nondefault values. For example,

load fisheriris
params = hyperparameters('fitcensemble',meas,species,'Tree');
params(4).Range = [1,30];

Pass params as the value of OptimizeHyperparameters.

By default, iterative display appears at the command line, and plots appear according to the number of hyperparameters in the optimization. For the optimization and plots, the objective function is log(1 + cross-validation loss) for regression and the misclassification rate for classification. To control the iterative display, set the Verbose field of the 'HyperparameterOptimizationOptions' name-value pair argument. To control the plots, set the ShowPlots field of the 'HyperparameterOptimizationOptions' name-value pair argument.

For an example, see Optimize Classification Ensemble.

Example: 'OptimizeHyperparameters',{'Method','NumLearningCycles','LearnRate','MinLeafSize','MaxNumSplits'}

Options for optimization, specified as the comma-separated pair consisting of 'HyperparameterOptimizationOptions' and a structure. This argument modifies the effect of the OptimizeHyperparameters name-value pair argument. All fields in the structure are optional.

Field NameValuesDefault
Optimizer
  • 'bayesopt' — Use Bayesian optimization. Internally, this setting calls bayesopt.

  • 'gridsearch' — Use grid search with NumGridDivisions values per dimension.

  • 'randomsearch' — Search at random among MaxObjectiveEvaluations points.

'gridsearch' searches in a random order, using uniform sampling without replacement from the grid. After optimization, you can get a table in grid order by using the command sortrows(Mdl.HyperparameterOptimizationResults).

'bayesopt'
AcquisitionFunctionName

  • 'expected-improvement-per-second-plus'

  • 'expected-improvement'

  • 'expected-improvement-plus'

  • 'expected-improvement-per-second'

  • 'lower-confidence-bound'

  • 'probability-of-improvement'

Acquisition functions whose names include per-second do not yield reproducible results because the optimization depends on the runtime of the objective function. Acquisition functions whose names include plus modify their behavior when they are overexploiting an area. For more details, see Acquisition Function Types.

'expected-improvement-per-second-plus'
MaxObjectiveEvaluationsMaximum number of objective function evaluations.30 for 'bayesopt' or 'randomsearch', and the entire grid for 'gridsearch'
MaxTime

Time limit, specified as a positive real. The time limit is in seconds, as measured by tic and toc. Run time can exceed MaxTime because MaxTime does not interrupt function evaluations.

Inf
NumGridDivisionsFor 'gridsearch', the number of values in each dimension. The value can be a vector of positive integers giving the number of values for each dimension, or a scalar that applies to all dimensions. This field is ignored for categorical variables.10
ShowPlotsLogical value indicating whether to show plots. If true, this field plots the best objective function value against the iteration number. If there are one or two optimization parameters, and if Optimizer is 'bayesopt', then ShowPlots also plots a model of the objective function against the parameters.true
SaveIntermediateResultsLogical value indicating whether to save results when Optimizer is 'bayesopt'. If true, this field overwrites a workspace variable named 'BayesoptResults' at each iteration. The variable is a BayesianOptimization object.false
Verbose

Display to the command line.

  • 0 — No iterative display

  • 1 — Iterative display

  • 2 — Iterative display with extra information

For details, see the bayesopt Verbose name-value pair argument.

1
UseParallelLogical value indicating whether to run Bayesian optimization in parallel, which requires Parallel Computing Toolbox™. For details, see Parallel Bayesian Optimization.false
Repartition

Logical value indicating whether to repartition the cross-validation at every iteration. If false, the optimizer uses a single partition for the optimization.

true usually gives the most robust results because this setting takes partitioning noise into account. However, for good results, true requires at least twice as many function evaluations.

false
Use no more than one of the following three field names.
CVPartitionA cvpartition object, as created by cvpartition.'Kfold',5 if you do not specify any cross-validation field
HoldoutA scalar in the range (0,1) representing the holdout fraction.
KfoldAn integer greater than 1.

Example: 'HyperparameterOptimizationOptions',struct('MaxObjectiveEvaluations',60)

Data Types: struct

Output Arguments

collapse all

Trained ensemble model, returned as one of the model objects in this table.

Model ObjectSpecify Any Cross-Validation Options?Method SettingResample Setting
ClassificationBaggedEnsembleNo'Bag''on'
ClassificationEnsembleNoAny ensemble aggregation method for classification'off'
ClassificationPartitionedEnsembleYesAny ensemble aggregation method for classification'off' or 'on'

The name-value pair arguments that control cross-validation are CrossVal, Holdout, KFold, Leaveout, and CVPartition.

To reference properties of Mdl, use dot notation. For example, to access or display the cell vector of weak learner model objects for an ensemble that has not been cross-validated, enter Mdl.Trained at the command line.

Tips

  • NumLearningCycles can vary from a few dozen to a few thousand. Usually, an ensemble with good predictive power requires from a few hundred to a few thousand weak learners. However, you do not have to train an ensemble for that many cycles at once. You can start by growing a few dozen learners, inspect the ensemble performance and then, if necessary, train more weak learners using resume for classification problems.

  • Ensemble performance depends on the ensemble setting and the setting of the weak learners. That is, if you specify weak learners with default parameters, then the ensemble can perform poorly. Therefore, like ensemble settings, it is good practice to adjust the parameters of the weak learners using templates, and to choose values that minimize generalization error.

  • If you specify to resample using Resample, then it is good practice to resample to entire data set. That is, use the default setting of 1 for FResample.

  • If the ensemble aggregation method (Method) is 'bag' and:

    • The misclassification cost (Cost) is highly imbalanced, then, for in-bag samples, the software oversamples unique observations from the class that has a large penalty.

    • The class prior probabilities (Prior) are highly skewed, the software oversamples unique observations from the class that has a large prior probability.

    For smaller sample sizes, these combinations can result in a low relative frequency of out-of-bag observations from the class that has a large penalty or prior probability. Consequently, the estimated out-of-bag error is highly variable and it can be difficult to interpret. To avoid large estimated out-of-bag error variances, particularly for small sample sizes, set a more balanced misclassification cost matrix using Cost or a less skewed prior probability vector using Prior.

  • Because the order of some input and output arguments correspond to the distinct classes in the training data, it is good practice to specify the class order using the ClassNames name-value pair argument.

    • To determine the class order quickly, remove all observations from the training data that are unclassified (that is, have a missing label), obtain and display an array of all the distinct classes, and then specify the array for ClassNames. For example, suppose the response variable (Y) is a cell array of labels. This code specifies the class order in the variable classNames.

      Ycat = categorical(Y);
      classNames = categories(Ycat)
      categorical assigns <undefined> to unclassified observations and categories excludes <undefined> from its output. Therefore, if you use this code for cell arrays of labels or similar code for categorical arrays, then you do not have to remove observations with missing labels to obtain a list of the distinct classes.

    • To specify that the class order from lowest-represented label to most-represented, then quickly determine the class order (as in the previous bullet), but arrange the classes in the list by frequency before passing the list to ClassNames. Following from the previous example, this code specifies the class order from lowest- to most-represented in classNamesLH.

      Ycat = categorical(Y);
      classNames = categories(Ycat);
      freq = countcats(Ycat);
      [~,idx] = sort(freq);
      classNamesLH = classNames(idx);

  • After training a model, you can generate C/C++ code that predicts labels for new data. Generating C/C++ code requires MATLAB Coder™. For details, see Introduction to Code Generation.

Algorithms

  • For details of ensemble aggregation algorithms, see Ensemble Algorithms.

  • If you set Method to be a boosting algorithm and Learners to be decision trees, then the software grows shallow decision trees by default. You can adjust tree depth by specifying the MaxNumSplits, MinLeafSize, and MinParentSize name-value pair arguments using templateTree.

  • For bagging ('Method','Bag'), fitcensemble generates in-bag samples by oversampling classes with large misclassification costs and undersampling classes with small misclassification costs. Consequently, out-of-bag samples have fewer observations from classes with large misclassification costs and more observations from classes with small misclassification costs. If you train a classification ensemble using a small data set and a highly skewed cost matrix, then the number of out-of-bag observations per class can be low. Therefore, the estimated out-of-bag error can have a large variance and can be difficult to interpret. The same phenomenon can occur for classes with large prior probabilities.

  • For the RUSBoost ensemble aggregation method ('Method','RUSBoost'), the name-value pair argument RatioToSmallest specifies the sampling proportion for each class with respect to the lowest-represented class. For example, suppose that there are two classes in the training data: A and B. A have 100 observations and B have 10 observations. and that the lowest-represented class has m observations in the training data.

    • If you set 'RatioToSmallest',2, then s*m = 2*10 = 20. Consequently, fitcensemble trains every learner using 20 observations from class A and 20 observations from class B. If you set 'RatioToSmallest',[2 2], then you obtain the same result.

    • If you set 'RatioToSmallest',[2,1], then s1*m = 2*10 = 20 and s2*m = 1*10 = 10. Consequently, fitcensemble trains every learner using 20 observations from class A and 10 observations from class B.

  • For dual-core systems and above, fitcensemble parallelizes training using Intel® Threading Building Blocks (TBB). For details on Intel TBB, see https://software.intel.com/en-us/intel-tbb.

References

[1] Breiman, L. “Bagging Predictors.” Machine Learning. Vol. 26, pp. 123–140, 1996.

[2] Breiman, L. “Random Forests.” Machine Learning. Vol. 45, pp. 5–32, 2001.

[3] Freund, Y. “A more robust boosting algorithm.” arXiv:0905.2138v1, 2009.

[4] Freund, Y. and R. E. Schapire. “A Decision-Theoretic Generalization of On-Line Learning and an Application to Boosting.” J. of Computer and System Sciences, Vol. 55, pp. 119–139, 1997.

[5] Friedman, J. “Greedy function approximation: A gradient boosting machine.” Annals of Statistics, Vol. 29, No. 5, pp. 1189–1232, 2001.

[6] Friedman, J., T. Hastie, and R. Tibshirani. “Additive logistic regression: A statistical view of boosting.” Annals of Statistics, Vol. 28, No. 2, pp. 337–407, 2000.

[7] Hastie, T., R. Tibshirani, and J. Friedman. The Elements of Statistical Learning section edition, Springer, New York, 2008.

[8] Ho, T. K. “The random subspace method for constructing decision forests.” IEEE Transactions on Pattern Analysis and Machine Intelligence, Vol. 20, No. 8, pp. 832–844, 1998.

[9] Schapire, R. E., Y. Freund, P. Bartlett, and W.S. Lee. “Boosting the margin: A new explanation for the effectiveness of voting methods.” Annals of Statistics, Vol. 26, No. 5, pp. 1651–1686, 1998.

[10] Seiffert, C., T. Khoshgoftaar, J. Hulse, and A. Napolitano. “RUSBoost: Improving classification performance when training data is skewed.” 19th International Conference on Pattern Recognition, pp. 1–4, 2008.

[11] Warmuth, M., J. Liao, and G. Ratsch. “Totally corrective boosting algorithms that maximize the margin.” Proc. 23rd Int’l. Conf. on Machine Learning, ACM, New York, pp. 1001–1008, 2006.

Extended Capabilities

Introduced in R2016b