随机生成数据并做线性回归和超参数代码MATLAB
时间: 2024-02-13 07:04:15 浏览: 32
以下是一个随机生成数据并进行线性回归和超参数调整的MATLAB示例代码:
```matlab
% 随机生成数据
x = rand(100, 1) * 10;
y = 3 * x + 2 + randn(100, 1);
% 绘制数据分布
figure;
scatter(x, y);
xlabel('x');
ylabel('y');
title('Randomly Generated Data');
% 切分数据集
m = length(y); % 样本数量
train_size = floor(0.7 * m); % 70%为训练集
train_idx = randperm(m, train_size);
test_idx = setdiff(1:m, train_idx);
X_train = x(train_idx);
y_train = y(train_idx);
X_test = x(test_idx);
y_test = y(test_idx);
% 设置超参数
alpha = 0.01; % 学习率
num_iters = 1000; % 迭代次数
lambda = 0.1; % 正则化参数
% 初始化参数
theta = zeros(2, 1); % 参数向量
X_train = [ones(train_size, 1), X_train]; % 添加截距项
X_test = [ones(m-train_size, 1), X_test];
% 训练模型
for iter = 1:num_iters
% 计算梯度
grad = (1/train_size) * X_train' * (X_train * theta - y_train) + lambda * theta;
% 更新参数
theta = theta - alpha * grad;
end
% 绘制拟合直线
hold on;
plot(X_test(:, 2), X_test * theta, '-');
legend('Training data', 'Linear regression');
hold off;
% 计算测试集误差
y_pred = X_test * theta;
mse = mean((y_pred - y_test).^2);
disp(['Test set MSE: ', num2str(mse)]);
```
在这个例子中,我们首先随机生成一组有噪声的数据,并将其分为训练集和测试集。然后,我们设置超参数,包括学习率、迭代次数和正则化参数。接着,我们初始化参数向量,并使用梯度下降算法进行模型训练。最后,我们绘制拟合直线,并计算测试集误差。
需要注意的是,在实际应用中,超参数的选择和调整是一个非常重要的任务。通常需要使用交叉验证等技术来选择最佳的超参数组合。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)