我有一个简单的等式,我通过
绘制def chernoff_bound(beta):
return 0.5 * np.exp(-beta * (1-beta))
betas = np.arange(0, 1, 0.01)
c_bound = chernoff_bound(betas)
plt.plot(betas, c_bound)
plt.title('Chernoff Bound')
plt.ylabel('P(error)')
plt.xlabel('parameter beta')
plt.show()
现在,我想找到P(误差)最小的值。
我尝试通过scipy.optimize.minimize()
函数来实现(老实说,我之前没有使用它,这里可能有一些想法错误......)
from scipy.optimize import minimize
x0 = [0.1,0.2,0.4,0.5,0.9]
fun = lambda x: 0.5 * np.exp(-x * (1-x))
res = minimize(fun, x0, method='Nelder-Mead')
我得到的错误是:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-25-2b04597c4341> in <module>()
3 x0 = [0.1,0.2,0.4,0.5,0.9]
4 fun = lambda x: 0.5 * np.exp(-x * (1-x))
----> 5 res = minimize(fun, x0, method='Nelder-Mead')
6 print(res)
/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/scipy/optimize/_minimize.py in minimize(fun, x0, args, method, jac, hess, hessp, bounds, constraints, tol, callback, options)
364
365 if meth == 'nelder-mead':
--> 366 return _minimize_neldermead(fun, x0, args, callback, **options)
367 elif meth == 'powell':
368 return _minimize_powell(fun, x0, args, callback, **options)
/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/scipy/optimize/optimize.py in _minimize_neldermead(func, x0, args, callback, xtol, ftol, maxiter, maxfev, disp, return_all, **unknown_options)
436 if retall:
437 allvecs = [sim[0]]
--> 438 fsim[0] = func(x0)
439 nonzdelt = 0.05
440 zdelt = 0.00025
ValueError: setting an array element with a sequence.
如果有人能指出我在正确的轨道上,我将非常感激!
答案 0 :(得分:1)
optimize.minimize
的第二个参数是一个初始猜测 - 您希望x
找到的最小optimize.minimize
- 值。所以,例如,
import numpy as np
from scipy import optimize
x0 = 0.1
fun = lambda x: 0.5 * np.exp(-x * (1-x))
res = optimize.minimize(fun, x0, method='Nelder-Mead')
print(res)
产量
status: 0
nfev: 36
success: True
fun: 0.38940039153570244
x: array([ 0.5])
message: 'Optimization terminated successfully.'
nit: 18
x0
不一定总是标量。它可以是一个数组 - 它取决于fun
。在上面的示例中,x0 = np.array([0.1])
也可以。关键在于,无论您猜测什么,fun(x0)
都应该是标量。