本文整理汇总了Python中cvxpy.Variable方法的典型用法代码示例。如果您正苦于以下问题:Python cvxpy.Variable方法的具体用法?Python cvxpy.Variable怎么用?Python cvxpy.Variable使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类cvxpy
的用法示例。
在下文中一共展示了cvxpy.Variable方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import Variable [as 别名]
def __init__(self):
"""
A large r_scale for a small scale problem will
ead to numerical problems as parameters become excessively small
and (it seems) precision is lost in the dynamics.
"""
self.set_random_initial_state()
self.x_init = np.concatenate(((self.m_wet,), self.r_I_init, self.v_I_init, self.q_B_I_init, self.w_B_init))
self.x_final = np.concatenate(((self.m_dry,), self.r_I_final, self.v_I_final, self.q_B_I_final, self.w_B_final))
self.r_scale = np.linalg.norm(self.r_I_init)
self.m_scale = self.m_wet
# slack variable for linear constraint relaxation
self.s_prime = cvx.Variable((K, 1), nonneg=True)
# slack variable for lossless convexification
# self.gamma = cvx.Variable(K, nonneg=True)
示例2: test_simple_batch_socp
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import Variable [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))
示例3: get_variable
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import Variable [as 别名]
def get_variable(self, name):
"""
:param name: Name of the variable.
:return The value of the variable.
The following variables can be accessed:
X
U
sigma
nu
"""
if name in self.var:
return self.var[name].value
else:
print(f'Variable \'{name}\' does not exist.')
return None
示例4: test_diff_fn
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import Variable [as 别名]
def test_diff_fn(self):
"""Test generic differentiable function operator.
"""
# Least squares.
tmp = Variable(10)
fn = diff_fn(tmp, lambda x: np.square(x).sum(), lambda x: 2 * x)
rho = 1
v = np.arange(10) * 1.0 - 5.0
x = fn.prox(rho, v.copy())
self.assertItemsAlmostEqual(x, v / (2 + rho))
# -log
n = 5
tmp = Variable(n)
fn = diff_fn(tmp, lambda x: -np.log(x).sum(), lambda x: -1.0 / x)
rho = 2
v = np.arange(n) * 2.0 + 1
x = fn.prox(rho, v.copy())
val = (v + np.sqrt(v**2 + 4 / rho)) / 2
self.assertItemsAlmostEqual(x, val)
示例5: get_sudoku_matrix
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import Variable [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)
示例6: __init__
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import Variable [as 别名]
def __init__(self, n, Qpenalty, qp_solver, trueInit=False):
super().__init__()
self.qp_solver = qp_solver
nx = (n**2)**3
self.Q = Variable(Qpenalty*torch.eye(nx).double().cuda())
self.Q_idx = spa.csc_matrix(self.Q.detach().cpu().numpy()).nonzero()
self.G = Variable(-torch.eye(nx).double().cuda())
self.h = Variable(torch.zeros(nx).double().cuda())
t = get_sudoku_matrix(n)
if trueInit:
self.A = Parameter(torch.DoubleTensor(t).cuda())
else:
self.A = Parameter(torch.rand(t.shape).double().cuda())
self.log_z0 = Parameter(torch.zeros(nx).double().cuda())
# self.b = Variable(torch.ones(self.A.size(0)).double().cuda())
if self.qp_solver == 'osqpth':
t = torch.cat((self.A, self.G), dim=0)
self.AG_idx = spa.csc_matrix(t.detach().cpu().numpy()).nonzero()
# @profile
示例7: forward
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import Variable [as 别名]
def forward(self, puzzles):
nBatch = puzzles.size(0)
x = puzzles.view(nBatch,-1)
x = self.fc_in(x)
e = Variable(torch.Tensor())
h = self.G.mv(self.z)+self.s
x = QPFunction(verbose=False)(
self.Q, x, self.G, h, e, e,
)
x = self.fc_out(x)
x = x.view_as(puzzles)
return x
# if __name__=="__main__":
# sudoku = SolveSudoku(2, 0.2)
# puzzle = [[4, 0, 0, 0], [0,0,4,0], [0,2,0,0], [0,0,0,1]]
# Y = Variable(torch.DoubleTensor(np.array([[np.array(np.eye(5,4,-1)[i,:]) for i in row] for row in puzzle])).cuda())
# solution = sudoku(Y.unsqueeze(0))
# print(solution.view(1,4,4,4))
示例8: get_inpaint_func_tv
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import Variable [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
示例9: ball_con
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import Variable [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)
示例10: relu
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import Variable [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)
示例11: running_example
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import Variable [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)
示例12: __call__
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import Variable [as 别名]
def __call__(self, *parameters, solver_args={}):
"""Solve problem (or a batch of problems) corresponding to `parameters`
Args:
parameters: a sequence of tf.Tensors; the n-th Tensor specifies
the value for the n-th CVXPY Parameter. These Tensors
can be batched: if a Tensor has 3 dimensions, then its
first dimension is interpreted as the batch size.
solver_args: a dict of optional arguments, to send to `diffcp`. Keys
should be the names of keyword arguments.
Returns:
a list of optimal variable values, one for each CVXPY Variable
supplied to the constructor.
"""
if len(parameters) != len(self.params):
raise ValueError('A tensor must be provided for each CVXPY '
'parameter; received %d tensors, expected %d' % (
len(parameters), len(self.params)))
compute = tf.custom_gradient(
lambda *parameters: self._compute(parameters, solver_args))
return compute(*parameters)
示例13: test_lml
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import Variable [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)
示例14: test_example
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import Variable [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()
示例15: run
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import Variable [as 别名]
def run(self):
''' Run experiment design. Returns a list of configurations and their scores'''
training_points = list(self._get_training_points())
num_points = len(training_points)
all_training_features = np.array([_get_features(point) for point in training_points])
covariance_matrices = list(_get_covariance_matrices(all_training_features))
lambdas = cvx.Variable(num_points)
objective = cvx.Minimize(_construct_objective(covariance_matrices, lambdas))
constraints = self._construct_constraints(lambdas, training_points)
problem = cvx.Problem(objective, constraints)
opt_val = problem.solve()
# TODO: Add debug logging
# print "solution status ", problem.status
# print "opt value is ", opt_val
filtered_lambda_idxs = []
for i in range(0, num_points):
if lambdas[i].value > self.MIN_WEIGHT_FOR_SELECTION:
filtered_lambda_idxs.append((lambdas[i].value, i))
sorted_by_lambda = sorted(filtered_lambda_idxs, key=lambda t: t[0], reverse=True)
return [(self._frac2parts(training_points[idx][0]), training_points[idx][0],
training_points[idx][1], l) for (l, idx) in sorted_by_lambda]