Documentation

### This is machine translation

Mouseover text to see original. Click the button below to return to the English version of the page.

Note: This page has been translated by MathWorks. Click here to see
To view all translated materials including this page, select Country from the country navigator on the bottom of this page.

# fitcdiscr

Fit discriminant analysis classifier

## Syntax

``Mdl = fitcdiscr(Tbl,ResponseVarName)``
``Mdl = fitcdiscr(Tbl,formula)``
``Mdl = fitcdiscr(Tbl,Y)``
``Mdl = fitcdiscr(X,Y)``
``Mdl = fitcdiscr(___,Name,Value)``

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

collapse all

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 | 1.4459 | 0.66667 | 0.66667 | 13.261 | 0.25218 | | 2 | Best | 0.02 | 0.63063 | 0.02 | 0.064227 | 2.7404e-05 | 0.073264 | | 3 | Accept | 0.04 | 0.74182 | 0.02 | 0.020084 | 3.2455e-06 | 0.46974 | | 4 | Accept | 0.66667 | 0.43767 | 0.02 | 0.020118 | 14.879 | 0.98622 | | 5 | Accept | 0.046667 | 0.38335 | 0.02 | 0.019907 | 0.00031449 | 0.97362 | | 6 | Accept | 0.04 | 0.44811 | 0.02 | 0.028438 | 4.5092e-05 | 0.43616 | | 7 | Accept | 0.046667 | 0.26748 | 0.02 | 0.031424 | 2.0973e-05 | 0.9942 | | 8 | Accept | 0.02 | 0.18823 | 0.02 | 0.022424 | 1.0554e-06 | 0.0024286 | | 9 | Accept | 0.02 | 0.29681 | 0.02 | 0.021105 | 1.1232e-06 | 0.00014039 | | 10 | Accept | 0.02 | 0.26399 | 0.02 | 0.020948 | 0.00011837 | 0.0032994 | | 11 | Accept | 0.02 | 0.39208 | 0.02 | 0.020172 | 1.0292e-06 | 0.027725 | | 12 | Accept | 0.02 | 0.234 | 0.02 | 0.020105 | 9.7792e-05 | 0.0022817 | | 13 | Accept | 0.02 | 0.27842 | 0.02 | 0.020038 | 0.00036014 | 0.0015136 | | 14 | Accept | 0.02 | 0.26855 | 0.02 | 0.019597 | 0.00021059 | 0.0044789 | | 15 | Accept | 0.02 | 0.40725 | 0.02 | 0.019461 | 1.1911e-05 | 0.0010135 | | 16 | Accept | 0.02 | 0.30443 | 0.02 | 0.01993 | 0.0017896 | 0.00071115 | | 17 | Accept | 0.02 | 0.19851 | 0.02 | 0.019551 | 0.00073745 | 0.0066899 | | 18 | Accept | 0.02 | 0.28091 | 0.02 | 0.019776 | 0.00079304 | 0.00011509 | | 19 | Accept | 0.02 | 0.24751 | 0.02 | 0.019678 | 0.007292 | 0.0007911 | | 20 | Accept | 0.046667 | 0.3518 | 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.25111 | 0.02 | 0.019043 | 0.0036004 | 0.0024547 | | 22 | Accept | 0.02 | 0.20161 | 0.02 | 0.019755 | 2.5238e-05 | 0.0015542 | | 23 | Accept | 0.02 | 0.20119 | 0.02 | 0.0191 | 1.5478e-05 | 0.0026899 | | 24 | Accept | 0.02 | 0.25256 | 0.02 | 0.019081 | 0.0040557 | 0.00046815 | | 25 | Accept | 0.02 | 0.2716 | 0.02 | 0.019333 | 2.959e-05 | 0.0011358 | | 26 | Accept | 0.02 | 0.24121 | 0.02 | 0.019369 | 2.3111e-06 | 0.0029205 | | 27 | Accept | 0.02 | 0.15572 | 0.02 | 0.019455 | 3.8898e-05 | 0.0011665 | | 28 | Accept | 0.02 | 0.27372 | 0.02 | 0.019449 | 0.0035925 | 0.0020278 | | 29 | Accept | 0.66667 | 0.32308 | 0.02 | 0.019479 | 998.93 | 0.064276 | | 30 | Accept | 0.02 | 0.24221 | 0.02 | 0.01947 | 8.1557e-06 | 0.0008004 | __________________________________________________________ Optimization completed. MaxObjectiveEvaluations of 30 reached. Total function evaluations: 30 Total elapsed time: 95.7914 seconds. Total objective function evaluation time: 10.4815 Best observed feasible point: Delta Gamma __________ ________ 2.7404e-05 0.073264 Observed objective function value = 0.02 Estimated objective function value = 0.01947 Function evaluation time = 0.63063 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.24834 ```
```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 achieved 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.

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

