fit ensemble of learners for classification -凯发k8网页登录
fit ensemble of learners for classification
syntax
description
returns the trained classification ensemble model object
(mdl
= fitcensemble(tbl
,responsevarname
)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.
applies mdl
= fitcensemble(tbl
,formula
)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
.
uses additional options specified by one or more mdl
= fitcensemble(___,name,value
)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
train classification ensemble
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 = classificationensemble predictornames: {'age' 'workclass' 'fnlwgt' 'education' 'education_num' 'marital_status' 'occupation' 'relationship' 'race' 'sex' 'capital_gain' 'capital_loss' 'hours_per_week' 'native_country'} 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.
speed up training by binning numeric predictor values
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 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 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 nan
s, then the corresponding xbinned
values are nan
s.
estimate generalization error of boosting ensemble
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.0769
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 classification ensemble
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 | 2.8201 | 0.10256 | 0.10256 | rusboost | 11 | 0.010199 | 17 | | 2 | best | 0.082621 | 6.3089 | 0.082621 | 0.083414 | logitboost | 206 | 0.96537 | 33 | | 3 | accept | 0.099715 | 4.0004 | 0.082621 | 0.082624 | adaboostm1 | 130 | 0.0072814 | 2 | | 4 | best | 0.068376 | 1.5887 | 0.068376 | 0.068395 | bag | 25 | - | 5 | | 5 | best | 0.059829 | 1.7618 | 0.059829 | 0.062829 | logitboost | 58 | 0.19016 | 5 | | 6 | accept | 0.068376 | 1.6662 | 0.059829 | 0.065561 | logitboost | 58 | 0.10005 | 5 | | 7 | accept | 0.088319 | 13.07 | 0.059829 | 0.065786 | logitboost | 494 | 0.014474 | 3 | | 8 | accept | 0.065527 | 0.79673 | 0.059829 | 0.065894 | logitboost | 26 | 0.75515 | 8 | | 9 | accept | 0.15385 | 0.93354 | 0.059829 | 0.061156 | logitboost | 32 | 0.0010037 | 59 | | 10 | accept | 0.059829 | 3.8828 | 0.059829 | 0.059731 | logitboost | 143 | 0.44428 | 1 | | 11 | accept | 0.35897 | 2.3272 | 0.059829 | 0.059826 | bag | 54 | - | 175 | | 12 | accept | 0.068376 | 0.53634 | 0.059829 | 0.059825 | bag | 10 | - | 1 | | 13 | accept | 0.12251 | 9.5155 | 0.059829 | 0.059826 | adaboostm1 | 442 | 0.57897 | 102 | | 14 | accept | 0.11966 | 4.9323 | 0.059829 | 0.059827 | rusboost | 95 | 0.80822 | 1 | | 15 | accept | 0.062678 | 4.2429 | 0.059829 | 0.059826 | gentleboost | 156 | 0.99502 | 1 | | 16 | accept | 0.065527 | 3.0688 | 0.059829 | 0.059824 | gentleboost | 115 | 0.99693 | 13 | | 17 | best | 0.05698 | 1.659 | 0.05698 | 0.056997 | gentleboost | 60 | 0.0010045 | 3 | | 18 | accept | 0.13675 | 2.0647 | 0.05698 | 0.057002 | gentleboost | 86 | 0.0010263 | 108 | | 19 | accept | 0.062678 | 2.4037 | 0.05698 | 0.05703 | gentleboost | 88 | 0.6344 | 4 | | 20 | accept | 0.065527 | 1.029 | 0.05698 | 0.057228 | gentleboost | 35 | 0.0010155 | 1 | |===================================================================================================================================| | iter | eval | objective | objective | bestsofar | bestsofar | method | numlearningc-| learnrate | minleafsize | | | result | | runtime | (observed) | (estim.) | | ycles | | | |===================================================================================================================================| | 21 | accept | 0.079772 | 0.44308 | 0.05698 | 0.057214 | logitboost | 11 | 0.9796 | 2 | | 22 | accept | 0.065527 | 21.191 | 0.05698 | 0.057523 | bag | 499 | - | 1 | | 23 | accept | 0.068376 | 20.294 | 0.05698 | 0.057671 | bag | 494 | - | 2 | | 24 | accept | 0.64103 | 1.2793 | 0.05698 | 0.057468 | rusboost | 30 | 0.088421 | 174 | | 25 | accept | 0.088319 | 0.53606 | 0.05698 | 0.057456 | rusboost | 10 | 0.010292 | 5 | | 26 | accept | 0.074074 | 0.36802 | 0.05698 | 0.05753 | adaboostm1 | 11 | 0.14192 | 13 | | 27 | accept | 0.099715 | 12.133 | 0.05698 | 0.057646 | adaboostm1 | 498 | 0.0010096 | 6 | | 28 | accept | 0.079772 | 10.877 | 0.05698 | 0.057886 | adaboostm1 | 474 | 0.030547 | 31 | | 29 | accept | 0.068376 | 12.326 | 0.05698 | 0.061326 | gentleboost | 493 | 0.36142 | 2 | | 30 | accept | 0.065527 | 0.3945 | 0.05698 | 0.061165 | logitboost | 11 | 0.71408 | 16 |
__________________________________________________________ optimization completed. maxobjectiveevaluations of 30 reached. total function evaluations: 30 total elapsed time: 165.9329 seconds total objective function evaluation time: 148.4504 best observed feasible point: method numlearningcycles learnrate minleafsize ___________ _________________ _________ ___________ gentleboost 60 0.0010045 3 observed objective function value = 0.05698 estimated objective function value = 0.061165 function evaluation time = 1.659 best estimated feasible point (according to models): method numlearningcycles learnrate minleafsize ___________ _________________ _________ ___________ gentleboost 60 0.0010045 3 estimated objective function value = 0.061165 estimated function evaluation time = 1.6503
mdl = classificationensemble responsename: 'y' categoricalpredictors: [] classnames: {'b' 'g'} scoretransform: 'none' numobservations: 351 hyperparameteroptimizationresults: [1×1 bayesianoptimization] numtrained: 60 method: 'gentleboost' learnernames: {'tree'} reasonfortermination: 'terminated normally after completing the requested number of training cycles.' fitinfo: [60×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.
optimize classification ensemble using cross-validation
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:
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.
estimate the cross-validated misclassification rate of each ensemble.
for tree-complexity level , , 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.
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 . m is such that 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.05128
fprintf('\noptimal parameter values:\nnum. trees = %d',idxnumtrees);
optimal parameter values: num. trees = 130
fprintf('\nmaxnumsplits = %d\nlearning rate = %0.2f\n',... maxnumsplits(idxmns),learnrate(idxlr))
maxnumsplits = 9 learning rate = 1.00
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 = classificationensemble responsename: 'y' categoricalpredictors: [] classnames: {'b' 'g'} scoretransform: 'none' numobservations: 351 numtrained: 130 method: 'logitboost' learnernames: {'tree'} reasonfortermination: 'terminated normally after completing the requested number of training cycles.' fitinfo: [130×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.094017 | 3.7194 | 0.094017 | 0.094017 | 137 | 0.001364 | 3 | | 2 | accept | 0.12251 | 0.66511 | 0.094017 | 0.095735 | 15 | 0.013089 | 144 |
| 3 | best | 0.065527 | 0.90035 | 0.065527 | 0.067815 | 31 | 0.47201 | 2 | | 4 | accept | 0.19943 | 8.6107 | 0.065527 | 0.070015 | 340 | 0.92167 | 7 | | 5 | accept | 0.071225 | 0.90081 | 0.065527 | 0.065583 | 32 | 0.14422 | 2 | | 6 | accept | 0.099715 | 0.688 | 0.065527 | 0.065573 | 23 | 0.0010566 | 2 | | 7 | accept | 0.11681 | 0.90799 | 0.065527 | 0.065565 | 28 | 0.0010156 | 259 | | 8 | accept | 0.17379 | 0.82143 | 0.065527 | 0.065559 | 29 | 0.0013435 | 1 | | 9 | best | 0.059829 | 0.59677 | 0.059829 | 0.059844 | 18 | 0.87865 | 3 | | 10 | accept | 0.11111 | 0.40132 | 0.059829 | 0.059843 | 10 | 0.0012112 | 48 | | 11 | accept | 0.08547 | 0.41121 | 0.059829 | 0.059842 | 10 | 0.62108 | 25 | | 12 | accept | 0.11681 | 0.41538 | 0.059829 | 0.059841 | 10 | 0.0012154 | 20 | | 13 | accept | 0.082621 | 0.46504 | 0.059829 | 0.059842 | 10 | 0.55351 | 35 | | 14 | accept | 0.079772 | 0.46297 | 0.059829 | 0.05984 | 11 | 0.74109 | 74 | | 15 | accept | 0.088319 | 0.69297 | 0.059829 | 0.05984 | 19 | 0.91106 | 347 | | 16 | accept | 0.062678 | 0.3637 | 0.059829 | 0.059886 | 10 | 0.97239 | 3 | | 17 | accept | 0.065527 | 1.9404 | 0.059829 | 0.059887 | 78 | 0.97069 | 3 | | 18 | accept | 0.065527 | 0.39816 | 0.059829 | 0.062228 | 11 | 0.75051 | 2 | | 19 | best | 0.054131 | 0.36381 | 0.054131 | 0.059083 | 10 | 0.69072 | 3 | | 20 | accept | 0.065527 | 0.38429 | 0.054131 | 0.060938 | 10 | 0.64403 | 3 | |====================================================================================================================| | iter | eval | objective | objective | bestsofar | bestsofar | numlearningc-| learnrate | maxnumsplits | | | result | | runtime | (observed) | (estim.) | ycles | | | |====================================================================================================================| | 21 | accept | 0.079772 | 0.40405 | 0.054131 | 0.060161 | 10 | 0.80548 | 13 | | 22 | accept | 0.05698 | 0.37983 | 0.054131 | 0.059658 | 10 | 0.56949 | 5 | | 23 | accept | 0.10826 | 0.36128 | 0.054131 | 0.059244 | 10 | 0.0055133 | 5 | | 24 | accept | 0.074074 | 0.38056 | 0.054131 | 0.05933 | 10 | 0.92056 | 6 | | 25 | accept | 0.11966 | 0.35336 | 0.054131 | 0.059132 | 10 | 0.27254 | 1 | | 26 | accept | 0.065527 | 0.77041 | 0.054131 | 0.059859 | 26 | 0.97412 | 3 | | 27 | accept | 0.068376 | 0.38116 | 0.054131 | 0.060205 | 10 | 0.82146 | 4 | | 28 | accept | 0.062678 | 0.47015 | 0.054131 | 0.060713 | 14 | 0.99445 | 3 | | 29 | accept | 0.11966 | 0.41033 | 0.054131 | 0.060826 | 10 | 0.0012621 | 344 | | 30 | accept | 0.08547 | 0.45352 | 0.054131 | 0.060771 | 10 | 0.93676 | 187 |
__________________________________________________________ optimization completed. maxobjectiveevaluations of 30 reached. total function evaluations: 30 total elapsed time: 41.5854 seconds total objective function evaluation time: 28.4744 best observed feasible point: numlearningcycles learnrate maxnumsplits _________________ _________ ____________ 10 0.69072 3 observed objective function value = 0.054131 estimated objective function value = 0.061741 function evaluation time = 0.36381 best estimated feasible point (according to models): numlearningcycles learnrate maxnumsplits _________________ _________ ____________ 14 0.99445 3 estimated objective function value = 0.060771 estimated function evaluation time = 0.48009
mdl = classificationensemble responsename: 'y' categoricalpredictors: [] classnames: {'b' 'g'} scoretransform: 'none' numobservations: 351 hyperparameteroptimizationresults: [1×1 bayesianoptimization] numtrained: 14 method: 'logitboost' learnernames: {'tree'} reasonfortermination: 'terminated normally after completing the requested number of training cycles.' fitinfo: [14×1 double] fitinfodescription: {2×1 cell} properties, methods
input arguments
tbl
— sample data
table
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. multicolumn
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 usingresponsevarname
.if
tbl
contains the response variable, and you want to use a subset of the remaining variables only as predictors, then specify a formula usingformula
.if
tbl
does not contain the response variable, then specify the response data usingy
. the length of response variable and the number of rows oftbl
must be equal.
note
to save memory and execution time, supply x
and y
instead
of tbl
.
data types: table
responsevarname
— response variable name
name of response variable in tbl
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
formula
— explanatory model of response variable and subset of predictor variables
character vector | string scalar
explanatory model of the response variable 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.
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
.
the variable names in the formula must be both variable names in tbl
(tbl.properties.variablenames
) and valid matlab® identifiers. you can verify the variable names in tbl
by
using the isvarname
function. if the variable names
are not valid, then you can convert them by using the matlab.lang.makevalidname
function.
data types: char
| string
x
— predictor data
numeric matrix
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
y
— response data
categorical array | character array | string array | logical vector | numeric vector | cell array of character vectors
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 arguments
specify optional pairs of arguments as
name1=value1,...,namen=valuen
, where name
is
the argument name and value
is the corresponding value.
name-value arguments must appear after other arguments, but the order of the
pairs does not matter.
before r2021a, use commas to separate each name and value, and enclose
name
in quotes.
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 argument together with the
'optimizehyperparameters'
name-value argument. you can modify the
cross-validation for 'optimizehyperparameters'
only by using the
'hyperparameteroptimizationoptions'
name-value argument.
method
— ensemble aggregation method
'bag'
| 'subspace'
| 'adaboostm1'
| 'adaboostm2'
| 'gentleboost'
| 'logitboost'
| 'lpboost'
| 'robustboost'
| 'rusboost'
| 'totalboost'
ensemble aggregation method, specified as the comma-separated pair
consisting of 'method'
and one of the following
values.
value | method | classification problem support | related 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
value is
'all' or use discriminant
analysis learners. | binary and multiclass | n/a |
'subspace' | random subspace | binary and multiclass | npredtosample |
'adaboostm1' | adaptive boosting | binary only | learnrate |
'adaboostm2' | adaptive boosting | multiclass only | learnrate |
'gentleboost' | gentle adaptive boosting | binary only | learnrate |
'logitboost' | adaptive logistic regression | binary only | learnrate |
'lpboost' | linear programming boosting — requires optimization toolbox™ | binary and multiclass | marginprecision |
'robustboost' | robust boosting — requires optimization toolbox | binary only | robusterrorgoal ,
robustmarginsigma ,
robustmaxmargin |
'rusboost' | random undersampling boosting | binary and multiclass | learnrate ,
ratiotosmallest |
'totalboost' | totally corrective boosting — requires optimization toolbox | binary and multiclass | marginprecision |
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, , and .
example: 'method','bag'
numlearningcycles
— number of ensemble learning cycles
100
(default) | positive integer | 'allpredictorcombinations'
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 trainsnumlearningcycles*numel(learners)
learners.if you specify
'allpredictorcombinations'
, then setmethod
to'subspace'
and specify one learner only forlearners
. with these settings, the software trains learners for all possible combinations of predictors takennpredtosample
at a time. consequently, the software trains(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
learners
— weak learners to use in ensemble
'discriminant'
| 'knn'
| 'tree'
| weak-learner template object | cell vector of weak-learner template objects
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 learner | weak-learner name | template object creation function | method
setting |
---|---|---|---|
discriminant analysis | 'discriminant' | recommended for 'subspace' | |
k-nearest neighbors | 'knn' | for 'subspace' only | |
decision tree | 'tree' | all 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'learners','discriminant'
is the same as specifying'learners',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 (seenumlearningcycles
). for example, for an ensemble composed of two types of classification trees, supply{t1 t2}
, wheret1
andt2
are classification tree template objects returned bytemplatetree
.
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 () is
n–1
, wheren
is the number of observations. the number of predictors to select at random for each split () 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.
see for the
default settings of a weak learner. to obtain reproducible results, you
must specify the name-value pair argument of
templatetree
as true
if
'numvariablestosample'
is not
'all'
.
for details on the number of learners to train, see
numlearningcycles
and tips.
example: 'learners',templatetree('maxnumsplits',5)
nprint
— printout frequency
'off'
(default) | positive integer
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
), thenfitcensemble
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
for fastest training of some boosted decision trees, set nprint
to the
default value 'off'
. this tip holds when the classification
method
is 'adaboostm1'
,
'adaboostm2'
, 'gentleboost'
, or
'logitboost'
, or when the regression method
is
'lsboost'
.
example: 'nprint',5
data types: single
| double
| char
| string
numbins
— number of bins for numeric predictors
[]
(empty) (default) | positive integer scalar
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,
'learners'
is either 'tree'
or a template
object created by using .
if the
'numbins'
value is empty (default), thenfitcensemble
does not bin any predictors.if you specify the
'numbins'
value as a positive integer scalar (numbins
), thenfitcensemble
bins every numeric predictor into at mostnumbins
equiprobable bins, and then grows trees on the bin indices instead of the original data.the number of bins can be less than
numbins
if a predictor has fewer thannumbins
unique values.fitcensemble
does not bin categorical predictors.
when you use a large training data set, this binning option speeds up training but might cause
a potential decrease in accuracy. you can try 'numbins',50
first, and
then change the 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
categoricalpredictors
— categorical predictors list
vector of positive integers | logical vector | character matrix | string array | cell array of character vectors | 'all'
categorical predictors list, specified as one of the values in this table.
value | description |
---|---|
vector of positive integers |
each entry in the vector is an index value indicating that the corresponding predictor is
categorical. the index values are between 1 and if |
logical vector |
a |
character matrix | each 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 vectors | each 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'
specifies tree learners.'learners'
specifies k-nearest learners where all predictors are categorical.
each learner identifies and treats categorical predictors in the same way as
the fitting function corresponding to the learner. see 'categoricalpredictors'
of fitcknn
for k-nearest learners and 'categoricalpredictors'
of fitctree
for tree learners.
example: 'categoricalpredictors','all'
data types: single
| double
| logical
| char
| string
| cell
predictornames
— predictor variable names
string array of unique names | cell array of unique character vectors
predictor variable names, specified as 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
andy
, then you can usepredictornames
to assign names to the predictor variables inx
.the order of the names in
predictornames
must correspond to the column order ofx
. that is,predictornames{1}
is the name ofx(:,1)
,predictornames{2}
is the name ofx(:,2)
, and so on. also,size(x,2)
andnumel(predictornames)
must be equal.by default,
predictornames
is{'x1','x2',...}
.
if you supply
tbl
, then you can usepredictornames
to choose which predictor variables to use in training. that is,fitcensemble
uses only the predictor variables inpredictornames
and the response variable during training.predictornames
must be a subset oftbl.properties.variablenames
and cannot include the name of the response variable.by default,
predictornames
contains the names of all predictor variables.a good practice is to specify the predictors for training using either
predictornames
orformula
, but not both.
example: "predictornames",["sepallength","sepalwidth","petallength","petalwidth"]
data types: string
| cell
responsename
— response variable name
"y"
(default) | character vector | string scalar
response variable name, specified as a character vector or string scalar.
if you supply
y
, then you can useresponsename
to specify a name for the response variable.if you supply
responsevarname
orformula
, then you cannot useresponsename
.
example: "responsename","response"
data types: char
| string
options
— options for computing in parallel and setting random numbers
structure
options for computing in parallel and setting random numbers, specified as a structure. create
the options
structure with .
note
you need parallel computing toolbox™ to compute in parallel.
this table lists the option fields and their values.
field name | value | default |
---|---|---|
useparallel | set this value to | false |
usesubstreams | set this value to to compute reproducibly, set
| false |
streams | specify this value as a object or cell array of such objects. use a single object except when the useparallel value is true and the usesubstreams value is false . in that case, use a cell array that has the same size as the parallel pool. | if you do not specify streams , then fitcensemble uses the default stream or streams. |
for an example using reproducible parallel training, see .
for dual-core systems and above, fitcensemble
parallelizes
training using intel® threading building blocks (tbb). therefore, specifying the
useparallel
option as true
might not provide a
significant speedup on a single computer. for details on intel tbb, see .
example: 'options',statset('useparallel',true)
data types: struct
crossval
— cross-validation flag
'off'
(default) | 'on'
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 or .
example: 'crossval','on'
cvpartition
— cross-validation partition
[]
(default) | cvpartition
partition object
cross-validation partition, specified as 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 specify only one of these four name-value
arguments: 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
.
holdout
— fraction of data for holdout validation
scalar value in the range (0,1)
fraction of the data used for holdout validation, specified as a scalar value in the range
(0,1). if you specify 'holdout',p
, then the software completes these
steps:
randomly select and reserve
p*100
% of the data as validation data, and train the model using the rest of the data.store the compact, trained model in the
trained
property of the cross-validated model.
to create a cross-validated model, you can specify only one of these four name-value
arguments: cvpartition
, holdout
,
kfold
, or leaveout
.
example: 'holdout',0.1
data types: double
| single
kfold
— number of folds
10
(default) | positive integer value greater than 1
number of folds to use in a cross-validated model, specified as a positive integer value
greater than 1. if you specify 'kfold',k
, then the software completes
these steps:
randomly partition the data into
k
sets.for each set, reserve the set as validation data, and train the model using the other
k
– 1 sets.store the
k
compact, trained models in ak
-by-1 cell vector in thetrained
property of the cross-validated model.
to create a cross-validated model, you can specify only one of these four name-value
arguments: cvpartition
, holdout
,
kfold
, or leaveout
.
example: 'kfold',5
data types: single
| double
leaveout
— leave-one-out cross-validation flag
'off'
(default) | 'on'
leave-one-out cross-validation flag, specified as '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:
reserve the one observation as validation data, and train the model using the other n – 1 observations.
store the n compact, trained models in an n-by-1 cell vector in the
trained
property of the cross-validated model.
to create a cross-validated model, you can specify only one of these four name-value
arguments: cvpartition
, holdout
,
kfold
, or leaveout
.
example: 'leaveout','on'
classnames
— names of classes to use for training
categorical array | character array | string array | logical vector | numeric vector | cell array of character vectors
names of classes to use for training, specified as 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 the response variable
in tbl
or y
.
if classnames
is a character array, then each element must correspond to one row of the array.
use classnames
to:
specify the order of 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 ofcost
or the column order of classification scores returned bypredict
.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 the response variable in tbl
or y
.
example: "classnames",["b","g"]
data types: categorical
| char
| string
| logical
| single
| double
| cell
cost
— misclassification cost
square matrix | structure array
misclassification cost, specified as the comma-separated pair
consisting of 'cost'
and a square matrix or structure.
if you specify:
the square matrix
cost
, thencost(i,j)
is the cost of classifying a point into classj
if its true class isi
. 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 ofcost
, also specify theclassnames
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 asy
s.classificationcosts
, which contains the cost matrix with rows and columns ordered as ins.classnames
the default is ones(
, where k
) -
eye(k
)k
is
the number of distinct classes.
fitcensemble
uses cost
to adjust the prior
class probabilities specified in prior
. then,
fitcensemble
uses the adjusted prior probabilities for
training.
example: 'cost',[0 1 2 ; 1 0 2; 2 2 0]
data types: double
| single
| struct
prior
— prior probabilities
'empirical'
(default) | 'uniform'
| numeric vector | structure array
prior probabilities for each class, specified as the comma-separated
pair consisting of 'prior'
and a value in this
table.
value | description |
---|---|
'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 vector | each 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
|
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
scoretransform
— score transformation
"none"
(default) | "doublelogit"
| "invlogit"
| "ismax"
| "logit"
| function handle | ...
score transformation, specified as a character vector, string scalar, or function handle.
this table summarizes the available character vectors and string scalars.
value | description |
---|---|
"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 e–x) |
"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 e–x) – 1 |
for a matlab function or a function you define, use its function handle for the 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
weights
— observation weights
numeric vector of positive values | name of variable in tbl
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(
,
where n
,1)n
is the number of observations in x
or tbl
.
data types: double
| single
| char
| string
fresample
— fraction of training set to resample
1
(default) | positive scalar in (0,1]
fraction of the training set to resample for every weak learner, specified as a positive
scalar in (0,1]. to use 'fresample'
, set
resample
to 'on'
.
example: 'fresample',0.75
data types: single
| double
replace
— flag indicating to sample with replacement
'on'
(default) | 'off'
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 setresample
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'
resample
— flag indicating to resample
'off'
| 'on'
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 (seefresample
) with or without replacement (seereplace
).
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
.
learnrate
— learning rate for shrinkage
1
(default) | numeric scalar in (0,1]
learning rate for shrinkage, specified as the comma-separated pair consisting of
'learnrate'
and 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
learnrate
— learning rate for shrinkage
1
(default) | numeric scalar in (0,1]
learning rate for shrinkage, specified as the comma-separated pair consisting of
'learnrate'
and 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
ratiotosmallest
— sampling proportion with respect to lowest-represented class
positive numeric scalar | numeric vector of positive values
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
, thenfitcensemble
samples
observations from each class, that is, it uses the same sampling proportion for each class. for more details, see .s
*m
if you specify the numeric vector
[
, thens1
,s2
,...,sk
]fitcensemble
samples
observations from classsi
*m
i
,i
= 1,...,k. the elements ofratiotosmallest
correspond to the order of the class names specified usingclassnames
(see ).
the default value is ones(
,
which specifies to sample k
,1)m
observations
from each class.
example: 'ratiotosmallest',[2,1]
data types: single
| double
marginprecision
— margin precision to control convergence speed
0.1
(default) | numeric scalar in [0,1]
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
robusterrorgoal
— target classification error
0.1
(default) | nonnegative numeric scalar
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
robustmarginsigma
— classification margin distribution spread
0.1
(default) | positive numeric scalar
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, .
example: 'robustmarginsigma',0.5
data types: single
| double
robustmaxmargin
— maximal classification margin
0
(default) | nonnegative numeric scalar
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
npredtosample
— number of predictors to sample
1
(default) | positive integer
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
optimizehyperparameters
— parameters to optimize
'none'
(default) | 'auto'
| 'all'
| string array or cell array of eligible parameter names | vector of optimizablevariable
objects
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 specifiedlearners
: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
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 . to control the
cross-validation type and other aspects of the optimization, use the
hyperparameteroptimizationoptions
name-value
pair.
note
the values of 'optimizehyperparameters'
override any values you specify
using other name-value arguments. for example, setting
'optimizehyperparameters'
to 'auto'
causes
fitcensemble
to optimize hyperparameters corresponding to the
'auto'
option and to ignore any specified values for the
hyperparameters.
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'
.
numlearningcycles
—fitcensemble
searches among positive integers, by default log-scaled with range[10,500]
.learnrate
—fitcensemble
searches among positive reals, by default log-scaled with range[1e-3,1]
.the eligible hyperparameters for the chosen
learners
:learners eligible hyperparameters
bold = used by defaultdefault range 'discriminant'
delta
log-scaled in the range [1e-6,1e3]
discrimtype
'linear'
,'quadratic'
,'diaglinear'
,'diagquadratic'
,'pseudolinear'
, and'pseudoquadratic'
gamma
real values in [0,1]
'knn'
distance
'cityblock'
,'chebychev'
,'correlation'
,'cosine'
,'euclidean'
,'hamming'
,'jaccard'
,'mahalanobis'
,'minkowski'
,'seuclidean'
, and'spearman'
distanceweight
'equal'
,'inverse'
, and'squaredinverse'
exponent
positive values in [0.5,3]
numneighbors
positive integer values log-scaled in the range [1, max(2,round(numobservations/2))]
standardize
'true'
and'false'
'tree'
maxnumsplits
integers log-scaled in the range [1,max(2,numobservations-1)]
minleafsize
integers log-scaled in the range [1,max(2,floor(numobservations/2))]
numvariablestosample
integers in the range [1,max(2,numpredictors)]
splitcriterion
'gdi'
,'deviance'
, and'twoing'
alternatively, use with your chosen
learners
. note that you must specify the predictor data and response when creating anoptimizablevariable
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, the 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 the misclassification rate. to control the
iterative display, set the verbose
field of the
'hyperparameteroptimizationoptions'
name-value argument. to control the
plots, set the showplots
field of the
'hyperparameteroptimizationoptions'
name-value argument.
for an example, see optimize classification ensemble.
example: 'optimizehyperparameters',{'method','numlearningcycles','learnrate','minleafsize','maxnumsplits'}
hyperparameteroptimizationoptions
— options for optimization
structure
options for optimization, specified as a structure. this argument modifies the effect of the
optimizehyperparameters
name-value argument. all fields in the
structure are optional.
field name | values | default |
---|---|---|
optimizer |
| 'bayesopt' |
acquisitionfunctionname |
acquisition functions whose names include
| 'expected-improvement-per-second-plus' |
maxobjectiveevaluations | maximum number of objective function evaluations. | 30 for 'bayesopt' and
'randomsearch' , and the entire grid for
'gridsearch' |
maxtime | time limit, specified as a positive real scalar. the time limit is in seconds, as
measured by | inf |
numgriddivisions | for '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 |
showplots | logical value indicating whether to show plots. if true , this field plots
the best observed objective function value against the iteration number. if you
use bayesian optimization (optimizer is
'bayesopt' ), then this field also plots the best
estimated objective function value. the best observed objective function values
and best estimated objective function values correspond to the values in the
bestsofar (observed) and bestsofar
(estim.) columns of the iterative display, respectively. you can
find these values in the properties objectiveminimumtrace and estimatedobjectiveminimumtrace of
mdl.hyperparameteroptimizationresults . if the problem
includes one or two optimization parameters for bayesian optimization, then
showplots also plots a model of the objective function
against the parameters. | true |
saveintermediateresults | logical 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 at the command line:
for details, see the | 1 |
useparallel | logical value indicating whether to run bayesian optimization in parallel, which requires parallel computing toolbox. due to the nonreproducibility of parallel timing, parallel bayesian optimization does not necessarily yield reproducible results. for details, see . | false |
repartition | logical value indicating whether to repartition the cross-validation at every
iteration. if this field is the setting
| false |
use no more than one of the following three options. | ||
cvpartition | a cvpartition object, as created by cvpartition | 'kfold',5 if you do not specify a cross-validation
field |
holdout | a scalar in the range (0,1) representing the holdout fraction | |
kfold | an integer greater than 1 |
example: 'hyperparameteroptimizationoptions',struct('maxobjectiveevaluations',60)
data types: struct
output arguments
mdl
— trained classification ensemble model
classificationbaggedensemble
model object | classificationensemble
model object | classificationpartitionedensemble
cross-validated
model object
trained ensemble model, returned as one of the model objects in this table.
model object | specify any cross-validation options? | method
setting | resample
setting |
---|---|---|---|
no | 'bag' | 'on' | |
no | any ensemble aggregation method for classification | 'off' | |
yes | any 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 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 of1
forfresample
.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 usingprior
.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 variableclassnames
.assignsycat = categorical(y); classnames = categories(ycat)
to unclassified observations and excludes
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 inclassnameslh
.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 .
if you set
method
to be a boosting algorithm andlearners
to be decision trees, then the software grows shallow decision trees by default. you can adjust tree depth by specifying themaxnumsplits
,minleafsize
, andminparentsize
name-value pair arguments using .if you specify the
cost
,prior
, andweights
name-value arguments, the output model object stores the specified values in thecost
,prior
, andw
properties, respectively. thecost
property stores the user-specified cost matrix (c) without modification. theprior
andw
properties store the prior probabilities and observation weights, respectively, after normalization. for model training, the software updates the prior probabilities and observation weights to incorporate the penalties described in the cost matrix. for details, see .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 argumentratiotosmallest
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 has 100 observations and b has 10 observations. suppose also that the lowest-represented class hasm
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 .
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
automatic parallel support
accelerate code by automatically running computation in parallel using parallel computing toolbox™.
fitcensemble
supports parallel training
using the 'options'
name-value argument. create options using , such as options = statset('useparallel',true)
.
parallel ensemble training requires you to set the 'method'
name-value
argument to 'bag'
. parallel training is available only for tree learners, the
default type for 'bag'
.
to perform parallel hyperparameter optimization, use the
'hyperparameteroptimizationoptions', struct('useparallel',true)
name-value argument in the call to the fitcensemble
function.
for more information on parallel hyperparameter optimization, see .
for general information about parallel computing, see (parallel computing toolbox).
gpu arrays
accelerate code by running on a graphics processing unit (gpu) using parallel computing toolbox™.
usage notes and limitations:
fitcensemble
supports only decision tree learners. you can specify the name-value argumentlearners
only as"tree"
, a learner template object or cell vector of learner template objects created bytemplatetree
. if you usetemplatetree
, you can specify the name-value argumentssurrogate
andpredictorselection
only as"off"
and"allsplits"
, respectively.you can specify the name-value argument
method
only as"adaboostm1"
,"adaboostm2"
,"gentleboost"
,"logitboost"
, or"rusboost"
.you cannot specify the name-value argument
npredtosample
.if you use
templatetree
and the data contains categorical predictors, the following apply:for multiclass classification,
fitcensemble
supports only theovabyclass
algorithm for finding the best split.you can specify the name-value argument
numvariablestosample
only as"all"
.
fitcensemble
fits the model on a gpu if either of the following apply:the input argument
x
is agpuarray
object.the input argument
tbl
containsgpuarray
predictor variables.
if you use
templatetree
to specifymaxnumsplits
, note thatfitcensemble
might not execute faster on a gpu than a cpu for deeper decision trees.
version history
introduced in r2016b
see also
| | | | | |
topics
打开示例
您曾对此示例进行过修改。是否要打开带有您的编辑的示例?
matlab 命令
您点击的链接对应于以下 matlab 命令:
请在 matlab 命令行窗口中直接输入以执行命令。web 浏览器不支持 matlab 命令。
select a web site
choose a web site to get translated content where available and see local events and offers. based on your location, we recommend that you select: .
you can also select a web site from the following list:
how to get best site performance
select the china site (in chinese or english) for best site performance. other mathworks country sites are not optimized for visits from your location.
americas
- (español)
- (english)
- (english)
europe
- (english)
- (english)
- (deutsch)
- (español)
- (english)
- (français)
- (english)
- (italiano)
- (english)
- (english)
- (english)
- (deutsch)
- (english)
- (english)
- switzerland
- (english)
asia pacific
- (english)
- (english)
- (english)
- 中国
- (日本語)
- (한국어)