我有矩阵,其中元素可以定义为算术表达式,并编写了Python代码来优化这些表达式中的参数,以便最小化矩阵的特定特征值。我已经使用了scipy来完成这个任务,但是我想知道是否可以使用NLopt,因为我想尝试更多的算法,它有(无导数的变体)。
在scipy中,我会这样做:
import numpy as np
from scipy.linalg import eig
from scipy.optimize import minimize
def my_func(x):
y, w = x
arr = np.array([[y+w,-2],[-2,w-2*(w+y)]])
ev, ew=eig(arr)
return ev[0]
x0 = np.array([10, 3.45]) # Initial guess
minimize(my_func, x0)在NLopt中,我尝试过这样做:
import numpy as np
from scipy.linalg import eig
import nlopt
def my_func(x,grad):
arr = np.array([[x[0]+x[1],-2],[-2,x[1]-2*(x[1]+x[0])]])
ev, ew=eig(arr)
return ev[0]
opt = nlopt.opt(nlopt.LN_BOBYQA, 2)
opt.set_lower_bounds([1.0,1.0])
opt.set_min_objective(my_func)
opt.set_xtol_rel(1e-7)
x = opt.optimize([10.0, 3.5])
minf = opt.last_optimum_value()
print "optimum at ", x[0],x[1]
print "minimum value = ", minf
print "result code = ", opt.last_optimize_result()这将返回:
ValueError: nlopt invalid argumentNLopt能够处理这个问题吗?
发布于 2018-02-07 13:53:02
my_func应返回double,张贴示例返回复杂
print(type(ev[0]))
None
<class 'numpy.complex128'>
ev[0]
(13.607794065928395+0j)My_func的正确版本:
def my_func(x, grad):
arr = np.array([[x[0]+x[1],-2],[-2,x[1]-2*(x[1]+x[0])]])
ev, ew=eig(arr)
return ev[0].real更新的样本返回:
optimum at [ 1. 1.]
minimum value = 2.7015621187164243
result code = 4https://stackoverflow.com/questions/45630286
复制相似问题