本文整理汇总了Python中cvxpy.Problem方法的典型用法代码示例。如果您正苦于以下问题:Python cvxpy.Problem方法的具体用法?Python cvxpy.Problem怎么用?Python cvxpy.Problem使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类cvxpy
的用法示例。
在下文中一共展示了cvxpy.Problem方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: sys_norm_h2_LMI
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import Problem [as 别名]
def sys_norm_h2_LMI(Acl, Bdisturbance, C):
#doesn't work very well, if problem poorly scaled Riccati works better.
#Dullerud p 210
n = Acl.shape[0]
X = cvxpy.Semidef(n)
Y = cvxpy.Semidef(n)
constraints = [ Acl*X + X*Acl.T + Bdisturbance*Bdisturbance.T == -Y,
]
obj = cvxpy.Minimize(cvxpy.trace(Y))
prob = cvxpy.Problem(obj, constraints)
prob.solve()
eps = 1e-16
if np.max(np.linalg.eigvals((-Acl*X - X*Acl.T - Bdisturbance*Bdisturbance.T).value)) > -eps:
print('Acl*X + X*Acl.T +Bdisturbance*Bdisturbance.T is not neg def.')
return np.Inf
if np.min(np.linalg.eigvals(X.value)) < eps:
print('X is not pos def.')
return np.Inf
return np.sqrt(np.trace(C*X.value*C.T))
示例2: polish
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import Problem [as 别名]
def polish(orig_prob, polish_depth=5, polish_func=None, *args, **kwargs):
# Fix noncvx variables and solve.
for var in get_noncvx_vars(orig_prob):
var.value = var.z.value
old_val = None
for t in range(polish_depth):
fix_constr = []
for var in get_noncvx_vars(orig_prob):
fix_constr += var.restrict(var.value)
polish_prob = cvx.Problem(orig_prob.objective, orig_prob.constraints + fix_constr)
polish_prob.solve(*args, **kwargs)
if polish_prob.status in [cvx.OPTIMAL, cvx.OPTIMAL_INACCURATE] and \
(old_val is None or (old_val - polish_prob.value)/(old_val + 1) > 1e-3):
old_val = polish_prob.value
else:
break
return polish_prob.value, polish_prob.status
# Add admm method to cvx Problem.
示例3: solve
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import Problem [as 别名]
def solve(self, X, missing_mask):
X = check_array(X, force_all_finite=False)
m, n = X.shape
S, objective = self._create_objective(m, n)
constraints = self._constraints(
X=X,
missing_mask=missing_mask,
S=S,
error_tolerance=self.error_tolerance)
problem = cvxpy.Problem(objective, constraints)
problem.solve(
verbose=self.verbose,
solver=cvxpy.SCS,
max_iters=self.max_iters,
# use_indirect, see: https://github.com/cvxgrp/cvxpy/issues/547
use_indirect=False)
return S.value
示例4: get_sudoku_matrix
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import Problem [as 别名]
def get_sudoku_matrix(n):
X = np.array([[cp.Variable(n**2) for i in range(n**2)] for j in range(n**2)])
cons = ([x >= 0 for row in X for x in row] +
[cp.sum(x) == 1 for row in X for x in row] +
[sum(row) == np.ones(n**2) for row in X] +
[sum([row[i] for row in X]) == np.ones(n**2) for i in range(n**2)] +
[sum([sum(row[i:i+n]) for row in X[j:j+n]]) == np.ones(n**2) for i in range(0,n**2,n) for j in range(0, n**2, n)])
f = sum([cp.sum(x) for row in X for x in row])
prob = cp.Problem(cp.Minimize(f), cons)
A = np.asarray(prob.get_problem_data(cp.ECOS)[0]["A"].todense())
A0 = [A[0]]
rank = 1
for i in range(1,A.shape[0]):
if np.linalg.matrix_rank(A0+[A[i]], tol=1e-12) > rank:
A0.append(A[i])
rank += 1
return np.array(A0)
示例5: get_inpaint_func_tv
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import Problem [as 别名]
def get_inpaint_func_tv():
def inpaint_func(image, mask):
"""Total variation inpainting"""
inpainted = np.zeros_like(image)
for c in range(image.shape[2]):
image_c = image[:, :, c]
mask_c = mask[:, :, c]
if np.min(mask_c) > 0:
# if mask is all ones, no need to inpaint
inpainted[:, :, c] = image_c
else:
h, w = image_c.shape
inpainted_c_var = cvxpy.Variable(h, w)
obj = cvxpy.Minimize(cvxpy.tv(inpainted_c_var))
constraints = [cvxpy.mul_elemwise(mask_c, inpainted_c_var) == cvxpy.mul_elemwise(mask_c, image_c)]
prob = cvxpy.Problem(obj, constraints)
# prob.solve(solver=cvxpy.SCS, max_iters=100, eps=1e-2) # scs solver
prob.solve() # default solver
inpainted[:, :, c] = inpainted_c_var.value
return inpainted
return inpaint_func
示例6: ball_con
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import Problem [as 别名]
def ball_con():
# print(f'--- {sys._getframe().f_code.co_name} ---')
print('ball con')
npr.seed(0)
n = 2
A = cp.Parameter((n, n))
z = cp.Parameter(n)
p = cp.Parameter(n)
x = cp.Variable(n)
t = cp.Variable(n)
obj = cp.Minimize(0.5 * cp.sum_squares(x - p))
# TODO automate introduction of variables.
cons = [0.5 * cp.sum_squares(A * t) <= 1, t == (x - z)]
prob = cp.Problem(obj, cons)
L = npr.randn(n, n)
A.value = L.T
z.value = npr.randn(n)
p.value = npr.randn(n)
prob.solve(solver=cp.SCS)
print(x.value)
示例7: relu
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import Problem [as 别名]
def relu():
# print(f'--- {sys._getframe().f_code.co_name} ---')
print('relu')
npr.seed(0)
n = 4
_x = cp.Parameter(n)
_y = cp.Variable(n)
obj = cp.Minimize(cp.sum_squares(_y - _x))
cons = [_y >= 0]
prob = cp.Problem(obj, cons)
_x.value = npr.randn(n)
prob.solve(solver=cp.SCS)
print(_y.value)
示例8: running_example
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import Problem [as 别名]
def running_example():
print("running example")
m = 20
n = 10
x = cp.Variable((n, 1))
F = cp.Parameter((m, n))
g = cp.Parameter((m, 1))
lambd = cp.Parameter((1, 1), nonneg=True)
objective_fn = cp.norm(F @ x - g) + lambd * cp.norm(x)
constraints = [x >= 0]
problem = cp.Problem(cp.Minimize(objective_fn), constraints)
assert problem.is_dcp()
assert problem.is_dpp()
print("is_dpp: ", problem.is_dpp())
F_t = torch.randn(m, n, requires_grad=True)
g_t = torch.randn(m, 1, requires_grad=True)
lambd_t = torch.rand(1, 1, requires_grad=True)
layer = CvxpyLayer(problem, parameters=[F, g, lambd], variables=[x])
x_star, = layer(F_t, g_t, lambd_t)
x_star.sum().backward()
print("F_t grad: ", F_t.grad)
print("g_t grad: ", g_t.grad)
示例9: test_lml
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import Problem [as 别名]
def test_lml(self):
tf.random.set_seed(0)
k = 2
x = cp.Parameter(4)
y = cp.Variable(4)
obj = -x * y - cp.sum(cp.entr(y)) - cp.sum(cp.entr(1. - y))
cons = [cp.sum(y) == k]
problem = cp.Problem(cp.Minimize(obj), cons)
lml = CvxpyLayer(problem, [x], [y])
x_tf = tf.Variable([1., -1., -1., -1.], dtype=tf.float64)
with tf.GradientTape() as tape:
y_opt = lml(x_tf, solver_args={'eps': 1e-10})[0]
loss = -tf.math.log(y_opt[1])
def f():
problem.solve(solver=cp.SCS, eps=1e-10)
return -np.log(y.value[1])
grad = tape.gradient(loss, [x_tf])
numgrad = numerical_grad(f, [x], [x_tf])
np.testing.assert_almost_equal(grad, numgrad, decimal=3)
示例10: test_example
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import Problem [as 别名]
def test_example(self):
n, m = 2, 3
x = cp.Variable(n)
A = cp.Parameter((m, n))
b = cp.Parameter(m)
constraints = [x >= 0]
objective = cp.Minimize(0.5 * cp.pnorm(A @ x - b, p=1))
problem = cp.Problem(objective, constraints)
assert problem.is_dpp()
cvxpylayer = CvxpyLayer(problem, parameters=[A, b], variables=[x])
A_tch = torch.randn(m, n, requires_grad=True)
b_tch = torch.randn(m, requires_grad=True)
# solve the problem
solution, = cvxpylayer(A_tch, b_tch)
# compute the gradient of the sum of the solution with respect to A, b
solution.sum().backward()
示例11: test_simple_batch_socp
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import Problem [as 别名]
def test_simple_batch_socp(self):
set_seed(243)
n = 5
m = 1
batch_size = 4
P_sqrt = cp.Parameter((n, n), name='P_sqrt')
q = cp.Parameter((n, 1), name='q')
A = cp.Parameter((m, n), name='A')
b = cp.Parameter((m, 1), name='b')
x = cp.Variable((n, 1), name='x')
objective = 0.5 * cp.sum_squares(P_sqrt @ x) + q.T @ x
constraints = [A@x == b, cp.norm(x) <= 1]
prob = cp.Problem(cp.Minimize(objective), constraints)
prob_tch = CvxpyLayer(prob, [P_sqrt, q, A, b], [x])
P_sqrt_tch = torch.randn(batch_size, n, n, requires_grad=True)
q_tch = torch.randn(batch_size, n, 1, requires_grad=True)
A_tch = torch.randn(batch_size, m, n, requires_grad=True)
b_tch = torch.randn(batch_size, m, 1, requires_grad=True)
torch.autograd.gradcheck(prob_tch, (P_sqrt_tch, q_tch, A_tch, b_tch))
示例12: test_shared_parameter
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import Problem [as 别名]
def test_shared_parameter(self):
set_seed(243)
m, n = 10, 5
A = cp.Parameter((m, n))
x = cp.Variable(n)
b1 = np.random.randn(m)
b2 = np.random.randn(m)
prob1 = cp.Problem(cp.Minimize(cp.sum_squares(A @ x - b1)))
layer1 = CvxpyLayer(prob1, parameters=[A], variables=[x])
prob2 = cp.Problem(cp.Minimize(cp.sum_squares(A @ x - b2)))
layer2 = CvxpyLayer(prob2, parameters=[A], variables=[x])
A_tch = torch.randn(m, n, requires_grad=True)
solver_args = {
"eps": 1e-10,
"acceleration_lookback": 0,
"max_iters": 10000
}
torch.autograd.gradcheck(lambda A: torch.cat(
[layer1(A, solver_args=solver_args)[0],
layer2(A, solver_args=solver_args)[0]]), (A_tch,))
示例13: __init__
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import Problem [as 别名]
def __init__(self, m, k, n, complex=False):
if not cvx_available:
raise RuntimeError('Cannot initialize when cvxpy is not available.')
# Initialize parameters and variables
A = cvx.Parameter((m, k), complex=complex)
B = cvx.Parameter((m, n), complex=complex)
l = cvx.Parameter(nonneg=True)
X = cvx.Variable((k, n), complex=complex)
# Create the problem
# CVXPY issue:
# cvx.norm does not work if axis is not 0.
# Workaround:
# use cvx.norm(X.T, 2, axis=0) instead of cvx.norm(X, 2, axis=1)
obj_func = 0.5 * cvx.norm(cvx.matmul(A, X) - B, 'fro')**2 + \
l * cvx.sum(cvx.norm(X.T, 2, axis=0))
self._problem = cvx.Problem(cvx.Minimize(obj_func))
self._A = A
self._B = B
self._l = l
self._X = X
示例14: fit
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import Problem [as 别名]
def fit(self, X, y):
"""
Fit the model using X, y as training data.
:param X: array-like, shape=(n_columns, n_samples, ) training data.
:param y: array-like, shape=(n_samples, ) training data.
:return: Returns an instance of self.
"""
X, y = check_X_y(X, y, estimator=self, dtype=FLOAT_DTYPES)
# Construct the problem.
betas = cp.Variable(X.shape[1])
objective = cp.Minimize(cp.sum_squares(X * betas - y))
constraints = [sum(betas) == 1]
if self.non_negative:
constraints.append(0 <= betas)
# Solve the problem.
prob = cp.Problem(objective, constraints)
prob.solve()
self.coefs_ = betas.value
return self
示例15: _mk_monotonic_average
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import Problem [as 别名]
def _mk_monotonic_average(xs, ys, intervals, method="increasing", **kwargs):
"""
Creates smoothed averages of `ys` at the intervals given by `intervals`.
:param xs: all the datapoints of a feature (represents the x-axis)
:param ys: all the datapoints what we'd like to predict (represents the y-axis)
:param intervals: the intervals at which we'd like to get a good average value
:param method: the method that is used for smoothing, can be either `increasing` or `decreasing`.
:return:
An array as long as `intervals` that represents the average `y`-values at those intervals,
keeping the constraint in mind.
"""
x_internal = np.array([xs >= i for i in intervals]).T.astype(np.float)
betas = cp.Variable(x_internal.shape[1])
objective = cp.Minimize(cp.sum_squares(x_internal * betas - ys))
if method == "increasing":
constraints = [betas[i + 1] >= 0 for i in range(betas.shape[0] - 1)]
elif method == "decreasing":
constraints = [betas[i + 1] <= 0 for i in range(betas.shape[0] - 1)]
else:
raise ValueError(
f"method must be either `increasing` or `decreasing`, got: {method}"
)
prob = cp.Problem(objective, constraints)
prob.solve()
return betas.value.cumsum()