% 定义两个数组
x = [1,2,3,4,5,6,7,8,9];
y = [2,2,3,3,4,5,6,5,6];
m = length(y); % 获取数组长度
plot(x,y,'x');
x = reshape(x,m,1); % 将一维数组变为向量
y = reshape(y,m,1);
x = [ones(m,1),x]; % 添加一列截距
theta = zeros(2,1); % 初始化系数
% 迭代次数
iterations = 1500;
% 学习率
alpha = 0.01;
% 梯度下降
for iter = 1:iterations
temp1 = theta(1) - alpha/m*sum((x*theta-y).*x(:,1)); % 优化截距
temp2 = theta(2) - alpha/m*sum((x*theta-y).*x(:,2)); % 优化系数
theta(1) = temp1;
theta(2) = temp2;
end
hold on; % 保持图像
plot(x(:,2),x*theta,'-') % 绘制拟合后的图形
legend('Training data','Linear Regression'); % 图例
hold off % 结束绘制
网友评论