bundles / scipy latest / scipy / optimize / _optimize / check_grad
function
scipy.optimize._optimize:check_grad
Signature
def check_grad ( func , grad , x0 , * args , epsilon = 1.4901161193847656e-08 , direction = all , rng = None , seed = None ) Summary
Check the correctness of a gradient function by comparing it against a (forward) finite-difference approximation of the gradient.
Parameters
func: callable ``func(x0, *args)``Function whose derivative is to be checked.
grad: callable ``grad(x0, *args)``Jacobian of
func.x0: ndarrayPoints to check
gradagainst forward difference approximation of grad usingfunc.args: \\*args, optionalExtra arguments passed to
funcandgrad.epsilon: float, optionalStep size used for the finite difference approximation. It defaults to
sqrt(np.finfo(float).eps), which is approximately 1.49e-08.direction: str, optionalIf set to
'random', then gradients along a random vector are used to checkgradagainst forward difference approximation usingfunc. By default it is'all', in which case, all the one hot direction vectors are considered to checkgrad. Iffuncis a vector valued function then only'all'can be used.rng: {None, int, `numpy.random.Generator`}, optionalIf
rngis passed by keyword, types other than numpy.random.Generator are passed to numpy.random.default_rng to instantiate aGenerator. Ifrngis already aGeneratorinstance, then the provided instance is used. Specifyrngfor repeatable function behavior.If this argument is passed by position or
seedis passed by keyword, legacy behavior for the argumentseedapplies:If
seedis None (or numpy.random), the numpy.random.RandomState singleton is used.If
seedis an int, a newRandomStateinstance is used, seeded withseed.If
seedis already aGeneratororRandomStateinstance then that instance is used.
The random numbers generated affect the random vector along which gradients are computed to check
grad. Note thatrngis only used whendirectionargument is set to'random'.
Returns
err: floatThe square root of the sum of squares (i.e., the 2-norm) of the difference between
grad(x0, *args)and the finite difference approximation ofgradusing func at the pointsx0.
Examples
import numpy as np def func(x): return x[0]**2 - 0.5 * x[1]**3 def grad(x): return [2 * x[0], -1.5 * x[1]**2] from scipy.optimize import check_grad✓
check_grad(func, grad, [1.5, -1.5])
✗rng = np.random.default_rng()
✓check_grad(func, grad, [1.5, -1.5], direction='random', seed=rng)✗
See also
Aliases
-
scipy.optimize.check_grad