Path: blob/master/Week 9/Programming Assignment - 8/ex8/fmincg.m
616 views
function [X, fX, i] = fmincg(f, X, options, P1, P2, P3, P4, P5)1% Minimize a continuous differentialble multivariate function. Starting point2% is given by "X" (D by 1), and the function named in the string "f", must3% return a function value and a vector of partial derivatives. The Polack-4% Ribiere flavour of conjugate gradients is used to compute search directions,5% and a line search using quadratic and cubic polynomial approximations and the6% Wolfe-Powell stopping criteria is used together with the slope ratio method7% for guessing initial step sizes. Additionally a bunch of checks are made to8% make sure that exploration is taking place and that extrapolation will not9% be unboundedly large. The "length" gives the length of the run: if it is10% positive, it gives the maximum number of line searches, if negative its11% absolute gives the maximum allowed number of function evaluations. You can12% (optionally) give "length" a second component, which will indicate the13% reduction in function value to be expected in the first line-search (defaults14% to 1.0). The function returns when either its length is up, or if no further15% progress can be made (ie, we are at a minimum, or so close that due to16% numerical problems, we cannot get any closer). If the function terminates17% within a few iterations, it could be an indication that the function value18% and derivatives are not consistent (ie, there may be a bug in the19% implementation of your "f" function). The function returns the found20% solution "X", a vector of function values "fX" indicating the progress made21% and "i" the number of iterations (line searches or function evaluations,22% depending on the sign of "length") used.23%24% Usage: [X, fX, i] = fmincg(f, X, options, P1, P2, P3, P4, P5)25%26% See also: checkgrad27%28% Copyright (C) 2001 and 2002 by Carl Edward Rasmussen. Date 2002-02-1329%30%31% (C) Copyright 1999, 2000 & 2001, Carl Edward Rasmussen32%33% Permission is granted for anyone to copy, use, or modify these34% programs and accompanying documents for purposes of research or35% education, provided this copyright notice is retained, and note is36% made of any changes that have been made.37%38% These programs and documents are distributed without any warranty,39% express or implied. As the programs were written for research40% purposes only, they have not been tested to the degree that would be41% advisable in any important application. All use of these programs is42% entirely at the user's own risk.43%44% [ml-class] Changes Made:45% 1) Function name and argument specifications46% 2) Output display47%4849% Read options50if exist('options', 'var') && ~isempty(options) && isfield(options, 'MaxIter')51length = options.MaxIter;52else53length = 100;54end555657RHO = 0.01; % a bunch of constants for line searches58SIG = 0.5; % RHO and SIG are the constants in the Wolfe-Powell conditions59INT = 0.1; % don't reevaluate within 0.1 of the limit of the current bracket60EXT = 3.0; % extrapolate maximum 3 times the current bracket61MAX = 20; % max 20 function evaluations per line search62RATIO = 100; % maximum allowed slope ratio6364argstr = ['feval(f, X']; % compose string used to call function65for i = 1:(nargin - 3)66argstr = [argstr, ',P', int2str(i)];67end68argstr = [argstr, ')'];6970if max(size(length)) == 2, red=length(2); length=length(1); else red=1; end71S=['Iteration '];7273i = 0; % zero the run length counter74ls_failed = 0; % no previous line search has failed75fX = [];76[f1 df1] = eval(argstr); % get function value and gradient77i = i + (length<0); % count epochs?!78s = -df1; % search direction is steepest79d1 = -s'*s; % this is the slope80z1 = red/(1-d1); % initial step is red/(|s|+1)8182while i < abs(length) % while not finished83i = i + (length>0); % count iterations?!8485X0 = X; f0 = f1; df0 = df1; % make a copy of current values86X = X + z1*s; % begin line search87[f2 df2] = eval(argstr);88i = i + (length<0); % count epochs?!89d2 = df2'*s;90f3 = f1; d3 = d1; z3 = -z1; % initialize point 3 equal to point 191if length>0, M = MAX; else M = min(MAX, -length-i); end92success = 0; limit = -1; % initialize quanteties93while 194while ((f2 > f1+z1*RHO*d1) || (d2 > -SIG*d1)) && (M > 0)95limit = z1; % tighten the bracket96if f2 > f197z2 = z3 - (0.5*d3*z3*z3)/(d3*z3+f2-f3); % quadratic fit98else99A = 6*(f2-f3)/z3+3*(d2+d3); % cubic fit100B = 3*(f3-f2)-z3*(d3+2*d2);101z2 = (sqrt(B*B-A*d2*z3*z3)-B)/A; % numerical error possible - ok!102end103if isnan(z2) || isinf(z2)104z2 = z3/2; % if we had a numerical problem then bisect105end106z2 = max(min(z2, INT*z3),(1-INT)*z3); % don't accept too close to limits107z1 = z1 + z2; % update the step108X = X + z2*s;109[f2 df2] = eval(argstr);110M = M - 1; i = i + (length<0); % count epochs?!111d2 = df2'*s;112z3 = z3-z2; % z3 is now relative to the location of z2113end114if f2 > f1+z1*RHO*d1 || d2 > -SIG*d1115break; % this is a failure116elseif d2 > SIG*d1117success = 1; break; % success118elseif M == 0119break; % failure120end121A = 6*(f2-f3)/z3+3*(d2+d3); % make cubic extrapolation122B = 3*(f3-f2)-z3*(d3+2*d2);123z2 = -d2*z3*z3/(B+sqrt(B*B-A*d2*z3*z3)); % num. error possible - ok!124if ~isreal(z2) || isnan(z2) || isinf(z2) || z2 < 0 % num prob or wrong sign?125if limit < -0.5 % if we have no upper limit126z2 = z1 * (EXT-1); % the extrapolate the maximum amount127else128z2 = (limit-z1)/2; % otherwise bisect129end130elseif (limit > -0.5) && (z2+z1 > limit) % extraplation beyond max?131z2 = (limit-z1)/2; % bisect132elseif (limit < -0.5) && (z2+z1 > z1*EXT) % extrapolation beyond limit133z2 = z1*(EXT-1.0); % set to extrapolation limit134elseif z2 < -z3*INT135z2 = -z3*INT;136elseif (limit > -0.5) && (z2 < (limit-z1)*(1.0-INT)) % too close to limit?137z2 = (limit-z1)*(1.0-INT);138end139f3 = f2; d3 = d2; z3 = -z2; % set point 3 equal to point 2140z1 = z1 + z2; X = X + z2*s; % update current estimates141[f2 df2] = eval(argstr);142M = M - 1; i = i + (length<0); % count epochs?!143d2 = df2'*s;144end % end of line search145146if success % if line search succeeded147f1 = f2; fX = [fX' f1]';148fprintf('%s %4i | Cost: %4.6e\r', S, i, f1);149s = (df2'*df2-df1'*df2)/(df1'*df1)*s - df2; % Polack-Ribiere direction150tmp = df1; df1 = df2; df2 = tmp; % swap derivatives151d2 = df1'*s;152if d2 > 0 % new slope must be negative153s = -df1; % otherwise use steepest direction154d2 = -s'*s;155end156z1 = z1 * min(RATIO, d1/(d2-realmin)); % slope ratio but max RATIO157d1 = d2;158ls_failed = 0; % this line search did not fail159else160X = X0; f1 = f0; df1 = df0; % restore point from before failed line search161if ls_failed || i > abs(length) % line search failed twice in a row162break; % or we ran out of time, so we give up163end164tmp = df1; df1 = df2; df2 = tmp; % swap derivatives165s = -df1; % try steepest166d1 = -s'*s;167z1 = 1/(1-d1);168ls_failed = 1; % this line search failed169end170if exist('OCTAVE_VERSION')171fflush(stdout);172end173end174fprintf('\n');175176177