When you execute calculations on tall arrays, the default execution environment uses either the local MATLAB session or a local parallel pool (if you have Parallel Computing Toolbox™). You can use the `mapreducer` function to change the execution environment.

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 Columns 1 through 5 10 21 3 642 8 10 26 1 1021 8 10 23 5 2055 21 10 23 5 1332 13 10 22 4 629 4 10 28 3 1446 59 10 8 4 928 3 10 10 6 859 11 : : : : : : : : : : Column 6 308 296 480 296 373 308 447 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 Control Where Your Code Runs (MATLAB).

```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 1.2 sec - Pass 2 of 2: Completed in 2.9 sec Evaluation completed in 5.2 sec Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 2.2 sec Evaluation completed in 2.3 sec |======================================================================================| | Iter | Eval | Objective | Objective | BestSoFar | BestSoFar | DiscrimType | | | result | | runtime | (observed) | (estim.) | | |======================================================================================| | 1 | Best | 0.11354 | 13.025 | 0.11354 | 0.11354 | quadratic | Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 2 sec Evaluation completed in 2.8 sec Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 1.4 sec Evaluation completed in 1.5 sec | 2 | Accept | 0.11354 | 8.9294 | 0.11354 | 0.11354 | pseudoQuadra | Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 1.4 sec Evaluation completed in 2.3 sec Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 1.9 sec Evaluation completed in 1.9 sec | 3 | Accept | 0.12869 | 9.0278 | 0.11354 | 0.11859 | pseudoLinear | Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 2 sec Evaluation completed in 2.8 sec Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 1.9 sec Evaluation completed in 2 sec | 4 | Accept | 0.12745 | 9.718 | 0.11354 | 0.1208 | diagLinear | Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 1.9 sec Evaluation completed in 2.7 sec Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 1.9 sec Evaluation completed in 1.9 sec | 5 | Accept | 0.12869 | 9.4755 | 0.11354 | 0.12238 | linear | Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 1.9 sec Evaluation completed in 2.7 sec Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 1.9 sec Evaluation completed in 1.9 sec | 6 | Best | 0.11301 | 9.0462 | 0.11301 | 0.12082 | diagQuadrati | Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 1.5 sec Evaluation completed in 2.2 sec Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 1.9 sec Evaluation completed in 2 sec | 7 | Accept | 0.11301 | 8.6959 | 0.11301 | 0.11301 | diagQuadrati | Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 2 sec Evaluation completed in 2.7 sec Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 1.9 sec Evaluation completed in 2 sec | 8 | Accept | 0.11301 | 9.2616 | 0.11301 | 0.11301 | diagQuadrati | Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 1.5 sec Evaluation completed in 2.3 sec Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 1.9 sec Evaluation completed in 2 sec | 9 | Accept | 0.11301 | 8.6907 | 0.11301 | 0.11301 | diagQuadrati | Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 2 sec Evaluation completed in 2.8 sec Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 1.9 sec Evaluation completed in 1.9 sec | 10 | Accept | 0.11301 | 9.3004 | 0.11301 | 0.11301 | diagQuadrati | Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 2 sec Evaluation completed in 2.8 sec Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 1.5 sec Evaluation completed in 1.5 sec | 11 | Accept | 0.11301 | 8.8961 | 0.11301 | 0.11301 | diagQuadrati | Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 2 sec Evaluation completed in 2.8 sec Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 1.9 sec Evaluation completed in 1.9 sec | 12 | Accept | 0.11301 | 9.1222 | 0.11301 | 0.11301 | diagQuadrati | Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 2 sec Evaluation completed in 2.8 sec Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 1.9 sec Evaluation completed in 1.9 sec | 13 | Accept | 0.11301 | 9.2164 | 0.11301 | 0.11301 | diagQuadrati | Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 2 sec Evaluation completed in 2.8 sec Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 1.9 sec Evaluation completed in 2 sec | 14 | Accept | 0.11301 | 9.2715 | 0.11301 | 0.11301 | diagQuadrati | Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 2 sec Evaluation completed in 2.8 sec Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 1.3 sec Evaluation completed in 1.4 sec | 15 | Accept | 0.11301 | 8.8737 | 0.11301 | 0.11301 | diagQuadrati | Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 1.5 sec Evaluation completed in 2.2 sec Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 1.9 sec Evaluation completed in 1.9 sec | 16 | Accept | 0.11301 | 8.7873 | 0.11301 | 0.11301 | diagQuadrati | Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 2 sec Evaluation completed in 2.8 sec Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 1.4 sec Evaluation completed in 1.5 sec | 17 | Accept | 0.11301 | 8.6403 | 0.11301 | 0.11301 | diagQuadrati | Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 2.1 sec Evaluation completed in 2.8 sec Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 1.9 sec Evaluation completed in 1.9 sec | 18 | Accept | 0.11301 | 9.2828 | 0.11301 | 0.11301 | diagQuadrati | Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 2 sec Evaluation completed in 2.7 sec Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 1.9 sec Evaluation completed in 2 sec | 19 | Accept | 0.11301 | 9.2442 | 0.11301 | 0.11301 | diagQuadrati | Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 2 sec Evaluation completed in 2.8 sec Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 1.9 sec Evaluation completed in 2 sec | 20 | Accept | 0.11301 | 9.3528 | 0.11301 | 0.11301 | diagQuadrati | Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 2 sec Evaluation completed in 2.8 sec Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 1.9 sec Evaluation completed in 2 sec |======================================================================================| | Iter | Eval | Objective | Objective | BestSoFar | BestSoFar | DiscrimType | | | result | | runtime | (observed) | (estim.) | | |======================================================================================| | 21 | Accept | 0.11301 | 9.4836 | 0.11301 | 0.11301 | diagQuadrati | Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 2.1 sec Evaluation completed in 2.9 sec Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 1.9 sec Evaluation completed in 1.9 sec | 22 | Accept | 0.11301 | 9.2958 | 0.11301 | 0.11301 | diagQuadrati | Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 1.9 sec Evaluation completed in 2.6 sec Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 1.9 sec Evaluation completed in 1.9 sec | 23 | Accept | 0.11301 | 8.9416 | 0.11301 | 0.11301 | diagQuadrati | Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 2 sec Evaluation completed in 2.7 sec Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 1.9 sec Evaluation completed in 1.9 sec | 24 | Accept | 0.11354 | 9.0714 | 0.11301 | 0.11301 | pseudoQuadra | Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 1.9 sec Evaluation completed in 2.7 sec Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 1.9 sec Evaluation completed in 2 sec | 25 | Accept | 0.11301 | 9.2182 | 0.11301 | 0.11301 | diagQuadrati | Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 1.5 sec Evaluation completed in 2.2 sec Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 1.4 sec Evaluation completed in 1.4 sec | 26 | Accept | 0.11301 | 8.0149 | 0.11301 | 0.11301 | diagQuadrati | Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 1.5 sec Evaluation completed in 2.2 sec Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 1.9 sec Evaluation completed in 2 sec | 27 | Accept | 0.11354 | 8.6475 | 0.11301 | 0.11301 | quadratic | Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 2 sec Evaluation completed in 2.7 sec Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 1.9 sec Evaluation completed in 2 sec | 28 | Accept | 0.11354 | 9.2114 | 0.11301 | 0.11301 | quadratic | Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 1.9 sec Evaluation completed in 2.8 sec Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 2 sec Evaluation completed in 2 sec | 29 | Accept | 0.12869 | 9.5296 | 0.11301 | 0.11301 | pseudoLinear | Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 1.9 sec Evaluation completed in 2.6 sec Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 1.9 sec Evaluation completed in 1.9 sec | 30 | Accept | 0.11301 | 8.9192 | 0.11301 | 0.11301 | diagQuadrati | __________________________________________________________ Optimization completed. MaxObjectiveEvaluations of 30 reached. Total function evaluations: 30 Total elapsed time: 313.4344 seconds. Total objective function evaluation time: 276.1909 Best observed feasible point: DiscrimType _____________ diagQuadratic Observed objective function value = 0.11301 Estimated objective function value = 0.11301 Function evaluation time = 9.0462 Best estimated feasible point (according to models): DiscrimType _____________ diagQuadratic Estimated objective function value = 0.11301 Estimated function evaluation time = 9.0901 Evaluating tall expression using the Parallel Pool 'local': - Pass 1 of 1: Completed in 1.2 sec Evaluation completed in 2 sec ```
```Mdl = classreg.learning.classif.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: 313.4344 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

collapse all

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.

Data Types: `table`

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, logical or numeric vector, or 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.

It is a good practice to specify the order of the classes by using the `ClassNames` name-value pair argument.

Data Types: `char` | `string`

Explanatory model of the response 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. The variables must be variable names in `Tbl` (`Tbl.Properties.VariableNames`).

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

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), `<missing>`, and `<undefined>` 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 Pair Arguments

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

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 pair argument along with the `'OptimizeHyperparameters'` name-value pair argument. You can modify the cross-validation for `'OptimizeHyperparameters'` only by using the `'HyperparameterOptimizationOptions'` name-value pair argument.

#### Model Parameters

collapse all

Names of classes to use for training, specified as the comma-separated pair consisting of `'ClassNames'` and 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 `Y`.

If `ClassNames` is a character array, then each element must correspond to one row of the array.

Use `ClassNames` to:

• Order 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 `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`

`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'`

