www.gusucode.com > stats 源码程序 matlab案例代码 > stats/FindTheBestPruningLevelUsingCrossValidation1Example.m
%% Find the Best Pruning Level Using Cross Validation % Apply _k_-fold cross validation to find the best level to prune a % regression tree for all of its subtrees. %% % Load the |carsmall| data set. Consider |Displacement|, |Horsepower|, and % |Weight| as predictors of the response |MPG|. % Copyright 2015 The MathWorks, Inc. load carsmall X = [Displacement Horsepower Weight]; %% % Grow a regression tree using the entire data set. View the resulting % tree. Mdl = fitrtree(X,MPG); view(Mdl,'Mode','graph') %% % Compute the 5-fold cross-validation error for each subtree except for the % first two lowest and highest pruning level. Specify to return the best pruning level over all % subtrees. rng(1); % For reproducibility m = max(Mdl.PruneList) - 1 [~,~,~,bestLevel] = cvloss(Mdl,'SubTrees',2:m,'KFold',5) %% % Of the |15| pruning levels, the best pruning level is |14|. %% % Prune the tree to the best level. View the resulting tree. MdlPrune = prune(Mdl,'Level',bestLevel); view(MdlPrune,'Mode','graph')