main content

fit discriminant analysis classifier -凯发k8网页登录

fit discriminant analysis classifier

description

mdl = fitcdiscr(tbl,responsevarname) returns a fitted discriminant analysis model based on the input variables (also known as predictors, features, or attributes) contained in the table tbl and output (response or labels) contained in responsevarname.

mdl = fitcdiscr(tbl,formula) returns a fitted discriminant analysis model based on the input variables contained in the table tbl. formula is an explanatory model of the response and a subset of predictor variables in tbl used to fit mdl.

mdl = fitcdiscr(tbl,y) returns a fitted discriminant analysis model based on the input variables contained in the table tbl and response y.

example

mdl = fitcdiscr(x,y) returns a discriminant analysis classifier based on the input variables x and response y.

example

mdl = fitcdiscr(___,name,value) fits a classifier with additional options specified by one or more name-value pair arguments, using any of the previous syntaxes. for example, you can optimize hyperparameters to minimize the model’s cross-validation loss, or specify the cost of misclassification, the prior probabilities for each class, or the observation weights.

examples

load fisher's iris data set.

load fisheriris

train a discriminant analysis model using the entire data set.

mdl = fitcdiscr(meas,species)
mdl = 
  classificationdiscriminant
             responsename: 'y'
    categoricalpredictors: []
               classnames: {'setosa'  'versicolor'  'virginica'}
           scoretransform: 'none'
          numobservations: 150
              discrimtype: 'linear'
                       mu: [3x4 double]
                   coeffs: [3x3 struct]
  properties, methods

mdl is a classificationdiscriminant model. to access its properties, use dot notation. for example, display the group means for each predictor.

mdl.mu
ans = 3×4
    5.0060    3.4280    1.4620    0.2460
    5.9360    2.7700    4.2600    1.3260
    6.5880    2.9740    5.5520    2.0260

to predict labels for new observations, pass mdl and predictor data to predict.

this example shows how to optimize hyperparameters automatically using fitcdiscr. the example uses fisher's iris data.

load the data.

load fisheriris

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(1)
mdl = fitcdiscr(meas,species,'optimizehyperparameters','auto',...
    'hyperparameteroptimizationoptions',...
    struct('acquisitionfunctionname','expected-improvement-plus'))
