我是回归的新手,我在matlab中编写了一个非常简单的代码,该代码使用套索函数来查看我是否了解套索的MSE是如何计算的。但是我得到的mse与套索的输出不同。我可能会丢失一些东西,如果有人可以告诉我我错了,我将不胜感激。为了计算MSE,我从该链接使用了以下公式:https://www.mathworks.com/help/stats/lasso.html
这是我编写的matlab代码:
clear;
close all;
clc;
% Checking lasso MSE from this link:
% https://www.mathworks.com/help/stats/lasso.html
n = 10;
p = 3;
X = 20*rand(n,p);
min_val = -20;
max_val = 20;
y = min_val + (max_val - min_val)*rand(n,1);
lambda_vals = [0.2, 0.8, 1, 1.5];
[beta_vectors , FitInfo] = lasso(X, y, 'Lambda', lambda_vals);
eps = 10^-10;
num_of_lambda_vals = length(lambda_vals);
for i=1:num_of_lambda_vals
current_calculated_mse = sum((y - FitInfo.Intercept(i) - X*beta_vectors(:,i)).^2)/(2*n) +...
lambda_vals(i)*sum(abs(beta_vectors(:,i)));
current_mse = FitInfo.MSE(i);
fprintf('current_calculated_mse = %f\n',current_calculated_mse);
fprintf('current_mse = %f\n',current_mse);
sqr_diff_mses = (current_calculated_mse-current_mse)^2;
if (sqr_diff_mses > eps)
fprintf('The calculated MSE is wrong!\n');
end
fprintf('\n');
end
如果运行代码,它将打印出计算的MSE错误。 有人可以告诉我代码有什么问题吗?
谢谢