用线性回归模型拟合数据集的matlab代码
时间: 2024-06-08 14:05:32 浏览: 121
以下是用线性回归模型拟合数据集的 MATLAB 代码示例:
```
% 读入数据集
data = load('dataset.txt');
X = data(:, 1); % 特征变量
y = data(:, 2); % 响应变量
m = length(y); % 样本数
% 添加一列常数项
X = [ones(m, 1), X];
% 初始化 theta
theta = zeros(size(X, 2), 1);
% 定义代价函数
function J = computeCost(X, y, theta)
m = length(y);
J = 1 / (2 * m) * sum((X * theta - y) .^ 2);
end
% 梯度下降求解最优 theta
function [theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters)
m = length(y);
J_history = zeros(num_iters, 1);
for iter = 1:num_iters
theta = theta - alpha / m * X' * (X * theta - y);
J_history(iter) = computeCost(X, y, theta);
end
end
% 运行梯度下降算法
alpha = 0.01; % 学习率
num_iters = 1500; % 迭代次数
[theta, J_history] = gradientDescent(X, y, theta, alpha, num_iters);
% 输出最终 theta 和代价函数的值
fprintf('Theta found by gradient descent: ');
fprintf('%f %f \n', theta(1), theta(2));
fprintf('Final cost: %f \n', J_history(end));
% 绘制拟合曲线
plot(X(:, 2), y, 'rx', 'MarkerSize', 10);
hold on;
plot(X(:, 2), X * theta, '-');
legend('Training data', 'Linear regression');
```
阅读全文