fit multiclass models for support vector machines or other classifiers -凯发k8网页登录
fit multiclass models for support vector machines or other classifiers
syntax
description
returns
a full, trained, multiclass, error-correcting
output codes (ecoc) model using the predictors in table mdl
= fitcecoc(tbl
,responsevarname
)tbl
and
the class labels in tbl.responsevarname
. fitcecoc
uses k(k –
1)/2 binary support vector machine (svm) models using the one-versus-one coding design, where k is
the number of unique class labels (levels). mdl
is
a classificationecoc
model.
returns
an ecoc model with additional options specified by one or more mdl
= fitcecoc(___,name,value
)name,value
pair
arguments, using any of the previous syntaxes.
for example, specify different binary learners, a different
coding design, or to cross-validate. it is good practice to cross-validate
using the kfold
name,value
pair
argument. the cross-validation results determine how well the model
generalizes.
[
also returns hyperparameter optimization details when you specify the
mdl
,hyperparameteroptimizationresults
]
= fitcecoc(___,name,value
)optimizehyperparameters
name-value pair argument and
use linear or kernel binary learners. for other learners
,
the hyperparameteroptimizationresults
property of
mdl
contains the results.
examples
train multiclass model using svm learners
train a multiclass error-correcting output codes (ecoc) model using support vector machine (svm) binary learners.
load fisher's iris data set. specify the predictor data x
and the response data y
.
load fisheriris
x = meas;
y = species;
train a multiclass ecoc model using the default options.
mdl = fitcecoc(x,y)
mdl = classificationecoc responsename: 'y' categoricalpredictors: [] classnames: {'setosa' 'versicolor' 'virginica'} scoretransform: 'none' binarylearners: {3x1 cell} codingname: 'onevsone' properties, methods
mdl
is a classificationecoc
model. by default, fitcecoc
uses svm binary learners and a one-versus-one coding design. you can access mdl
properties using dot notation.
display the class names and the coding design matrix.
mdl.classnames
ans = 3x1 cell
{'setosa' }
{'versicolor'}
{'virginica' }
codingmat = mdl.codingmatrix
codingmat = 3×3
1 1 0
-1 0 1
0 -1 -1
a one-versus-one coding design for three classes yields three binary learners. the columns of codingmat
correspond to the learners, and the rows correspond to the classes. the class order is the same as the order in mdl.classnames
. for example, codingmat(:,1)
is [1; –1; 0]
and indicates that the software trains the first svm binary learner using all observations classified as 'setosa'
and 'versicolor'
. because 'setosa'
corresponds to 1
, it is the positive class; 'versicolor'
corresponds to –1
, so it is the negative class.
you can access each binary learner using cell indexing and dot notation.
mdl.binarylearners{1} % the first binary learner
ans = compactclassificationsvm responsename: 'y' categoricalpredictors: [] classnames: [-1 1] scoretransform: 'none' beta: [4x1 double] bias: 1.4505 kernelparameters: [1x1 struct] properties, methods
compute the resubstitution classification error.
error = resubloss(mdl)
error = 0.0067
the classification error on the training data is small, but the classifier might be an overfitted model. you can cross-validate the classifier using crossval
and compute the cross-validation classification error instead.
train multiclass linear classification model
train an ecoc model composed of multiple binary, linear classification models.
load the nlp data set.
load nlpdata
x
is a sparse matrix of predictor data, and y
is a categorical vector of class labels. there are more than two classes in the data.
create a default linear-classification-model template.
t = templatelinear();
to adjust the default values, see the name-value pair arguments on templatelinear
page.
train an ecoc model composed of multiple binary, linear classification models that can identify the product given the frequency distribution of words on a documentation web page. for faster training time, transpose the predictor data, and specify that observations correspond to columns.
x = x'; rng(1); % for reproducibility mdl = fitcecoc(x,y,'learners',t,'observationsin','columns')
mdl = compactclassificationecoc responsename: 'y' classnames: [comm dsp ecoder fixedpoint hdlcoder phased physmod simulink stats supportpkg symbolic vision xpc] scoretransform: 'none' binarylearners: {78x1 cell} codingmatrix: [13x78 double] properties, methods
alternatively, you can train an ecoc model composed of default linear classification models using 'learners','linear'
.
to conserve memory, fitcecoc
returns trained ecoc models composed of linear classification learners in compactclassificationecoc
model objects.
cross-validate ecoc classifier
cross-validate an ecoc classifier with svm binary learners, and estimate the generalized classification error.
load fisher's iris data set. specify the predictor data x
and the response data y
.
load fisheriris x = meas; y = species; rng(1); % for reproducibility
create an svm template, and standardize the predictors.
t = templatesvm('standardize',true)
t = fit template for classification svm. alpha: [0x1 double] boxconstraint: [] cachesize: [] cachingmethod: '' clipalphas: [] deltagradienttolerance: [] epsilon: [] gaptolerance: [] kkttolerance: [] iterationlimit: [] kernelfunction: '' kernelscale: [] kerneloffset: [] kernelpolynomialorder: [] numprint: [] nu: [] outlierfraction: [] removeduplicates: [] shrinkageperiod: [] solver: '' standardizedata: 1 savesupportvectors: [] verbositylevel: [] version: 2 method: 'svm' type: 'classification'
t
is an svm template. most of the template object properties are empty. when training the ecoc classifier, the software sets the applicable properties to their default values.
train the ecoc classifier, and specify the class order.
mdl = fitcecoc(x,y,'learners',t,... 'classnames',{'setosa','versicolor','virginica'});
mdl
is a classificationecoc
classifier. you can access its properties using dot notation.
cross-validate mdl
using 10-fold cross-validation.
cvmdl = crossval(mdl);
cvmdl
is a classificationpartitionedecoc
cross-validated ecoc classifier.
estimate the generalized classification error.
generror = kfoldloss(cvmdl)
generror = 0.0400
the generalized classification error is 4%, which indicates that the ecoc classifier generalizes fairly well.
estimate posterior probabilities using ecoc classifier
train an ecoc classifier using svm binary learners. first predict the training-sample labels and class posterior probabilities. then predict the maximum class posterior probability at each point in a grid. visualize the results.
load fisher's iris data set. specify the petal dimensions as the predictors and the species names as the response.
load fisheriris x = meas(:,3:4); y = species; rng(1); % for reproducibility
create an svm template. standardize the predictors, and specify the gaussian kernel.
t = templatesvm('standardize',true,'kernelfunction','gaussian');
t
is an svm template. most of its properties are empty. when the software trains the ecoc classifier, it sets the applicable properties to their default values.
train the ecoc classifier using the svm template. transform classification scores to class posterior probabilities (which are returned by predict
or resubpredict
) using the 'fitposterior'
name-value pair argument. specify the class order using the 'classnames'
name-value pair argument. display diagnostic messages during training by using the 'verbose'
name-value pair argument.
mdl = fitcecoc(x,y,'learners',t,'fitposterior',true,... 'classnames',{'setosa','versicolor','virginica'},... 'verbose',2);
training binary learner 1 (svm) out of 3 with 50 negative and 50 positive observations. negative class indices: 2 positive class indices: 1 fitting posterior probabilities for learner 1 (svm). training binary learner 2 (svm) out of 3 with 50 negative and 50 positive observations. negative class indices: 3 positive class indices: 1 fitting posterior probabilities for learner 2 (svm). training binary learner 3 (svm) out of 3 with 50 negative and 50 positive observations. negative class indices: 3 positive class indices: 2 fitting posterior probabilities for learner 3 (svm).
mdl
is a classificationecoc
model. the same svm template applies to each binary learner, but you can adjust options for each binary learner by passing in a cell vector of templates.
predict the training-sample labels and class posterior probabilities. display diagnostic messages during the computation of labels and class posterior probabilities by using the 'verbose'
name-value pair argument.
[label,~,~,posterior] = resubpredict(mdl,'verbose',1);
predictions from all learners have been computed. loss for all observations has been computed. computing posterior probabilities...
mdl.binaryloss
ans = 'quadratic'
the software assigns an observation to the class that yields the smallest average binary loss. because all binary learners are computing posterior probabilities, the binary loss function is quadratic
.
display a random set of results.
idx = randsample(size(x,1),10,1); mdl.classnames
ans = 3x1 cell
{'setosa' }
{'versicolor'}
{'virginica' }
table(y(idx),label(idx),posterior(idx,:),... 'variablenames',{'truelabel','predlabel','posterior'})
ans=10×3 table
truelabel predlabel posterior
______________ ______________ ______________________________________
{'virginica' } {'virginica' } 0.0039322 0.003987 0.99208
{'virginica' } {'virginica' } 0.017067 0.018263 0.96467
{'virginica' } {'virginica' } 0.014948 0.015856 0.9692
{'versicolor'} {'versicolor'} 2.2197e-14 0.87318 0.12682
{'setosa' } {'setosa' } 0.999 0.00025092 0.00074638
{'versicolor'} {'virginica' } 2.2195e-14 0.05943 0.94057
{'versicolor'} {'versicolor'} 2.2194e-14 0.97001 0.029985
{'setosa' } {'setosa' } 0.999 0.00024991 0.0007474
{'versicolor'} {'versicolor'} 0.0085642 0.98259 0.0088487
{'setosa' } {'setosa' } 0.999 0.00025013 0.00074717
the columns of posterior
correspond to the class order of mdl.classnames
.
define a grid of values in the observed predictor space. predict the posterior probabilities for each instance in the grid.
xmax = max(x); xmin = min(x); x1pts = linspace(xmin(1),xmax(1)); x2pts = linspace(xmin(2),xmax(2)); [x1grid,x2grid] = meshgrid(x1pts,x2pts); [~,~,~,posteriorregion] = predict(mdl,[x1grid(:),x2grid(:)]);
for each coordinate on the grid, plot the maximum class posterior probability among all classes.
contourf(x1grid,x2grid,... reshape(max(posteriorregion,[],2),size(x1grid,1),size(x1grid,2))); h = colorbar; h.ylabel.string = 'maximum posterior'; h.ylabel.fontsize = 15; hold on gh = gscatter(x(:,1),x(:,2),y,'krk','*xd',8); gh(2).linewidth = 2; gh(3).linewidth = 2; title('iris petal measurements and maximum posterior') xlabel('petal length (cm)') ylabel('petal width (cm)') axis tight legend(gh,'location','northwest') hold off
speed up training ecoc classifiers using binning and parallel computing
this example uses:
train a one-versus-all ecoc classifier using a gentleboost
ensemble of decision trees with surrogate splits. to speed up training, bin numeric predictors and use parallel computing. binning is valid only when fitcecoc
uses a tree learner. after training, estimate the classification error using 10-fold cross-validation. note that parallel computing requires parallel computing toolbox™.
load sample data
load and inspect the arrhythmia
data set.
load arrhythmia
[n,p] = size(x)
n = 452
p = 279
islabels = unique(y); nlabels = numel(islabels)
nlabels = 13
tabulate(categorical(y))
value count percent 1 245 54.20% 2 44 9.73% 3 15 3.32% 4 15 3.32% 5 13 2.88% 6 25 5.53% 7 3 0.66% 8 2 0.44% 9 9 1.99% 10 50 11.06% 14 4 0.88% 15 5 1.11% 16 22 4.87%
the data set contains 279
predictors, and the sample size of 452
is relatively small. of the 16 distinct labels, only 13 are represented in the response (y
). each label describes various degrees of arrhythmia, and 54.20% of the observations are in class 1
.
train one-versus-all ecoc classifier
create an ensemble template. you must specify at least three arguments: a method, a number of learners, and the type of learner. for this example, specify 'gentleboost'
for the method, 100
for the number of learners, and a decision tree template that uses surrogate splits because there are missing observations.
ttree = templatetree('surrogate','on'); tensemble = templateensemble('gentleboost',100,ttree);
tensemble
is a template object. most of its properties are empty, but the software fills them with their default values during training.
train a one-versus-all ecoc classifier using the ensembles of decision trees as binary learners. to speed up training, use binning and parallel computing.
binning (
'numbins',50
) — when you have a large training data set, you can speed up training (a potential decrease in accuracy) by using the'numbins'
name-value pair argument. this argument is valid only whenfitcecoc
uses a tree learner. if you specify the'numbins'
value, 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. you can try'numbins',50
first, and then change the'numbins'
value depending on the accuracy and training speed.parallel computing (
'options',statset('useparallel',true)
) — with a parallel computing toolbox license, you can speed up the computation by using parallel computing, which sends each binary learner to a worker in the pool. the number of workers depends on your system configuration. when you use decision trees for binary learners,fitcecoc
parallelizes training using intel® threading building blocks (tbb) for dual-core systems and above. therefore, specifying the'useparallel'
option is not helpful on a single computer. use this option on a cluster.
additionally, specify that the prior probabilities are 1/k, where k = 13 is the number of distinct classes.
options = statset('useparallel',true); mdl = fitcecoc(x,y,'coding','onevsall','learners',tensemble,... 'prior','uniform','numbins',50,'options',options);
starting parallel pool (parpool) using the 'local' profile ... connected to the parallel pool (number of workers: 6).
mdl
is a classificationecoc
model.
cross-validation
cross-validate the ecoc classifier using 10-fold cross-validation.
cvmdl = crossval(mdl,'options',options);
warning: one or more folds do not contain points from all the groups.
cvmdl
is a classificationpartitionedecoc
model. the warning indicates that some classes are not represented while the software trains at least one fold. therefore, those folds cannot predict labels for the missing classes. you can inspect the results of a fold using cell indexing and dot notation. for example, access the results of the first fold by entering cvmdl.trained{1}
.
use the cross-validated ecoc classifier to predict validation-fold labels. you can compute the confusion matrix by using . move and resize the chart by changing the inner position property to ensure that the percentages appear in the row summary.
ooflabel = kfoldpredict(cvmdl,'options',options); confmat = confusionchart(y,ooflabel,'rowsummary','total-normalized'); confmat.innerposition = [0.10 0.12 0.85 0.85];
reproduce binned data
reproduce binned predictor data by using the binedges
property of the trained model and the function.
x = mdl.x; % predictor data xbinned = zeros(size(x)); edges = mdl.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.
optimize ecoc classifier
optimize hyperparameters automatically using fitcecoc
.
load the fisheriris
data set.
load fisheriris
x = meas;
y = species;
find hyperparameters that minimize five-fold cross-validation loss by using automatic hyperparameter optimization. for reproducibility, set the random seed and use the 'expected-improvement-plus'
acquisition function.
rng default mdl = fitcecoc(x,y,'optimizehyperparameters','auto',... 'hyperparameteroptimizationoptions',struct('acquisitionfunctionname',... 'expected-improvement-plus'))
|====================================================================================================================| | iter | eval | objective | objective | bestsofar | bestsofar | coding | boxconstraint| kernelscale | | | result | | runtime | (observed) | (estim.) | | | | |====================================================================================================================| | 1 | best | 0.10667 | 1.8617 | 0.10667 | 0.10667 | onevsone | 5.6939 | 200.36 | | 2 | best | 0.046667 | 3.3373 | 0.046667 | 0.049769 | onevsone | 94.849 | 0.0032549 | | 3 | accept | 0.08 | 0.4551 | 0.046667 | 0.049209 | onevsall | 0.01378 | 0.076021 | | 4 | accept | 0.08 | 0.33126 | 0.046667 | 0.047942 | onevsall | 889 | 38.798 | | 5 | accept | 0.046667 | 1.8781 | 0.046667 | 0.046652 | onevsone | 2.1285 | 0.0027554 | | 6 | best | 0.04 | 0.46065 | 0.04 | 0.040219 | onevsone | 0.0020155 | 0.0010001 | | 7 | accept | 0.046667 | 2.0586 | 0.04 | 0.043609 | onevsone | 0.4143 | 0.0010032 | | 8 | accept | 0.04 | 0.29713 | 0.04 | 0.039781 | onevsone | 0.0010403 | 0.0010304 | | 9 | accept | 0.046667 | 1.6647 | 0.04 | 0.039758 | onevsone | 993.63 | 0.064389 | | 10 | accept | 0.046667 | 0.5751 | 0.04 | 0.039752 | onevsone | 0.0010072 | 0.01665 | | 11 | accept | 0.04 | 0.48179 | 0.04 | 0.039716 | onevsone | 0.0010394 | 0.0018643 | | 12 | accept | 0.04 | 0.38461 | 0.04 | 0.039928 | onevsone | 0.001014 | 0.0010761 | | 13 | accept | 0.33333 | 0.36364 | 0.04 | 0.039747 | onevsall | 0.0010661 | 982.42 | | 14 | accept | 0.04 | 0.44782 | 0.04 | 0.039738 | onevsall | 932.91 | 2.9173 | | 15 | accept | 0.41333 | 12.776 | 0.04 | 0.039864 | onevsall | 929.37 | 0.0010004 | | 16 | accept | 0.04 | 0.29786 | 0.04 | 0.039887 | onevsone | 913.75 | 2.7842 | | 17 | accept | 0.33333 | 0.76909 | 0.04 | 0.040013 | onevsall | 0.0011214 | 0.57694 | | 18 | accept | 0.04 | 0.56909 | 0.04 | 0.039829 | onevsall | 0.62669 | 0.096307 | | 19 | accept | 0.06 | 0.33527 | 0.04 | 0.039941 | onevsall | 744.9 | 7.5881 | | 20 | accept | 0.10667 | 0.40723 | 0.04 | 0.039948 | onevsone | 0.0010766 | 2.5209 | |====================================================================================================================| | iter | eval | objective | objective | bestsofar | bestsofar | coding | boxconstraint| kernelscale | | | result | | runtime | (observed) | (estim.) | | | | |====================================================================================================================| | 21 | accept | 0.14667 | 8.8584 | 0.04 | 0.040006 | onevsall | 979.04 | 0.15295 | | 22 | accept | 0.046667 | 4.0229 | 0.04 | 0.040008 | onevsall | 0.023947 | 0.0032873 | | 23 | accept | 0.046667 | 0.50241 | 0.04 | 0.040005 | onevsone | 6.3496 | 0.46716 | | 24 | accept | 0.046667 | 0.7856 | 0.04 | 0.040003 | onevsall | 0.091577 | 0.019408 | | 25 | accept | 0.046667 | 3.4279 | 0.04 | 0.040002 | onevsall | 0.001022 | 0.0010928 | | 26 | accept | 0.046667 | 0.4446 | 0.04 | 0.040001 | onevsall | 29.705 | 1.0323 | | 27 | accept | 0.10667 | 0.29157 | 0.04 | 0.040001 | onevsone | 959.24 | 989.48 | | 28 | accept | 0.04 | 0.46752 | 0.04 | 0.040003 | onevsone | 0.16662 | 0.04099 | | 29 | accept | 0.10667 | 0.67695 | 0.04 | 0.040004 | onevsone | 0.0010206 | 959.92 | | 30 | accept | 0.04 | 0.80142 | 0.04 | 0.040004 | onevsall | 0.0028825 | 0.0053013 |
__________________________________________________________ optimization completed. maxobjectiveevaluations of 30 reached. total function evaluations: 30 total elapsed time: 65.9019 seconds total objective function evaluation time: 50.0309 best observed feasible point: coding boxconstraint kernelscale ________ _____________ ___________ onevsone 0.0020155 0.0010001 observed objective function value = 0.04 estimated objective function value = 0.039977 function evaluation time = 0.46065 best estimated feasible point (according to models): coding boxconstraint kernelscale ________ _____________ ___________ onevsone 0.001014 0.0010761 estimated objective function value = 0.040004 estimated function evaluation time = 0.37201
mdl = classificationecoc responsename: 'y' categoricalpredictors: [] classnames: {'setosa' 'versicolor' 'virginica'} scoretransform: 'none' binarylearners: {3x1 cell} codingname: 'onevsone' hyperparameteroptimizationresults: [1x1 bayesianoptimization] properties, methods
train multiclass ecoc model with svms and tall arrays
create two multiclass ecoc models trained on tall data. use linear binary learners for one of the models and kernel binary learners for the other. compare the resubstitution classification error of the two models.
in general, you can perform multiclass classification of tall data by using fitcecoc
with linear or kernel binary learners. when you use fitcecoc
to train a model on tall arrays, you cannot use svm binary learners directly. however, you can use either linear or kernel binary classification models that use svms.
when you perform calculations on tall arrays, matlab® uses either a parallel pool (default if you have parallel computing toolbox™) or the local matlab session. if you want to run the example using the local matlab session when you have parallel computing toolbox, you can change the global execution environment by using the function.
create a datastore that references the folder containing fisher's iris data set. specify 'na'
values as missing data so that datastore
replaces them with nan
values. create tall versions of the predictor and response data.
ds = datastore('fisheriris.csv','treatasmissing','na'); t = tall(ds);
starting parallel pool (parpool) using the 'local' profile ... connected to the parallel pool (number of workers: 6).
x = [t.sepallength t.sepalwidth t.petallength t.petalwidth]; y = t.species;
standardize the predictor data.
z = zscore(x);
train a multiclass ecoc model that uses tall data and linear binary learners. by default, when you pass tall arrays to fitcecoc
, the software trains linear binary learners that use svms. because the response data contains only three unique classes, change the coding scheme from one-versus-all (which is the default when you use tall data) to one-versus-one (which is the default when you use in-memory data).
for reproducibility, set the seeds of the random number generators using rng
and tallrng
. the results can vary depending on the number of workers and the execution environment for the tall arrays. for details, see .
rng('default') tallrng('default') mdllinear = fitcecoc(z,y,'coding','onevsone')
training binary learner 1 (linear) out of 3. training binary learner 2 (linear) out of 3. training binary learner 3 (linear) out of 3.
mdllinear = compactclassificationecoc responsename: 'y' classnames: {'setosa' 'versicolor' 'virginica'} scoretransform: 'none' binarylearners: {3×1 cell} codingmatrix: [3×3 double] properties, methods
mdllinear
is a compactclassificationecoc
model composed of three binary learners.
train a multiclass ecoc model that uses tall data and kernel binary learners. first, create a templatekernel
object to specify the properties of the kernel binary learners; in particular, increase the number of expansion dimensions to .
tkernel = templatekernel('numexpansiondimensions',2^16)
tkernel = fit template for classification kernel. betatolerance: [] blocksize: [] boxconstraint: [] epsilon: [] numexpansiondimensions: 65536 gradienttolerance: [] hessianhistorysize: [] iterationlimit: [] kernelscale: [] lambda: [] learner: 'svm' lossfunction: [] stream: [] verbositylevel: [] version: 1 method: 'kernel' type: 'classification'
by default, the kernel binary learners use svms.
pass the templatekernel
object to fitcecoc
and change the coding scheme to one-versus-one.
mdlkernel = fitcecoc(z,y,'learners',tkernel,'coding','onevsone')
training binary learner 1 (kernel) out of 3. training binary learner 2 (kernel) out of 3. training binary learner 3 (kernel) out of 3.
mdlkernel = compactclassificationecoc responsename: 'y' classnames: {'setosa' 'versicolor' 'virginica'} scoretransform: 'none' binarylearners: {3×1 cell} codingmatrix: [3×3 double] properties, methods
mdlkernel
is also a compactclassificationecoc
model composed of three binary learners.
compare the resubstitution classification error of the two models.
errorlinear = gather(loss(mdllinear,z,y))
evaluating tall expression using the parallel pool 'local': - pass 1 of 1: completed in 1.4 sec evaluation completed in 1.6 sec
errorlinear = 0.0333
errorkernel = gather(loss(mdlkernel,z,y))
evaluating tall expression using the parallel pool 'local': - pass 1 of 1: completed in 15 sec evaluation completed in 16 sec
errorkernel = 0.0067
mdlkernel
misclassifies a smaller percentage of the training data than mdllinear
.
input arguments
tbl
— sample data
table
sample data, specified as a table. each row of tbl
corresponds
to one observation, and each column corresponds to one predictor.
optionally, tbl
can contain one additional column
for the response variable. multicolumn variables and cell arrays other
than cell arrays of character vectors are not accepted.
if tbl
contains the response variable, and
you want to use all remaining variables in tbl
as
predictors, then specify the response variable using responsevarname
.
if tbl
contains the response variable, and
you want to use only a subset of the remaining variables in tbl
as
predictors, specify a formula using formula
.
if tbl
does not contain the response variable,
specify a response variable using y
. the length
of response variable and the number of tbl
rows
must be equal.
data types: table
responsevarname
— response variable name
name of variable in tbl
response variable name, specified as the name of a variable in
tbl
.
you must specify responsevarname
as a character vector or string scalar.
for example, if the response variable y
is
stored as tbl.y
, then specify it as
"y"
. otherwise, the software
treats all columns of tbl
, including
y
, as predictors when training
the model.
the response variable must be a categorical, character, or string array; a logical or numeric
vector; or a cell array of character vectors. if
y
is a character array, then each
element of the response variable must correspond to one row of
the array.
a good practice is to specify the order of the classes by using the
classnames
name-value
argument.
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
y
— class labels
categorical array | character array | string array | logical vector | numeric vector | cell array of character vectors
class labels to which the ecoc model is trained, specified as a categorical, character, or string array, logical or numeric vector, or cell array of character vectors.
if y
is a character array, then each element
must correspond to one row of the array.
the length of y
and the number of rows of tbl
or x
must
be equal.
it is good practice to specify the class order using the classnames
name-value
pair argument.
data types: categorical
| char
| string
| logical
| single
| double
| cell
x
— predictor data
full matrix | sparse matrix
predictor data, specified as a full or sparse matrix.
the length of y
and the number of observations
in 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.
note
for linear classification learners, if you orient
x
so that observations correspond to columns and specify'observationsin','columns'
, then you can experience a significant reduction in optimization-execution time.for all other learners, orient
x
so that observations correspond to rows.fitcecoc
supports sparse matrices for training linear classification models only.
data types: double
| single
note
the software treats nan
, empty character vector
(''
), empty string (""
),
, and
elements as missing data. the software removes rows of x
corresponding to missing values in y
. however, the treatment of
missing values in x
varies among binary learners. for details,
see the training functions for your binary learners: fitcdiscr
, , fitcknn
, fitclinear
, fitcnb
, fitcsvm
, fitctree
, or fitcensemble
. removing observations decreases the effective training
or cross-validation sample size.
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: 'learners','tree','coding','onevsone','crossval','on'
specifies to use decision trees for all binary learners, a one-versus-one coding
design, and to implement 10-fold cross-validation.
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.
coding
— coding design
'onevsone'
(default) | 'allpairs'
| 'binarycomplete'
| 'denserandom'
| 'onevsall'
| 'ordinal'
| 'sparserandom'
| 'ternarycomplete'
| numeric matrix
coding design name, specified as the comma-separated pair consisting
of 'coding'
and a numeric matrix or a value in
this table.
value | number of binary learners | description |
---|---|---|
'allpairs' and 'onevsone' | k(k – 1)/2 | for each binary learner, one class is positive, another is negative, and the software ignores the rest. this design exhausts all combinations of class pair assignments. |
'binarycomplete' | this design partitions the classes into all binary combinations, and does not ignore any
classes. for each binary learner, all class assignments are
–1 and 1 with at least one positive
class and one negative class in the assignment. | |
'denserandom' | random, but approximately 10 log2k | for each binary learner, the software randomly assigns classes into positive or negative classes, with at least one of each type. for more details, see random coding design matrices. |
'onevsall' | k | for each binary learner, one class is positive and the rest are negative. this design exhausts all combinations of positive class assignments. |
'ordinal' | k – 1 | for the first binary learner, the first class is negative and the rest are positive. for the second binary learner, the first two classes are negative and the rest are positive, and so on. |
'sparserandom' | random, but approximately 15 log2k | for each binary learner, the software randomly assigns classes as positive or negative with probability 0.25 for each, and ignores classes with probability 0.5. for more details, see random coding design matrices. |
'ternarycomplete' | this design partitions the classes into all ternary combinations. all class assignments are
0 , –1 , and 1 with
at least one positive class and one negative class in each assignment. |
you can also specify a coding design using a custom coding matrix, which is a
k-by-l matrix. each row corresponds to a class
and each column corresponds to a binary learner. the class order (rows) corresponds to
the order in classnames
. create the
matrix by following these guidelines:
every element of the custom coding matrix must be
–1
,0
, or1
, and the value must correspond to a dichotomous class assignment. considercoding(i,j)
, the class that learnerj
assigns to observations in classi
.value dichotomous class assignment –1
learner j
assigns observations in classi
to a negative class.0
before training, learner j
removes observations in classi
from the data set.1
learner j
assigns observations in classi
to a positive class.every column must contain at least one
–1
and one1
.for all column indices
i
,j
wherei
≠j
,coding(:,i)
cannot equalcoding(:,j)
, andcoding(:,i)
cannot equal–coding(:,j)
.all rows of the custom coding matrix must be different.
for more details on the form of custom coding design matrices, see custom coding design matrices.
example: 'coding','ternarycomplete'
data types: char
| string
| double
| single
| int16
| int32
| int64
| int8
fitposterior
— flag indicating whether to transform scores to posterior probabilities
false
or 0
(default) | true
or 1
flag indicating whether to transform scores to posterior probabilities,
specified as the comma-separated pair consisting of 'fitposterior'
and
a true
(1
) or false
(0
).
if fitposterior
is true
,
then the software transforms binary-learner classification scores
to posterior probabilities. you can obtain posterior probabilities
by using , predict
,
or .
fitcecoc
does not support fitting posterior probabilities if:
the ensemble method is
adaboostm2
,lpboost
,rusboost
,robustboost
, ortotalboost
.the binary learners (
learners
) are linear or kernel classification models that implement svm. to obtain posterior probabilities for linear or kernel classification models, implement logistic regression instead.
example: 'fitposterior',true
data types: logical
learners
— binary learner templates
'svm'
(default) | 'discriminant'
| 'kernel'
| 'knn'
| 'linear'
| 'naivebayes'
| 'tree'
| template object | cell vector of template objects
binary learner templates, specified as the comma-separated pair consisting of
'learners'
and a character vector, string scalar, template
object, or cell vector of template objects. specifically, you can specify binary
classifiers such as svm, and the ensembles that use gentleboost
,
logitboost
, and robustboost
, to solve
multiclass problems. however, fitcecoc
also supports multiclass
models as binary classifiers.
if
learners
is a character vector or string scalar, then the software trains each binary learner using the default values of the specified algorithm. this table summarizes the available algorithms.value description 'discriminant'
discriminant analysis. for default options, see . 'kernel'
kernel classification model. for default options, see . 'knn'
k-nearest neighbors. for default options, see . 'linear'
linear classification model. for default options, see templatelinear
.'naivebayes'
naive bayes. for default options, see . 'svm'
svm. for default options, see templatesvm
.'tree'
classification trees. for default options, see . if
learners
is a template object, then each binary learner trains according to the stored options. you can create a template object using:, for discriminant analysis.
, for ensemble learning. you must at least specify the learning method (), the number of learners (), and the type of learner (). you cannot use the
adaboostm2
ensemble method for binary learning., for kernel classification.
, for k-nearest neighbors.
templatelinear
, for linear classification., for naive bayes.
templatesvm
, for svm., for classification trees.
if
learners
is a cell vector of template objects, then:cell j corresponds to binary learner j (in other words, column j of the coding design matrix), and the cell vector must have length l. l is the number of columns in the coding design matrix. for details, see
coding
.to use one of the built-in loss functions for prediction, then all binary learners must return a score in the same range. for example, you cannot include default svm binary learners with default naive bayes binary learners. the former returns a score in the range (-∞,∞), and the latter returns a posterior probability as a score. otherwise, you must provide a custom loss as a function handle to functions such as
predict
and .you cannot specify linear classification model learner templates with any other template.
similarly, you cannot specify kernel classification model learner templates with any other template.
by default, the software trains learners using default svm templates.
example: 'learners','tree'
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
fitcecoc
uses a tree learner, that is,
'learners'
is either 'tree'
or a template object created by using , or a template
object created by using with tree
weak learners.
if the
'numbins'
value is empty (default), thenfitcecoc
does not bin any predictors.if you specify the
'numbins'
value as a positive integer scalar (numbins
), thenfitcecoc
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.fitcecoc
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
numconcurrent
— number of binary learners concurrently trained
1
(default) | positive integer scalar
number of binary learners concurrently trained, specified as the
comma-separated pair consisting of 'numconcurrent'
and a positive integer scalar. the default value is
1
, which means fitcecoc
trains
the binary learners sequentially.
note
this option applies only when you use
fitcecoc
on tall arrays. see tall arrays
for more information.
data types: single
| double
observationsin
— predictor data observation dimension
'rows'
(default) | 'columns'
predictor data observation dimension, specified as the comma-separated
pair consisting of 'observationsin'
and
'columns'
or 'rows'
.
note
for linear classification learners, if you orient
x
so that observations correspond to columns and specify'observationsin','columns'
, then you can experience a significant reduction in optimization-execution time.for all other learners, orient
x
so that observations correspond to rows.
example: 'observationsin','columns'
verbose
— verbosity level
0
(default) | 1
| 2
verbosity level, specified as the comma-separated pair consisting of
'verbose'
and 0
,
1
, or 2
.
verbose
controls the amount of diagnostic
information per binary learner that the software displays in the command
window.
this table summarizes the available verbosity level options.
value | description |
---|---|
0 | the software does not display diagnostic information. |
1 | the software displays diagnostic messages every time it trains a new binary learner. |
2 | the software displays extra diagnostic messages every time it trains a new binary learner. |
each binary learner has its own verbosity level that is independent of
this name-value pair argument. to change the verbosity level of a binary
learner, create a template object and specify the
'verbose'
name-value pair argument. then, pass
the template object to fitcecoc
by using the
'learners'
name-value pair argument.
example: 'verbose',1
data types: double
| single
crossval
— flag to train cross-validated classifier
'off'
(default) | 'on'
flag to train a cross-validated classifier, specified as the
comma-separated pair consisting of 'crossval'
and
'on'
or 'off'
.
if you specify 'on'
, then the software trains a
cross-validated classifier with 10 folds.
you can override this cross-validation setting using one of the
cvpartition
, holdout
,
kfold
, or leaveout
name-value pair arguments. you can only use one cross-validation
name-value pair argument at a time to create a cross-validated
model.
alternatively, cross-validate later by passing
mdl
to .
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 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
size(mdl.x,1)
, the software:
reserves the observation as validation data, and trains the model using the other n – 1 observations
stores the n compact, trained models in the cells of a 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
options only: cvpartition
,
holdout
, kfold
, or
leaveout
.
note
leave-one-out is not recommended for cross-validating ecoc models composed of linear or kernel classification model learners.
example: 'leaveout','on'
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:
at least one predictor is categorical and all binary learners are classification trees, naive bayes learners, svms, linear learners, kernel learners, or ensembles of classification trees.
all predictors are categorical and at least one binary learner is knn.
if you specify 'categoricalpredictors'
for any other learner, then the software warns that it cannot train that
binary learner. for example, the software cannot train discriminant
analysis classifiers using categorical predictors.
each learner identifies and treats categorical predictors in the same
way as the fitting function corresponding to the learner. see of
fitckernel
for kernel learners, 'categoricalpredictors'
of fitcknn
for k-nearest learners, 'categoricalpredictors'
of
fitclinear
for linear learners, 'categoricalpredictors'
of fitcnb
for naive bayes learners, 'categoricalpredictors'
of fitcsvm
for svm learners, and 'categoricalpredictors'
of fitctree
for tree learners.
example: 'categoricalpredictors','all'
data types: single
| double
| logical
| char
| string
| cell
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
, additionally 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.
example: 'cost',[0 1 2 ; 1 0 2; 2 2
0]
data types: double
| single
| struct
options
— parallel computing options
[]
(default) | structure array returned by statset
parallel computing options, specified as the comma-separated pair consisting of
'options'
and a structure array returned by . parallel computation requires parallel computing
toolbox™. fitcecoc
uses
'streams'
, 'useparallel'
, and
'usesubtreams'
fields.
this table summarizes the available options.
option | description |
---|---|
'streams' |
a object
or cell array of such objects. if you do not specify
in that case, use a cell array of the same size as the
parallel pool. if a parallel pool is not open, then the software
tries to open one (depending on your preferences), and
|
'useparallel' | if you have parallel computing toolbox, then you can invoke a
pool of workers by setting
when you use
decision trees for binary learners,
|
'usesubstreams' | set to true to compute in parallel using
the stream specified by 'streams' . default is false .
for example, set streams to a type allowing substreams,
such as'mlfg6331_64' or 'mrg32k3a' . |
a best practice to ensure more
predictable results is to use parpool
(parallel computing toolbox) and
explicitly create a parallel pool before you invoke parallel computing
using fitcecoc
.
example: 'options',statset('useparallel',true)
data types: struct
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,fitcecoc
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
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 |
a structure
|
for more details on how the software incorporates class prior probabilities, see prior probabilities and misclassification cost.
example: struct('classnames',{{'setosa','versicolor','virginica'}},'classprobs',1:3)
data types: single
| double
| char
| string
| struct
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
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
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{'coding'}
along with the default parameters for the specifiedlearners
:learners
='svm'
(default) —{'boxconstraint','kernelscale'}
learners
='discriminant'
—{'delta','gamma'}
learners
='kernel'
—{'kernelscale','lambda'}
learners
='knn'
—{'distance','numneighbors'}
learners
='linear'
—{'lambda','learner'}
learners
='tree'
—{'minleafsize'}
'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 fitcecoc
by varying the parameters. for
information about cross-validation loss 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
fitcecoc
to optimize hyperparameters corresponding to the
'auto'
option and to ignore any specified values for the
hyperparameters.
the eligible parameters for fitcecoc
are:
coding
—fitcecoc
searches among'onevsall'
and'onevsone'
.the eligible hyperparameters for the chosen
learners
, as specified in this table.learners eligible hyperparameters
(bold = default)default 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]
'kernel'
positive values log-scaled in the range [1e-3/numobservations,1e3/numobservations]
positive values log-scaled in the range [1e-3,1e3]
'svm'
and'logistic'
integers log-scaled in the range [100,10000]
'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'
'linear'
lambda
positive values log-scaled in the range [1e-5/numobservations,1e5/numobservations]
learner
'svm'
and'logistic'
regularization
'ridge'
and'lasso'
when
regularization
is'ridge'
, the function uses a limited-memory bfgs (lbfgs) solver by default.when
regularization
is'lasso'
, the function uses a sparse reconstruction by separable approximation (sparsa) solver by default.
'svm'
boxconstraint
positive values log-scaled in the range [1e-3,1e3]
kernelscale
positive values log-scaled in the range [1e-3,1e3]
kernelfunction
'gaussian'
,'linear'
, and'polynomial'
polynomialorder
integers in the range [2,4]
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
, such asload fisheriris % hyperparameters requires data and learner params = hyperparameters('fitcecoc',meas,species,'svm');
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('fitcecoc',meas,species,'svm'); params(2).range = [1e-4,1e6];
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 ecoc classifier.
example: 'auto'
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 ecoc model
classificationecoc
model object | compactclassificationecoc
model object | classificationpartitionedecoc
cross-validated model
object | classificationpartitionedlinearecoc
cross-validated
model object | classificationpartitionedkernelecoc
cross-validated
model object
trained ecoc classifier, returned as a classificationecoc
or
compactclassificationecoc
model
object, or a classificationpartitionedecoc
, classificationpartitionedlinearecoc
, or
classificationpartitionedkernelecoc
cross-validated
model object.
this table shows how the types of model objects returned by fitcecoc
depend on the type of binary learners you specify and whether you perform
cross-validation.
linear classification model learners | kernel classification model learners | cross-validation | returned model object |
---|---|---|---|
no | no | no | classificationecoc |
no | no | yes | |
yes | no | no | compactclassificationecoc |
yes | no | yes | |
no | yes | no | compactclassificationecoc |
no | yes | yes |
hyperparameteroptimizationresults
— description of cross-validation optimization of hyperparameters
bayesianoptimization
object | table of hyperparameters and associated values
description of the cross-validation optimization of hyperparameters,
returned as a bayesianoptimization
object or a
table of hyperparameters and associated values.
hyperparameteroptimizationresults
is nonempty when
the optimizehyperparameters
name-value pair argument is
nonempty and the learners
name-value pair argument
designates linear or kernel binary learners. the value depends on the
setting of the hyperparameteroptimizationoptions
name-value pair argument:
'bayesopt'
(default) — object of classbayesianoptimization
'gridsearch'
or'randomsearch'
— table of hyperparameters used, observed objective function values (cross-validation loss), and rank of observation from smallest (best) to highest (worst)
data types: table
limitations
fitcecoc
supports sparse matrices for training linear classification models only. for all other models, supply a full matrix of predictor data instead.
more about
error-correcting output codes model
an error-correcting output codes (ecoc) model reduces the problem of classification with three or more classes to a set of binary classification problems.
ecoc classification requires a coding design, which determines the classes that the binary learners train on, and a decoding scheme, which determines how the results (predictions) of the binary classifiers are aggregated.
assume the following:
the classification problem has three classes.
the coding design is one-versus-one. for three classes, this coding design is
you can specify a different coding design by using the
coding
name-value argument when you create a classification model.the model determines the predicted class by using the loss-weighted decoding scheme with the binary loss function g. the software also supports the loss-based decoding scheme. you can specify the decoding scheme and binary loss function by using the
decoding
andbinaryloss
name-value arguments, respectively, when you call object functions, such aspredict
,loss
,margin
,edge
, and so on.
the ecoc algorithm follows these steps.
learner 1 trains on observations in class 1 or class 2, and treats class 1 as the positive class and class 2 as the negative class. the other learners are trained similarly.
let m be the coding design matrix with elements mkl, and sl be the predicted classification score for the positive class of learner l. the algorithm assigns a new observation to the class () that minimizes the aggregation of the losses for the b binary learners.
ecoc models can improve classification accuracy, compared to other multiclass models [2].
coding design
the coding design is a matrix whose elements direct which classes are trained by each binary learner, that is, how the multiclass problem is reduced to a series of binary problems.
each row of the coding design corresponds to a distinct class, and each column corresponds to a binary learner. in a ternary coding design, for a particular column (or binary learner):
a row containing 1 directs the binary learner to group all observations in the corresponding class into a positive class.
a row containing –1 directs the binary learner to group all observations in the corresponding class into a negative class.
a row containing 0 directs the binary learner to ignore all observations in the corresponding class.
coding design matrices with large, minimal, pairwise row distances based on the hamming measure are optimal. for details on the pairwise row distance, see random coding design matrices and [3].
this table describes popular coding designs.
coding design | description | number of learners | minimal pairwise row distance |
---|---|---|---|
one-versus-all (ova) | for each binary learner, one class is positive and the rest are negative. this design exhausts all combinations of positive class assignments. | k | 2 |
one-versus-one (ovo) | for each binary learner, one class is positive, one class is negative, and the rest are ignored. this design exhausts all combinations of class pair assignments. | k(k – 1)/2 | 1 |
binary complete | this design partitions the classes into all binary
combinations, and does not ignore any classes. that is, all class
assignments are | 2k – 1 – 1 | 2k – 2 |
ternary complete | this design partitions the classes into all ternary
combinations. that is, all class assignments are
| (3k – 2k 1 1)/2 | 3k – 2 |
ordinal | for the first binary learner, the first class is negative and the rest are positive. for the second binary learner, the first two classes are negative and the rest are positive, and so on. | k – 1 | 1 |
dense random | for each binary learner, the software randomly assigns classes into positive or negative classes, with at least one of each type. for more details, see random coding design matrices. | random, but approximately 10 log2k | variable |
sparse random | for each binary learner, the software randomly assigns classes as positive or negative with probability 0.25 for each, and ignores classes with probability 0.5. for more details, see random coding design matrices. | random, but approximately 15 log2k | variable |
this plot compares the number of binary learners for the coding designs with an increasing number of classes (k).
tips
the number of binary learners grows with the number of classes. for a problem with many classes, the
binarycomplete
andternarycomplete
coding designs are not efficient. however:if k ≤ 4, then use
ternarycomplete
coding design rather thansparserandom
.if k ≤ 5, then use
binarycomplete
coding design rather thandenserandom
.
you can display the coding design matrix of a trained ecoc classifier by entering
mdl.codingmatrix
into the command window.you should form a coding matrix using intimate knowledge of the application, and taking into account computational constraints. if you have sufficient computational power and time, then try several coding matrices and choose the one with the best performance (e.g., check the confusion matrices for each model using ).
leave-one-out cross-validation (
leaveout
) is inefficient for data sets with many observations. instead, use k-fold cross-validation (kfold
).
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
custom coding design matrices
custom coding matrices must have a certain form. the software validates a custom coding matrix by ensuring:
every element is –1, 0, or 1.
every column contains as least one –1 and one 1.
for all distinct column vectors u and v, u ≠ v and u ≠ –v.
all row vectors are unique.
the matrix can separate any two classes. that is, you can move from any row to any other row following these rules:
move vertically from 1 to –1 or –1 to 1.
move horizontally from a nonzero element to another nonzero element.
use a column of the matrix for a vertical move only once.
if it is not possible to move from row i to row j using these rules, then classes i and j cannot be separated by the design. for example, in the coding design
classes 1 and 2 cannot be separated from classes 3 and 4 (that is, you cannot move horizontally from –1 in row 2 to column 2 because that position contains a 0). therefore, the software rejects this coding design.
parallel computing
if you use parallel computing (see options
),
then fitcecoc
trains binary learners in parallel.
prior probabilities and misclassification cost
if you specify the cost
,
prior
, and weights
name-value arguments, the
output model object stores the specified values in the cost
,
prior
, and w
properties, respectively. the
cost
property stores the user-specified cost matrix as is. the
prior
and w
properties store the prior probabilities
and observation weights, respectively, after normalization. for details, see .
for each binary learner, the software normalizes the prior probabilities into a
vector of two elements, and normalizes the cost matrix into a 2-by-2 matrix. then,
the software adjusts the prior probability vector by incorporating the penalties
described in the 2-by-2 cost matrix, and sets the cost matrix to the default cost
matrix. the cost
and prior
properties of the
binary learners in mdl
(mdl.binarylearners
)
store the adjusted values. specifically, the software completes these steps:
the software normalizes the specified class prior probabilities (
prior
) for each binary learner. let m be the coding design matrix and i(a,c) be an indicator matrix. the indicator matrix has the same dimensions as a. if the corresponding element of a is c, then the indicator matrix has elements equaling one, and zero otherwise. let m 1 and m-1 be k-by-l matrices such that:m 1 = m○i(m,1), where ○ is element-wise multiplication (that is,
mplus = m.*(m == 1)
). also, let be column vector l of m 1.m-1 = -m○i(m,-1) (that is,
mminus = -m.*(m == -1)
). also, let be column vector l of m-1.
let and , where π is the vector of specified, class prior probabilities (
prior
).then, the positive and negative, scalar class prior probabilities for binary learner l are
where j = {-1,1} and is the one-norm of a.
the software normalizes the k-by-k cost matrix c (
cost
) for each binary learner. for binary learner l, the cost of classifying a negative-class observation into the positive class issimilarly, the cost of classifying a positive-class observation into the negative class is
the cost matrix for binary learner l is
ecoc models accommodate misclassification costs by incorporating them with class prior probabilities. the software adjusts the class prior probabilities and sets the cost matrix to the default cost matrix for binary learners as follows:
random coding design matrices
for a given number of classes k, the software generates random coding design matrices as follows.
the software generates one of these matrices:
dense random — the software assigns 1 or –1 with equal probability to each element of the k-by-ld coding design matrix, where .
sparse random — the software assigns 1 to each element of the k-by-ls coding design matrix with probability 0.25, –1 with probability 0.25, and 0 with probability 0.5, where .
if a column does not contain at least one 1 and one –1, then the software removes that column.
for distinct columns u and v, if u = v or u = –v, then the software removes v from the coding design matrix.
the software randomly generates 10,000 matrices by default, and retains the matrix with the largest, minimal, pairwise row distance based on the hamming measure ([3]) given by
where mkjl is an element of coding design matrix j.
support vector storage
by default and for efficiency, fitcecoc
empties the alpha
, supportvectorlabels
,
and supportvectors
properties
for all linear svm binary learners. fitcecoc
lists beta
, rather than
alpha
, in the model display.
to store alpha
, supportvectorlabels
, and
supportvectors
, pass a linear svm template that specifies storing
support vectors to fitcecoc
. for example,
enter:
t = templatesvm('savesupportvectors',true) mdl = fitcecoc(x,y,'learners',t);
you can remove the support vectors and related values by passing the resulting
classificationecoc
model to
discardsupportvectors
.
references
[1] allwein, e., r. schapire, and y. singer. “reducing multiclass to binary: a unifying approach for margin classifiers.” journal of machine learning research. vol. 1, 2000, pp. 113–141.
[2] fürnkranz, johannes. “round robin classification.” j. mach. learn. res., vol. 2, 2002, pp. 721–747.
[3] escalera, s., o. pujol, and p. radeva. “separability of ternary codes for sparse designs of error-correcting output codes.” pattern recog. lett., vol. 30, issue 3, 2009, pp. 285–297.
[4] escalera, s., o. pujol, and p. radeva. “on the decoding process in ternary error-correcting output codes.” ieee transactions on pattern analysis and machine intelligence. vol. 32, issue 7, 2010, pp. 120–134.
extended capabilities
tall arrays
calculate with arrays that have more rows than fit in memory.
usage notes and limitations:
supported syntaxes are:
mdl = fitcecoc(x,y)
mdl = fitcecoc(x,y,name,value)
[mdl,fitinfo,hyperparameteroptimizationresults] = fitcecoc(x,y,name,value)
—fitcecoc
returns the additional output argumentsfitinfo
andhyperparameteroptimizationresults
when you specify the'optimizehyperparameters'
name-value pair argument.
the
fitinfo
output argument is an empty structure array currently reserved for possible future use.options related to cross-validation are not supported. the supported name-value pair arguments are:
'classnames'
'cost'
'coding'
— default value is'onevsall'
.'hyperparameteroptimizationoptions'
— for cross-validation, tall optimization supports only'holdout'
validation. by default, the software selects and reserves 20% of the data as holdout validation data, and trains the model using the rest of the data. you can specify a different value for the holdout fraction by using this argument. for example, specify'hyperparameteroptimizationoptions',struct('holdout',0.3)
to reserve 30% of the data as validation data.'learners'
— default value is'linear'
. you can specify'linear'
,'kernel'
, atemplatelinear
ortemplatekernel
object, or a cell array of such objects.'optimizehyperparameters'
— when you use linear binary learners, the value of the'regularization'
hyperparameter must be'ridge'
.'prior'
'verbose'
— default value is1
.'weights'
this additional name-value pair argument is specific to tall arrays:
'numconcurrent'
— a positive integer scalar specifying the number of binary learners that are trained concurrently by combining file i/o operations. the default value for'numconcurrent'
is1
, which meansfitcecoc
trains the binary learners sequentially.'numconcurrent'
is most beneficial when the input arrays cannot fit into the distributed cluster memory. otherwise, the input arrays can be cached and speedup is negligible.if you run your code on apache® spark™,
numconcurrent
is upper bounded by the memory available for communications. check the'spark.executor.memory'
and'spark.driver.memory'
properties in your apache spark configuration. see (parallel computing toolbox) for more details. for more information on apache spark and other execution environments that control where your code runs, see .
for more information, see .
automatic parallel support
accelerate code by automatically running computation in parallel using parallel computing toolbox™.
to run in parallel, set the 'useparallel'
option to
true
in one of these ways:
set the
'useparallel'
field of the options structure totrue
usingstatset
and specify the'options'
name-value pair argument in the call tofitceoc
.for example:
'options',statset('useparallel',true)
for more information, see the
'options'
name-value pair argument.perform parallel hyperparameter optimization by using the
'hyperparameteroptions',struct('useparallel',true)
name-value pair argument in the call tofitceoc
.for more information on parallel hyperparameter optimization, see .
gpu arrays
accelerate code by running on a graphics processing unit (gpu) using parallel computing toolbox™.
usage notes and limitations:
you can specify the name-value argument
'learners'
only as one of the learners specified in this table.learner learner name template object creation function information about gpuarray
supportsupport vector machine 'svm'
templatesvm
gpu arrays for fitcsvm
k-nearest neighbors 'knn'
gpu arrays for fitcknn
classification tree 'tree'
gpu arrays for fitctree
for more information, see run matlab functions on a gpu (parallel computing toolbox).
version history
introduced in r2014br2022a: regularization method determines the linear learner solver used during hyperparameter optimization
starting in r2022a, when you specify to optimize hyperparameters for an ecoc model
with linear binary learners ('linear'
or templatelinear
) and do not specify to use a particular solver,
fitcecoc
uses either a limited-memory bfgs (lbfgs)
solver or a sparse reconstruction by separable approximation (sparsa) solver,
depending on the regularization type selected during each iteration of the
hyperparameter optimization.
when
regularization
is'ridge'
, the function sets thesolver
value to'lbfgs'
by default.when
regularization
is'lasso'
, the function sets thesolver
value to'sparsa'
by default.
in previous releases, the default solver selection during hyperparameter
optimization depended on various factors, including the regularization type, learner
type, and number of predictors. for more information, see solver
.
打开示例
您曾对此示例进行过修改。是否要打开带有您的编辑的示例?
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)
- 中国
- (日本語)
- (한국어)