|=====================================================================================================|
| iter | eval   | objective   | objective   | bestsofar   | bestsofar   |        delta |        gamma |
|      | result |             | runtime     | (observed)  | (estim.)    |              |              |
|=====================================================================================================|
|    1 | best   |     0.66667 |     0.78078 |     0.66667 |     0.66667 |       13.261 |      0.25218 |
|    2 | best   |        0.02 |     0.21703 |        0.02 |    0.064227 |   2.7404e-05 |     0.073264 |
|    3 | accept |        0.04 |     0.16635 |        0.02 |    0.020084 |   3.2455e-06 |      0.46974 |
|    4 | accept |     0.66667 |     0.40977 |        0.02 |    0.020118 |       14.879 |      0.98622 |
|    5 | accept |    0.046667 |      0.3931 |        0.02 |    0.019907 |   0.00031449 |      0.97362 |
|    6 | accept |        0.04 |     0.17642 |        0.02 |    0.028438 |   4.5092e-05 |      0.43616 |
|    7 | accept |    0.046667 |      0.1639 |        0.02 |    0.031424 |   2.0973e-05 |       0.9942 |
|    8 | accept |        0.02 |      0.1803 |        0.02 |    0.022424 |   1.0554e-06 |    0.0024286 |
|    9 | accept |        0.02 |     0.23864 |        0.02 |    0.021105 |   1.1232e-06 |   0.00014039 |
|   10 | accept |        0.02 |      0.3988 |        0.02 |    0.020948 |   0.00011837 |    0.0032994 |
|   11 | accept |        0.02 |     0.42415 |        0.02 |    0.020172 |   1.0292e-06 |     0.027725 |
|   12 | accept |        0.02 |     0.17113 |        0.02 |    0.020105 |   9.7792e-05 |    0.0022817 |
|   13 | accept |        0.02 |     0.17196 |        0.02 |    0.020038 |   0.00036014 |    0.0015136 |
|   14 | accept |        0.02 |     0.32145 |        0.02 |    0.019597 |   0.00021059 |    0.0044789 |
|   15 | accept |        0.02 |     0.20075 |        0.02 |    0.019461 |   1.1911e-05 |    0.0010135 |
|   16 | accept |        0.02 |     0.31766 |        0.02 |     0.01993 |    0.0017896 |   0.00071115 |
|   17 | accept |        0.02 |     0.15641 |        0.02 |    0.019551 |   0.00073745 |    0.0066899 |
|   18 | accept |        0.02 |     0.15582 |        0.02 |    0.019776 |   0.00079304 |   0.00011509 |
|   19 | accept |        0.02 |     0.20742 |        0.02 |    0.019678 |     0.007292 |    0.0007911 |
|   20 | accept |    0.046667 |     0.16348 |        0.02 |    0.019785 |    0.0074408 |      0.99945 |
|=====================================================================================================|
| iter | eval   | objective   | objective   | bestsofar   | bestsofar   |        delta |        gamma |
|      | result |             | runtime     | (observed)  | (estim.)    |              |              |
|=====================================================================================================|
|   21 | accept |        0.02 |     0.18501 |        0.02 |    0.019043 |    0.0036004 |    0.0024547 |
|   22 | accept |        0.02 |     0.15478 |        0.02 |    0.019755 |   2.5238e-05 |    0.0015542 |
|   23 | accept |        0.02 |     0.31243 |        0.02 |      0.0191 |   1.5478e-05 |    0.0026899 |
|   24 | accept |        0.02 |     0.12887 |        0.02 |    0.019081 |    0.0040557 |   0.00046815 |
|   25 | accept |        0.02 |     0.21078 |        0.02 |    0.019333 |    2.959e-05 |    0.0011358 |
|   26 | accept |        0.02 |     0.28811 |        0.02 |    0.019369 |   2.3111e-06 |    0.0029205 |
|   27 | accept |        0.02 |       0.274 |        0.02 |    0.019455 |   3.8898e-05 |    0.0011665 |
|   28 | accept |        0.02 |     0.17585 |        0.02 |    0.019449 |    0.0035925 |    0.0020278 |
|   29 | accept |     0.66667 |     0.30916 |        0.02 |    0.019479 |       998.93 |     0.064276 |
|   30 | accept |        0.02 |     0.42451 |        0.02 |     0.01947 |   8.1557e-06 |    0.0008004 |

figure contains an axes object. the axes object with title min objective vs. number of function evaluations, xlabel function evaluations, ylabel min objective contains 2 objects of type line. these objects represent min observed objective, estimated min objective.

figure contains an axes object. the axes object with title objective function model, xlabel delta, ylabel gamma contains 5 objects of type line, surface, contour. one or more of the lines displays its values using only markers these objects represent observed points, model mean, next point, model minimum feasible.

__________________________________________________________
optimization completed.
maxobjectiveevaluations of 30 reached.
total function evaluations: 30
total elapsed time: 48.3543 seconds
total objective function evaluation time: 7.8788
best observed feasible point:
      delta        gamma  
    __________    ________
    2.7404e-05    0.073264
observed objective function value = 0.02
estimated objective function value = 0.022693
function evaluation time = 0.21703
best estimated feasible point (according to models):
      delta         gamma  
    __________    _________
    2.5238e-05    0.0015542
estimated objective function value = 0.01947
estimated function evaluation time = 0.23296
mdl = 
  classificationdiscriminant
                         responsename: 'y'
                categoricalpredictors: []
                           classnames: {'setosa'  'versicolor'  'virginica'}
                       scoretransform: 'none'
                      numobservations: 150
    hyperparameteroptimizationresults: [1x1 bayesianoptimization]
                          discrimtype: 'linear'
                                   mu: [3x4 double]
                               coeffs: [3x3 struct]
  properties, methods

the fit achieves about 2% loss for the default 5-fold cross validation.

this example shows how to optimize hyperparameters of a discriminant analysis model automatically using a tall array. the sample data set airlinesmall.csv is a large data set that contains a tabular file of airline flight data. this example creates a tall table containing the data and uses it to run the optimization procedure.

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 location with the data. select a subset of the variables to work with, and treat 'na' values as missing data so that datastore replaces them with nan values. create a tall table that contains the data in the datastore.

