THMMY's "Optimization Techniques" course assignments.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

63 lines
2.4 KiB

  1. % Define environment (functions, gradients etc...)
  2. GivenEnv
  3. % Define parameters
  4. max_iter = 300; % Maximum iterations
  5. tol = 1e-4; % Tolerance
  6. % Methods tuning
  7. amijo_beta = 0.5; % Armijo reduction factor
  8. amijo_sigma = 0.1; % Armijo condition constant
  9. % Point x0 = (0, 0)
  10. point = 1;
  11. x0 = [0, 0];
  12. f = fun(x0(1), x0(2));
  13. gf = grad_fun(x0(1), x0(2));
  14. hf = hessian_fun(x0(1), x0(2));
  15. fprintf('Initial point (%d, %d), f = %f, grad = [%f;%f], hessian = [%f %f ; %f %f]. Can not use method\n\n', x0, f, gf, hf);
  16. % Points x0 = (-1, 1), (1, -1)
  17. %x0s = [-1, 1 ; 1, -1]; % Initial points
  18. % Point x0 = (-1, 1)
  19. point = 2;
  20. x0 = [-1, 1];
  21. point_str = "[" + x0(1) + ", " + x0(2) + "]";
  22. f = fun(-1, 1);
  23. gf = grad_fun(x0(1), x0(2));
  24. hf = hessian_fun(x0(1), x0(2));
  25. fprintf('Initial point (%d, %d), f = %f, grad = [%f;%f], hessian = [%f %f ; %f %f]. Can use method\n', x0, f, gf, hf);
  26. % Find the best fixed gamma
  27. k = zeros(100, 1);
  28. j = 1;
  29. n = linspace(0.1, 1.5, 100);
  30. for g = n
  31. gamma_fixed_step = g;
  32. [~, ~, k(j)] = method_steepest_descent(fun, grad_fun, x0, tol, max_iter, 'fixed');
  33. j = j + 1;
  34. end
  35. plotItersOverGamma(n, k, "Iteration for different $\gamma$ values", "figures/StDes_Iter_o_gamma_" + point + ".png");
  36. [~, j] = min(k);
  37. gamma_fixed_step = n(j);
  38. [x_fixed, f_fixed, kk] = method_steepest_descent(fun, grad_fun, x0, tol, max_iter, 'fixed');
  39. fprintf('Fixed step: Initial point (%f, %f), steps:%d, Final (x,y)=(%f, %f), f(x,y)=%f\n', x0, kk, x_fixed(end, :), f_fixed(end));
  40. plotPointsOverContour(x_fixed, fun, [-2, 0], [-2, 2], 100, point_str + ": Steepest descent $\gamma$ = " + gamma_fixed_step, "figures/StDes_fixed_" + point + ".png");
  41. % Minimized f
  42. [x_minimized, f_minimized, kk] = method_steepest_descent(fun, grad_fun, x0, tol, max_iter, 'minimized');
  43. fprintf('Minimized f(g): Initial point (%f, %f), steps:%d, Final (x,y)=(%f, %f), f(x,y)=%f\n', x0, kk, x_minimized(end, :), f_minimized(end));
  44. plotPointsOverContour(x_minimized, fun, [-2, 2], [-2, 2], 100, point_str + ": Steepest descent minimized $f(x_k + \gamma_kd_k)$", "StDes_minimized_" + i + ".png");
  45. % Armijo Rule
  46. [x_armijo, f_armijo, kk] = method_steepest_descent(fun, grad_fun, x0, tol, max_iter, 'armijo');
  47. fprintf('Armijo step: Initial point (%f, %f), steps:%d, Final (x,y)=(%f, %f), f(x,y)=%f\n', x0, kk, x_armijo(end, :), f_armijo(end));
  48. plotPointsOverContour(x_armijo, fun, [-2, 2], [-2, 2], 100, point_str + ": Steepest descent Armijo method", "StDes_armijo_" + i + ".png");