首页 > 解决方案 > 如何将 scipy.optimize 与数组函数一起使用?

问题描述

我创建了一个定制的指数平滑函数。由于 scipy.optimize.basinhopping,我想优化它的参数。

如果我只优化一次系列的功能,它就可以工作

import numpy as np
from scipy.optimize import basinhopping
d = [1,2,3,4]   
cols = len(d) 
def simple_exp_smooth(inputs):
    ini,alpha = inputs
    f = np.full(cols,np.nan) 
    f[0] = ini
    for t in range(1,cols):
        f[t] = alpha*d[t-1]+(1-alpha)*f[t-1]           
    error = sum(abs(f[1:] - d[1:]))
    return error
func = simple_exp_smooth
bounds = np.array([(0,4),(0.0, 1.0)])
x0 = (1,0.1)
res = basinhopping(func, x0, minimizer_kwargs={'bounds': bounds},stepsize=0.1,niter=45)

其中一个问题是,如果你有 1000 个时间序列要优化,它会很慢。所以我创建了一个数组版本来一次执行多个时间序列的指数平滑。

def simple(inputs):
    a0,alpha  = inputs
    a = np.full([rows,cols],np.nan)
    a[:,0] = a0
    for t in range(1,cols):
        a[:,t] = alpha*d[:,t]+(1-alpha)*a[:,t-1]
    MAE = abs(d - a).mean(axis=1)/d.mean(axis=1)
    return sum(MAE)

d = np.array([[1,2,3,4],
              [10,20,30,40]])
rows, cols = d.shape

a0_bound = np.vstack((d.min(axis=1),d.max(axis=1))).T
a0_ini = d.mean(axis=1)
bounds = ([a0_bound,(0.0, 1.0)])
x0 = (a0_ini,0.2)
res = basinhopping(simple, x0, minimizer_kwargs={'bounds': bounds},stepsize=0.1)

但是现在,盆地跳跃给了我这个错误:

bounds = [(None if l == -np.inf else l, None if u == np.inf else u) for l, u in bounds]

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

有什么方法可以让我使用盆地跳跃来一次优化我的整个阵列,而不是逐行优化?

标签: pythonoptimizationscipy

解决方案


推荐阅读