www.gusucode.com > stats 源码程序 matlab案例代码 > stats/PredictForModelsWithSeveralRegularizationStrengthsExample.m
%% Predict for Models Containing Several Regularization Strengths %% % Simulate 10000 observations as in <docid:stats_ug.bu7yjem>. rng(1) % For reproducibility n = 1e4; d = 1e3; nz = 0.1; X = sprandn(n,d,nz); Y = X(:,100) + 2*X(:,200) + 0.3*randn(n,1); %% % Create a set of 15 logarithmically-spaced regularization strengths from % $10^{-5}$ through $10^{-1}$. Lambda = logspace(-5,-1,15); %% % Cross-validate the models. To increase execution speed, transpose the % predictor data and specify that the observations are in columns. Specify % to use least squares with a lasso penalty, and solve the objective % function using SpaRSA. X = X'; CVMdl = fitrlinear(X,Y,'ObservationsIn','columns','KFold',5,'Lambda',Lambda,... 'Learner','leastsquares','Solver','sparsa','Regularization','lasso'); %% % |CVMdl| is a |RegressionPartitionedLinear| model. Its |Trained| property % contains a 5-by-1 cell array of trained |RegressionLinear| models, each % one holds out a different fold during training. Because |fitrlinear| % trained using 15 regularization strengths, you can think of each % |RegressionLinear| model as 15 models. %% % Predict cross-validated responses. YHat = kfoldPredict(CVMdl); size(YHat) YHat(2,:) %% % |YHat| is a 10000-by-15 matrix. |YHat(2,:)| is the cross-validated % response for observation 2 using the model regularized with all 15 % regularization values.