annotate toolboxes/FullBNT-1.0.7/netlab3.3/gradchek.m @ 0:cc4b1211e677 tip

initial commit to HG from Changeset: 646 (e263d8a21543) added further path and more save "camirversion.m"
author Daniel Wolff
date Fri, 19 Aug 2016 13:07:06 +0200
parents
children
rev   line source
Daniel@0 1 function [gradient, delta] = gradchek(w, func, grad, varargin)
Daniel@0 2 %GRADCHEK Checks a user-defined gradient function using finite differences.
Daniel@0 3 %
Daniel@0 4 % Description
Daniel@0 5 % This function is intended as a utility for other netlab functions
Daniel@0 6 % (particularly optimisation functions) to use. It enables the user to
Daniel@0 7 % check whether a gradient calculation has been correctly implmented
Daniel@0 8 % for a given function. GRADCHEK(W, FUNC, GRAD) checks how accurate the
Daniel@0 9 % gradient GRAD of a function FUNC is at a parameter vector X. A
Daniel@0 10 % central difference formula with step size 1.0e-6 is used, and the
Daniel@0 11 % results for both gradient function and finite difference
Daniel@0 12 % approximation are printed. The optional return value GRADIENT is the
Daniel@0 13 % gradient calculated using the function GRAD and the return value
Daniel@0 14 % DELTA is the difference between the functional and finite difference
Daniel@0 15 % methods of calculating the graident.
Daniel@0 16 %
Daniel@0 17 % GRADCHEK(X, FUNC, GRAD, P1, P2, ...) allows additional arguments to
Daniel@0 18 % be passed to FUNC and GRAD.
Daniel@0 19 %
Daniel@0 20 % See also
Daniel@0 21 % CONJGRAD, GRADDESC, HMC, OLGD, QUASINEW, SCG
Daniel@0 22 %
Daniel@0 23
Daniel@0 24 % Copyright (c) Ian T Nabney (1996-2001)
Daniel@0 25
Daniel@0 26 % Reasonable value for step size
Daniel@0 27 epsilon = 1.0e-6;
Daniel@0 28
Daniel@0 29 func = fcnchk(func, length(varargin));
Daniel@0 30 grad = fcnchk(grad, length(varargin));
Daniel@0 31
Daniel@0 32 % Treat
Daniel@0 33 nparams = length(w);
Daniel@0 34 deltaf = zeros(1, nparams);
Daniel@0 35 step = zeros(1, nparams);
Daniel@0 36 for i = 1:nparams
Daniel@0 37 % Move a small way in the ith coordinate of w
Daniel@0 38 step(i) = 1.0;
Daniel@0 39 fplus = feval('linef', epsilon, func, w, step, varargin{:});
Daniel@0 40 fminus = feval('linef', -epsilon, func, w, step, varargin{:});
Daniel@0 41 % Use central difference formula for approximation
Daniel@0 42 deltaf(i) = 0.5*(fplus - fminus)/epsilon;
Daniel@0 43 step(i) = 0.0;
Daniel@0 44 end
Daniel@0 45 gradient = feval(grad, w, varargin{:});
Daniel@0 46 fprintf(1, 'Checking gradient ...\n\n');
Daniel@0 47 delta = gradient - deltaf;
Daniel@0 48 fprintf(1, ' analytic diffs delta\n\n');
Daniel@0 49 disp([gradient', deltaf', delta'])