Search code examples
pythonscipyargsminimization

Scipy.optimize check_grad function gives "Unknown keyword arguments: ['args']" error


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?


Solution

  • *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.