为啥我从 scipy.optimize.fmin 得到不正确的结果?
Posted
技术标签:
【中文标题】为啥我从 scipy.optimize.fmin 得到不正确的结果?【英文标题】:Why am I getting incorrect results from scipy.optimize.fmin?为什么我从 scipy.optimize.fmin 得到不正确的结果? 【发布时间】:2016-11-04 06:33:39 【问题描述】:import pandas as pd
from scipy.optimize import fmin
data = pd.DataFrame('DIV': [1,2,3]*3,
'MONTH': ['May','May','May','June','June','Jun','Jul','Jul','Jul'],
'C':[8]*9,
'U':[3,2,1]*3,
'S':[9]*9)
data.to_csv(r'C:\Users\mbabski\Documents\Unit Plan Summer 2016\data_test.csv')
def return_array(x):
return x.values
def mape(c,u,s,r): #returns an array of line level Mean Absolute Percentage Errors
p = c + u * r
m = abs(1.0-(p/s))
return m
def e(c,u,s,r): #calculates average of the MAPEs
return np.mean(mape(c,u,s,r))
for d in range(1,4):
div_data = data[data.DIV==d]
c = return_array(div_data.C)
u = return_array(div_data.U)
s = return_array(div_data.S)
r0 = [[1.0]]
t = fmin(e,r0,args=(c,u,s))
print 'r:',t
优化成功终止。 当前函数值:0.000000 迭代次数:29 函数评估:58 r:[-69.] 优化成功终止。 当前函数值:0.000000 迭代次数:29 函数评估:58 r:[-70.] 优化成功终止。 当前函数值:0.000000 迭代次数:29 函数评估:58 r:[-71.]
为什么我得到 r = -69、-70 和 -71? 我应该用这些数据得到 r = 0.333、0.555 和 0.999。
【问题讨论】:
【参考方案1】:scipy.optimize.fmin
会将它试图最小化的值作为第一个参数传递给函数。如果您将函数重写为
def e(r,c,u,s): #calculates average of the MAPEs
return np.mean(mape(c,u,s,r))
你得到正确的结果
for d in range(1,4):
div_data = data[data.DIV==d]
c = return_array(div_data.C)
u = return_array(div_data.U)
s = return_array(div_data.S)
r0 = [[1.0]]
t = fmin(e,r0,args=(c,u,s))
print 'r:',t
Optimization terminated successfully. Current function value: 0.000011 Iterations: 16 Function evaluations: 32 r: [ 0.33330078] Optimization terminated successfully. Current function value: 0.000000 Iterations: 15 Function evaluations: 30 r: [ 0.5] Optimization terminated successfully. Current function value: 0.000000 Iterations: 10 Function evaluations: 20 r: [ 1.]
【讨论】:
以上是关于为啥我从 scipy.optimize.fmin 得到不正确的结果?的主要内容,如果未能解决你的问题,请参考以下文章
Scipy优化算法--scipy.optimize.fmin_tnc()/minimize()