【问题标题】:Using scipy.optimize.brute使用 scipy.optimize.brute
【发布时间】:2017-12-09 00:11:07
【问题描述】:

基于this post,我正在尝试使用 brute 在 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)

一旦我解决了这个问题,我的目标实际上是在 order 和seasonal_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()))

【问题讨论】:

    标签: python scipy nonlinear-optimization arima


    【解决方案1】:

    所有这些变量名的代码看起来有点奇怪。内多格, 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
    

    【讨论】:

    • 你是对的变量名。我编辑了我的问题并包含了您的答案。我可以对 SARIMAX 进行优化,我可能会发布它。谢谢
    猜你喜欢
    • 2020-01-21
    • 1970-01-01
    • 2014-02-14
    • 2016-08-31
    • 2021-04-01
    • 1970-01-01
    • 2016-03-23
    • 2015-09-08
    • 2020-12-19
    相关资源
    最近更新 更多