我正在尝试使用scipy minimise优化函数以找到rev_tot
的最大值。这里的obj_data
是几率列表,prem
是一个常数,inc
可以取任何实际值。以下是我为目标函数编写的代码:
import numpy as np
import pandas as pd
import scipy
from scipy.optimize import minimize
def objective(x,*args):
prem = args[0]
prob = args[1]
inc = x[0]
rev_tot = 0
rev = 0
del_p = 0.2*(1-np.exp(-2*(1-np.exp(-inc/400))))
for i in range(len(prob)):
rev = (prob[i]*(1+del_p)*prem) - inc
rev_tot = rev_tot + rev
return 1/rev_tot
prem = 3300
par = [0.9,0.1,0.5,0.4]
x0 = np.array([3]) # initial guess
solve = minimize(objective,x0,args=(prem,par),method='SLSQP')
solve.x
我想找到一个inc
值,它将使1/rev_tot
最小化(从而使rev_tot
最大化。
当我打电话时:
minimize(objective,x0,args=(prem,par),method='SLSQP')
该函数运行,但是solve.x
的初始值没有变化。我无法弄清楚为什么没有发生最小化。
答案 0 :(得分:2)
您的问题是,由于您的return 1/rev_tot
,求解器必须处理很小的数字。因此,x轴上的变化不能很好地反映在y值的变化中,并且求解器估计它已经收敛:
import numpy as np
import pandas as pd
import scipy
from scipy.optimize import minimize
def objective(x,*args):
prem = args[0]
prob = args[1]
inc = x[0]
rev_tot = 0
rev = 0
del_p = 0.2*(1-np.exp(-2*(1-np.exp(-inc/400))))
for i in range(len(prob)):
rev = (prob[i]*(1+del_p)*prem) - inc
rev_tot = rev_tot + rev
return 1/rev_tot
prem = 3300
par = [0.9,0.1,0.5,0.4]
x0 = np.array([2]) # initial guess
solve = minimize(objective,x0,args=(prem,par),method='SLSQP')
x_min = solve.x
print(x_min)
#plot your function to visualize the outcome
x_func = np.linspace(1, 100, 1000)
y_func = []
for item in x_func:
y_func.append((objective(np.asarray([item]), prem, par)))
y_min = objective(np.asarray([x_min]), prem, par)
plt.plot(x_func, y_func)
plt.plot(x_min, y_min, "ro")
plt.show()
输出:
[2.]
解决方案1)
Different solvers manage certain problems better than others.将求解器更改为“ Nelder-Mead”。输出:
[63.07910156]
解决方案2)
使用return 1000000/rev_tot
扩展求解器“ SLSQP”的返回值。输出:
[63.07110511]