Python:如何使用lambda函数创建许多fmin_cobyla优化的约束 [英] Python: how to create many constraints for fmin_cobyla optimization using lambda functions

查看:201
本文介绍了Python:如何使用lambda函数创建许多fmin_cobyla优化的约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个几百个数字条目的向量(像这样:Xo = [x1,y1,x2,y2,...,xN,yN])其中N是任意数。我需要传递这个向量到scipy fmin_cobyla优化器,每个条目简单的约束:
1.所有的x(即x1,x2,...,xN)是这样的-1

我试着使用lambda函数来指定这样的约束。

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

但是我完全不知道如何传递正确的索引n。我想要所有的偶数n受b0和b1,但所有奇数n受b2和b3

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


$ b b

我可能需要在fmin_cobyla中使用consargs。任何帮助将非常感激。

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

推荐答案

这些约束需要是连续的吗?如果没有,这里有一个简单的方法来做一个函数。如果满足约束,它将返回1,如果不满足则返回-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,)

如果你需要连续的约束,有很多方法可以做到。这里是一个有2N个线性函数,N为正约束,N为负约束。

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)]

这篇关于Python:如何使用lambda函数创建许多fmin_cobyla优化的约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