# [Exercise 1] Linear Regression

## 线性回归

$J\left(\mathit{\theta }\right)$$J(\theta)$公式：$J\left(\mathit{\theta }\right)=\frac{1}{2m}\sum _{i=1}^{m}\left({h}_{\mathit{\theta }}\left({x}^{\left(i\right)}\right)-{y}^{\left(i\right)}{\right)}^{2}$$J(\theta) =\frac{1}{2m}\sum_{i=1}^m(h_\theta(x^{(i)})-y^{(i)}) ^2$

1. 实现梯度下降$\mathit{\alpha }=0.07$$\alpha=0.07$
2. 迭代计算${\mathit{\theta }}_{0}{\mathit{\theta }}_{1}$$\theta_0 \theta_1$
3. 预测x = 3 .5 和x=7

## 实验结果和程序[matlab]

x = load('ex2x.dat');

figure
plot(x,y,'o')
xlabel('Age in years')
ylabel('Height in meters')

m = length(y);  %store the number of training examples
x = [ones(m,1), x]; %Add a colum of ones to x
w = inv(x'*x)*x'*y
hold on
% w = 0.7502 0.0639
plot(x(:,2), 0.0639*x(:,2) + 0.7502)

%exercise 2 linearRegression
% x refers to a boy's age
% y is a boy's height in meters

clear all; close all,clc
m = length(y);

% plot the traning
figure;
plot(x,y,'o')
ylabel('Height in meters')
xlabel('Age in years')

x = [ones(m,1), x];
theta = zeros(size(x(1,:)))';
MAX_ITR = 1500;
alpha = 0.07;

for num_iterations = 1:MAX_ITR
end
%print theta to screeen
theta

%plot the linear fit
hold on;
plot(x(:,2), x*theta, '-')
legend('Traning data', 'Linear regression')
hold off

exact_theta = (x'*x)\x'*y
%predict values for age 3.5 and 7
predict1 = [1, 3.5]*theta
predict2 = [1, 7]*theta

%calculate J matrx
theta0_vals = linspace(-3,3,100);
theta1_vals = linspace(-1,1,100);
J_vals = zeros(length(theta0_vals), length(theta1_vals));

for i = 1:length(theta0_vals)
for j = 1:length(theta1_vals)
t = [theta0_vals(i); theta1_vals(j)];
J_vals(i,j) = (0.5/m).*(x*t - y)'*(x*t - y);
end

end

J_vals = J_vals';
figure;
surf(theta0_vals, theta1_vals, J_vals)
xlabel('\theta_0');
ylabel('\theta_1');

figure;
contour(theta0_vals, theta1_vals, J_vals, logspace(-2,2,15))
xlabel('\theta_0');
ylabel('\theta_1');

• 本文已收录于以下专栏：

举报原因： 您举报文章：[Exercise 1] Linear Regression 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)