Python: how to create many constraints for fmin_cobyla optimization using lambda functions

拈花ヽ惹草 提交于 2019-12-08 03:20:39

问题


I have a vector of a few hundred numerical entries (like this: Xo = [x1, y1, x2, y2,..., xN, yN]) where N is an arbitrary number. I need to pass this vector to the scipy fmin_cobyla optimizer with simple simple constraints on each of the entries: 1. All of the x's (ie. x1, x2, ..., xN) are such that -1

I've tried to use lambda functions to specify the constraints like this

b0 = lambda Xo: 1 - Xo[n]
b1 = lambda Xo: Xo[n] + 1

however I am completely unsure of how to pass in the proper index n. I want all the even n to be subject to b0 and b1 but all the odd n to be subject to b2 and b3

b2 = lambda Xo: 2 - Xo[n]
b3 = lambda Xo: Xo[n] + 2

I may need to use consargs in fmin_cobyla. Any help would be much appreciated.


回答1:


Do the constraints need to be continuous? If not, here's a simple way to do it with one function. It will return 1 if the constraints are met, and -1 if they're not:

def checkall(xs):
    for j, x in enumerate(xs):
        if abs(x) > (2 if j % 2 else 1):
            return -1
    return 1
cons = (checkall,)

If you need continuous constraints, there are many ways to do it. Here's one with 2N linear functions, N for the positive constraint, and N for the negative constraints.

def checkpos(j):
    if j % 2:
        return lambda xs: 2 - xs[j]
    else:
        return lambda xs: 1 - xs[j]
def checkneg(j):
    if j % 2:
        return lambda xs: 2 + xs[j]
    else:
        return lambda xs: 1 + xs[j]

cons = [checkpos(j) for j in range(N)] + [checkneg(j) for j in range(N)]



回答2:


try this

even = lambda x: (x < 1 and x > -1)
odd = lambda x: (x < 2 and x > -2)
constraint = lambda index: (index % 2) and odd or even
filtered = [x for index, x in enumerate(Xo) if constraint(index)(x)]

Honestly, I have no idea what fmin_cobyla, but this is another try after reading David's comment

even = lambda n: ((lambda x: 1 - x[n]), (lambda x: x[n] + 1))
odd = lambda n: ((lambda x: 2 - x[n]), (lambda x: 2 - x[n]))
constraint = lambda n: (n % 2) and odd(n) or even(n)
constraint_list = sum([constraint(i) for i in range(2 * N)], ())


来源:https://stackoverflow.com/questions/6536161/python-how-to-create-many-constraints-for-fmin-cobyla-optimization-using-lambda

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!