moving towards automating model selection using bayesian optimization -凯发k8网页登录
this example shows how to build multiple classification models for a given training data set, optimize their hyperparameters using bayesian optimization, and select the model that performs the best on a test data set.
training several models and tuning their hyperparameters can often take days or weeks. creating a script to develop and compare multiple models automatically can be much faster. you can also use bayesian optimization to speed up the process. instead of training each model with different sets of hyperparameters, you select a few different models and tune their default hyperparameters using bayesian optimization. bayesian optimization finds an optimal set of hyperparameters for a given model by minimizing the objective function of the model. this optimization algorithm strategically selects new hyperparameters in each iteration and typically arrives at the optimal set of hyperparameters more quickly than a simple grid search. you can use the script in this example to train several classification models using bayesian optimization for a given training data set and identify the model that performs best on a test data set.
alternatively, to choose a classification model automatically across a selection of classifier types and hyperparameter values, use fitcauto
. for an example, see automated classifier selection with bayesian and asha optimization.
load sample data
this example uses 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 the sample data census1994
and display the variables in the data set.
load census1994
whos
name size bytes class attributes description 20x74 2960 char adultdata 32561x15 1872566 table adulttest 16281x15 944466 table
census1994
contains the training data set adultdata
and the test data set adulttest
. for this example, to reduce the running time, subsample 5000 training and test observations each, from the original tables adultdata
and adulttest
, by using the function. (you can skip this step if you want to use the complete data sets.)
numsamples = 5000; s = randstream('mlfg6331_64'); % for reproducibility adultdata = datasample(s,adultdata,numsamples,'replace',false); adulttest = datasample(s,adulttest,numsamples,'replace',false);
preview the first few rows of the training data set.
head(adultdata)
age workclass fnlwgt education education_num marital_status occupation relationship race sex capital_gain capital_loss hours_per_week native_country salary ___ ___________ __________ ____________ _____________ __________________ _________________ ______________ _____ ______ ____________ ____________ ______________ ______________ ______ 39 private 4.91e 05 bachelors 13 never-married exec-managerial other-relative black male 0 0 45 united-states <=50k 25 private 2.2022e 05 11th 7 never-married handlers-cleaners own-child white male 0 0 45 united-states <=50k 24 private 2.2761e 05 10th 6 divorced handlers-cleaners unmarried white female 0 0 58 united-states <=50k 51 private 1.7329e 05 hs-grad 9 divorced other-service not-in-family white female 0 0 40 united-states <=50k 54 private 2.8029e 05 some-college 10 married-civ-spouse sales husband white male 0 0 32 united-states <=50k 53 federal-gov 39643 hs-grad 9 widowed exec-managerial not-in-family white female 0 0 58 united-states <=50k 52 private 81859 hs-grad 9 married-civ-spouse machine-op-inspct husband white male 0 0 48 united-states >50k 37 private 1.2429e 05 some-college 10 married-civ-spouse adm-clerical husband white male 0 0 50 united-states <=50k
each row represents the attributes of one adult, such as age, education, and occupation. the last column salary
shows whether a person has a salary less than or equal to $50,000 per year or greater than $50,000 per year.
understand data and choose classification models
statistics and machine learning toolbox™ provides several options for classification, including classification trees, discriminant analysis, naive bayes, nearest neighbors, support vector machines (svms), and classification ensembles. for the complete list of algorithms, see classification.
before choosing the algorithms to use for your problem, inspect your data set. the census data has several noteworthy characteristics:
the data is tabular and contains both numeric and categorical variables.
the data contains missing values.
the response variable (
salary
) has two classes (binary classification).
without making any assumptions or using prior knowledge of algorithms that you expect to work well on your data, you simply train all the algorithms that support tabular data and binary classification. error-correcting output codes (ecoc) models are used for data with more than two classes. discriminant analysis and nearest neighbor algorithms do not analyze data that contains both numeric and categorical variables. therefore, the algorithms appropriate for this example are svms, a decision tree, an ensemble of decision trees, and a naive bayes model. some of these models, like decision tree and naive bayes models, are better at handling data with missing values; that is, they return non-nan
predicted scores for observations with missing values.
build models and tune hyperparameters
to speed up the process, customize the hyperparameter optimization options. specify 'showplots'
as false
and 'verbose'
as 0 to disable plot and message displays, respectively. also, specify 'useparallel'
as true
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.
hypopts = struct('showplots',false,'verbose',0,'useparallel',true);
start a parallel pool.
poolobj = gcp;
starting parallel pool (parpool) using the 'local' profile ... connected to the parallel pool (number of workers: 8).
you can fit the training data set and tune parameters easily by calling each fitting function and setting its 'optimizehyperparameters'
name-value pair argument to 'auto'
. create the classification models.
% svms: svm with polynomial kernel & svm with gaussian kernel mdls{1} = fitcsvm(adultdata,'salary','kernelfunction','polynomial','standardize','on', ... 'optimizehyperparameters','auto','hyperparameteroptimizationoptions', hypopts); mdls{2} = fitcsvm(adultdata,'salary','kernelfunction','gaussian','standardize','on', ... 'optimizehyperparameters','auto','hyperparameteroptimizationoptions', hypopts); % decision tree mdls{3} = fitctree(adultdata,'salary', ... 'optimizehyperparameters','auto','hyperparameteroptimizationoptions', hypopts); % ensemble of decision trees mdls{4} = fitcensemble(adultdata,'salary','learners','tree', ... 'optimizehyperparameters','auto','hyperparameteroptimizationoptions', hypopts); % naive bayes mdls{5} = fitcnb(adultdata,'salary', ... 'optimizehyperparameters','auto','hyperparameteroptimizationoptions', hypopts);
warning: it is recommended that you first standardize all numeric predictors when optimizing the naive bayes 'width' parameter. ignore this warning if you have done that.
plot minimum objective curves
extract the bayesian optimization results from each model and plot the minimum observed value of the objective function for each model over every iteration of the hyperparameter optimization. the objective function value corresponds to the misclassification rate measured by five-fold cross-validation using the training data set. the plot compares the performance of each model.
figure hold on n = length(mdls); for i = 1:n mdl = mdls{i}; results = mdls{i}.hyperparameteroptimizationresults; plot(results.objectiveminimumtrace,'marker','o','markersize',5); end names = {'svm-polynomial','svm-gaussian','decision tree','ensemble-trees','naive bayes'}; legend(names,'location','northeast') title('bayesian optimization') xlabel('number of iterations') ylabel('minimum objective value')
using bayesian optimization to find better hyperparameter sets improves the performance of models over several iterations. in this case, the plot indicates that the ensemble of decision trees has the best prediction accuracy for the data. this model performs well consistently over several iterations and different sets of bayesian optimization hyperparameters.
check performance with test set
check the classifier performance with the test data set by using the confusion matrix and the receiver operating characteristic (roc) curve.
find the predicted labels and the score values of the test data set.
label = cell(n,1); score = cell(n,1); for i = 1:n [label{i},score{i}] = predict(mdls{i},adulttest); end
confusion matrix
obtain the most likely class for each test observation by using the predict
function of each model. then compute the confusion matrix with the predicted classes and the known (true) classes of the test data set by using the function.
figure c = cell(n,1); for i = 1:n subplot(2,3,i) c{i} = confusionchart(adulttest.salary,label{i}); title(names{i}) end
the diagonal elements indicate the number of correctly classified instances of a given class. the off-diagonal elements are instances of misclassified observations.
roc curve
inspect the classifier performance more closely by plotting a roc curve for each classifier and computing the area under the roc curve (auc). a roc curve shows the true positive rate versus the false positive rate for different thresholds of classification scores. for a perfect classifier, whose true positive rate is always 1 regardless of the threshold, auc = 1. for a binary classifier that randomly assigns observations to classes, auc = 0.5. a large auc value (close to 1) indicates good classifier performance.
compute the metrics for a roc curve and find the auc value by creating a object for each classifier. plot the roc curves for the label '<=50k'
by using the plot
function of rocmetrics
.
figure auc = zeros(1,n); for i = 1:n rocobj = rocmetrics(adulttest.salary,score{i},mdls{i}.classnames); [r,g] = plot(rocobj,'classnames','<=50k'); r.displayname = replace(r.displayname,'<=50k',names{i}); g(1).displayname = join([names{i},' model operating point']); auc(i) = rocobj.auc(1); hold on end title('roc curves for class <=50k') hold off
a roc curve shows the true positive rate versus the false positive rate (or, sensitivity versus 1–specificity) for different thresholds of the classifier output.
now plot the auc values using a bar graph. for a perfect classifier, whose true positive rate is always 1 regardless of the thresholds, auc = 1. for a classifier that randomly assigns observations to classes, auc = 0.5. larger auc values indicate better classifier performance.
figure bar(auc) title('area under the curve') xlabel('model') ylabel('auc') xticklabels(names) xtickangle(30) ylim([0.85,0.925])
based on the confusion matrix and the auc bar graph, the ensemble of decision trees and svm models achieve better accuracy than the decision tree and naive bayes models.
resume optimization of most promising models
running bayesian optimization on all models for further iterations can be computationally expensive. instead, select a subset of models that have performed well so far and continue the optimization for 30 more iterations by using the function. plot the minimum observed values of the objective function for each iteration of bayesian optimization.
figure hold on selectedmdls = mdls([1,2,4]); newresults = cell(1,length(selectedmdls)); for i = 1:length(selectedmdls) newresults{i} = resume(selectedmdls{i}.hyperparameteroptimizationresults,'maxobjectiveevaluations',30); plot(newresults{i}.objectiveminimumtrace,'marker','o','markersize',5) end title('bayesian optimization with resume') xlabel('number of iterations') ylabel('minimum objective value') legend({'svm-polynomial','svm-gaussian','ensemble-trees'},'location','northeast')
the first 30 iterations correspond to the first round of bayesian optimization. the next 30 iterations correspond to the results of the resume
function. resuming optimization is useful because the loss continues to reduce further after the first 30 iterations.
see also
| | | bayesianoptimization