Python 减少计算偏导数的时间

Python 减少计算偏导数的时间,python,derivative,Python,Derivative,我用三个未知值计算函数的一阶和二阶偏导数(使用numdifftools),以找到函数具有最小值的值。代码如下: def gaussian(x, mu, sig): return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.))) def partial_function(f___,input,pos,value): tmp = input[pos] input[pos] = value ret = f

我用三个未知值计算函数的一阶和二阶偏导数(使用numdifftools),以找到函数具有最小值的值。代码如下:

def gaussian(x, mu, sig):
    return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))

def partial_function(f___,input,pos,value):
    tmp  = input[pos]
    input[pos] = value
    ret = f___(*input)
    input[pos] = tmp
    return ret

def derivative(f,input):
    # f - function I want to derive
    # input - points where I want to calculate the derivative
    first = np.empty(len(input))
    second = np.empty(len(input))
    for i in range(len(input)):
        fg = lambda x:partial_function(f,input,i,x)
        first[i] = nd.Derivative(fg)(input[i])                 #first deriv
        second[i] = nd.Derivative(nd.Derivative(fg))(input[i]) #second deriv
    deriv = np.vstack((first,second))
    return deriv
我要最小化的函数如下所示:

func = lambda w,m,s: sum((gamma_[k,:]-w*gaussian(x,m,s))**2)
其中,
gamma_k,:]
是一个已知向量

我这样称呼导数方法:

func = lambda w,m,s: sum((gamma_[k,:]-w*gaussian(x,m,s))**2)
d=导数(func,param0)

其中
param0
是初始猜测(本例中为1x3向量)


问题是,我多次运行优化算法,由于派生计算,每次迭代的时间非常长。为了减少计算这些导数的时间,我可以采取哪种方法?

我使用有限差分为导数编写了自己的函数:

def firstDerivative(f, param):
    h = 1e-5
    deriv = np.zeros(len(param))
    for i in range(len(param)):
        rise = np.copy(param)
        rise[i] = rise[i] + h
        deriv[i] = (f(rise) - f(param))/h
    return deriv
在这个函数中,
f
是我计算导数的表达式,
param
是值。
这些函数的性能比我在问题中使用的函数要好得多。因为二阶导数几乎是一样的,只需检查一下:

我认为二阶[I]=nd.导数(nd.导数(fg))(输入[I])应该是二阶[I]=nd.导数(fg,n=2)(输入[I])#二阶deriv@RootTwo是的,这就是问题所在。谢谢你的回答。@RootTwo它仍然很慢:我的优化算法的300次迭代大约需要20秒,但使用我的答案的有限差分法只需要不到3秒。