train generalized additive model for binary classification -凯发k8网页登录
this example shows how to train a with optimal parameters and how to assess the predictive performance of the trained model. the example first finds the optimal parameter values for a univariate gam (parameters for linear terms) and then finds the values for a bivariate gam (parameters for interaction terms). also, the example explains how to interpret the trained model by examining local effects of terms on a specific prediction and by computing the partial dependence of the predictions on predictors.
load sample data
load the 1994 census data stored in census1994.mat
. the data set consists of demographic data from the us census bureau to predict whether an individual makes over $50,000 per year. the classification task is to fit a model that predicts the salary category of people given their age, working class, education level, marital status, race, and so on.
load census1994
census1994
contains the training data set adultdata
and the test data set adulttest
. to reduce the running time for this example, subsample 500 training observations and 500 test observations by using the function.
rng(1) % for reproducibility numsamples = 5e2; adultdata = datasample(adultdata,numsamples,'replace',false); adulttest = datasample(adulttest,numsamples,'replace',false);
train gam with optimal hyperparameters
train a gam with hyperparameters that minimize the cross-validation loss by using the name-value argument.
you can specify optimizehyperparameters
as 'auto'
or 'all'
to find optimal hyperparameter values for both univariate and bivariate parameters. alternatively, you can find optimal values for univariate parameters using the 'auto-univariate'
or 'all-univariate'
option, and then find optimal values for bivariate parameters using the 'auto-bivariate'
or 'all-bivariate'
option. this example uses 'auto-univariate'
and 'auto-bivariate'
.
train a univariate gam. specify optimizehyperparameters
as 'auto-univariate'
so that fitcgam
finds optimal values of the initiallearnrateforpredictors
and numtreesperpredictor
name-value arguments. for reproducibility, use the 'expected-improvement-plus'
acquisition function. specify showplots
as false
and verbose
as 0 to disable plot and message displays, respectively.
mdl_univariate = fitcgam(adultdata,'salary','weights','fnlwgt', ... 'optimizehyperparameters','auto-univariate', ... 'hyperparameteroptimizationoptions',struct('acquisitionfunctionname','expected-improvement-plus', ... 'showplots',false,'verbose',0))
mdl_univariate = classificationgam predictornames: {'age' 'workclass' 'education' 'education_num' 'marital_status' 'occupation' 'relationship' 'race' 'sex' 'capital_gain' 'capital_loss' 'hours_per_week' 'native_country'} responsename: 'salary' categoricalpredictors: [2 3 5 6 7 8 9 13] classnames: [<=50k >50k] scoretransform: 'logit' intercept: -1.3118 numobservations: 500 hyperparameteroptimizationresults: [1×1 bayesianoptimization] properties, methods
fitcgam
returns a classificationgam
model object that uses the best estimated feasible point. the best estimated feasible point indicates the set of hyperparameters that minimizes the upper confidence bound of the objective function value based on the underlying objective function model of the bayesian optimization process. you can obtain the best point from the hyperparameteroptimizationresults
property or by using the bestpoint
function.
x = mdl_univariate.hyperparameteroptimizationresults.xatminestimatedobjective
x=1×2 table
initiallearnrateforpredictors numtreesperpredictor
_____________________________ ____________________
0.02257 118
bestpoint(mdl_univariate.hyperparameteroptimizationresults)
ans=1×2 table
initiallearnrateforpredictors numtreesperpredictor
_____________________________ ____________________
0.02257 118
for more details on the optimization process, see .
train a bivariate gam. specify optimizehyperparameters
as 'auto-bivariate'
so that fitcgam
finds optimal values of the interactions
, initiallearnrateforinteractions
, and numtreesperinteraction
name-value arguments. use the univariate parameter values in x
so that the software finds optimal parameter values for interaction terms based on the x values.
mdl = fitcgam(adultdata,'salary','weights','fnlwgt', ... 'initiallearnrateforpredictors',x.initiallearnrateforpredictors, ... 'numtreesperpredictor',x.numtreesperpredictor, ... 'optimizehyperparameters','auto-bivariate', ... 'hyperparameteroptimizationoptions',struct('acquisitionfunctionname','expected-improvement-plus', ... 'showplots',false,'verbose',0))
mdl = classificationgam predictornames: {'age' 'workclass' 'education' 'education_num' 'marital_status' 'occupation' 'relationship' 'race' 'sex' 'capital_gain' 'capital_loss' 'hours_per_week' 'native_country'} responsename: 'salary' categoricalpredictors: [2 3 5 6 7 8 9 13] classnames: [<=50k >50k] scoretransform: 'logit' intercept: -1.4587 interactions: [6×2 double] numobservations: 500 hyperparameteroptimizationresults: [1×1 bayesianoptimization] properties, methods
display the optimal bivariate hyperparameters.
mdl.hyperparameteroptimizationresults.xatminestimatedobjective
ans=1×3 table
interactions initiallearnrateforinteractions numtreesperinteraction
____________ _______________________________ ______________________
6 0.0061954 422
the model display of mdl
shows a partial list of the model properties. to view the full list of the model properties, double-click the variable name mdl
in the workspace. the variables editor opens for mdl
. alternatively, you can display the properties in the command window by using dot notation. for example, display the reasonfortermination
property.
mdl.reasonfortermination
ans = struct with fields:
predictortrees: 'terminated after training the requested number of trees.'
interactiontrees: 'terminated after training the requested number of trees.'
you can use the reasonfortermination
property to determine whether the trained model contains the specified number of trees for each linear term and each interaction term.
display the interaction terms in mdl
.
mdl.interactions
ans = 6×2
5 12
1 6
6 12
1 12
7 9
2 6
each row of interactions
represents one interaction term and contains the column indexes of the predictor variables for the interaction term. you can use the interactions
property to check the interaction terms in the model and the order in which fitcgam
adds them to the model.
display the interaction terms in mdl
using the predictor names.
mdl.predictornames(mdl.interactions)
ans = 6×2 cell
{'marital_status'} {'hours_per_week'}
{'age' } {'occupation' }
{'occupation' } {'hours_per_week'}
{'age' } {'hours_per_week'}
{'relationship' } {'sex' }
{'workclass' } {'occupation' }
assess predictive performance on new observations
assess the performance of the trained model by using the test sample adulttest
and the object functions predict
, loss
, edge
, and margin
. you can use a full or compact model with these functions.
— classify observations
— compute classification loss (misclassification rate in decimal, by default)
— compute classification margins
— compute classification edge (average of classification margins)
if you want to assess the performance of the training data set, use the resubstitution object functions: , , , and . to use these functions, you must use the full model that contains the training data.
create a compact model to reduce the size of the trained model.
cmdl = compact(mdl); whos('mdl','cmdl')
name size bytes class attributes cmdl 1x1 5126918 classreg.learning.classif.compactclassificationgam mdl 1x1 5272831 classificationgam
predict labels and scores for the test data set (adulttest
), and compute model statistics (loss, margin, and edge) using the test data set.
[labels,scores] = predict(cmdl,adulttest); l = loss(cmdl,adulttest,'weights',adulttest.fnlwgt); m = margin(cmdl,adulttest); e = edge(cmdl,adulttest,'weights',adulttest.fnlwgt);
predict labels and scores and compute the statistics without including interaction terms in the trained model.
[labels_nointeraction,scores_nointeraction] = predict(cmdl,adulttest,'includeinteractions',false); l_nointeractions = loss(cmdl,adulttest,'weights',adulttest.fnlwgt,'includeinteractions',false); m_nointeractions = margin(cmdl,adulttest,'includeinteractions',false); e_nointeractions = edge(cmdl,adulttest,'weights',adulttest.fnlwgt,'includeinteractions',false);
compare the results obtained by including both linear and interaction terms to the results obtained by including only linear terms.
create a confusion chart from the true labels adulttest.salary
and the predicted labels.
tiledlayout(1,2); nexttile confusionchart(adulttest.salary,labels) title('linear and interaction terms') nexttile confusionchart(adulttest.salary,labels_nointeraction) title('linear terms only')
display the computed loss and edge values.
table([l; e], [l_nointeractions; e_nointeractions], ... 'variablenames',{'linear and interaction terms','only linear terms'}, ... 'rownames',{'loss','edge'})
ans=2×2 table
linear and interaction terms only linear terms
____________________________ _________________
loss 0.1748 0.17872
edge 0.57902 0.54756
the model achieves a smaller loss value and a higher edge value when both linear and interaction terms are included.
display the distributions of the margins using box plots.
figure boxplot([m m_nointeractions],'labels',{'linear and interaction terms','linear terms only'}) title('box plots of test sample margins')
interpret prediction
interpret the prediction for the first test observation by using the function. also, create partial dependence plots for some important terms in the model by using the plotpartialdependence
function.
classify the first observation of the test data, and plot the local effects of the terms in cmdl
on the prediction. to display an existing underscore in any predictor name, change the ticklabelinterpreter
value of the axes to 'none'
.
[label,score] = predict(cmdl,adulttest(1,:))
label = categorical
<=50k
score = 1×2
0.9895 0.0105
f1 = figure;
plotlocaleffects(cmdl,adulttest(1,:))
f1.currentaxes.ticklabelinterpreter = 'none';
the predict
function classifies the first observation adulttest(1,:)
as '<=50k'
. the plotlocaleffects
function creates a horizontal bar graph that shows the local effects of the 10 most important terms on the prediction. each local effect value shows the contribution of each term to the classification score for '<=50k'
, which is the logit of the posterior probability that the classification is '<=50k'
for the observation.
create a partial dependence plot for the term age
. specify both the training and test data sets to compute the partial dependence values using both sets.
figure
plotpartialdependence(cmdl,'age',label,[adultdata; adulttest])
the plotted line represents the averaged partial relationships between the predictor age
and the score of the class <=50k
in the trained model. the x
-axis minor ticks represent the unique values in the predictor age
.
create partial dependence plots for the terms education_num
and relationship
.
f2 = figure; plotpartialdependence(cmdl,["education_num","relationship"],label,[adultdata; adulttest]) f2.currentaxes.ticklabelinterpreter = 'none'; view([55 40])
the plot shows the partial dependence of the score value for the class <=50
on education_num
and relationship
.
see also
| | | | plotpartialdependence
| |