comparison toolboxes/FullBNT-1.0.7/netlab3.3/gradchek.m @ 0:e9a9cd732c1e tip

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