[Python] Error while running constraints optimization using cvxpy

Discussão em 'Python' iniciado por Stack, Maio 26, 2025.

  1. Stack

    Stack Membro Participativo

    I faced some issues when doing constrainted optmiziation. Use CVXPY Variables in Optimization: I'll set the unknown values (NaNs) to be part of the CVXPY optimization variable.

    import cvxpy as cp
    import numpy as np

    def optimize_x_simple(A, x_values):
    # Convert the list to a numpy array
    x_values = np.array(x_values, dtype=float)

    # Identify which entries are NaN (unknown)
    known_mask = np.isnan(x_values)

    # Set up CVXPY variables for the unknowns
    x_unknown = cp.Variable(np.sum(known_mask), nonneg=True) # only unknown values are optimized

    # Replace known values (non-NaN) in x with their values
    x_full = np.copy(x_values)

    # The indices of the unknown values
    unknown_indices = np.where(known_mask)[0]

    # Construct the full vector with CVXPY variables for unknowns
    for idx, unknown_idx in enumerate(unknown_indices):
    x_full[unknown_idx] = x_unknown[idx]

    # Compute b = A @ x, where x is the full vector
    b = A @ x_full

    # Define the constraints: 1.0 <= b_i <= 2.0 for each entry in b
    constraints = [b >= 1.0, b <= 2.0]

    # Define the objective function: minimize the sum of unknown values (just an example)
    objective = cp.Minimize(cp.sum(x_unknown))

    # Create the optimization problem
    problem = cp.Problem(objective, constraints)

    # Solve the optimization problem
    problem.solve()

    if problem.status != cp.OPTIMAL:
    raise ValueError(f"Optimization failed: {problem.status}")

    # Replace optimized values back into the result
    x_optimized = np.copy(x_full)
    for idx, unknown_idx in enumerate(unknown_indices):
    x_optimized[unknown_idx] = x_unknown.value[idx]

    return x_optimized, b.value


    # Example usage:
    A = np.random.randn(5895, 393) # Replace with your actual A matrix
    x_example = [0.1, 0.2, np.nan, 0.1, 0.0] # Example input with NaN for unknowns

    # Call the optimization function
    x_optimized, b_vector = optimize_x_simple(A, x_example)

    # Print the optimized x and resulting b
    print("Optimized x:", x_optimized)
    print("Result b:", b_vector)


    # Construct the full vector with CVXPY variables for unknowns
    for idx, unknown_idx in enumerate(unknown_indices):
    x_full[unknown_idx] = x_unknown[idx]

    ValueError: setting an array element with a sequence.


    How do I solve the above error?

    Continue reading...

Compartilhe esta Página