python - 如何将 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()
有什么方法可以让我使用盆地跳跃来一次优化我的整个阵列,而不是逐行优化?
解决方案
推荐阅读
- saml-2.0 - 对于某些 Idp,只有 Acs URL 发送 500 错误,不幸的是,没有记录或返回任何内容,以便了解究竟发生了什么
- typescript - 如何在 Typescript 中为工厂模式应用不同的编译时警告和语法突出显示?
- flutter - 错误:错误:必须初始化不可为空的实例字段“searchBar”。(在 _SearchBarDemoHomeState() { searchBar = SearchBar( )
- reactjs - 当数据是对象数组时重命名 Grid.js dataTable 中的列标题(Svelte)
- api - 回调 API 到 URL
- uwsgi - 使用 uwsgi 时没有名为“编码”的模块
- reactjs - `getDerivedStateFromProps` 没有更新状态
- gupshup - 有没有办法从流程构建器进行 http 调用?
- java - 最大汉明距离
- reactjs - 是否可以从 Messenger Webview 打开相机