fit discriminant analysis classifier -凯发k8网页登录
fit discriminant analysis classifier
syntax
description
returns a fitted discriminant analysis model based on the input variables (also
known as predictors, features, or attributes) contained in the table
mdl
= fitcdiscr(tbl
,responsevarname
)tbl
and output (response or labels) contained in
responsevarname
.
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.mdl
= fitcdiscr(___,name,value
)
examples
train discriminant analysis model
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
.
optimize discriminant analysis model
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 |
__________________________________________________________ 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.
optimize discriminant analysis model on tall array
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
tbl
— sample data
table
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 intbl
as predictors, then specify the response variable by usingresponsevarname
.if
tbl
contains the response variable, and you want to use only a subset of the remaining variables intbl
as predictors, then specify a formula by usingformula
.if
tbl
does not contain the response variable, then specify a response variable by usingy
. the length of the response variable and the number of rows intbl
must be equal.
responsevarname
— response variable name
name of variable in tbl
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
formula
— explanatory model of response variable and subset of predictor variables
character vector | string scalar
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
y
— class labels
categorical array | character array | string array | logical vector | numeric vector | cell array of character vectors
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
x
— predictor data
numeric matrix
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.
classnames
— names of classes to use for training
categorical array | character array | string array | logical vector | numeric vector | cell array of character vectors
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 ofcost
or the column order of classification scores returned bypredict
.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
— cost of misclassification
square matrix | structure
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 classj
if its true class isi
(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 ofcost
, additionally specify theclassnames
name-value pair argument.structure
s
having two fields:s.classnames
containing the group names as a variable of the same type asy
, ands.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
delta
— linear coefficient threshold
0
(default) | nonnegative scalar value
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
discrimtype
— discriminant type
'linear'
(default) | 'quadratic'
| 'diaglinear'
| 'diagquadratic'
| 'pseudolinear'
| 'pseudoquadratic'
discriminant type, specified as the comma-separated pair consisting of
'discrimtype'
and a character vector or string scalar in this
table.
value | description | predictor covariance treatment |
---|---|---|
'linear' | regularized linear discriminant analysis (lda) |
|
'diaglinear' | lda | all classes have the same, diagonal covariance matrix. |
'pseudolinear' | lda | all 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' | qda | the covariance matrices are diagonal and can vary among classes. |
'pseudoquadratic' | qda | the 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'
fillcoeffs
— coeffs
property flag
'on'
| 'off'
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'
gamma
— amount of regularization
scalar value in the interval [0,1]
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 setdiscrimtype
to'diaglinear'
or'diagquadratic'
for diagonal covariance matrices.
example: 'gamma',1
data types: single
| double
predictornames
— predictor variable names
string array of unique names | cell array of unique character vectors
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
andy
, then you can usepredictornames
to assign names to the predictor variables inx
.the order of the names in
predictornames
must correspond to the column order ofx
. that is,predictornames{1}
is the name ofx(:,1)
,predictornames{2}
is the name ofx(:,2)
, and so on. also,size(x,2)
andnumel(predictornames)
must be equal.by default,
predictornames
is{'x1','x2',...}
.
if you supply
tbl
, then you can usepredictornames
to choose which predictor variables to use in training. that is,fitcdiscr
uses only the predictor variables inpredictornames
and the response variable during training.predictornames
must be a subset oftbl.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
orformula
, but not both.
example: "predictornames",["sepallength","sepalwidth","petallength","petalwidth"]
data types: string
| cell
prior
— prior probabilities
'empirical'
(default) | 'uniform'
| vector of scalar values | structure
prior probabilities for each class, specified as the comma-separated
pair consisting of 'prior'
and a value in this
table.
value | description |
---|---|
'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 vector | each 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
|
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
responsename
— response variable name
"y"
(default) | character vector | string scalar
response variable name, specified as a character vector or string scalar.
if you supply
y
, then you can useresponsename
to specify a name for the response variable.if you supply
responsevarname
orformula
, then you cannot useresponsename
.
example: "responsename","response"
data types: char
| string
savememory
— flag to save covariance matrix
'off'
(default) | 'on'
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'
scoretransform
— score transformation
"none"
(default) | "doublelogit"
| "invlogit"
| "ismax"
| "logit"
| function handle | ...
score transformation, specified as a character vector, string scalar, or function handle.
this table summarizes the available character vectors and string scalars.
value | description |
---|---|
"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 e–x) |
"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 e–x) – 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
weights
— observation weights
numeric vector of positive values | name of variable in tbl
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(
,
where n
,1)n
is the number of observations in x
or tbl
.
data types: double
| single
| char
| string
crossval
— cross-validation flag
'off'
(default) | 'on'
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'
cvpartition
— cross-validation partition
[]
(default) | cvpartition
partition object
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
.
holdout
— fraction of data for holdout validation
scalar value in the range (0,1)
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:
randomly select and reserve
p*100
% of the data as validation data, and train the model using the rest of the data.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
kfold
— number of folds
10
(default) | positive integer value greater than 1
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:
randomly partition the data into
k
sets.for each set, reserve the set as validation data, and train the model using the other
k
– 1 sets.store the
k
compact, trained models in ak
-by-1 cell vector in thetrained
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
leaveout
— leave-one-out cross-validation flag
'off'
(default) | 'on'
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:
reserve the one observation as validation data, and train the model using the other n – 1 observations.
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'
optimizehyperparameters
— parameters to optimize
'none'
(default) | 'auto'
| 'all'
| string array or cell array of eligible parameter names | vector of optimizablevariable
objects
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:
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, 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'
hyperparameteroptimizationoptions
— options for optimization
structure
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 name | values | default |
---|---|---|
optimizer |
| 'bayesopt' |
acquisitionfunctionname |
acquisition functions whose names include
| 'expected-improvement-per-second-plus' |
maxobjectiveevaluations | maximum 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 | 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 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 |
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 at the command line:
for details, see the | 1 |
useparallel | logical 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 the setting
| false |
use no more than one of the following three options. | ||
cvpartition | a cvpartition object, as created by cvpartition | 'kfold',5 if you do not specify a 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
mdl
— trained discriminant analysis classification model
classificationdiscriminant
model object | classificationpartitionedmodel
cross-validated model
object
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 assumesx
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:
where
is the predicted classification.
k is the number of classes.
is the of class k for observation x.
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
, andweights
name-value arguments, the output model object stores the specified values in thecost
,prior
, andw
properties, respectively. thecost
property stores the user-specified cost matrix as is. theprior
andw
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
tall arrays
calculate with arrays that have more rows than fit in memory.
usage notes and limitations:
supported syntaxes are:
mdl = fitcdiscr(tbl,y)
mdl = fitcdiscr(x,y)
mdl = fitcdiscr(___,name,value)
[mdl,fitinfo,hyperparameteroptimizationresults] = fitcdiscr(___,name,value)
—fitcdiscr
returns the additional output argumentsfitinfo
andhyperparameteroptimizationresults
when you specify the'optimizehyperparameters'
name-value pair argument.
the
fitinfo
output argument is an empty structure array currently reserved for possible future use.the
hyperparameteroptimizationresults
output argument is abayesianoptimization
object or a table of hyperparameters with associated values that describe the cross-validation optimization of hyperparameters.'hyperparameteroptimizationresults'
is nonempty when the'optimizehyperparameters'
name-value pair argument is nonempty at the time you create the model. the values in'hyperparameteroptimizationresults'
depend on the value you specify for the'hyperparameteroptimizationoptions'
name-value pair argument when you create the model.if you specify
'bayesopt'
(default), thenhyperparameteroptimizationresults
is an object of classbayesianoptimization
.if you specify
'gridsearch'
or'randomsearch'
, thenhyperparameteroptimizationresults
is a table of the hyperparameters used, observed objective function values (cross-validation loss), and rank of observations from lowest (best) to highest (worst).
supported name-value pair arguments, and any differences, are:
'classnames'
'cost'
'discrimtype'
'hyperparameteroptimizationoptions'
— for cross-validation, tall optimization supports only'holdout'
validation. by default, the software selects and reserves 20% of the data as holdout validation data, and trains the model using the rest of the data. you can specify a different value for the holdout fraction by using this argument. for example, specify'hyperparameteroptimizationoptions',struct('holdout',0.3)
to reserve 30% of the data as validation data.'optimizehyperparameters'
— the only eligible parameter to optimize is'discrimtype'
. specifying'auto'
uses'discrimtype'
.'predictornames'
'prior'
'responsename'
'scoretransform'
'weights'
for tall arrays and tall tables,
fitcdiscr
returns acompactclassificationdiscriminant
object, which contains most of the same properties as aclassificationdiscriminant
object. the main difference is that the compact object is sensitive to memory requirements. the compact object does not include properties that include the data, or that include an array of the same size as the data. the compact object does not contain theseclassificationdiscriminant
properties:modelparameters
numobservations
hyperparameteroptimizationresults
rowsused
xcentered
w
x
y
additionally, the compact object does not support these
classificationdiscriminant
methods:compact
crossval
cvshrink
resubedge
resubloss
resubmargin
resubpredict
for more information, see .
automatic parallel support
accelerate code by automatically running computation in parallel using parallel computing toolbox™.
to perform parallel hyperparameter optimization, use the
'hyperparameteroptimizationoptions', struct('useparallel',true)
name-value argument in the call to the fitcdiscr
function.
for more information on parallel hyperparameter optimization, see .
for general information about parallel computing, see (parallel computing toolbox).
version history
introduced in r2014a
see also
| | | |
topics
打开示例
您曾对此示例进行过修改。是否要打开带有您的编辑的示例?
matlab 命令
您点击的链接对应于以下 matlab 命令:
请在 matlab 命令行窗口中直接输入以执行命令。web 浏览器不支持 matlab 命令。
select a web site
choose a web site to get translated content where available and see local events and offers. based on your location, we recommend that you select: .
you can also select a web site from the following list:
how to get best site performance
select the china site (in chinese or english) for best site performance. other mathworks country sites are not optimized for visits from your location.
americas
- (español)
- (english)
- (english)
europe
- (english)
- (english)
- (deutsch)
- (español)
- (english)
- (français)
- (english)
- (italiano)
- (english)
- (english)
- (english)
- (deutsch)
- (english)
- (english)
- switzerland
- (english)
asia pacific
- (english)
- (english)
- (english)
- 中国
- (日本語)
- (한국어)