scipy.minimize - “TypeError: numpy.float64' 对象不可调用运行”

Nip*_*per 5 python compiler-errors numpy minimize scipy

运行 scipy.minimize 函数“我得到 TypeError: 'numpy.float64' object is not callable”。具体在执行过程中:

    .../scipy/optimize/optimize.py", line 292, in function_wrapper
return function(*(wrapper_args + args))
Run Code Online (Sandbox Code Playgroud)

我已经在这里查看了以前的类似主题,通常会出现此问题,因为 .minimize 的第一个输入参数不是函数。我很难弄清楚,因为“a”是函数。你怎么认为?

    ### "data" is a pandas data frame of float values
    ### "w" is a numpy float array i.e. [0.11365704 0.00886848 0.65302202 0.05680696 0.1676455 ]

    def a(data, w):
        ### Return a negative float value from position [2] of an numpy array of float values calculated via the "b" function i.e -0.3632965490830499 
        return -b(data, w)[2]

    constraint = ({'type': 'eq', 'fun': lambda x: np.sum(x) - 1})

    ### i.e ((0, 1), (0, 1), (0, 1), (0, 1), (0, 1))
    bound = tuple((0, 1) for x in range (len(symbols)))

    opts = scipy.minimize(a(data, w), len(symbols) * [1. / len(symbols),], method = 'SLSQP', bounds = bound, constraints = constraint)
Run Code Online (Sandbox Code Playgroud)

tel*_*tel 5

简答

它应该是:

opts = scipy.minimize(a, len(symbols) * [1. / len(symbols),], args=(w,), method='SLSQP', bounds=bound, constraints=constraint)
Run Code Online (Sandbox Code Playgroud)

细节

a(data, w)不是一个函数,它是一个函数调用。换句话说,a(data, w) 有效地具有返回值的值和类型的函数aminimize需要没有调用的实际函数(即没有括号(...)和中间的所有内容),作为它的第一个参数。

scipy.optimize.minimize文档

scipy.optimize.minimize(fun, x0, args=(), method=None, jac=None, hess=None, hessp=None, bounds=None, constraint=(), tol=None, callback=None, options=没有任何)

...

乐趣:可调用

要最小化的目标函数。必须采用 f(x, *args) 形式。优化参数 x 是一个一维点数组,而 args 是完整指定函数所需的任何附加固定参数的元组。

...

args : 元组,可选

传递给目标函数的额外参数...

因此,假设w是固定的(至少相对于所需的最小化),你将它传递给minimize通过args参数,因为我之前所做的那样。