predict - Classify observations using multiclass error-correcting output codes (ECOC)

  model - MATLAB ([original](http://www.mathworks.com/help/stats/classificationecoc.predict.html)) ([raw](?raw))

Classify observations using multiclass error-correcting output codes (ECOC) model

Syntax

Description

[label](#mw%5Fadb3b070-66e4-4296-ac03-0ffdc741df3d) = predict([Mdl](#bufel6%5F%5Fsep%5Fshared-Mdl),[X](#mw%5F78b5b256-d492-41ec-b52a-a91048abea22)) returns a vector of predicted class labels (label) for the predictor data in the table or matrix X, based on the trained multiclass error-correcting output codes (ECOC) model Mdl. The trained ECOC model can be either full or compact.

example

[label](#mw%5Fadb3b070-66e4-4296-ac03-0ffdc741df3d) = predict([Mdl](#bufel6%5F%5Fsep%5Fshared-Mdl),[X](#mw%5F78b5b256-d492-41ec-b52a-a91048abea22),[Name,Value](#namevaluepairarguments)) 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.

example

[[label](#mw%5Fadb3b070-66e4-4296-ac03-0ffdc741df3d),[NegLoss](#bufel6%5F-NegLoss),[PBScore](#mw%5F4913d699-5d55-49a8-83c7-d2dbd5729787)] = predict(___) uses any of the input argument combinations in the previous syntaxes and additionally returns:

example

[[label](#mw%5Fadb3b070-66e4-4296-ac03-0ffdc741df3d),[NegLoss](#bufel6%5F-NegLoss),[PBScore](#mw%5F4913d699-5d55-49a8-83c7-d2dbd5729787),[Posterior](#mw%5F7566e162-d07a-4719-b1b0-a381c2b78a85)] = predict(___) additionally returns posterior class probability estimates for the observations (Posterior).

To obtain posterior class probabilities, you must set'FitPosterior',true when training the ECOC model using fitcecoc. Otherwise, predict throws an error.

example

Examples

collapse all

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.

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:

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 = 3×1 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.

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...

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 = 3×1 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.0039319     0.0039866       0.99208
{'virginica' }    {'virginica' }      0.017066      0.018262       0.96467
{'virginica' }    {'virginica' }      0.014947      0.015855        0.9692
{'versicolor'}    {'versicolor'}    2.2197e-14       0.87318       0.12682
{'setosa'    }    {'setosa'    }         0.999    0.00025091    0.00074639
{'versicolor'}    {'virginica' }    2.2195e-14      0.059427       0.94057
{'versicolor'}    {'versicolor'}    2.2194e-14       0.97002      0.029984
{'setosa'    }    {'setosa'    }         0.999     0.0002499    0.00074741
{'versicolor'}    {'versicolor'}     0.0085638       0.98259     0.0088482
{'setosa'    }    {'setosa'    }         0.999    0.00025013    0.00074718

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

Figure contains an axes object. The axes object with title Iris Petal Measurements and Maximum Posterior, xlabel Petal length (cm), ylabel Petal width (cm) contains 4 objects of type contour, line. One or more of the lines displays its values using only markers These objects represent setosa, versicolor, virginica.

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%

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

collapse all

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.

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 inMdl.BinaryLearner{j}.Mu and standard deviations inMdl.BinaryLearner{j}.Sigma.

Data Types: table | double | single

Name-Value Arguments

collapse all

Specify optional pairs of arguments asName1=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.

Data Types: char | string | function_handle

Data Types: char | string

Data Types: single | double

Posterior probability estimation method, specified as the comma-separated pair consisting of 'PosteriorMethod' and 'kl' or 'qp'.

Example: 'PosteriorMethod','qp'

Data Types: single | double

Output Arguments

collapse all

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 trainMdl 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 valuelabel(i,j) is the predicted label of observationi for the model trained using regularization strengthMdl.BinaryLearners{1}.Lambda(j).

Otherwise, label is a column vector of length_m_.

Negated average binary losses, returned as a numeric matrix or array.

Positive-class scores for each binary learner, returned as a numeric matrix or array.

Posterior class probabilities, returned as a numeric matrix or array.

More About

collapse all

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:

The software supports two decoding schemes:

The predict, resubPredict, andkfoldPredict 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(–2_yjsj_)]/[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(2_sj_ – 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 theLossFun name-value argument of the loss andpredict object functions), which measures how well an ECOC classifier performs as a whole.

Algorithms

collapse all

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:

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 wj=∑Sjwi∗ is the weight for binary learner j.

The software minimizes the divergence iteratively. The first step is to choose initial values p^k(0); k=1,...,K for the class posterior probabilities.

At iteration t, the software completes these steps:

  1. Compute
  2. Estimate the next class posterior probability using
  3. Normalize p^k(t+1); k=1,...,K so that they sum to 1.
  4. Check for convergence.

For more details, see [Hastie et al.] and [Zadrozny].

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:

  1. Estimate the positive-class posterior probabilities,rj, for binary learners_j_ = 1,...,L.
  2. Using the relationship between rj and p^k [Wu et al.], minimize
    with respect to p^k and the restrictions
    The software performs minimization using quadprog (Optimization Toolbox).

Alternative Functionality

To integrate the prediction of an ECOC classification model into Simulink®, you can use the ClassificationECOC Predict block in the Statistics and Machine Learning Toolbox™ library or a MATLAB® Function block with the predict function. For examples, see Predict Class Labels Using ClassificationECOC Predict Block and Predict Class Labels Using MATLAB Function Block.

When deciding which approach to use, consider the following:

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

expand all

Thepredict function supports tall arrays with the following usage notes and limitations:

For more information, see Tall Arrays.

Usage notes and limitations:

For more information, see Introduction to Code Generation.

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 usingstatset:

Options=statset(UseParallel=true)

For more information about parallel computing, see Run MATLAB Functions with Automatic Parallel Support (Parallel Computing Toolbox).

Usage notes and limitations:

For more information, see Run MATLAB Functions on a GPU (Parallel Computing Toolbox).

Version History

Introduced in R2014b