I have two vectors w1
and w2
(each of length 100), and I want to minimize the sum of their absolute difference i.e.
import numpy as np
def diff(w: np.ndarray) -> float:
"""Get the sum of absolute differences in the vector w.
Args:
w: A flattened vector of length 200, with the first 100 elements
pertaining to w1, and the last 100 elements pertaining to w2.
Returns:
sum of absolute differences.
"""
return np.sum(np.absolute(w[:100] - w[-100:]))
I need to write diff()
as only taking one argument since scipy.opyimize.minimize
requires the array passed to the x0
argument to be 1 dimensional.
As for constraints, I have
w1
is fixed and not allowed to changew2
is allowed to change- The sum of absolute values
w2
is between 0.1 and 1.1:0.1 <= sum(abs(w2)) <= 1.1
|w2_i| < 0.01
for any elementi
inw2
I am confused as to how we code these constraints using the Bounds
and LinearConstraints
objects. What I've tried so far is the following
from scipy.optimize import minimize, Bounds, LinearConstraint
bounds = Bounds(lb=[-0.01] * 200, ub=[0.01] * 200) # constraint #4
lc = LinearConstraint([[1] * 200], [0.1], [1.1]) # constraint #3
res = minimize(
fun=diff,
method='trust-constr',
x0=w, # my flattened vector containing w1 first 100 elements, and w2 in last 100 elements
bounds=bounds,
constraints=(lc)
)
My logic for the bounds
variable is from constrain #4, and for the lc
variable comes from constrain #3. However I know I've coded this wrong because because the lower and upper bounds are of length 200 which seems to indicate they are applied to both w1
and w2
whereas I only wan't to apply the constrains to w2
(I get an error ValueError: operands could not be broadcast together with shapes (200,) (100,)
if I try to change the length of the array in Bounds
from 200 to 100).
The shapes and argument types for LinearConstraint
are especially confusing to me, but I did try to follow the scipy example.
This current implementation never seems to finish, it just hangs forever.
How do I properly implement bounds
and LinearConstraint
so that it satisfies my constraints list above, if that is even possible?