使用scipy.optimize.brute

时间:2017-12-09 00:11:08

标签: python scipy nonlinear-optimization arima

基于this post我试图用粗暴的方法在ARIMA模型上进行网格搜索,但我无法让它运行。我是这样做的原则证明,但我对这些论点做错了什么?

y = pd.DataFrame([0,1,4,9,16]) + 3
def objfunc(coeffs, endog):
    exp = coeffs[0]
    const = coeffs[1]
    print(exp, const, endog)
    out = 0
    for i in range(4):
        out += i**exp + const
    return out

from scipy.optimize import brute
grid = (slice(0, 2, 1), slice(3, 4, 1))
brute(objfunc, ranges=grid, args=y)

(0, 3, 0)
(0, 3, 0)
(1, 3, 0)
...
TypeError: objfunc() takes exactly 2 arguments (1 given)

一旦我解决了这个问题,我的目标实际上就是按顺序优化这个功能,而season_order分别是这个(_,_,_)和这个(_,_,_,12)的元组。

def objfunc(coeffs, endog):
    order = coeffs[0]
    seasonal = coeffs[1]
    fit = sm.tsa.statespace.SARIMAX(endog, trend='n', order=order, seasonal_order=seasonal).fit()
    return fit.aic()

编辑:此代码有效(感谢@sasha),变量名称更清晰,更有意义(我最小化错误的功能)。

import pandas as pd    
y = np.array([0,1,4,9,16]) + 3 #polynomial x^2+3 with x=0:4
def objfunc(coeffs, *args):
    arr = args[0]                       # access first element of tuple: y
    exp = coeffs[0]                       #     assuming y should become endog
    const = coeffs[1]
    pol = [i**exp + const for i in range(len(y))]
    print coeffs
    return abs(sum(pol) - sum(arr))

from scipy.optimize import brute
grid = (slice(1, 3, 1), slice(2, 5, 1))
resbrute = brute(objfunc, ranges=grid, args=(y,), full_output=True, finish=None)
print("Best coeffs: {}".format(resbrute[0]))
print("Score with best coeffs: {}".format(resbrute[1]))
print("Grid: {}".format(resbrute[2].tolist()))
print("Scores for grid: {}".format(resbrute[3].tolist()))

1 个答案:

答案 0 :(得分:1)

对于所有这些变量名,代码看起来有点奇怪。 endog,y; y变成了endog?

但是以下可能是方法,它完全遵循documentation

  

args:元组,可选

     

完全指定函数所需的任何其他固定参数。

代码:

import pandas as pd

y = pd.DataFrame([0,1,4,9,16]) + 3
def objfunc(coeffs, *args):
    endog = args[0]                       # access first element of tuple: y
    exp = coeffs[0]                       #     assuming y should become endog
    const = coeffs[1]
    print(exp, const, endog)
    out = 0
    for i in range(4):
        out += i**exp + const
    return out

from scipy.optimize import brute
grid = (slice(0, 2, 1), slice(3, 4, 1))
brute(objfunc, ranges=grid, args=(y,))    # in general a tuple; first pos: y