Esta página aún no se ha traducido para esta versión. Puede ver la versión más reciente de esta página en inglés.

predict

Predict labels using multiclass, error-correcting output codes model

Sintaxis

label = predict(Mdl,X)
label = predict(Mdl,X,Name,Value)
[label,NegLoss,PBScore] = predict(___)
[label,NegLoss,PBScore,Posterior] = predict(___)

Description

ejemplo

label = predict(Mdl,X) returns a vector of predicted class labels for the predictor data in the table or matrix X, based on the full or compact, trained, multiclass, error-correcting output code (ECOC) model Mdl.

ejemplo

label = predict(Mdl,X,Name,Value) uses additional options specified by one or more Name,Value pair arguments. For example, specify the posterior probability estimation method, decoding scheme, or verbosity level.

ejemplo

[label,NegLoss,PBScore] = predict(___) uses any of the input arguments in the previous syntaxes and additionally returns:

  • An array of negated average binary loss per class (NegLoss). For each observation in X, 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.

ejemplo

[label,NegLoss,PBScore,Posterior] = predict(___) additionally returns posterior class probability estimates for observations (Posterior).

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

Argumentos de entrada

expandir todo

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.

Predictor data to be classified, specified as a numeric matrix or table.

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

  • For a numeric matrix:

    • The variables making up the columns of X must have the same order as the predictor variables that trained Mdl.

    • If you trained Mdl using a table (for example, Tbl), then X can be a numeric matrix if Tbl contains all numeric predictor variables. To treat numeric predictors in Tbl as categorical during training, identify categorical predictors using the CategoricalPredictors name-value pair argument of fitcecoc. If Tbl contains heterogeneous predictor variables (for example, numeric and categorical data types) and X is a numeric matrix, then predict throws an error.

  • For a table:

    • predict does not support multicolumn variables and cell arrays other than cell arrays of character vectors.

    • If you trained Mdl using a table (for example, Tbl), then all predictor variables in X must have the same variable names and data types as those that trained Mdl (stored in Mdl.PredictorNames). However, the column order of X does not need to correspond to the column order of Tbl. Tbl and X can contain additional variables (response variables, observation weights, etc.), but predict ignores them.

    • If you trained Mdl using a numeric matrix, then the predictor names in Mdl.PredictorNames and corresponding predictor variable names in X must be the same. To specify predictor names during training, see the PredictorNames name-value pair argument of fitcecoc. All predictor variables in X must be numeric vectors. X can contain additional variables (response variables, observation weights, etc.), but predict ignores them.

Nota

If Mdl.BinaryLearners contains linear or kernel classification models (that is, ClassificationLinear or ClassificationKernel model objects), then you cannot specify sample data in a table. Instead, pass a matrix of predictor data.

Tipos de datos: table | double | single

Argumentos de par nombre-valor

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

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 contains names and descriptions of the built-in 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 formula.

    ValueDescriptionScore Domaing(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 such that the loss is 0.5 when yj = 0. Also, the software calculates the mean binary loss for each class.

  • For a custom binary loss function, for example, customFunction, specify its function handle 'BinaryLoss',@customFunction.

    customFunction has this form:

    bLoss = customFunction(M,s)
    where:

    • M is the K-by-L coding matrix stored in Mdl.CodingMatrix.

    • s is the 1-by-L 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.

    • L is the number of binary learners.

    For an example of passing a custom binary loss function, see Predict Test-Sample Labels of ECOC Models Using Custom Binary Loss Function.

By default, if all binary learners are:

  • SVMs or either linear or kernel classification models of SVM learners, then BinaryLoss is 'hinge'

  • Ensembles trained by AdaboostM1 or GentleBoost, then BinaryLoss is 'exponential'

  • Ensembles trained by LogitBoost, then BinaryLoss is 'binodeviance'

  • Linear or kernel classification models of logistic regression learners, or you specify to predict class posterior probabilities (that is, set 'FitPosterior',1 in fitcecoc), then BinaryLoss is 'quadratic'

Otherwise, the default value for 'BinaryLoss' is 'hamming'. To check the default value, use dot notation to display the BinaryLoss property of the trained model at the command line.

Ejemplo: 'BinaryLoss','binodeviance'

Tipos de datos: char | string | function_handle

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.

Ejemplo: 'Decoding','lossbased'

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.

Ejemplo: 'NumKLInitializations',5

Tipos de datos: single | double

Predictor data observation dimension, specified as the comma-separated pair consisting of 'ObservationsIn' and 'columns' or 'rows'. Mdl.BinaryLearners must contain linear classification models.

Nota

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.

Estimation options, specified as the comma-separated pair consisting of 'Options' and a structure array returned by statset.

To invoke parallel computing:

  • You need a Parallel Computing Toolbox™ license.

  • Specify 'Options',statset('UseParallel',1).

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

Ejemplo: 'PosteriorMethod','qp'

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.

Ejemplo: 'Verbose',1

Tipos de datos: single | double

Output Arguments

expandir todo

Predicted class labels, returned as a categorical, character, logical, or numeric array, or cell array of character vectors. The software 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).