ds = datastore('airlinesmall.csv');
ds.selectedvariablenames = {'month','dayofmonth','dayofweek',...
                            'deptime','arrdelay','distance','depdelay'};
ds.treatasmissing = 'na';
tt  = tall(ds) % tall table
starting parallel pool (parpool) using the 'local' profile ...
connected to the parallel pool (number of workers: 6).
tt =
  m×7 tall table
    month    dayofmonth    dayofweek    deptime    arrdelay    distance    depdelay
    _____    __________    _________    _______    ________    ________    ________
     10          21            3          642          8         308          12   
     10          26            1         1021          8         296           1   
     10          23            5         2055         21         480          20   
     10          23            5         1332         13         296          12   
     10          22            4          629          4         373          -1   
     10          28            3         1446         59         308          63   
     10           8            4          928          3         447          -2   
     10          10            6          859         11         954          -1   
      :          :             :           :          :           :           :
      :          :             :           :          :           :           :

determine the flights that are late by 10 minutes or more by defining a logical variable that is true for a late flight. this variable contains the class labels. a preview of this variable includes the first few rows.

y = tt.depdelay > 10 % class labels
y =
  m×1 tall logical array
   1
   0
   1
   1
   0
   1
   0
   0
   :
   :

create a tall array for the predictor data.

x = tt{:,1:end-1} % predictor data
x =
  m×6 tall double matrix
          10          21           3         642           8         308
          10          26           1        1021           8         296
          10          23           5        2055          21         480
          10          23           5        1332          13         296
          10          22           4         629           4         373
          10          28           3        1446          59         308
          10           8           4         928           3         447
          10          10           6         859          11         954
          :           :            :          :           :           :
          :           :            :          :           :           :

remove rows in x and y that contain missing data.

r = rmmissing([x y]); % data with missing entries removed
x = r(:,1:end-1); 
y = r(:,end); 

standardize the predictor variables.

z = zscore(x);

optimize hyperparameters automatically using the 'optimizehyperparameters' name-value pair argument. find the optimal 'discrimtype' value that minimizes holdout cross-validation loss. (specifying 'auto' uses 'discrimtype'.) for reproducibility, use the 'expected-improvement-plus' acquisition function and 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')
[mdl,fitinfo,hyperparameteroptimizationresults] = fitcdiscr(z,y,...
    'optimizehyperparameters','auto',...
    'hyperparameteroptimizationoptions',struct('holdout',0.3,...
    'acquisitionfunctionname','expected-improvement-plus'))
