Jam*_*ood 5 python numpy machine-learning mathematical-optimization scipy
我正在使用scipy.optimize.minimize
COBYLA方法来查找分类分布的参数矩阵.我需要强加每个参数大于零的约束,并且参数矩阵的行总和是一列1.
我不清楚如何实现这一点scipy.minimize
,因为检查约束是非负性而非真理.如果我只是将数组作为约束传递,则最小化会引发异常.
有谁知道如何实施这些约束?
第一个约束x > 0
可以非常简单地表达:
{'type':'ineq', 'fun': lambda x: x}
Run Code Online (Sandbox Code Playgroud)
第二个约束是一个等式约束,COBYLA本身不支持.但是,您可以将其表示为两个单独的不等式约束:
{'type':'ineq', 'fun': lambda x: np.sum(x, 0) - 1} # row sum >= 1
{'type':'ineq', 'fun': lambda x: 1 - np.sum(x, 0)} # row sum <= 1
Run Code Online (Sandbox Code Playgroud)
否则,您可以尝试使用SLSQP,它确实支持相等约束.
您需要对强制执行np.sum(x, 1) == 1
和不等式约束的等式约束x >= 0
.
但是,COBYLA方法只能处理不等式约束,如文档中所述minimize
(参见解释该constraints
参数的部分).相反,您可以使用Sequential Least SQuares Programming(SLSQP),它支持两种类型的约束.该minimize
函数应根据您指定的约束自动为您选择正确的求解器.
您需要的约束可以像这样实现:
def ineq_constraint(x):
"""constrain all elements of x to be >= 0"""
return x
def eq_constraint(x):
"""constrain the sum of all rows to be equal to 1"""
return np.sum(x, 1) - 1
constraints = [{'type': 'ineq', 'fun': ineq_constraint},
{'type': 'eq', 'fun': eq_constraint}]
result = minimize(objective_function, x0, constraints=constraints)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4444 次 |
最近记录: |