Search code examples
pythonoptimizationminimizecvxpyconvex-optimization

ValueError: setting an array element with a sequence in CVXPY minimize function


I tried to solve a convex problem with cvxpy as below.

        import cvxpy as cp
        import numpy as np

        # Problem data.
        Q = np.array([[13, 12, -2], [12, 17, 6], [-2, 6, 12]])
        q = np.array([[-22, -14.5, 13]])
        r = 1

        # Construct the problem.
        x = cp.Variable((3,1))
        objective = cp.Minimize(np.dot(np.dot(x.T, Q), x) + np.dot(q, x) + r)

        constraints = [0 <= x[0:], x[0:] <= 1]
        prob = cp.Problem(objective, constraints)

        # The optimal objective value is returned by `prob.solve()`.
        result = prob.solve()
        # The optimal value for x is stored in `x.value`.
        print(x.value)
        # The optimal Lagrange multiplier for a constraint is stored in
        # `constraint.dual_value`.
        print(constraints[0].dual_value)

However, I get this error:

        ValueError: setting an array element with a sequence.

I don't know why this error occurs because everything else seems to work.

Edit: Please let me know if the problem statement is needed.


Solution

  • See comments above:

    import cvxpy as cp
    import numpy as np
    
    # Problem data.
    Q = np.array([[13, 12, -2], [12, 17, 6], [-2, 6, 12]])
    q = np.array([[-22, -14.5, 13]])
    r = 1
    
    # Construct the problem.
    x = cp.Variable((3,1))
    
    # WE CAN'T USE NUMPY'S DOT
    # ALSO: WE WANT TO EXPRESS AS MUCH STRUCTURE AS POSSIBLE -> cp.quad_form()!
    # q*x is cvxpy-compatible expression -> quite algebraic compared to numpy
    # -------------------------------------------------------------------------
    objective = cp.Minimize(cp.quad_form(x, Q) + q*x + r)
    
    # ORIGINAL SLICING IS A NO-OP
    # ---------------------------
    constraints = [0 <= x, x <= 1]
    
    prob = cp.Problem(objective, constraints)
    
            # The optimal objective value is returned by `prob.solve()`.
    result = prob.solve()
            # The optimal value for x is stored in `x.value`.
    print(x.value)
            # The optimal Lagrange multiplier for a constraint is stored in
            # `constraint.dual_value`.
    print(constraints[0].dual_value)
    

    Output:

    [[ 8.46153846e-01]
    [-6.34467676e-25]
    [-1.92032635e-25]]
    [[0.        ]
    [5.80769231]
    [9.61538462]]