Python 优化。使用CG最小化
我一直在使用以下代码:Python 优化。使用CG最小化,python,python-3.x,scipy,scipy-optimize-minimize,Python,Python 3.x,Scipy,Scipy Optimize Minimize,我一直在使用以下代码: options = {'maxiter':50, 'disp':True} res = optimize.minimize( fun=lrCostFunction, x0=theta_k, args=(X, y_k, lambda_), method='CG', options=options ) 这给了我以下的错误: TypeError: only size-1 arrays ca
options = {'maxiter':50, 'disp':True}
res = optimize.minimize(
fun=lrCostFunction,
x0=theta_k,
args=(X, y_k, lambda_),
method='CG',
options=options
)
这给了我以下的错误:
TypeError: only size-1 arrays can be converted to Python scalars
The above exception was the direct cause of the following exception:
ValueError: setting an array element with a sequence.
但是当我设置jac=True
如下:
options = {'maxiter':50, 'disp':True}
res = optimize.minimize(
fun=lrCostFunction,
x0=theta_k,
jac=True,
args=(X, y_k, lambda_),
method='CG',
options=options
)
一切正常,但文档中没有说明必须设置
jac=True
,所以这里有什么问题?我猜目标函数lrCostFunction
同时返回函数值和梯度。根据minimize
如果jac
是一个布尔值且为真,则假定fun
与目标函数一起返回梯度。如果为假,将使用“2点”有限差分估计来估计梯度
因此,如果当目标函数也返回梯度时jac=False
,您将收到一些错误。比如说
# objective function
def obj_func(x,a,b,c):
func_val = a*x[0]**2 + b*x[1] + c
func_grad = 2*a*x[0] + b
return func_val,func_grad
x0 = np.random.rand(3)
res = minimize(obj_func,x0,args=(1,2,3),method='CG')
如果我运行此代码,我将收到一个TypeError
。如果我设置了jac=True
,一切正常