本文介绍了为什么我从scipy.optimize.fmin得到不正确的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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
为什么我会得到r = -69,-70和-71?根据这些数据,我应该得到r = 0.333、0.555和0.999.
Why am I getting r = -69, -70, and -71?I should be getting r = 0.333, 0.555, and 0.999 with this data.
推荐答案
scipy.optimize.fmin
会将尝试最小化的值作为函数的第一个参数传递.如果您将函数重写为
scipy.optimize.fmin
will pass the value it is trying to minimize as the first argument to the function. If you rewrite your function as
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得到不正确的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!