0
$\begingroup$

I've defined a function in this way:

def qfun(par):
    return(par[0]+atan(par[3])*par[1]+atan(par[4])*par[2])

How can I obtain the gradient of this function for only some of the elements (par [0:2]) in a specific point? I only find functions with only one "x", so for those cases it is simple, but when your function has more parameters what should I do?

$\endgroup$

1 Answer 1

1
$\begingroup$

Several options:

  • You can use the defintion of the derivative to have an approximation....

    def f(x):
        return x[0]**2 + 3*x[1]**3
    
    def der(f, x, der_index=[]):
        # der_index: variable w.r.t. get gradient
    
        epsilon = 2.34E-10
        grads = []
    
       for idx in der_index:
           x_ = x.copy()
           x_[idx]+=epsilon
    
           grads.append((f(x_) - f(x))/epsilon)
    
       return grads
    
    print(der(f, np.array([1.,1.]), der_index=[0, 1]))
    
  • If you can solve it analytically, it is better you write the derivative function by yourself

  • You can also use symbolic programming, like in Matlab, with the library sympy https://towardsdatascience.com/taking-derivatives-in-python-d6229ba72c64

  • Another way to do it is going for the "differentiable programming" paradigm or "software 2.0"

$\endgroup$
1
  • $\begingroup$ Yeah the analytical way is obviously the best one but once you have a lot of parameters and a complex function it becomes a little bit lenghty. I think I will opt for the approximation, thank you! $\endgroup$
    – unter_983
    Commented May 8, 2020 at 13:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.