label is of the same data type as the class labels used to train Mdl. (The software treats string arrays as cell arrays of character vectors.) The number of rows of label and the number of observations in X are equal.

If Mdl.BinaryLearners contains linear classification 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 (i.e., numel(Mdl.BinaryLearners{1}.Lambda)). 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.

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

  • If Mdl.BinaryLearners contains linear classification models, then NegLoss is a 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 (that is, numel(Mdl.ClassNames)).

    • L is the number of regularization strengths in the linear classification models (that is, numel(Mdl.BinaryLearners{1}.Lambda)).

    NegLoss(i,k,j) is the negated, average binary loss for observation i, corresponding to class Mdl.ClassNames(k), for the model trained using regularization strength Mdl.BinaryLearners{1}.Lambda(j).

  • Otherwise, NegLoss is an m-by-K matrix.

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

  • If Mdl.BinaryLearners contains linear classification models, then PBScore is an m-by-B-by-L array.

    • m is the number of observations in X.

    • B is the number of binary learners (that is, numel(Mdl.BinaryLearners)).

    • L is the number of regularization strengths in the linear classification models (that is, numel(Mdl.BinaryLearners{1}.Lambda)).

    PBScore(i,b,j) is the positive-class score for observation i, using binary learner b, for the model trained using regularization strength Mdl.BinaryLearners{1}.Lambda(j).

  • Otherwise, PBScore is an m-by-B matrix.

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

  • If Mdl.BinaryLearners contains linear classification models, then Posterior is an m-by-K-by-L array. For dimension definitions, see NegLoss. Posterior(i,k,j) is the posterior probability that observation i comes from class Mdl.ClassNames(k), for the model trained using regularization strength Mdl.BinaryLearners{1}.Lambda(j).

  • Otherwise, Posterior is an m-by-K matrix.

Ejemplos

expandir todo

Load Fisher's iris data set.

load fisheriris
X = meas;
Y = categorical(species);
classOrder = unique(Y);
rng(1); % For reproducibility

Train an ECOC model using SVM binary classifiers and specify a 30% holdout sample. It is good practice to define the class order. Specify to standardize the predictors using an SVM template.

t = templateSVM('Standardize',1);
CVMdl = fitcecoc(X,Y,'Holdout',0.30,'Learners',t,'ClassNames',classOrder);
CMdl = CVMdl.Trained{1};           % Extract trained, compact classifier
testInds = test(CVMdl.Partition);  % Extract the test indices
XTest = X(testInds,:);
YTest = Y(testInds,:);

CVMdl is a ClassificationPartitionedECOC model. It contains the property Trained, which is a 1-by-1 cell array holding a CompactClassificationECOC model that the software trained using the training set.

Predict the test-sample labels. Print a random subset of true and predicted labels.

labels = predict(CMdl,XTest);
idx = randsample(sum(testInds),10);
table(YTest(idx),labels(idx),...
    'VariableNames',{'TrueLabels','PredictedLabels'})
ans =

  10x2 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 labeled all except one of the test-sample observations with indices idx.

Load Fisher's iris data set.

load fisheriris
X = meas;
Y = categorical(species);
classOrder = unique(Y); % Class order
K = numel(classOrder);  % Number of classes
rng(1); % For reproducibility

Train an ECOC model using SVM binary classifiers and specify a 30% holdout sample. It is good practice to define the class order. Specify to standardize the predictors using an SVM template.

t = templateSVM('Standardize',1);
CVMdl = fitcecoc(X,Y,'Holdout',0.30,'Learners',t,'ClassNames',classOrder);
CMdl = CVMdl.Trained{1};           % Extract trained, compact classifier
testInds = test(CVMdl.Partition);  % Extract the test indices
XTest = X(testInds,:);
YTest = Y(testInds,:);

CVMdl is a ClassificationPartitionedECOC model. It contains the property Trained, which is a 1-by-1 cell array holding a 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:

  • Maps the coding design matrix (M) and positive-class classification scores (s) for each learner to the binary loss for each observation

  • Uses linear loss

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

customBL = @(M,s)nanmedian(1 - bsxfun(@times,M,s),2)/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.

[label,NegLoss] = predict(CMdl,XTest,'BinaryLoss',customBL);

idx = randsample(sum(testInds),10);
classOrder
table(YTest(idx),label(idx),NegLoss(idx,:),'VariableNames',...
    {'TrueLabel','PredictedLabel','NegLoss'})
classOrder = 

  3x1 categorical array

     setosa 
     versicolor 
     virginica 


