fmincg.m 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. function [X, fX, i] = fmincg(f, X, options, P1, P2, P3, P4, P5)
  2. % Minimize a continuous differentialble multivariate function. Starting point
  3. % is given by "X" (D by 1), and the function named in the string "f", must
  4. % return a function value and a vector of partial derivatives. The Polack-
  5. % Ribiere flavour of conjugate gradients is used to compute search directions,
  6. % and a line search using quadratic and cubic polynomial approximations and the
  7. % Wolfe-Powell stopping criteria is used together with the slope ratio method
  8. % for guessing initial step sizes. Additionally a bunch of checks are made to
  9. % make sure that exploration is taking place and that extrapolation will not
  10. % be unboundedly large. The "length" gives the length of the run: if it is
  11. % positive, it gives the maximum number of line searches, if negative its
  12. % absolute gives the maximum allowed number of function evaluations. You can
  13. % (optionally) give "length" a second component, which will indicate the
  14. % reduction in function value to be expected in the first line-search (defaults
  15. % to 1.0). The function returns when either its length is up, or if no further
  16. % progress can be made (ie, we are at a minimum, or so close that due to
  17. % numerical problems, we cannot get any closer). If the function terminates
  18. % within a few iterations, it could be an indication that the function value
  19. % and derivatives are not consistent (ie, there may be a bug in the
  20. % implementation of your "f" function). The function returns the found
  21. % solution "X", a vector of function values "fX" indicating the progress made
  22. % and "i" the number of iterations (line searches or function evaluations,
  23. % depending on the sign of "length") used.
  24. %
  25. % Usage: [X, fX, i] = fmincg(f, X, options, P1, P2, P3, P4, P5)
  26. %
  27. % See also: checkgrad
  28. %
  29. % Copyright (C) 2001 and 2002 by Carl Edward Rasmussen. Date 2002-02-13
  30. %
  31. %
  32. % (C) Copyright 1999, 2000 & 2001, Carl Edward Rasmussen
  33. %
  34. % Permission is granted for anyone to copy, use, or modify these
  35. % programs and accompanying documents for purposes of research or
  36. % education, provided this copyright notice is retained, and note is
  37. % made of any changes that have been made.
  38. %
  39. % These programs and documents are distributed without any warranty,
  40. % express or implied. As the programs were written for research
  41. % purposes only, they have not been tested to the degree that would be
  42. % advisable in any important application. All use of these programs is
  43. % entirely at the user's own risk.
  44. %
  45. % [ml-class] Changes Made:
  46. % 1) Function name and argument specifications
  47. % 2) Output display
  48. %
  49. % Read options
  50. if exist('options', 'var') && ~isempty(options) && isfield(options, 'MaxIter')
  51. length = options.MaxIter;
  52. else
  53. length = 100;
  54. end
  55. RHO = 0.01; % a bunch of constants for line searches
  56. SIG = 0.5; % RHO and SIG are the constants in the Wolfe-Powell conditions
  57. INT = 0.1; % don't reevaluate within 0.1 of the limit of the current bracket
  58. EXT = 3.0; % extrapolate maximum 3 times the current bracket
  59. MAX = 20; % max 20 function evaluations per line search
  60. RATIO = 100; % maximum allowed slope ratio
  61. argstr = ['feval(f, X']; % compose string used to call function
  62. for i = 1:(nargin - 3)
  63. argstr = [argstr, ',P', int2str(i)];
  64. end
  65. argstr = [argstr, ')'];
  66. if max(size(length)) == 2, red=length(2); length=length(1); else red=1; end
  67. S=['Iteration '];
  68. i = 0; % zero the run length counter
  69. ls_failed = 0; % no previous line search has failed
  70. fX = [];
  71. [f1 df1] = eval(argstr); % get function value and gradient
  72. i = i + (length<0); % count epochs?!
  73. s = -df1; % search direction is steepest
  74. d1 = -s'*s; % this is the slope
  75. z1 = red/(1-d1); % initial step is red/(|s|+1)
  76. while i < abs(length) % while not finished
  77. i = i + (length>0); % count iterations?!
  78. X0 = X; f0 = f1; df0 = df1; % make a copy of current values
  79. X = X + z1*s; % begin line search
  80. [f2 df2] = eval(argstr);
  81. i = i + (length<0); % count epochs?!
  82. d2 = df2'*s;
  83. f3 = f1; d3 = d1; z3 = -z1; % initialize point 3 equal to point 1
  84. if length>0, M = MAX; else M = min(MAX, -length-i); end
  85. success = 0; limit = -1; % initialize quanteties
  86. while 1
  87. while ((f2 > f1+z1*RHO*d1) || (d2 > -SIG*d1)) && (M > 0)
  88. limit = z1; % tighten the bracket
  89. if f2 > f1
  90. z2 = z3 - (0.5*d3*z3*z3)/(d3*z3+f2-f3); % quadratic fit
  91. else
  92. A = 6*(f2-f3)/z3+3*(d2+d3); % cubic fit
  93. B = 3*(f3-f2)-z3*(d3+2*d2);
  94. z2 = (sqrt(B*B-A*d2*z3*z3)-B)/A; % numerical error possible - ok!
  95. end
  96. if isnan(z2) || isinf(z2)
  97. z2 = z3/2; % if we had a numerical problem then bisect
  98. end
  99. z2 = max(min(z2, INT*z3),(1-INT)*z3); % don't accept too close to limits
  100. z1 = z1 + z2; % update the step
  101. X = X + z2*s;
  102. [f2 df2] = eval(argstr);
  103. M = M - 1; i = i + (length<0); % count epochs?!
  104. d2 = df2'*s;
  105. z3 = z3-z2; % z3 is now relative to the location of z2
  106. end
  107. if f2 > f1+z1*RHO*d1 || d2 > -SIG*d1
  108. break; % this is a failure
  109. elseif d2 > SIG*d1
  110. success = 1; break; % success
  111. elseif M == 0
  112. break; % failure
  113. end
  114. A = 6*(f2-f3)/z3+3*(d2+d3); % make cubic extrapolation
  115. B = 3*(f3-f2)-z3*(d3+2*d2);
  116. z2 = -d2*z3*z3/(B+sqrt(B*B-A*d2*z3*z3)); % num. error possible - ok!
  117. if ~isreal(z2) || isnan(z2) || isinf(z2) || z2 < 0 % num prob or wrong sign?
  118. if limit < -0.5 % if we have no upper limit
  119. z2 = z1 * (EXT-1); % the extrapolate the maximum amount
  120. else
  121. z2 = (limit-z1)/2; % otherwise bisect
  122. end
  123. elseif (limit > -0.5) && (z2+z1 > limit) % extraplation beyond max?
  124. z2 = (limit-z1)/2; % bisect
  125. elseif (limit < -0.5) && (z2+z1 > z1*EXT) % extrapolation beyond limit
  126. z2 = z1*(EXT-1.0); % set to extrapolation limit
  127. elseif z2 < -z3*INT
  128. z2 = -z3*INT;
  129. elseif (limit > -0.5) && (z2 < (limit-z1)*(1.0-INT)) % too close to limit?
  130. z2 = (limit-z1)*(1.0-INT);
  131. end
  132. f3 = f2; d3 = d2; z3 = -z2; % set point 3 equal to point 2
  133. z1 = z1 + z2; X = X + z2*s; % update current estimates
  134. [f2 df2] = eval(argstr);
  135. M = M - 1; i = i + (length<0); % count epochs?!
  136. d2 = df2'*s;
  137. end % end of line search
  138. if success % if line search succeeded
  139. f1 = f2; fX = [fX' f1]';
  140. fprintf('%s %4i | Cost: %4.6e\r', S, i, f1);
  141. s = (df2'*df2-df1'*df2)/(df1'*df1)*s - df2; % Polack-Ribiere direction
  142. tmp = df1; df1 = df2; df2 = tmp; % swap derivatives
  143. d2 = df1'*s;
  144. if d2 > 0 % new slope must be negative
  145. s = -df1; % otherwise use steepest direction
  146. d2 = -s'*s;
  147. end
  148. z1 = z1 * min(RATIO, d1/(d2-realmin)); % slope ratio but max RATIO
  149. d1 = d2;
  150. ls_failed = 0; % this line search did not fail
  151. else
  152. X = X0; f1 = f0; df1 = df0; % restore point from before failed line search
  153. if ls_failed || i > abs(length) % line search failed twice in a row
  154. break; % or we ran out of time, so we give up
  155. end
  156. tmp = df1; df1 = df2; df2 = tmp; % swap derivatives
  157. s = -df1; % try steepest
  158. d1 = -s'*s;
  159. z1 = 1/(1-d1);
  160. ls_failed = 1; % this line search failed
  161. end
  162. if exist('OCTAVE_VERSION')
  163. fflush(stdout);
  164. end
  165. end
  166. fprintf('\n');