Advertisement
Guest User

Untitled

a guest
Jun 27th, 2019
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.76 KB | None | 0 0
  1. clear all; close all; clc;
  2.  
  3. alpha = 0.01;
  4. num_iters = 1000;
  5.  
  6. %% Plotting data
  7. x1 = linspace(0,3,50);
  8. mqtrue = 5;
  9. cqtrue = 30;
  10. dat1 = mqtrue*x1+5*randn(1,50);
  11.  
  12. x2 = linspace(7,10,50);
  13. dat2 = mqtrue*x2 + (cqtrue + 5*randn(1,50));
  14.  
  15. x = [x1 x2]'; % X
  16.  
  17. subplot(2,2,1);
  18. dat = [dat1 dat2]'; % Y
  19.  
  20. scatter(x1, dat1); hold on;
  21. scatter(x2, dat2, '*'); hold on;
  22. classdata = (dat>40);
  23.  
  24. % Setup the data matrix appropriately, and add ones for the intercept term
  25. [m, n] = size(x);
  26.  
  27. % Add intercept term to x and X_test
  28. x = [ones(m, 1) x];
  29.  
  30. % Initialize fitting parameters
  31. theta = zeros(n + 1, 1);
  32. %initial_theta = [0.2; 0.2];
  33.  
  34. J_history = zeros(num_iters, 1);
  35.  
  36. plot_x = [min(x(:,2))-2, max(x(:,2))+2]
  37.  
  38. for iter = 1:num_iters
  39. % Compute and display initial cost and gradient
  40. [cost, grad] = logistic_costFunction(theta, x, classdata);
  41. theta = theta - alpha * grad;
  42. J_history(iter) = cost;
  43.  
  44. fprintf('Iteration #%d - Cost = %d... rn',iter, cost);
  45.  
  46.  
  47. subplot(2,2,2);
  48. hold on; grid on;
  49. plot(iter, J_history(iter), '.r'); title(sprintf('Plot of cost against number of iterations. Cost is %g',J_history(iter)));
  50. xlabel('Iterations')
  51. ylabel('MSE')
  52. drawnow
  53.  
  54. subplot(2,2,3);
  55. grid on;
  56. plot3(theta(1), theta(2), J_history(iter),'o')
  57. title(sprintf('Tita0 = %g, Tita1=%g', theta(1), theta(2)))
  58. xlabel('Tita0')
  59. ylabel('Tita1')
  60. zlabel('Cost')
  61. hold on;
  62. drawnow
  63.  
  64. subplot(2,2,1);
  65. grid on;
  66. % Calculate the decision boundary line
  67. plot_y = theta(2).*plot_x + theta(1); % <--- Boundary line
  68. % Plot, and adjust axes for better viewing
  69. plot(plot_x, plot_y)
  70. hold on;
  71. drawnow
  72.  
  73. end
  74.  
  75. fprintf('Cost at initial theta (zeros): %fn', cost);
  76. fprintf('Gradient at initial theta (zeros): n');
  77. fprintf(' %f n', grad);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement