众所周知,Nelder-Mead Simplex Method(由上述 cmets 中的 Cristián Antuña 建议)是优化(可能表现不佳)函数的好选择(请参阅Numerical Recipies In C, Chapter 10)。
您的问题有两个具体方面。第一个是对输入的约束,第二个是缩放问题。以下建议解决这些问题,但您可能需要在它们之间手动迭代几次,直到一切正常。
输入约束
假设您的输入约束形成convex region(如您上面的示例所示,但我想概括一下),那么您可以编写一个函数
is_in_bounds(p):
# Return if p is in the bounds
使用此函数,假设算法要从点 from_ 移动到点 to,其中已知 from_ 在该区域中。然后下面的函数将有效地找到它可以继续的两点之间的直线上的最远点:
from numpy.linalg import norm
def progress_within_bounds(from_, to, eps):
"""
from_ -- source (in region)
to -- target point
eps -- Eucliedan precision along the line
"""
if norm(from_, to) < eps:
return from_
mid = (from_ + to) / 2
if is_in_bounds(mid):
return progress_within_bounds(mid, to, eps)
return progress_within_bounds(from_, mid, eps)
(请注意,此函数可以针对某些区域进行优化,但几乎不值得费心,因为它甚至不调用您的原始对象函数,这是昂贵的。)
Nelder-Mead 的优点之一是该函数执行一系列非常直观的步骤。其中一些点显然会让你离开这个区域,但很容易修改它。这是一个implementation of Nelder Mead,在################################################################## 形式的两行之间标记了修改:
import copy
'''
Pure Python/Numpy implementation of the Nelder-Mead algorithm.
Reference: https://en.wikipedia.org/wiki/Nelder%E2%80%93Mead_method
'''
def nelder_mead(f, x_start,
step=0.1, no_improve_thr=10e-6, no_improv_break=10, max_iter=0,
alpha = 1., gamma = 2., rho = -0.5, sigma = 0.5):
'''
@param f (function): function to optimize, must return a scalar score
and operate over a numpy array of the same dimensions as x_start
@param x_start (numpy array): initial position
@param step (float): look-around radius in initial step
@no_improv_thr, no_improv_break (float, int): break after no_improv_break iterations with
an improvement lower than no_improv_thr
@max_iter (int): always break after this number of iterations.
Set it to 0 to loop indefinitely.
@alpha, gamma, rho, sigma (floats): parameters of the algorithm
(see Wikipedia page for reference)
'''
# init
dim = len(x_start)
prev_best = f(x_start)
no_improv = 0
res = [[x_start, prev_best]]
for i in range(dim):
x = copy.copy(x_start)
x[i] = x[i] + step
score = f(x)
res.append([x, score])
# simplex iter
iters = 0
while 1:
# order
res.sort(key = lambda x: x[1])
best = res[0][1]
# break after max_iter
if max_iter and iters >= max_iter:
return res[0]
iters += 1
# break after no_improv_break iterations with no improvement
print '...best so far:', best
if best < prev_best - no_improve_thr:
no_improv = 0
prev_best = best
else:
no_improv += 1
if no_improv >= no_improv_break:
return res[0]
# centroid
x0 = [0.] * dim
for tup in res[:-1]:
for i, c in enumerate(tup[0]):
x0[i] += c / (len(res)-1)
# reflection
xr = x0 + alpha*(x0 - res[-1][0])
##################################################################
##################################################################
xr = progress_within_bounds(x0, x0 + alpha*(x0 - res[-1][0]), prog_eps)
##################################################################
##################################################################
rscore = f(xr)
if res[0][1] <= rscore < res[-2][1]:
del res[-1]
res.append([xr, rscore])
continue
# expansion
if rscore < res[0][1]:
xe = x0 + gamma*(x0 - res[-1][0])
##################################################################
##################################################################
xe = progress_within_bounds(x0, x0 + gamma*(x0 - res[-1][0]), prog_eps)
##################################################################
##################################################################
escore = f(xe)
if escore < rscore:
del res[-1]
res.append([xe, escore])
continue
else:
del res[-1]
res.append([xr, rscore])
continue
# contraction
xc = x0 + rho*(x0 - res[-1][0])
##################################################################
##################################################################
xc = progress_within_bounds(x0, x0 + rho*(x0 - res[-1][0]), prog_eps)
##################################################################
##################################################################
cscore = f(xc)
if cscore < res[-1][1]:
del res[-1]
res.append([xc, cscore])
continue
# reduction
x1 = res[0][0]
nres = []
for tup in res:
redx = x1 + sigma*(tup[0] - x1)
score = f(redx)
nres.append([redx, score])
res = nres
注意这个实现是GPL,这对你来说是否合适。不过,从任何伪代码修改 NM 都非常容易,无论如何您都可能想输入simulated annealing。
缩放
这是一个更棘手的问题,但jasaarim 对此提出了一个有趣的观点。一旦修改后的 NM 算法找到了一个点,您可能希望在修复几个维度的同时运行 matplotlib.contour,以查看函数的行为方式。此时,您可能需要重新调整一个或多个维度,并重新运行修改后的 NM。
——