www.gusucode.com > stats 源码程序 matlab案例代码 > stats/SpecifyCustomRegressionLoss1Example.m
%% Specify Custom Regression Loss %% % Simulate data as in <docid:stats_ug.bu7s7c0>. 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); X = X'; % Put observations in columns for faster training %% % Cross-validate a linear regression model using 10-fold cross-validation. % Solve the objective function using SpaRSA. CVMdl = fitrlinear(X,Y,'CrossVal','on','ObservationsIn','columns',... 'Solver','sparsa'); %% % |CVMdl| is a |RegressionPartitionedLinear| model. It contains % the property |Trained|, which is a 10-by-1 cell array holding % |RegressionLinear| models that the software trained using the % training set. %% % Create an anonymous function that measures Huber loss ($\delta$ = 1), % that is, % % $$\begin{array}{*{20}{c}} % {L = \frac{1}{{\sum {{w_j}} }}\sum\limits_{j = 1}^n {{w_j}{\ell _j}} ,\;\;{\rm{where}}}\\ % {{\ell _j} = \left\{ {\begin{array}{*{20}{c}} % {0.5{{\hat e}^2}}\\ % {\left| {\hat e} \right| - 0.5\;\;} % \end{array}\begin{array}{*{20}{c}} % {{\rm{for}}\;\;{\left| {\hat e} \right|} \le 1}\\ % {{\rm{otherwise}}} % \end{array}} \right..} % \end{array}$$ % % $\hat e_j$ is the residual for observation _j_. Custom loss functions must % be written in a particular form. For rules on writing a custom loss % function, see the |LossFun| name-value pair argument. huberloss = @(Y,Yhat,W)sum(W.*((0.5*(abs(Y-Yhat)<=1).*(Y-Yhat).^2) + ... ((abs(Y-Yhat)>1).*abs(Y-Yhat)-0.5)))/sum(W); %% % Estimate the average Huber loss over the folds. Also, obtain the Huber % loss for each fold. mseAve = kfoldLoss(CVMdl,'LossFun',huberloss) mseFold = kfoldLoss(CVMdl,'LossFun',huberloss,'Mode','individual')