Linear Regression代码-Andrew NG Machine Learning Ex2

本文详细介绍了如何使用Matlab实现Andrew Ng课程Exercise2中的线性回归作业代码,包括数据加载、绘图、参数初始化、梯度下降更新规则以及成本函数的可视化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

大神Andrew NG课程Exercise 2作业代码,题目详见网页:

点击打开链接


matlab代码如下所示:

x = load('ex2x.dat');
y = load('ex2y.dat');
figure
plot(x,y,'o');
xlabel('Height in meters');
ylabel('Age in years');

m = length(x);
x = [ones(m,1),x];

alpha = 0.07;
theta = [0;0];

while 1
    thetaPre   = theta;
    theta(1,1) = theta(1,1) - alpha*sum((x*theta-y).*x(:,1))/m;
    theta(2,1) = theta(2,1) - alpha*sum((x*theta-y).*x(:,2))/m;
    if sum(abs(thetaPre-theta))<=0.0
        break;
    end
end

hold on; % Plot new data without clearing old plot
plot(x(:,2), x*theta, '-'); % remember that x is now a matrix with 2 columns
                           % and the second column contains the time info
legend('Training data', 'Linear regression');

J_vals = zeros(100, 100);   % initialize Jvals to 100x100 matrix of 0's
theta0_vals = linspace(-3, 3, 100);
theta1_vals = linspace(-1, 1, 100);
for i = 1:length(theta0_vals)
	for j = 1:length(theta1_vals)
	     t = [theta0_vals(i); theta1_vals(j)];
	     J_vals(i,j) = sum((x*t-y).^2)/(2*m);
    end
end

% Plot the surface plot
% Because of the way meshgrids work in the surf command, we need to 
% transpose J_vals before calling surf, or else the axes will be flipped
J_vals = J_vals';
figure;
surf(theta0_vals, theta1_vals, J_vals)
xlabel('\theta_0'); ylabel('\theta_1')

figure;
% Plot the cost function with 15 contours spaced logarithmically
% between 0.01 and 100
contour(theta0_vals, theta1_vals, J_vals, logspace(-2, 2, 15))
xlabel('\theta_0'); ylabel('\theta_1')


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值