Predictor variable names, specified as the comma-separated pair consisting of `'PredictorNames'` and 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 give the predictor variables in `X` names.

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

• It is a good practice to specify the predictors for training using either `'PredictorNames'` or `formula` only.

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 the comma-separated pair consisting of `'ResponseName'` and a character vector or string scalar.

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 `predict` 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 the comma-separated pair consisting of `'ScoreTransform'` and 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 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

collapse all

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

Example: `'CrossVal','on'`

Cross-validation partition, specified as the comma-separated pair consisting of `'CVPartition'` and 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 use one of these four name-value pair arguments only: `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 the comma-separated pair consisting of `'Holdout'` and 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 use one of these four name-value pair arguments only: `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 the comma-separated pair consisting of `'KFold'` and 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 the cells of a `k`-by-1 cell vector in the `Trained` property of the cross-validated model.

To create a cross-validated model, you can use one of these four name-value pair arguments only: `CVPartition`, `Holdout`, `KFold`, or `Leaveout`.

Example: `'KFold',5`

Data Types: `single` | `double`

Leave-one-out cross-validation flag, specified as the comma-separated pair consisting of `'Leaveout'` and `'on'` or `'off'`. If you specify `'Leaveout','on'`, then, for each of the n observations (where n is the number of observations excluding missing observations, specified in the `NumObservations` property of the model), the software completes these steps:

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

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

