大神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')