evaluating tall expression using the parallel pool 'local':
- pass 1 of 2: completed in 5.7 sec
- pass 2 of 2: completed in 4.3 sec
evaluation completed in 16 sec
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 2.5 sec
evaluation completed in 2.8 sec
|======================================================================================|
| iter | eval   | objective   | objective   | bestsofar   | bestsofar   |  discrimtype |
|      | result |             | runtime     | (observed)  | (estim.)    |              |
|======================================================================================|
|    1 | best   |     0.11354 |      25.315 |     0.11354 |     0.11354 |    quadratic |
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 1.5 sec
evaluation completed in 2.7 sec
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 1.4 sec
evaluation completed in 1.6 sec
|    2 | accept |     0.11354 |      7.9367 |     0.11354 |     0.11354 | pseudoquadra |
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.87 sec
evaluation completed in 2 sec
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.78 sec
evaluation completed in 0.91 sec
|    3 | accept |     0.12869 |      6.5057 |     0.11354 |     0.11859 | pseudolinear |
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.9 sec
evaluation completed in 1.7 sec
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 1.3 sec
evaluation completed in 1.4 sec
|    4 | accept |     0.12745 |      6.4167 |     0.11354 |      0.1208 |   diaglinear |
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.85 sec
evaluation completed in 1.7 sec
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.8 sec
evaluation completed in 0.93 sec
|    5 | accept |     0.12869 |      6.1236 |     0.11354 |     0.12238 |       linear |
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.85 sec
evaluation completed in 1.5 sec
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.75 sec
evaluation completed in 0.9 sec
|    6 | best   |     0.11301 |      5.4147 |     0.11301 |     0.12082 | diagquadrati |
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.82 sec
evaluation completed in 1.5 sec
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.77 sec
evaluation completed in 0.89 sec
|    7 | accept |     0.11301 |       5.297 |     0.11301 |     0.11301 | diagquadrati |
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.84 sec
evaluation completed in 1.5 sec
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.8 sec
evaluation completed in 0.93 sec
|    8 | accept |     0.11301 |      5.6152 |     0.11301 |     0.11301 | diagquadrati |
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 1.3 sec
evaluation completed in 2.1 sec
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.75 sec
evaluation completed in 0.88 sec
|    9 | accept |     0.11301 |      5.9147 |     0.11301 |     0.11301 | diagquadrati |
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.88 sec
evaluation completed in 1.6 sec
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 1.3 sec
evaluation completed in 1.4 sec
|   10 | accept |     0.11301 |      6.0504 |     0.11301 |     0.11301 | diagquadrati |
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.82 sec
evaluation completed in 1.5 sec
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 1.3 sec
evaluation completed in 1.4 sec
|   11 | accept |     0.11301 |      5.9595 |     0.11301 |     0.11301 | diagquadrati |
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.86 sec
evaluation completed in 1.6 sec
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.76 sec
evaluation completed in 0.91 sec
|   12 | accept |     0.11301 |      5.4266 |     0.11301 |     0.11301 | diagquadrati |
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.88 sec
evaluation completed in 1.6 sec
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.75 sec
evaluation completed in 0.87 sec
|   13 | accept |     0.11301 |      5.3869 |     0.11301 |     0.11301 | diagquadrati |
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.83 sec
evaluation completed in 1.5 sec
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.8 sec
evaluation completed in 0.97 sec
|   14 | accept |     0.11301 |      5.4876 |     0.11301 |     0.11301 | diagquadrati |
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.85 sec
evaluation completed in 1.5 sec
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.73 sec
evaluation completed in 0.85 sec
|   15 | accept |     0.11301 |      5.4052 |     0.11301 |     0.11301 | diagquadrati |
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.87 sec
evaluation completed in 1.5 sec
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.78 sec
evaluation completed in 0.9 sec
|   16 | accept |     0.11301 |      5.4434 |     0.11301 |     0.11301 | diagquadrati |
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.89 sec
evaluation completed in 1.6 sec
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.8 sec
evaluation completed in 0.93 sec
|   17 | accept |     0.11301 |      5.5804 |     0.11301 |     0.11301 | diagquadrati |
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.94 sec
evaluation completed in 1.6 sec
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.79 sec
evaluation completed in 0.92 sec
|   18 | accept |     0.11354 |       5.616 |     0.11301 |     0.11301 | pseudoquadra |
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.85 sec
evaluation completed in 1.5 sec
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.76 sec
evaluation completed in 0.88 sec
|   19 | accept |     0.11301 |      5.4031 |     0.11301 |     0.11301 | diagquadrati |
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.76 sec
evaluation completed in 1.4 sec
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.75 sec
evaluation completed in 0.88 sec
|   20 | accept |     0.11301 |      5.1974 |     0.11301 |     0.11301 | diagquadrati |
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.77 sec
evaluation completed in 1.4 sec
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.75 sec
evaluation completed in 0.87 sec
|======================================================================================|
| iter | eval   | objective   | objective   | bestsofar   | bestsofar   |  discrimtype |
|      | result |             | runtime     | (observed)  | (estim.)    |              |
|======================================================================================|
|   21 | accept |     0.11301 |      5.1418 |     0.11301 |     0.11301 | diagquadrati |
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 1.3 sec
evaluation completed in 2 sec
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.73 sec
evaluation completed in 0.86 sec
|   22 | accept |     0.11301 |      5.9864 |     0.11301 |     0.11301 | diagquadrati |
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.88 sec
evaluation completed in 1.6 sec
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.78 sec
evaluation completed in 0.91 sec
|   23 | accept |     0.11354 |      5.5656 |     0.11301 |     0.11301 |    quadratic |
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.82 sec
evaluation completed in 1.5 sec
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.77 sec
evaluation completed in 0.9 sec
|   24 | accept |     0.11354 |      5.3012 |     0.11301 |     0.11301 | pseudoquadra |
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 1.4 sec
evaluation completed in 2.1 sec
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.77 sec
evaluation completed in 0.9 sec
|   25 | accept |     0.11301 |      6.2276 |     0.11301 |     0.11301 | diagquadrati |
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.86 sec
evaluation completed in 1.6 sec
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.77 sec
evaluation completed in 0.89 sec
|   26 | accept |     0.11301 |      5.5308 |     0.11301 |     0.11301 | diagquadrati |
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.92 sec
evaluation completed in 1.6 sec
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.88 sec
evaluation completed in 1 sec
|   27 | accept |     0.11301 |      5.7396 |     0.11301 |     0.11301 | diagquadrati |
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.83 sec
evaluation completed in 1.5 sec
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.78 sec
evaluation completed in 0.9 sec
|   28 | accept |     0.11354 |      5.4403 |     0.11301 |     0.11301 |    quadratic |
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.86 sec
evaluation completed in 1.5 sec
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.81 sec
evaluation completed in 0.93 sec
|   29 | accept |     0.11301 |      5.3572 |     0.11301 |     0.11301 | diagquadrati |
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.89 sec
evaluation completed in 1.6 sec
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.74 sec
evaluation completed in 0.85 sec
|   30 | accept |     0.11354 |      5.2718 |     0.11301 |     0.11301 |    quadratic |

