Минимизация функции с LinearConstraint
Решаю задачу поиска минимума функции с помощью scipy.optimize.LinearConstraint. Вот пример кода:
import numpy as np
from scipy.optimize import LinearConstraint, minimize
m = 35
n = 20
np.random.seed(1)
s0 = np.random.randn(m)
lamb0 = np.maximum(-s0, 0)
s0 = np.maximum(s0, 0)
x0 = np.random.randn(n)
A = np.random.randn(m, n)
b = A@x0 + s0
c = -A.T@lamb0
linear_constraint = LinearConstraint (A, [-np.inf], b)
def f_2(x):
return np.dot(np.transpose(c), x)
x = np.ones(n)
minimize(f_2, x0=x, constraints=linear_constraint)
Не могу понять с чем связана ошибка:
IndexError Traceback (most recent call last)
<ipython-input-37-51d74c49b301> in <module>()
1 x = np.ones(n)
----> 2 minimize(f_2, x0=x, constraints=linear_constraint)
3 frames
/usr/local/lib/python3.6/dist-packages/scipy/optimize/_constraints.py in __init__(self, constraint, x0, sparse_jacobian, finite_diff_bounds)
242 mask = keep_feasible & (lb != ub)
243 f0 = fun.f
--> 244 if np.any(f0[mask] < lb[mask]) or np.any(f0[mask] > ub[mask]):
245 raise ValueError("`x0` is infeasible with respect to some "
246 "inequality constraint with `keep_feasible` "
IndexError: boolean index did not match indexed array along dimension 0; dimension is 1 but corresponding boolean dimension is 15
Буду признателен за помощь!
Ответы (1 шт):
Автор решения: Scouser57
→ Ссылка
Проблема была в этой строчке linear_constraint = LinearConstraint (A, [-np.inf], b). Вместо [-np.inf] нужно было указать ограничение в виде вектора нужного размера
ogr1 = np.full(m, -np.inf)
linear_constraint = LinearConstraint (A, ogr1, b)