my_ex1.m 757 B

123456789101112131415161718192021222324
  1. data = load('ex1data1.txt');
  2. X = data(:, 1); y = data(:, 2);
  3. m = length(y); % number of training examples
  4. X = [ones(m, 1), data(:,1)]; % Add a column of ones to x
  5. theta = zeros(2, 1); % initialize fitting parameters
  6. % Some gradient descent settings
  7. iterations = 1500;
  8. alpha = 0.01;
  9. fprintf('\nTesting the cost function ...\n')
  10. % compute and display initial cost
  11. J = computeCost(X, y, theta);
  12. fprintf('With theta = [0 ; 0]\nCost computed = %f\n', J);
  13. fprintf('Expected cost value (approx) 32.07\n');
  14. % run gradient descent
  15. theta = gradientDescent(X, y, theta, alpha, iterations);
  16. % print theta to screen
  17. fprintf('Theta found by gradient descent:\n');
  18. fprintf('%f\n', theta);
  19. fprintf('Expected theta values (approx)\n');
  20. fprintf(' -3.6303\n 1.1664\n\n');