Example_2_6#
CVXPY “Hello world” program
!wget --no-cache -O init.py -q https://raw.githubusercontent.com/jdariasl/OTBD/main/content/init.py
import init; init.init(force_download=False)
from local.lib.Generation import scenarios_regression
from local.lib.utils import solver_cvx
import numpy as np
#!pip install cvxpy
import cvxpy as cp
# Loading scenarios
# ===========================
scenario=1;
data_reg, set_up=scenarios_regression(scenario);
# Definition of the problem
#===================================
loss_LS = lambda n, X, Y, w, lambd: (1/n)*cp.pnorm(X @ w - Y, p=2)**2
# Different ways to solve the LS
#=========================================
# Solution of the empirical risk using CVX
# Analytical solution
Xtrain = set_up['Xtrain'][:,:set_up['d']+1]
x_opt=np.linalg.inv(Xtrain.T@Xtrain)@Xtrain.T@set_up['ytrain'][:,0];
# Solution with cvx
x_cvx=solver_cvx(set_up,loss_LS);
# Verification
print(data_reg['Reg_opt'], x_cvx, x_opt)
[2 1] [2.02729816 0.95685858] [2.02729816 0.95685858]