减少计算偏导数的时间

时间:2016-02-24 13:22:37

标签: 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___(*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,:]是已知的向量。

我称之为衍生方法:

d = derivative(func,param0)

其中param0是初始猜测(在这种情况下为1x3向量)

问题在于,由于推导计算,我多次运行优化算法,每次迭代的时间很长。我可以采取哪种方法来缩短计算这些衍生物的时间?

1 个答案:

答案 0 :(得分:0)

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

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是值。 这些函数的性能比我在我的问题中使用的函数要好得多。对于二阶导数几乎相同,只需检查:https://en.wikipedia.org/wiki/Finite_difference

相关问题