ans =

  10x3 table

    TrueLabel     PredictedLabel                 NegLoss              
    __________    ______________    __________________________________

    setosa          versicolor        0.1857       1.9878      -3.6735
    versicolor      virginica        -1.3316     -0.12333    -0.045053
    setosa          versicolor       0.13898       1.9261      -3.5651
    virginica       virginica        -1.5133     -0.38263      0.39592
    versicolor      versicolor      -0.87209      0.74777      -1.3757
    setosa          versicolor       0.48381       1.9972       -3.981
    virginica       virginica        -1.9364     -0.67508       1.1114
    virginica       virginica         -1.579     -0.83339      0.91235
    setosa          versicolor       0.51001       2.1208      -4.1308
    setosa          versicolor       0.36119       2.0594      -3.9206

The order of the columns corresponds to the elements of classOrder. The software predicts the label based on the maximum negated loss. The results seem to indicate that the median of the linear losses might not perform as well as other losses.

Load Fisher's iris data set. Train the classifier using the petal dimensions as predictors.

load fisheriris
X = meas(:,3:4);
Y = species;
rng(1); % For reproducibility

Create an SVM template, and specify the Gaussian kernel. It is good practice to standardize the predictors.

t = templateSVM('Standardize',1,'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. Display diagnostic messages during the training using the 'Verbose' name-value pair argument. It is good practice to specify the class order.

Mdl = fitcecoc(X,Y,'Learners',t,'FitPosterior',1,...
    '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 in-sample labels and class posterior probabilities. Display diagnostic messages during the computation of labels and class posterior probabilities using the 'Verbose' name-value pair argument.

[label,~,~,Posterior] = resubPredict(Mdl,'Verbose',1);
Mdl.BinaryLoss
Predictions from all learners have been computed.
Loss for all observations has been computed.
Computing posterior probabilities...

ans =

    'quadratic'

The software assigns an observation to the class that yields the smallest average binary loss. Since 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
table(Y(idx),label(idx),Posterior(idx,:),...
    'VariableNames',{'TrueLabel','PredLabel','Posterior'})
ans =

  3x1 cell array

    {'setosa'    }
    {'versicolor'}
    {'virginica' }


ans =

  10x3 table

     TrueLabel       PredLabel                    Posterior               
    ____________    ____________    ______________________________________

    'virginica'     'virginica'      0.0039321     0.0039869       0.99208
    'virginica'     'virginica'       0.017067      0.018263       0.96467
    'virginica'     'virginica'       0.014948      0.015856        0.9692
    'versicolor'    'versicolor'    2.2197e-14       0.87317       0.12683
    'setosa'        'setosa'             0.999    0.00025091    0.00074639
    'versicolor'    'virginica'     2.2195e-14      0.059429       0.94057
    'versicolor'    'versicolor'    2.2194e-14       0.97001      0.029986
    'setosa'        'setosa'             0.999     0.0002499    0.00074741
    'versicolor'    'versicolor'     0.0085646       0.98259      0.008849
    '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.

figure;
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

Train an error-correcting output codes, multiclass model and estimate posterior probabilities using parallel computing.

Load the arrhythmia data set. Determine the class distribution.

load arrhythmia
Y = categorical(Y);
tabulate(Y)
n = numel(Y);
K = numel(unique(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 the options are empty ([]). The software uses default values for all empty options during training.

Since there are many classes, specify a sparse random coding design.

rng(1); % For reproducibility
Coding = designecoc(K,'sparserandom');

Train an ECOC model using parallel computing. Hold out 15% of the data and fit posterior probabilities.

pool = parpool;                      % Invokes workers
options = statset('UseParallel',1);
CVMdl = fitcecoc(X,Y,'Learner',t,'Options',options,'Coding',Coding,...
    'FitPosterior',1,'Holdout',0.15);

CMdl = CVMdl.Trained{1};           % Extract trained, compact classifier
testInds = test(CVMdl.Partition);  % Extract the test indices
XTest = X(testInds,:);
YTest = Y(testInds,:);
Starting parallel pool  parpool  using the 'local' profile ... connected to 4 workers.

CVMdl is a ClassificationPartitionedECOC model. It contains the property Trained, which is a 1-by-1 cell array holding a CompactClassificationECOC model that the software trained using the training set.

The pool invokes four workers. 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.

[~,~,~,posterior] = predict(CMdl,XTest,'Options',options);
idx = randsample(sum(testInds),10);
table(idx,YTest(idx),posterior(idx,1),...
    'VariableNames',{'TestSampleIndex','TrueLabel','PosteriorNoArrhythmia'})
ans = 

    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              

Más acerca de

expandir todo

Algoritmos

expandir todo

  • If you train Mdl specifying to standardize the predictor data, then the software standardizes the columns of X using the corresponding means and standard deviations that the software stored in Mdl.BinaryLearner{j}.Mu and Mdl.BinaryLearner{j}.Sigma for learner j.

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

    • p^k 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.

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

[4] Escalera, S., O. Pujol, and P. Radeva. “Separability of ternary codes for sparse designs of error-correcting output codes.” Pattern Recognition. Vol. 30, Issue 3, 2009, pp. 285–297.

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

Capacidades ampliadas

Introducido en R2014b