我已经读过整数编程要么非常棘手,要么用SciPy不可能 ,我可能需要使用像zibopt这样的东西来用Python做.但我真的认为我可以通过为SciPy优化的向量中的每个元素创建一个"is binary"约束来实现.
为此,我利用http://docs.python-guide.org/en/latest/writing/gotchas/#late-binding-closures中的闭包技巧, 为每个元素创建了一个约束函数,如下所示:
def get_binary_constraints(vector, indices_to_make_binary=None):
indices_to_make_binary = indices_to_make_binary or range(len(vector))
for i in indices_to_make_binary:
def ith_element_is_binary(vector, index=i):
return vector[index] == 0 or vector[index] == 1
yield ith_element_is_binary
test_vector = scipy.array([0.5, 1, 3])
constraints = list(get_binary_constraints(test_vector))
for constraint in constraints:
print constraint(test_vector)
Run Code Online (Sandbox Code Playgroud)
打印:
False
True
False
Run Code Online (Sandbox Code Playgroud)
然后我为fmin_cobyla修改了get_binary_constraints,其约束是"所有必须> = 0的函数序列".
def get_binary_constraints(vector, indices_to_make_binary=None):
indices_to_make_binary = indices_to_make_binary or range(len(vector))
for i in indices_to_make_binary:
def ith_element_is_binary(vector, index=i):
return int(vector[index] == 0 or vector[index] == 1) - 1 …Run Code Online (Sandbox Code Playgroud)