Skip to content

Different solutions for cvxpy and cvxpylayers #149

Open
@ManuelP96

Description

@ManuelP96

I have a little example of a cvxpy problem

import numpy as np
import cvxpy as cp
import tensorflow as tf
from   cvxpylayers.tensorflow import CvxpyLayer

b=np.ones(6)/6
vol = np.array([0.2, 0.2, 0.15, 0.15, 0.1, 0.1])
rho   = np.array([[   1,  0.7,  0.8,  0.3, -0.2,  0.4],
                  [ 0.7,    1,  0.5,  0.2, -0.1,  0.1], 
                  [ 0.8,  0.5,    1,  0.3, -0.1, 0.1], 
                  [ 0.3,  0.2,  0.3,    1, -0.2,  0.2],
                  [-0.2, -0.1, -0.1, -0.2,    1,    0], 
                  [ 0.4,  0.1,  0.1,  0.2,    0,    1]])
Sigma = np.matmul(np.diag(vol), np.matmul(rho, np.diag(vol)))

btf = tf.Variable(b)
Sigmatf = tf.Variable(Sigma)

w = cp.Variable(6) 

obj = 0.5 * cp.quad_form(w, Sigma) - cp.sum(cp.multiply(b, cp.log(w)))
constr = [w>=0] 
prob = cp.Problem(cp.Minimize(obj), constr)

prob.solve()
w = w/cp.sum(w)

print("Portfolio weights\t", w.value)

but, when I replicate the problem into a cvxpylayer, I get different results. In fact, it seems like the cvxpylayer returns the parameter values:

n,_ = Sigmatf.get_shape()

w = cp.Variable(n)
risk = cp.Parameter(n, nonneg = True)
obj = 0.5 * cp.quad_form(w, Sigma) - risk.T @ cp.log(w)
constr = [w>=0]
prob = cp.Problem(cp.Minimize(obj), constr)
cvxpylayer = CvxpyLayer(prob, parameters=[risk], variables=[w])

b1 = tf.reshape(btf,[6])

with tf.GradientTape() as tape:
    solution,  = cvxpylayer(b1)

solution = solution/tf.reduce_sum(solution)
print(solution.numpy())

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions