2

I want to use scipy.optimize.check_grad to evaluate correctness of gradients. I specify

def func(x, a):
    return x[0]**2 - 0.5 * x[1]**3 + a**2 

def grad(x, a):
        return [2 * x[0], -1.5 * x[1]**2 + 2*a]

from scipy.optimize import check_grad
a = 5 
check_grad(func, grad, [1.5, -1.5], args = (a))

And get error

Unknown keyword arguments: ['args']

Noteworthy args is listed as an argumet in the help file. Shouldn't this work?

tomka
  • 2,516
  • 7
  • 31
  • 45
  • Note that [`*args`](http://stackoverflow.com/questions/3394835/args-and-kwargs) is different than `args` in the definition of a function. In this case, what you should provide is `check_grad(func, grad, [1.5, -1.5], a)`. – Stelios Oct 27 '16 at 14:15

1 Answers1

1

*args just passes the position args to the the func and grad functions.

You want to just pass the value of the meta parameter, a, as the argument after x0.

def func(x, a, b):
    return x[0]**2 - 0.5 * x[1]**3 + a**2 + b

def grad(x, a, b):
        return [2 * x[0], -1.5 * x[1]**2 + 2*a + b]

from scipy.optimize import check_grad
a = 5 
b = 10
check_grad(func, grad, [1.5, -1.5], a, b)

See https://github.com/scipy/scipy/blob/a81bc79ba38825139e97b14c91e158f4aabc0bed/scipy/optimize/optimize.py#L736-L737 for the implementation.

Bob Baxley
  • 3,551
  • 1
  • 22
  • 28
  • Thanks -- however, what do I have to do if I have multiple arguments to be passed to `func`. If I add an additive `b` to `func` for example, and call `check_grad(func, grad, x0 = [3, -3], a, b)` then I get error `positional argument follows keyword argument ` – tomka Oct 27 '16 at 14:24
  • You can't name `x0` in the arg list for that to work. If you remove `x0=` it will work fine to pass multiple arguments. When you name `x0`, python thinks you have moved on to the `**kwargs`. – Bob Baxley Oct 27 '16 at 14:38
  • This is very subtle. I understand now. – tomka Oct 27 '16 at 14:56