如何从 MATLAB 中的 LASSO 拟合获得决定系数 (R^2)?

How to obtain coefficient of determination (R^2) from a LASSO fit in MATLAB?

在 MATLAB 中,我们可以使用

执行交叉验证的 LASSO
[w, FitInfo] = lasso(X, y, 'CV', 3);

并获得最佳权重

w(:,FitInfo.IndexMinMSE)

我们如何找到决定系数?

如果我理解 MATLAB documentation and the coefficient of determination definition,我认为下面的代码应该可以完成工作:

 optimal_weights = w(:,FitInfo.IndexMinMSE);
 SStot = var(y)*length(y);
 predicted_values = X*optimal_weights;
 SSres = sum( (y(:)-predicted_values(:)).^2 );
 R2 = 1 - SSres/SStot;

注意 SStot 可以用 sum() 计算,但我认为使用 var() 会更快一些。

Yellows 的上述回答是正确的,但您必须确保包括拦截项 ==> Predicted_values = X*2(:,fitInfo.IndexMinMSE) + fitInfo.Intercept(fitInfo.IndexMinMSE)