Advertisement
Guest User

fit parabola

a guest
Jan 22nd, 2019
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.72 KB | None | 0 0
  1. function [coeffs, mean_loss] = fit_parabola(coeffs, x, y, visual)
  2. % --------------- Do Not Edit this Part!!! ---------------
  3. % Setup
  4. iter = 0;
  5. learning_rate = 1e-4;
  6. plot_every_iters = 5;
  7. max_iterations = 1e6;
  8. mean_loss = 1;
  9.  
  10. if visual
  11. figure();
  12. hold on;
  13. plot(x, y, 'b', 'LineWidth', 2);
  14. title('True Parabola vs. Our Predictions');
  15. xlabel('X Axis [N.U.]');
  16. ylabel('Y Axis [N.U.]');
  17. end
  18.  
  19. % Training loop
  20. while(mean_loss > 1e-6)
  21.  
  22. % --------------- Edit From Here ---------------
  23. predictions = coeffs(1) * x.^2 + coeffs(2) * x + coeffs(3);
  24. mean_loss = mean(predictions-y).^2;
  25. gradients = auto_diff_p2(x, y, predictions);
  26. coeffs = coeffs - learning_rate * gradients;
  27.  
  28. % --------------- Do Not Edit From Here!!! ---------------
  29. if visual
  30. % Print the current mean error & plot true parabola vs. the current prediction
  31. disp(['The mean loss in iteration #', num2str(iter + 1), ' is: ',...
  32. num2str(mean_loss), '.']);
  33.  
  34. if iter == 20
  35. plot_every_iters = 100;
  36.  
  37. elseif iter == 1000
  38. plot_every_iters = 10000;
  39.  
  40. end
  41.  
  42. if mod(iter, plot_every_iters) == 0
  43. plot(x, predictions, 'r--')
  44. legend('True Parabola', 'Our Current Prediction');
  45. drawnow;
  46. end
  47. end
  48.  
  49. iter = iter + 1;
  50. end
  51.  
  52. % Plot the true parabola vs. the final prediction
  53. if visual
  54. close all;
  55. figure();
  56. hold on;
  57. plot(x, y, 'b', 'LineWidth', 2);
  58. plot(x, predictions, 'r--x')
  59. title('True Parabola vs. Our Predictions');
  60. xlabel('X Axis [N.U.]');
  61. ylabel('Y Axis [N.U.]');
  62. legend('True Parabola', 'Our Final Prediction');
  63. end
  64.  
  65. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement