0

我需要帮助使用三个变量约束来最小化 python 中的函数。

我已经发布了给我错误的代码。如果您愿意,我可以发布整个代码以显示数学计算。:

# the time-series data.
coeff = [0.2, 0.3, 0.4]

x =[146, 96, 59, 133, 192, 127, 79, 186, 272, 155, 98, 219]
test = y(x,coeff)
print("x : ", x)
print("y : ",test)

result = minimize(mape, coeff, (x,), bounds =[(0,1),(0,1), (0,1)], method='SLSQP')

opt = result.x
print("opt : ", result.x)

这是我的代码:

from __future__ import division
import numpy as np
from scipy.optimize import minimize



#coeffList[0] = alpha
#coeffList[1] = beta
#coeffList[2] =gamma

def mape(x, coeffList):
    diff = abs(y(x,coeffList)-x)
    print("np.mean(diff/x) : ", np.mean(diff/x))
    return np.mean(diff/x)


#Holt Winters-Multiplicative



def y(x, coeffList , debug=True):

    c =4 
    #Compute initial b and intercept using the first two complete c periods.
    xlen =len(x)
    print("xlen : ", xlen)
    #if xlen % c !=0:
    #    return None
    fc =float(c)
    xbar2 =sum([x[i] for i in range(c, 2 * c)])/ fc
    print("xbar2 : ",xbar2)

    xbar1 =sum([x[i] for i in range(c)]) / fc


    print("xbar1 : ", xbar1)
    b0 =(xbar2 - xbar1) / fc
    if debug: print ("b0 = ", b0)

    #Compute for the level estimate a0 using b0 above.
    tbar  =sum(i for i in range(1, c+1)) / fc
    print("tbar : ",tbar)
    a0 =xbar1  - b0 * tbar
    if debug: print ("a0 = ", a0)

    #Compute for initial indices - seasonality
    I =[x[i] / (a0 + (i+1) * b0) for i in range(0, xlen)]
    if debug: print ("Initial indices = ", I)

    S=[0] * (xlen+ c)
    for i in range(c):
        S[i] =(I[i] + I[i+c]) / 2.0
        print ("S[",i,"]=", S[i])

    #Normalize so S[i] for i in [0, c)  will add to c.
    tS =c / sum([S[i] for i in range(c)])
    print("tS : ", tS)
    for i in range(c):
        S[i] *=tS
        if debug: print ("Normalized S[",i,"]=", S[i])

    # Holt - winters proper ...
    if debug: print( "Use Holt Winters formulae")


    At =a0
    Bt =b0
    #y =[0] * (xlen) 
    y = np.empty(len(x),float)
    for i in range(xlen):
        Atm1 =At
        Btm1 =Bt
        At =coeffList[0] * x[i] / S[i] + (1.0-coeffList[0]) * (Atm1 + Btm1)
        Bt =coeffList[1] * (At - Atm1) + (1- coeffList[1]) * Btm1
        S[i+c] =coeffList[2] * x[i] / At + (1.0 - coeffList[2]) * S[i]
        y[i]=(a0 + b0 * (i+1)) * S[i]
        #print ("i=", i+1, "y=", y[i], "S=", S[i], "(level)Atm1=", Atm1, "(trend)Btm1=",Btm1, "(level)At=", At, "Bt=", Bt, "S[i+c]=", S[i+c], "y[i]=", y[i])
        print ("i=", i+1, "y=", y[i], "S=", S[i], "(level)At=", At, "Bt=", Bt, "y[i]=", y[i])
#coeffList[0] = alpha
#coeffList[1] = beta
#coeffList[2] =gamma

    return y

        #print (i,y[i],  F[i])
    #Forecast for next c periods:
    #for m in range(c):
        #print( "forecast:", (At + Bt* (m+1))* S[ylen + m])

    # the time-series data.
coeff = [0.2, 0.3, 0.4]

x =[146, 96, 59, 133, 192, 127, 79, 186, 272, 155, 98, 219]
bnds = ((0,1), (0,1), (0,1))
coeff = [0.2, 0.3, 0.4]
test = y(x,coeff)
print("x : ", x)
print("y : ",test)
#cons = ({'type' :'alpha', 'fun' :lambda x: np.array(x[0]<=1 and x[0]>=0)})
result = minimize(mape, coeff, (x,), method ="L-BFGS-B", bounds =bnds)

opt = result.x(0)
print("opt : ", result.x)

这是错误信息。没有最小化函数的函数工作得很好。

Traceback (most recent call last):
  File "C:\Users\gelalmp\Desktop\Bibha Gelal_SD\testing_Optimization_HWM.py", line 100, in <module>
    result = minimize(mape, coeff, (x,), method ="L-BFGS-B", bounds =bnds)
  File "C:\Python27\lib\site-packages\scipy\optimize\_minimize.py", line 380, in minimize
    callback=callback, **options)
  File "C:\Python27\lib\site-packages\scipy\optimize\lbfgsb.py", line 314, in _minimize_lbfgsb
    f, g = func_and_grad(x)
  File "C:\Python27\lib\site-packages\scipy\optimize\lbfgsb.py", line 258, in func_and_grad
    f = fun(x, *args)
  File "C:\Users\gelalmp\Desktop\Bibha Gelal_SD\testing_Optimization_HWM.py", line 12, in mape
    diff = abs(y(x,coeffList)-x)
  File "C:\Users\gelalmp\Desktop\Bibha Gelal_SD\testing_Optimization_HWM.py", line 30, in y
    xbar2 =sum([x[i] for i in range(c, 2 * c)])/ fc
IndexError: index out of bounds
4

1 回答 1

1

将最后 4 行更改为:

M=lambda p1, p2: mape(p2, p1)
result = minimize(M, coeff, (x,), method ="L-BFGS-B", bounds =bnds)

opt = result['x']
print("opt : ", result['x'])

它现在应该可以工作了,需要解释吗?我得到优化结果('opt : ', array([ 0.45330204, 0.26761714, 0. ]))

lambda函数颠倒了参数提供给 的顺序mape。当您试图找到coeff最小化mape()给定一个固定x的 时,目标函数应该取coeff第一个和x第二个,而mape.

对于您的评论问题:我以为您L-BFGS-B在代码中使用。此处解释了差异:http: //docs.scipy.org/doc/scipy/reference/tutorial/optimize.html#tutorial-sqlsp。我不得不承认我并没有SLSQP像很久以前在研究生院那样详细说明。BFGS更常见,每本教科书都有解释。L-BFGS-B支持有界约束最小化。SLSQP支持边界,以及等式和不等式约束。所以,SLSQP不能的时候可以发挥作用L-BFGS-B。见,http://scipy-lectures.github.io/advanced/mathematical_optimization/index.html ?utm_source=twitterfeed&utm_medium=twitter 。

于 2014-03-16T01:26:12.783 回答