我正在为另一个项目测试scipy.optimize
,并在设置最小化使用SLSQP方法的初始条件时发现了一些异常行为。我假设这是因为顺序最小二乘算法在临界点(start_pos1
)初始化时立即返回而不检查二阶导数条件。我仔细查看了文档并没有看到任何内容 - 有人能说出发生了什么吗?
from scipy import optimize
import numpy as np
def simplex(x):
return 1 - sum(x)
def sphere_min(x):
return sum(x[i]**2 for i in range(len(x)))**.5
def sphere_max(x):
return -sphere_min(x)
if __name__ == "__main__":
dimensions = 3
start_pos1 = np.ones(dimensions) * 1.0/dimensions
start_pos2 = [2*float(i+1)/(dimensions*(dimensions+1)) for i in range(dimensions)]
raw_start_pos = np.random.uniform(0, 1, dimensions)
start_pos3 = raw_start_pos/raw_start_pos.sum()
bnds = tuple((0, 1) for i in range(dimensions))
cons = ({'type': 'eq', 'fun': simplex})
for start_pos in (start_pos1, start_pos2, start_pos3):
print 'Start Position: {}'.format(start_pos)
res = optimize.minimize(sphere_min, start_pos, method='SLSQP', bounds=bnds, constraints=cons)
print 'Min: x = {}, value = {}'.format(res.x, res.fun)
res = optimize.minimize(sphere_max, start_pos, method='SLSQP', bounds=bnds, constraints=cons)
print 'Max: x = {}, value = {}'.format(res.x, -res.fun)
print '\n==============\n'