__________________________________________________________
optimization completed.
maxobjectiveevaluations of 30 reached.
total function evaluations: 30
total elapsed time: 229.5689 seconds.
total objective function evaluation time: 191.058
best observed feasible point:
     discrimtype 
    _____________
    diagquadratic
observed objective function value = 0.11301
estimated objective function value = 0.11301
function evaluation time = 5.4147
best estimated feasible point (according to models):
     discrimtype 
    _____________
    diagquadratic
estimated objective function value = 0.11301
estimated function evaluation time = 5.784
evaluating tall expression using the parallel pool 'local':
- pass 1 of 1: completed in 0.76 sec
evaluation completed in 1.4 sec
mdl = 
  compactclassificationdiscriminant
           predictornames: {'x1'  'x2'  'x3'  'x4'  'x5'  'x6'}
             responsename: 'y'
    categoricalpredictors: []
               classnames: [0 1]
           scoretransform: 'none'
              discrimtype: 'diagquadratic'
                       mu: [2×6 double]
                   coeffs: [2×2 struct]
  properties, methods
fitinfo = struct with no fields.
hyperparameteroptimizationresults = 
  bayesianoptimization with properties:
                      objectivefcn: @createobjfcn/tallobjfcn
              variabledescriptions: [1×1 optimizablevariable]
                           options: [1×1 struct]
                      minobjective: 0.1130
                   xatminobjective: [1×1 table]
             minestimatedobjective: 0.1130
          xatminestimatedobjective: [1×1 table]
           numobjectiveevaluations: 30
                  totalelapsedtime: 229.5689
                         nextpoint: [1×1 table]
                            xtrace: [30×1 table]
                    objectivetrace: [30×1 double]
                  constraintstrace: []
                     userdatatrace: {30×1 cell}
      objectiveevaluationtimetrace: [30×1 double]
                iterationtimetrace: [30×1 double]
                        errortrace: [30×1 double]
                  feasibilitytrace: [30×1 logical]
       feasibilityprobabilitytrace: [30×1 double]
               indexofminimumtrace: [30×1 double]
             objectiveminimumtrace: [30×1 double]
    estimatedobjectiveminimumtrace: [30×1 double]

input arguments

sample data used to train the model, specified as a table. each row of tbl corresponds to one observation, and each column corresponds to one predictor variable. 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 allowed.

  • if tbl contains the response variable, and you want to use all remaining variables in tbl as predictors, then specify the response variable by using responsevarname.

  • if tbl contains the response variable, and you want to use only a subset of the remaining variables in tbl as predictors, then specify a formula by using formula.

  • if tbl does not contain the response variable, then specify a response variable by using y. the length of the response variable and the number of rows in tbl must be equal.

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

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

class labels, specified as a categorical, character, or string array, a logical or numeric vector, or a cell array of character vectors. each row of y represents the classification of the corresponding row of x.

the software considers nan, '' (empty character vector), "" (empty string), , and values in y to be missing values. consequently, the software does not train using observations with a missing response.

data types: categorical | char | string | logical | single | double | cell

predictor values, specified as a numeric matrix. each column of x represents one variable, and each row represents one observation.

