Skip to content

Instantly share code, notes, and snippets.

@theXYZT
Created September 30, 2021 16:23
Show Gist options
  • Save theXYZT/30379eb2ebbd83a33fe877864c067c92 to your computer and use it in GitHub Desktop.
Save theXYZT/30379eb2ebbd83a33fe877864c067c92 to your computer and use it in GitHub Desktop.
CVXPY Test
import numpy as np
import cvxpy as cp
import time
RAND = np.random.default_rng(seed=42)
def random_matrix(shape, dtype=np.complex128):
M = RAND.random(shape) + 1j * RAND.random(shape)
return M.astype(dtype)
A = random_matrix((1000, 100))
y = random_matrix(A.shape[0])
x = cp.Variable(A.shape[1], complex=True)
# RSS if x = 0
rss_max = np.sum(y.real**2 + y.imag**2)
# RSS minimized
rss_min = np.linalg.lstsq(A, y, rcond=None)[1][0]
# Pick RSS in between for L2 regularization
a = 0.1
rss_mid = a * rss_max + (1 - a) * rss_min
prob = cp.Problem(cp.Minimize(cp.pnorm(x, p=2)),
constraints=[cp.pnorm(y - A@x, p=2)**2 <= rss_mid])
print(f"Problem Size: {A.shape}")
print(f"RSS range = [{rss_min:.4f}, {rss_max:.4f}]")
print(f"RSS constraint: {rss_mid:.4f}")
t0 = time.time()
prob.solve(solver='ECOS', verbose=False)
print(f"\nSolving took {time.time() - t0:.4f}s!")
print(f"Achieved RSS: {np.sum(np.abs(A @ x.value - y)**2)}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment