classify observations using multiclass error-凯发k8网页登录
classify observations using multiclass error-correcting output codes (ecoc) model
syntax
description
uses additional options specified by one or more name-value pair arguments. for example, you
can specify the posterior probability estimation method, decoding scheme, and verbosity
level.label
= predict(mdl
,x
,name,value
)
[
uses any of the input argument combinations in the previous syntaxes and additionally
returns: label
,negloss
,pbscore
]
= predict(___)
an array of negated average binary losses (
negloss
). for each observation inx
,predict
assigns the label of the class yielding the largest negated average binary loss (or, equivalently, the smallest average binary loss).an array of positive-class scores (
pbscore
) for the observations classified by each binary learner.
examples
predict test-sample labels of training data using ecoc model
load fisher's iris data set. specify the predictor data x
, the response data y
, and the order of the classes in y
.
load fisheriris x = meas; y = categorical(species); classorder = unique(y); rng(1); % for reproducibility
train an ecoc model using svm binary classifiers. specify a 30% holdout sample, standardize the predictors using an svm template, and specify the class order.
t = templatesvm('standardize',true); pmdl = fitcecoc(x,y,'holdout',0.30,'learners',t,'classnames',classorder); mdl = pmdl.trained{1}; % extract trained, compact classifier
pmdl
is a classificationpartitionedecoc
model. it has the property trained
, a 1-by-1 cell array containing the compactclassificationecoc
model that the software trained using the training set.
predict the test-sample labels. print a random subset of true and predicted labels.
testinds = test(pmdl.partition); % extract the test indices xtest = x(testinds,:); ytest = y(testinds,:); labels = predict(mdl,xtest); idx = randsample(sum(testinds),10); table(ytest(idx),labels(idx),... 'variablenames',{'truelabels','predictedlabels'})
ans=10×2 table
truelabels predictedlabels
__________ _______________
setosa setosa
versicolor virginica
setosa setosa
virginica virginica
versicolor versicolor
setosa setosa
virginica virginica
virginica virginica
setosa setosa
setosa setosa
mdl
correctly labels all except one of the test-sample observations with indices idx
.
predict test-sample labels of ecoc model using custom binary loss function
load fisher's iris data set. specify the predictor data x
, the response data y
, and the order of the classes in y
.
load fisheriris x = meas; y = categorical(species); classorder = unique(y); % class order rng(1); % for reproducibility
train an ecoc model using svm binary classifiers and specify a 30% holdout sample. standardize the predictors using an svm template, and specify the class order.
t = templatesvm('standardize',true); pmdl = fitcecoc(x,y,'holdout',0.30,'learners',t,'classnames',classorder); mdl = pmdl.trained{1}; % extract trained, compact classifier
pmdl
is a classificationpartitionedecoc
model. it has the property trained
, a 1-by-1 cell array containing the compactclassificationecoc
model that the software trained using the training set.
svm scores are signed distances from the observation to the decision boundary. therefore, is the domain. create a custom binary loss function that does the following:
map the coding design matrix (m) and positive-class classification scores (s) for each learner to the binary loss for each observation.
use linear loss.
aggregate the binary learner loss using the median.
you can create a separate function for the binary loss function, and then save it on the matlab® path. or, you can specify an anonymous binary loss function. in this case, create a function handle (custombl
) to an anonymous binary loss function.
custombl = @(m,s) median(1 - (m.*s),2,'omitnan')/2;
predict test-sample labels and estimate the median binary loss per class. print the median negative binary losses per class for a random set of 10 test-sample observations.
testinds = test(pmdl.partition); % extract the test indices xtest = x(testinds,:); ytest = y(testinds,:); [label,negloss] = predict(mdl,xtest,'binaryloss',custombl); idx = randsample(sum(testinds),10); classorder
classorder = 3x1 categorical
setosa
versicolor
virginica
table(ytest(idx),label(idx),negloss(idx,:),'variablenames',... {'truelabel','predictedlabel','negloss'})
ans=10×3 table
truelabel predictedlabel negloss
__________ ______________ __________________________________
setosa versicolor 0.1858 1.9878 -3.6736
versicolor virginica -1.3315 -0.12361 -0.044843
setosa versicolor 0.13891 1.9261 -3.565
virginica virginica -1.513 -0.38284 0.39588
versicolor versicolor -0.87221 0.74738 -1.3752
setosa versicolor 0.48413 1.9976 -3.9818
virginica virginica -1.936 -0.67566 1.1117
virginica virginica -1.5786 -0.83331 0.91194
setosa versicolor 0.51027 2.1211 -4.1314
setosa versicolor 0.36128 2.0596 -3.9209
the order of the columns corresponds to the elements of classorder
. the software predicts the label based on the maximum negated loss. the results indicate that the median of the linear losses might not perform as well as other losses.
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
estimate test-sample posterior probabilities using parallel computing
this example uses:
train a multiclass ecoc model and estimate posterior probabilities using parallel computing.
load the arrhythmia
data set. examine the response data y
, and determine the number of classes.
load arrhythmia
y = categorical(y);
tabulate(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%
k = numel(unique(y));
several classes are not represented in the data, and many of the other classes have low relative frequencies.
specify an ensemble learning template that uses the gentleboost method and 50 weak classification tree learners.
t = templateensemble('gentleboost',50,'tree');
t
is a template object. most of its properties are empty ([]
). the software uses default values for all empty properties during training.
because the response variable contains many classes, specify a sparse random coding design.
rng(1); % for reproducibility coding = designecoc(k,'sparserandom');
train an ecoc model using parallel computing. specify a 15% holdout sample, and fit posterior probabilities.
pool = parpool; % invokes workers
starting parallel pool (parpool) using the 'local' profile ... connected to the parallel pool (number of workers: 6).
options = statset('useparallel',true); pmdl = fitcecoc(x,y,'learner',t,'options',options,'coding',coding,... 'fitposterior',true,'holdout',0.15); mdl = pmdl.trained{1}; % extract trained, compact classifier
pmdl
is a classificationpartitionedecoc
model. it has the property trained
, a 1-by-1 cell array containing the compactclassificationecoc
model that the software trained using the training set.
the pool invokes six workers, although the number of workers might vary among systems.
estimate posterior probabilities, and display the posterior probability of being classified as not having arrhythmia (class 1) given the data for a random set of test-sample observations.
testinds = test(pmdl.partition); % extract the test indices xtest = x(testinds,:); ytest = y(testinds,:); [~,~,~,posterior] = predict(mdl,xtest,'options',options); idx = randsample(sum(testinds),10); table(idx,ytest(idx),posterior(idx,1),... 'variablenames',{'testsampleindex','truelabel','posteriornoarrhythmia'})
ans=10×3 table
testsampleindex truelabel posteriornoarrhythmia
_______________ _________ _____________________
11 6 0.60631
41 4 0.23674
51 2 0.13802
33 10 0.43831
12 1 0.94332
8 1 0.97278
37 1 0.62807
24 10 0.96876
56 16 0.29375
30 1 0.64512
input arguments
mdl
— full or compact multiclass ecoc model
classificationecoc
model object | compactclassificationecoc
model
object
full or compact multiclass ecoc model, specified as a
classificationecoc
or
compactclassificationecoc
model
object.
to create a full or compact ecoc model, see classificationecoc
or compactclassificationecoc
.
x
— predictor data to be classified
numeric matrix | table
predictor data to be classified, specified as a numeric matrix or table.
by default, each row of x
corresponds to one observation, and
each column corresponds to one variable.
for a numeric matrix:
the variables that constitute the columns of
x
must have the same order as the predictor variables that trainmdl
.if you train
mdl
using a table (for example,tbl
), thenx
can be a numeric matrix iftbl
contains all numeric predictor variables. to treat numeric predictors intbl
as categorical during training, identify categorical predictors using thecategoricalpredictors
name-value pair argument offitcecoc
. iftbl
contains heterogeneous predictor variables (for example, numeric and categorical data types) andx
is a numeric matrix, thenpredict
throws an error.
for a table:
predict
does not support multicolumn variables or cell arrays other than cell arrays of character vectors.if you train
mdl
using a table (for example,tbl
), then all predictor variables inx
must have the same variable names and data types as the predictor variables that trainmdl
(stored inmdl.predictornames
). however, the column order ofx
does not need to correspond to the column order oftbl
. bothtbl
andx
can contain additional variables (response variables, observation weights, and so on), butpredict
ignores them.if you train
mdl
using a numeric matrix, then the predictor names inmdl.predictornames
and the corresponding predictor variable names inx
must be the same. to specify predictor names during training, see thepredictornames
name-value pair argument offitcecoc
. all predictor variables inx
must be numeric vectors.x
can contain additional variables (response variables, observation weights, and so on), butpredict
ignores them.
note
if mdl.binarylearners
contains linear classification models
(classificationlinear
), then you can orient
your predictor matrix so that observations correspond to columns and specify
'observationsin','columns'
. however, you cannot specify
'observationsin','columns'
for predictor data in a table.
when training mdl
, assume that you set
'standardize',true
for a template object specified in the
'learners'
name-value pair argument of fitcecoc
. in
this case, for the corresponding binary learner j
, the software standardizes
the columns of the new predictor data using the corresponding means in
mdl.binarylearner{j}.mu
and standard deviations in
mdl.binarylearner{j}.sigma
.
data types: table
| double
| single
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: predict(mdl,x,'binaryloss','quadratic','decoding','lossbased')
specifies a quadratic binary learner loss function and a loss-based decoding scheme for
aggregating the binary losses.
binaryloss
— binary learner loss function
'hamming'
| 'linear'
| 'logit'
| 'exponential'
| 'binodeviance'
| 'hinge'
| 'quadratic'
| function handle
binary learner loss function, specified as the comma-separated pair consisting of
'binaryloss'
and a built-in loss function name or function handle.
this table describes the built-in functions, where yj is the class label for a particular binary learner (in the set {–1,1,0}), sj is the score for observation j, and g(yj,sj) is the binary loss formula.
value description score domain g(yj,sj) 'binodeviance'
binomial deviance (–∞,∞) log[1 exp(–2yjsj)]/[2log(2)] 'exponential'
exponential (–∞,∞) exp(–yjsj)/2 'hamming'
hamming [0,1] or (–∞,∞) [1 – sign(yjsj)]/2 'hinge'
hinge (–∞,∞) max(0,1 – yjsj)/2 'linear'
linear (–∞,∞) (1 – yjsj)/2 'logit'
logistic (–∞,∞) log[1 exp(–yjsj)]/[2log(2)] 'quadratic'
quadratic [0,1] [1 – yj(2sj – 1)]2/2 the software normalizes binary losses so that the loss is 0.5 when yj = 0. also, the software calculates the mean binary loss for each class [1].
for a custom binary loss function, for example
customfunction
, specify its function handle'binaryloss',@customfunction
.customfunction
has this form:bloss = customfunction(m,s)
m
is the k-by-b coding matrix stored inmdl.codingmatrix
.s
is the 1-by-b row vector of classification scores.bloss
is the classification loss. this scalar aggregates the binary losses for every learner in a particular class. for example, you can use the mean binary loss to aggregate the loss over the learners for each class.k is the number of classes.
b is the number of binary learners.
for an example of passing a custom binary loss function, see predict test-sample labels of ecoc model using custom binary loss function.
this table identifies the default binaryloss
value, which depends on the
score ranges returned by the binary learners.
assumption | default value |
---|---|
all binary learners are any of the following:
| 'quadratic' |
all binary learners are svms or linear or kernel classification models of svm learners. | 'hinge' |
all binary learners are ensembles trained by
adaboostm1 or
gentleboost . | 'exponential' |
all binary learners are ensembles trained by
logitboost . | 'binodeviance' |
you specify to predict class posterior probabilities by setting
'fitposterior',true in fitcecoc . | 'quadratic' |
binary learners are heterogeneous and use different loss functions. | 'hamming' |
to check the default value, use dot notation to display the binaryloss
property of the trained model at the command line.
example: 'binaryloss','binodeviance'
data types: char
| string
| function_handle
decoding
— decoding scheme
'lossweighted'
(default) | 'lossbased'
decoding scheme that aggregates the binary losses, specified as the comma-separated pair
consisting of 'decoding'
and 'lossweighted'
or
'lossbased'
. for more information, see binary loss.
example: 'decoding','lossbased'
numklinitializations
— number of random initial values
0
(default) | nonnegative integer scalar
number of random initial values for fitting posterior probabilities by kullback-leibler
divergence minimization, specified as the comma-separated pair consisting of
'numklinitializations'
and a nonnegative integer scalar.
if you do not request the fourth output argument (posterior
) and set
'posteriormethod','kl'
(the default), then the software ignores
the value of numklinitializations
.
for more details, see posterior estimation using kullback-leibler divergence.
example: 'numklinitializations',5
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'
. mdl.binarylearners
must contain
classificationlinear
models.
note
if you orient your predictor matrix so that
observations correspond to columns and specify
'observationsin','columns'
, you
can experience a significant reduction in
execution time. you cannot specify
'observationsin','columns'
for
predictor data in a table.
options
— estimation options
[]
(default) | structure array returned by statset
estimation options, specified as the comma-separated pair consisting
of 'options'
and a structure array returned by .
to invoke parallel computing:
you need a parallel computing toolbox™ license.
specify
'options',statset('useparallel',true)
.
posteriormethod
— posterior probability estimation method
'kl'
(default) | 'qp'
posterior probability estimation method, specified as the comma-separated
pair consisting of 'posteriormethod'
and 'kl'
or 'qp'
.
if
posteriormethod
is'kl'
, then the software estimates multiclass posterior probabilities by minimizing the kullback-leibler divergence between the predicted and expected posterior probabilities returned by binary learners. for details, see posterior estimation using kullback-leibler divergence.if
posteriormethod
is'qp'
, then the software estimates multiclass posterior probabilities by solving a least-squares problem using quadratic programming. you need an optimization toolbox™ license to use this option. for details, see posterior estimation using quadratic programming.if you do not request the fourth output argument (
posterior
), then the software ignores the value ofposteriormethod
.
example: 'posteriormethod','qp'
verbose
— verbosity level
0
(default) | 1
verbosity level, specified as the comma-separated pair consisting of
'verbose'
and 0
or 1
.
verbose
controls the number of diagnostic messages that the
software displays in the command window.
if verbose
is 0
, then the software does not display
diagnostic messages. otherwise, the software displays diagnostic messages.
example: 'verbose',1
data types: single
| double
output arguments
label
— predicted class labels
categorical array | character array | logical array | numeric array | cell array of character vectors
predicted class labels, returned as a categorical, character, logical, or numeric array, or a cell array of character vectors.
the predict
function predicts the
classification of an observation by assigning the observation to the class yielding the largest
negated average binary loss (or, equivalently, the smallest average binary loss). for an
observation with nan
loss values, the function classifies the observation
into the majority class, which makes up the largest proportion of the training labels.
label
has the same data type as the class labels used to train
mdl
and has the same number of rows as x
.
(the software treats string arrays as cell arrays of character
vectors.)
if mdl.binarylearners
contains classificationlinear
models, then label
is an
m-by-l matrix, where m is the
number of observations in x
, and l is the number
of regularization strengths in the linear classification models
(numel(mdl.binarylearners{1}.lambda)
). the value
label(i,j)
is the predicted label of observation
i
for the model trained using regularization strength
mdl.binarylearners{1}.lambda(j)
.
otherwise, label
is a column vector of length
m.
negloss
— negated average binary losses
numeric matrix | numeric array
negated average binary losses, returned as a numeric matrix or array.
if
mdl.binarylearners
containsclassificationlinear
models, thennegloss
is an m-by-k-by-l array.m is the number of observations in
x
.k is the number of distinct classes in the training data (
numel(mdl.classnames)
).l is the number of regularization strengths in the linear classification models (
numel(mdl.binarylearners{1}.lambda)
).
negloss(i,k,j)
is the negated average binary loss for observationi
, corresponding to classmdl.classnames(k)
, for the model trained using regularization strengthmdl.binarylearners{1}.lambda(j)
.if
decoding
is'lossbased'
, thennegloss(i,k,j)
is the sum of the binary losses divided by the total number of binary learners.if
decoding
is'lossweighted'
, thennegloss(i,k,j)
is the sum of the binary losses divided by the number of binary learners for the kth class.
for more details, see binary loss.
otherwise,
negloss
is an m-by-k matrix.
pbscore
— positive-class scores
numeric matrix | numeric array
positive-class scores for each binary learner, returned as a numeric matrix or array.
if
mdl.binarylearners
containsclassificationlinear
models, thenpbscore
is an m-by-b-by-l array.m is the number of observations in
x
.b is the number of binary learners (
numel(mdl.binarylearners)
).l is the number of regularization strengths in the linear classification models (
numel(mdl.binarylearners{1}.lambda)
).
pbscore(i,b,j)
is the positive-class score for observationi
, using binary learnerb
, for the model trained using regularization strengthmdl.binarylearners{1}.lambda(j)
.otherwise,
pbscore
is an m-by-b matrix.
posterior
— posterior class probabilities
numeric matrix | numeric array
posterior class probabilities, returned as a numeric matrix or array.
if
mdl.binarylearners
containsclassificationlinear
models, thenposterior
is an m-by-k-by-l array. for dimension definitions, seenegloss
.posterior(i,k,j)
is the posterior probability that observationi
comes from classmdl.classnames(k)
, for the model trained using regularization strengthmdl.binarylearners{1}.lambda(j)
.otherwise,
posterior
is an m-by-k matrix.
more about
binary loss
the binary loss is a function of the class and classification score that determines how well a binary learner classifies an observation into the class. the decoding scheme of an ecoc model specifies how the software aggregates the binary losses and determines the predicted class for each observation.
assume the following:
mkj is element (k,j) of the coding design matrix m—that is, the code corresponding to class k of binary learner j. m is a k-by-b matrix, where k is the number of classes, and b is the number of binary learners.
sj is the score of binary learner j for an observation.
g is the binary loss function.
is the predicted class for the observation.
the software supports two decoding schemes:
loss-based decoding [3] (
decoding
is'lossbased'
) — the predicted class of an observation corresponds to the class that produces the minimum average of the binary losses over all binary learners.loss-weighted decoding [4] (
decoding
is'lossweighted'
) — the predicted class of an observation corresponds to the class that produces the minimum average of the binary losses over the binary learners for the corresponding class.the denominator corresponds to the number of binary learners for class k. [1] suggests that loss-weighted decoding improves classification accuracy by keeping loss values for all classes in the same dynamic range.
the predict
, resubpredict
, and
kfoldpredict
functions return the negated value of the objective
function of argmin
as the second output argument
(negloss
) for each observation and class.
this table summarizes the supported binary loss functions, where yj is a class label for a particular binary learner (in the set {–1,1,0}), sj is the score for observation j, and g(yj,sj) is the binary loss function.
value | description | score domain | g(yj,sj) |
---|---|---|---|
"binodeviance" | binomial deviance | (–∞,∞) | log[1 exp(–2yjsj)]/[2log(2)] |
"exponential" | exponential | (–∞,∞) | exp(–yjsj)/2 |
"hamming" | hamming | [0,1] or (–∞,∞) | [1 – sign(yjsj)]/2 |
"hinge" | hinge | (–∞,∞) | max(0,1 – yjsj)/2 |
"linear" | linear | (–∞,∞) | (1 – yjsj)/2 |
"logit" | logistic | (–∞,∞) | log[1 exp(–yjsj)]/[2log(2)] |
"quadratic" | quadratic | [0,1] | [1 – yj(2sj – 1)]2/2 |
the software normalizes binary losses so that the loss is 0.5 when yj = 0, and aggregates using the average of the binary learners [1].
do not confuse the binary loss with the overall classification loss (specified by the
lossfun
name-value argument of the loss
and
predict
object functions), which measures how well an ecoc classifier
performs as a whole.
algorithms
the software can estimate class posterior probabilities by minimizing the kullback-leibler divergence or by using quadratic programming. for the following descriptions of the posterior estimation algorithms, assume that:
mkj is the element (k,j) of the coding design matrix m.
i is the indicator function.
is the class posterior probability estimate for class k of an observation, k = 1,...,k.
rj is the positive-class posterior probability for binary learner j. that is, rj is the probability that binary learner j classifies an observation into the positive class, given the training data.
posterior estimation using kullback-leibler divergence
by default, the software minimizes the kullback-leibler divergence to estimate class posterior probabilities. the kullback-leibler divergence between the expected and observed positive-class posterior probabilities is
where is the weight for binary learner j.
sj is the set of observation indices on which binary learner j is trained.
is the weight of observation i.
the software minimizes the divergence iteratively. the first step is to choose initial values for the class posterior probabilities.
if you do not specify
'numkliterations'
, then the software tries both sets of deterministic initial values described next, and selects the set that minimizes δ.is the solution of the system
where m01 is m with all mkj = –1 replaced with 0, and r is a vector of positive-class posterior probabilities returned by the l binary learners . the software uses to solve the system.
if you specify
'numkliterations',c
, wherec
is a natural number, then the software does the following to choose the set , and selects the set that minimizes δ.the software tries both sets of deterministic initial values as described previously.
the software randomly generates
c
vectors of length k using , and then normalizes each vector to sum to 1.
at iteration t, the software completes these steps:
compute
estimate the next class posterior probability using
normalize so that they sum to 1.
check for convergence.
for more details, see and .
posterior estimation using quadratic programming
posterior probability estimation using quadratic programming requires an optimization toolbox license. to estimate posterior probabilities for an observation using this method, the software completes these steps:
estimate the positive-class posterior probabilities, rj, for binary learners j = 1,...,l.
using the relationship between rj and , minimize
with respect to and the restrictions
the software performs minimization using (optimization toolbox).
alternative functionality
simulink block
to integrate the prediction of an ecoc classification model into simulink®, you can use the block in the statistics and machine learning toolbox™ library or a matlab® function block with the predict
function. for examples,
see and predict class labels using matlab function block.
when deciding which approach to use, consider the following:
if you use the statistics and machine learning toolbox library block, you can use the (fixed-point designer) to convert a floating-point model to fixed point.
support for variable-size arrays must be enabled for a matlab function block with the
predict
function.if you use a matlab function block, you can use matlab functions for preprocessing or post-processing before or after predictions in the same matlab function block.
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] dietterich, t., and g. bakiri. “solving multiclass learning problems via error-correcting output codes.” journal of artificial intelligence research. vol. 2, 1995, pp. 263–286.
[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.
[5] hastie, t., and r. tibshirani. “classification by pairwise coupling.” annals of statistics. vol. 26, issue 2, 1998, pp. 451–471.
[6] wu, t. f., c. j. lin, and r. weng. “probability estimates for multi-class classification by pairwise coupling.” journal of machine learning research. vol. 5, 2004, pp. 975–1005.
[7] zadrozny, b. “reducing multiclass to binary by coupling probability estimates.” nips 2001: proceedings of advances in neural information processing systems 14, 2001, pp. 1041–1048.
extended capabilities
tall arrays
calculate with arrays that have more rows than fit in memory.
usage notes and limitations:
predict
does not support talltable
data whenmdl
contains kernel or linear binary learners.
for more information, see .
c/c code generation
generate c and c code using matlab® coder™.
usage notes and limitations:
you can generate c/c code for both
predict
andupdate
by using a coder configurer. or, generate code only forpredict
by usingsavelearnerforcoder
,loadlearnerforcoder
, andcodegen
.code generation for
predict
andupdate
— create a coder configurer by usinglearnercoderconfigurer
and then generate code by using . then you can update model parameters in the generated code without having to regenerate the code.code generation for
predict
— save a trained model by usingsavelearnerforcoder
. define an entry-point function that loads the saved model by usingloadlearnerforcoder
and calls thepredict
function. then usecodegen
(matlab coder) to generate code for the entry-point function.
to generate single-precision c/c code for
predict
, specify the name-value argument"datatype","single"
when you call theloadlearnerforcoder
function.this table contains notes about the arguments of
predict
. arguments not included in this table are fully supported.argument notes and limitations mdl
if you use
savelearnerforcoder
to save a model that is equipped to predict posterior probabilities, and useloadlearnerforcoder
to load the model, thenloadlearnerforcoder
cannot restore thescoretransform
property into the matlab workspace. however,loadlearnerforcoder
can load the model, including thescoretransform
property, within an entry-point function at compile time for code generation.for the usage notes and limitations of the model object, see code generation of the
compactclassificationecoc
object.
x
for general code generation,
x
must be a single-precision or double-precision matrix or a table containing numeric variables, categorical variables, or both.in the coder configurer workflow,
x
must be a single-precision or double-precision matrix.the number of observations in
x
can be a variable size, but the number of variables inx
must be fixed.if you want to specify
x
as a table, then your model must be trained using a table, and your entry-point function for prediction must do the following:accept data as arrays.
create a table from the data input arguments and specify the variable names in the table.
pass the table to
predict
.
for an example of this table workflow, see . for more information on using tables in code generation, see (matlab coder) and (matlab coder).
posterior
this output argument is not supported. name-value pair arguments names in name-value arguments must be compile-time constants. binaryloss
the value for the
'binaryloss'
name-value pair argument must be a compile-time constant. for example, to use the'binaryloss','logit'
name-value pair argument in the generated code, include{coder.constant('binaryloss'),coder.constant('logit')}
in the-args
value ofcodegen
(matlab coder).to set the
'binaryloss'
name-value pair argument to a custom binary loss function in the generated code, define a custom function on the matlab search path, and specify the name of the custom function instead of its function handle. the custom function name must be a compile-time constant. for example, if you define a custom function namedcustomfunction
, then include{coder.constant('binaryloss'),coder.constant('customfunction')}
in the-args
value ofcodegen
(matlab coder).
numklinitializations
this name-value pair argument is not supported. observationsin
the value for the
observationsin
name-value argument must be a compile-time constant. for example, to use the"observationsin","columns"
name-value argument in the generated code, include{coder.constant("observationsin"),coder.constant("columns")}
in the-args
value ofcodegen
(matlab coder).options
this name-value pair argument is not supported. posteriormethod
this name-value pair argument is not supported. verbose
if you plan to generate a mex file without using a coder configurer, then you can specify verbose
. otherwise,codegen
does not supportverbose
.
for more information, see introduction to code generation.
automatic parallel support
accelerate code by automatically running computation in parallel using parallel computing toolbox™.
to run in parallel, specify the options
name-value argument in the call to
this function and set the useparallel
field of the
options structure to true
using
statset
:
"options",statset("useparallel",true)
for more 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:
the
predict
function does not support models trained using decision tree learners with surrogate splits.the
predict
function does not support models trained using svm learners.
for more information, see run matlab functions on a gpu (parallel computing toolbox).
version history
introduced in r2014b
see also
compactclassificationecoc
| classificationecoc
| fitcecoc
| | | (optimization toolbox) |
打开示例
您曾对此示例进行过修改。是否要打开带有您的编辑的示例?
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)
- 中国
- (日本語)
- (한국어)