www.gusucode.com > stats 源码程序 matlab案例代码 > stats/PredictResponsesUsingLinearRegressionModelExample.m
%% Predict Responses Using Linear Regression Model %% % Simulate 10000 observations from this model % % $$y = x_{100} + 2x_{200} + e.$$ % % % * $X = \{x_1,...,x_{1000}\}$ is a 10000-by-1000 sparse matrix with 10% % nonzero standard normal elements. % * _e_ is random normal error with mean 0 and standard deviation % 0.3. % 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); %% % Hold out 5% of the data. rng(1); % For reproducibility cvp = cvpartition(n,'Holdout',0.05) %% % |cvp| is a |CVPartition| object that defines the random partition of _n_ % data into training and test sets. %% % Train a linear regression model using the training set. For % faster training time, orient the predictor data matrix so that the % observations are in columns. idxTrain = training(cvp); % Extract training set indices X = X'; Mdl = fitrlinear(X(:,idxTrain),Y(idxTrain),'ObservationsIn','columns'); %% % Predict observations and the mean squared error (MSE) for the hold out sample. idxTest = test(cvp); % Extract test set indices yHat = predict(Mdl,X(:,idxTest),'ObservationsIn','columns'); L = loss(Mdl,X(:,idxTest),Y(idxTest),'ObservationsIn','columns') %% % The hold-out sample MSE is 0.1852.