Multivariate Linear Regression代码-Andrew NG Machine Learning Ex3

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


点击打开链接


matlab实现代码如下所示:

x = load('ex3x.dat');
y = load('ex3y.dat');
m = length(x);
x = [ones(m,1), x];

% Feature Scaling
sigma = std(x);
mu = mean(x);
x(:,2) = (x(:,2) - mu(2))./ sigma(2);
x(:,3) = (x(:,3) - mu(3))./ sigma(3);

alpha = [0.01, 0.03, 0.1, 0.3, 1.0, 1.3]; %% Your initial learning rate %%
plotstyle = {'b', 'r', 'g', 'k', 'b--', 'r--'};
J = zeros(50, 1); 

for k = 1:6
theta = zeros(size(x(1,:)))'; % initialize fitting parameters
for num_iterations = 1:50
    J(num_iterations) = ((x*theta-y)'*(x*theta-y))/(2*m); %% Calculate your cost function here %%
    theta = theta - alpha(k)*((x*theta-y)'*x)'/m;          %% Result of gradient descent update %%
end

if alpha(k)==1
    thetaBest = theta;
end
    
% now plot J
% technically, the first J starts at the zero-eth iteration
% but Matlab/Octave doesn't have a zero index
hold on;
plot(0:49, J(1:50),char(plotstyle(k)));
end
xlabel('Number of iterations');
ylabel('Cost J');
legend('0.01', '0.03', '0.1', '0.3', '1.0', '1.3');

price_grad_desc = dot(thetaBest, [1, (1650 - mu(2))/sigma(2), (3 - mu(3))/sigma(3)]);

% Normal Equation
% Reload Data.
x = load('ex3x.dat');
y = load('ex3y.dat');
m = length(x);
x = [ones(m,1), x];

theta_normal = (x' * x)\x' * y;
price_normal = dot(theta_normal, [1, 1650, 3]);


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值