To create a cross-validated model, you can use one of these four name-value pair arguments only: `CVPartition`, `Holdout`, `KFold`, or `Leaveout`.

Example: `'Leaveout','on'`

#### Hyperparameter Optimization

collapse all

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.

• `${\stackrel{^}{\Sigma }}_{\gamma }=\left(1-\gamma \right)\stackrel{^}{\Sigma }+\gamma \text{diag}\left(\stackrel{^}{\Sigma }\right).$`

$\stackrel{^}{\Sigma }$ 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'`

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`

#### Hyperparameter Optimization

collapse all

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

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 Classification Loss. To control the cross-validation type and other aspects of the optimization, use the `HyperparameterOptimizationOptions` name-value pair.

### Note

`'OptimizeHyperparameters'` values override any values you set using other name-value pair arguments. For example, setting `'OptimizeHyperparameters'` to `'auto'` causes the `'auto'` values to apply.

The eligible parameters for `fitcdiscr` are:

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

• `DiscrimType``fitcdiscr` searches among `'linear'`, `'quadratic'`, `'diagLinear'`, `'diagQuadratic'`, `'pseudoLinear'`, and `'pseudoQuadratic'`.

• `Gamma``fitcdiscr` 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, 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 log(1 + cross-validation loss) for regression and the misclassification rate for classification. To control the iterative display, set the `Verbose` field of the `'HyperparameterOptimizationOptions'` name-value pair argument. To control the plots, set the `ShowPlots` field of the `'HyperparameterOptimizationOptions'` name-value pair argument.

For an example, see Optimize Discriminant Analysis Model.

Example: `'auto'`

Options for optimization, specified as the comma-separated pair consisting of `'HyperparameterOptimizationOptions'` and a structure. This argument modifies the effect of the `OptimizeHyperparameters` name-value pair argument. All fields in the structure are optional.

Field NameValuesDefault
`Optimizer`
• `'bayesopt'` — Use Bayesian optimization. Internally, this setting calls `bayesopt`.

• `'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'`
`MaxObjectiveEvaluations`Maximum number of objective function evaluations.`30` for `'bayesopt'` or `'randomsearch'`, and the entire grid for `'gridsearch'`
`MaxTime`

Time limit, specified as a positive real. The time limit is in seconds, as measured by `tic` and `toc`. Run time can exceed `MaxTime` because `MaxTime` does not interrupt function evaluations.

`Inf`
`NumGridDivisions`For `'gridsearch'`, the number of values in each dimension. The value can be a vector of positive integers giving the number of values for each dimension, or a scalar that applies to all dimensions. This field is ignored for categorical variables.`10`
`ShowPlots`Logical value indicating whether to show plots. If `true`, this field plots the best objective function value against the iteration number. If there are one or two optimization parameters, and if `Optimizer` is `'bayesopt'`, then `ShowPlots` also plots a model of the objective function against the parameters.`true`
`SaveIntermediateResults`Logical value indicating whether to save results when `Optimizer` is `'bayesopt'`. If `true`, this field overwrites a workspace variable named `'BayesoptResults'` at each iteration. The variable is a `BayesianOptimization` object.`false`
`Verbose`

Display to the command line.

• `0` — No iterative display

• `1` — Iterative display

• `2` — Iterative display with extra information

For details, see the `bayesopt` `Verbose` name-value pair argument.

`1`
`UseParallel`Logical value indicating whether to run Bayesian optimization in parallel, which requires Parallel Computing Toolbox™. For details, see Parallel Bayesian Optimization.`false`
`Repartition`

Logical value indicating whether to repartition the cross-validation at every iteration. If `false`, the optimizer uses a single partition for the optimization.

`true` usually gives the most robust results because this setting 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 field names.
`CVPartition`A `cvpartition` object, as created by `cvpartition`.`'Kfold',5` if you do not specify any cross-validation field
`Holdout`A scalar in the range `(0,1)` representing the holdout fraction.
`Kfold`An integer greater than 1.

Example: `'HyperparameterOptimizationOptions',struct('MaxObjectiveEvaluations',60)`

Data Types: `struct`

## Output Arguments

collapse all

Trained discriminant analysis classification model, returned as a `ClassificationDiscriminant` model object or a `ClassificationPartitionedModel` 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

collapse all

### 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 (`gmdistribution`).

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

`$\stackrel{^}{y}=\underset{y=1,...,K}{\mathrm{arg}\mathrm{min}}\sum _{k=1}^{K}\stackrel{^}{P}\left(k|x\right)C\left(y|k\right),$`

where

• $\stackrel{^}{y}$ is the predicted classification.

• K is the number of classes.

• $\stackrel{^}{P}\left(k|x\right)$ is the posterior probability of class k for observation x.

• $C\left(y|k\right)$ is the cost of classifying an observation as y when its true class is k.

For details, see Prediction Using Discriminant Analysis Models.

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

## Alternative Functionality

### Functions

The `classify` 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.

Download ebook