如何强制scipy优化模块的功能同时采取功能及其梯度 [英] How to force the functions of the optimize module of scipy to take a function and its gradient simultaneously

查看:77
本文介绍了如何强制scipy优化模块的功能同时采取功能及其梯度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要优化的函数f(x),我正在使用Scipy的scipy.optimize模块中的fmin_bfgs函数.这迫使我分别给出最小化函数和梯度f'(x)的函数,这很遗憾,因为在评估函数f(x)时可以完成一些梯度计算.

I have a fairly complex function f(x) that I want to optimize and I am using the fmin_bfgs function from the scipy.optimize module from Scipy. It forces me to give the function to minimize and the function of the gradient f'(x) separately, which is a pity because some of the computations for the gradient can be done when evaluating the function f(x).

是否有一种将两种功能结合在一起的方法?我当时正在考虑保存两个函数所需的中间值,但是我不知道fmin_bfgs函数是否保证f(x)的计算要早于f'(x).

Is there a way of combining both functions? I was considering saving the intermediate values required for both functions, but I don't know if the fmin_bfgs function guarantees that f(x) is evaluated before than f'(x).

谢谢

推荐答案

您可以使用备忘录来缓存中间值.不管第一个调用哪个函数,第二个都将能够利用存储的值.

You could use memoization to cache the intermediate values. Regardless of which function is called first, the second will be able to take advantage of the memoized value.

cache={}
def expensive_calc(x):
    # If x is a numpy array, you need to convert x into something hashable so it
    # can be used as a key in cache.
    key=tuple(x)
    try:
        return cache[key]
    except KeyError:
        # do expensive calc for result
        cache[key] = result
        return result

def func(x):
    y=expensive_calc(x)
    return something_based_on_y

def func_der(x):
    y=expensive_calc(x)
    return something_else_based_on_y

def optimize_fmin_bfgs():
    xopt = fmin_bfgs(func, x_guess, fprime=func_der)  

这篇关于如何强制scipy优化模块的功能同时采取功能及其梯度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