fitcdiscr considers nan values in x as missing values. fitcdiscr does not use observations with missing values for x in the fit.

data types: single | double

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: 'discrimtype','quadratic','savememory','on' specifies a quadratic discriminant classifier and does not store the covariance matrix in the output object.

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.

model parameters

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 of cost or the column order of classification scores returned by predict.

  • 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 of misclassification of a point, specified as the comma-separated pair consisting of 'cost' and one of the following:

  • square matrix, where cost(i,j) is the cost of classifying a point into class j if its true class is i (i.e., 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 of cost, additionally specify the classnames name-value pair argument.

  • structure s having two fields: s.classnames containing the group names as a variable of the same type as y, and s.classificationcosts containing the cost matrix.

the default is cost(i,j)=1 if i~=j, and cost(i,j)=0 if i=j.

data types: single | double | struct

linear coefficient threshold, specified as the comma-separated pair consisting of 'delta' and a nonnegative scalar value. if a coefficient of mdl has magnitude smaller than delta, mdl sets this coefficient to 0, and you can eliminate the corresponding predictor from the model. set delta to a higher value to eliminate more predictors.

delta must be 0 for quadratic discriminant models.

data types: single | double

discriminant type, specified as the comma-separated pair consisting of 'discrimtype' and a character vector or string scalar in this table.

valuedescriptionpredictor covariance treatment
'linear'regularized linear discriminant analysis (lda)
  • all classes have the same covariance matrix.

  • σ^γ=(1γ)σ^ γdiag(σ^).

    σ^ is the empirical, pooled covariance matrix and γ is the amount of regularization.

'diaglinear'ldaall classes have the same, diagonal covariance matrix.
'pseudolinear'ldaall classes have the same covariance matrix. the software inverts the covariance matrix using the pseudo inverse.
'quadratic'quadratic discriminant analysis (qda)the covariance matrices can vary among classes.
'diagquadratic'qdathe covariance matrices are diagonal and can vary among classes.
'pseudoquadratic'qdathe covariance matrices can vary among classes. the software inverts the covariance matrix using the pseudo inverse.

note

to use regularization, you must specify 'linear'. to specify the amount of regularization, use the gamma name-value pair argument.

example: 'discrimtype','quadratic'

coeffs property flag, specified as the comma-separated pair consisting of 'fillcoeffs' and 'on' or 'off'. setting the flag to 'on' populates the coeffs property in the classifier object. this can be computationally intensive, especially when cross-validating. the default is 'on', unless you specify a cross-validation name-value pair, in which case the flag is set to 'off' by default.

example: 'fillcoeffs','off'

amount of regularization to apply when estimating the covariance matrix of the predictors, specified as the comma-separated pair consisting of 'gamma' and a scalar value in the interval [0,1]. gamma provides finer control over the covariance matrix structure than discrimtype.

  • if you specify 0, then the software does not use regularization to adjust the covariance matrix. that is, the software estimates and uses the unrestricted, empirical covariance matrix.

    • for linear discriminant analysis, if the empirical covariance matrix is singular, then the software automatically applies the minimal regularization required to invert the covariance matrix. you can display the chosen regularization amount by entering mdl.gamma at the command line.

    • for quadratic discriminant analysis, if at least one class has an empirical covariance matrix that is singular, then the software throws an error.

  • if you specify a value in the interval (0,1), then you must implement linear discriminant analysis, otherwise the software throws an error. consequently, the software sets discrimtype to 'linear'.

  • if you specify 1, then the software uses maximum regularization for covariance matrix estimation. that is, the software restricts the covariance matrix to be diagonal. alternatively, you can set discrimtype to 'diaglinear' or 'diagquadratic' for diagonal covariance matrices.

example: 'gamma',1

data types: single | double

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 and y, then you can use predictornames to assign names to the predictor variables in x.

    • the order of the names in predictornames must correspond to the column order of x. that is, predictornames{1} is the name of x(:,1), predictornames{2} is the name of x(:,2), and so on. also, size(x,2) and numel(predictornames) must be equal.

    • by default, predictornames is {'x1','x2',...}.

  • if you supply tbl, then you can use predictornames to choose which predictor variables to use in training. that is, fitcdiscr uses only the predictor variables in predictornames and the response variable during training.

    • predictornames must be a subset of tbl.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 or formula, but not both.

example: "predictornames",["sepallength","sepalwidth","petallength","petalwidth"]

data types: string | cell

prior probabilities for each class, specified as the comma-separated pair consisting of 'prior' and a value in this table.

valuedescription
'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 vectoreach 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 s with two fields:

  • s.classnames contains the class names as a variable of the same type as y.

  • s.classprobs contains a vector of corresponding prior probabilities. the software normalizes the elements such that they sum to 1.

if you set values for both weights and prior, the weights are renormalized to add up to the value of the prior probability in the respective class.

example: 'prior','uniform'

data types: char | string | single | double | struct

response variable name, specified as a character vector or string scalar.

  • if you supply y, then you can use responsename to specify a name for the response variable.

  • if you supply responsevarname or formula, then you cannot use responsename.

example: "responsename","response"

data types: char | string

flag to save covariance matrix, specified as the comma-separated pair consisting of 'savememory' and either 'on' or 'off'. if you specify 'on', then fitcdiscr does not store the full covariance matrix, but instead stores enough information to compute the matrix. the method computes the full covariance matrix for prediction, and does not store the matrix. if you specify 'off', then fitcdiscr computes and stores the full covariance matrix in mdl.

specify savememory as 'on' when the input matrix contains thousands of predictors.

example: 'savememory','on'

score transformation, specified as a character vector, string scalar, or function handle.

this table summarizes the available character vectors and string scalars.

valuedescription
"doublelogit"1/(1 e–2x)
"invlogit"log(x / (1 – x))
"ismax"sets the score for the class with the largest score to 1, and sets the scores for all other classes to 0
"logit"1/(1 ex)
"none" or "identity"x (no transformation)
"sign"–1 for x < 0
0 for x = 0
1 for x > 0
"symmetric"2x – 1
"symmetricismax"sets the score for the class with the largest score to 1, and sets the scores for all other classes to –1
"symmetriclogit"2/(1 ex) – 1

for a matlab function or a function you define, use its function handle for the score transform. the function handle must accept a matrix (the original scores) and return a matrix of the same size (the transformed scores).

example: "scoretransform","logit"

data types: char | string | function_handle

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(n,1), where n is the number of observations in x or tbl.

data types: double | single | char | string

cross-validation options

cross-validation flag, specified as the comma-separated pair consisting of 'crossval' and 'on' or 'off'.

if you specify 'on', then the software implements 10-fold cross-validation.

to override this cross-validation setting, use one of these name-value pair arguments: cvpartition, holdout, kfold, or leaveout. to create a cross-validated model, you can use one cross-validation name-value pair argument at a time only.

alternatively, cross-validate later by passing mdl to .

example: 'crossval','on'

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.

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:

  1. randomly select and reserve p*100% of the data as validation data, and train the model using the rest of the data.

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

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:

  1. randomly partition the data into k sets.

  2. for each set, reserve the set as validation data, and train the model using the other k – 1 sets.

  3. store the k compact, trained models in a k-by-1 cell vector in the trained property of the cross-validated model.

to create a cross-validated model, you can specify only one of these four name-value arguments: cvpartition, holdout, kfold, or leaveout.

example: 'kfold',5

data types: single | double

leave-one-out cross-validation flag, specified as 'on' or 'off'. if you specify 'leaveout','on', then for each of the n observations (where n is the number of observations, excluding missing observations, specified in the numobservations property of the model), the software completes these steps:

  1. reserve the one observation as validation data, and train the model using the other n – 1 observations.

  2. store the n compact, trained models in an n-by-1 cell vector in the trained property of the cross-validated model.

to create a cross-validated model, you can specify only one of these four name-value arguments: cvpartition, holdout, kfold, or leaveout.

example: 'leaveout','on'

hyperparameter optimization options

parameters to optimize, specified as the comma-separated pair consisting of 'optimizehyperparameters' and one of the following:

  • 'none' — do not optimize.

  • 'auto' — use {'delta','gamma'}.

  • '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 fitcdiscr by varying the parameters. for information about cross-validation loss (albeit in a different context), see . to control the cross-validation type and other aspects of the optimization, use the hyperparameteroptimizationoptions name-value pair.

note

the values of 'optimizehyperparameters' override any values you specify using other name-value arguments. for example, setting 'optimizehyperparameters' to 'auto' causes fitcdiscr to optimize hyperparameters corresponding to the 'auto' option and to ignore any specified values for the hyperparameters.

the eligible parameters for fitcdiscr are:

  • deltafitcdiscr searches among positive values, by default log-scaled in the range [1e-6,1e3].

  • discrimtypefitcdiscr searches among 'linear', 'quadratic', 'diaglinear', 'diagquadratic', 'pseudolinear', and 'pseudoquadratic'.

  • gammafitcdiscr searches among real values in the range [0,1].

set nondefault parameters by passing a vector of optimizablevariable objects that have nondefault values. for example,

load fisheriris
params = hyperparameters('fitcdiscr',meas,species);
params(1).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 discriminant analysis model.

example: 'auto'

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 namevaluesdefault
optimizer
  • 'bayesopt' — use bayesian optimization. internally, this setting calls .

  • 'gridsearch' — use grid search with numgriddivisions values per dimension.

  • 'randomsearch' — search at random among maxobjectiveevaluations points.

'gridsearch' searches in a random order, using uniform sampling without replacement from the grid. after optimization, you can get a table in grid order by using the command sortrows(mdl.hyperparameteroptimizationresults).

'bayesopt'
acquisitionfunctionname
  • 'expected-improvement-per-second-plus'

  • 'expected-improvement'

  • 'expected-improvement-plus'

  • 'expected-improvement-per-second'

  • 'lower-confidence-bound'

  • 'probability-of-improvement'

acquisition functions whose names include per-second do not yield reproducible results because the optimization depends on the runtime of the objective function. acquisition functions whose names include plus modify their behavior when they are overexploiting an area. for more details, see acquisition function types.

'expected-improvement-per-second-plus'
maxobjectiveevaluationsmaximum 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 tic and toc. the run time can exceed maxtime because maxtime does not interrupt function evaluations.

inf
numgriddivisionsfor '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
showplotslogical 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
saveintermediateresultslogical 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:

  • 0 — no iterative display

  • 1 — iterative display

  • 2 — iterative display with extra information

for details, see the bayesopt name-value argument and the example .

1
useparallellogical 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 false, the optimizer uses a single partition for the optimization.

the setting true usually gives the most robust results because it takes partitioning noise into account. however, for good results, true requires at least twice as many function evaluations.

false
use no more than one of the following three options.
cvpartitiona cvpartition object, as created by cvpartition'kfold',5 if you do not specify a cross-validation field
holdouta scalar in the range (0,1) representing the holdout fraction
kfoldan integer greater than 1

example: 'hyperparameteroptimizationoptions',struct('maxobjectiveevaluations',60)

data types: struct

output arguments

trained discriminant analysis classification model, returned as a model object or a cross-validated model object.

if you set any of the name-value pair arguments kfold, holdout, crossval, or cvpartition, then mdl is a classificationpartitionedmodel cross-validated model object. otherwise, mdl is a classificationdiscriminant model object.

to reference properties of mdl, use dot notation. for example, to display the estimated component means at the command window, enter mdl.mu.

more about

discriminant classification

the model for discriminant analysis is:

  • each class (y) generates data (x) using a multivariate normal distribution. that is, the model assumes x has a gaussian mixture distribution ().

    • for linear discriminant analysis, the model has the same covariance matrix for each class, only the means vary.

    • for quadratic discriminant analysis, both means and covariances of each class vary.

predict classifies so as to minimize the expected classification cost:

y^=argminy=1,...,kk=1kp^(k|x)c(y|k),

where

  • y^ is the predicted classification.

  • k is the number of classes.

  • p^(k|x) is the of class k for observation x.

  • c(y|k) is the of classifying an observation as y when its true class is k.

for details, see .

tips

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

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

  • the software uses the cost property for prediction, but not training. therefore, cost is not read-only; you can change the property value by using dot notation after creating the trained model.

alternative functionality

functions

the function also performs discriminant analysis. classify is usually more awkward to use.

  • classify requires you to fit the classifier every time you make a new prediction.

  • classify does not perform cross-validation or hyperparameter optimization.

  • classify requires you to fit the classifier when changing prior probabilities.

extended capabilities

version history

introduced in r2014a

see also

| | | |

topics

    网站地图