Python cvxpy.mul_elemwise() Examples
The following are 9
code examples of cvxpy.mul_elemwise().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
cvxpy
, or try the search function
.
Example #1
Source File: measure_utils.py From ambient-gan with MIT License | 6 votes |
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
Example #2
Source File: qcqp.py From qcqp with MIT License | 5 votes |
def solve_spectral(prob, *args, **kwargs): """Solve the spectral relaxation with lambda = 1. """ # TODO: do this efficiently without SDP lifting # lifted variables and semidefinite constraint X = cvx.Semidef(prob.n + 1) W = prob.f0.homogeneous_form() rel_obj = cvx.Minimize(cvx.sum_entries(cvx.mul_elemwise(W, X))) W1 = sum([f.homogeneous_form() for f in prob.fs if f.relop == '<=']) W2 = sum([f.homogeneous_form() for f in prob.fs if f.relop == '==']) rel_prob = cvx.Problem( rel_obj, [ cvx.sum_entries(cvx.mul_elemwise(W1, X)) <= 0, cvx.sum_entries(cvx.mul_elemwise(W2, X)) == 0, X[-1, -1] == 1 ] ) rel_prob.solve(*args, **kwargs) if rel_prob.status not in [cvx.OPTIMAL, cvx.OPTIMAL_INACCURATE]: raise Exception("Relaxation problem status: %s" % rel_prob.status) (w, v) = LA.eig(X.value) return np.sqrt(np.max(w))*np.asarray(v[:-1, np.argmax(w)]).flatten(), rel_prob.value
Example #3
Source File: qcqp.py From qcqp with MIT License | 5 votes |
def solve_sdr(prob, *args, **kwargs): """Solve the SDP relaxation. """ # lifted variables and semidefinite constraint X = cvx.Semidef(prob.n + 1) W = prob.f0.homogeneous_form() rel_obj = cvx.Minimize(cvx.sum_entries(cvx.mul_elemwise(W, X))) rel_constr = [X[-1, -1] == 1] for f in prob.fs: W = f.homogeneous_form() lhs = cvx.sum_entries(cvx.mul_elemwise(W, X)) if f.relop == '==': rel_constr.append(lhs == 0) else: rel_constr.append(lhs <= 0) rel_prob = cvx.Problem(rel_obj, rel_constr) rel_prob.solve(*args, **kwargs) if rel_prob.status not in [cvx.OPTIMAL, cvx.OPTIMAL_INACCURATE]: raise Exception("Relaxation problem status: %s" % rel_prob.status) return X.value, rel_prob.value # phase 1: optimize infeasibility
Example #4
Source File: loss.py From GLRM with MIT License | 5 votes |
def __str__(self): return "huber loss" # class FractionalLoss(Loss): # PRECISION = 1e-10 # def loss(self, A, U): # B = cp.Constant(A) # U = cp.max_elemwise(U, self.PRECISION) # to avoid dividing by zero # return cp.max_elemwise(cp.mul_elemwise(cp.inv_pos(cp.pos(U)), B-U), \ # return maximum((A - U)/U, (U - A)/A) #
Example #5
Source File: loss.py From GLRM with MIT License | 5 votes |
def loss(self, A, U): return cp.sum_entries(cp.pos(ones(A.shape)-cp.mul_elemwise(cp.Constant(A), U)))
Example #6
Source File: loss.py From GLRM with MIT License | 5 votes |
def loss(self, A, U): return cp.sum_entries(sum(cp.mul_elemwise(1*(b >= A),\ cp.pos(U-b*ones(A.shape))) + cp.mul_elemwise(1*(b < A), \ cp.pos(-U + (b+1)*ones(A.shape))) for b in range(int(self.Amin), int(self.Amax))))
Example #7
Source File: glrm.py From GLRM with MIT License | 5 votes |
def _initialize_probs(self, A, k, missing_list, regX, regY): # useful parameters m = A[0].shape[0] ns = [a.shape[1] for a in A] if missing_list == None: missing_list = [[]]*len(self.L) # initialize A, X, Y B = self._initialize_A(A, missing_list) X0, Y0 = self._initialize_XY(B, k, missing_list) self.X0, self.Y0 = X0, Y0 # cvxpy problems Xv, Yp = cp.Variable(m,k), [cp.Parameter(k+1,ni) for ni in ns] Xp, Yv = cp.Parameter(m,k+1), [cp.Variable(k+1,ni) for ni in ns] Xp.value = copy(X0) for yj, yj0 in zip(Yp, Y0): yj.value = copy(yj0) onesM = cp.Constant(ones((m,1))) obj = sum(L(Aj, cp.mul_elemwise(mask, Xv*yj[:-1,:] \ + onesM*yj[-1:,:]) + offset) + ry(yj[:-1,:])\ for L, Aj, yj, mask, offset, ry in \ zip(self.L, A, Yp, self.masks, self.offsets, regY)) + regX(Xv) pX = cp.Problem(cp.Minimize(obj)) pY = [cp.Problem(cp.Minimize(\ L(Aj, cp.mul_elemwise(mask, Xp*yj) + offset) \ + ry(yj[:-1,:]) + regX(Xp))) \ for L, Aj, yj, mask, offset, ry in zip(self.L, A, Yv, self.masks, self.offsets, regY)] self.probX = (Xv, Yp, pX) self.probY = (Xp, Yv, pY)
Example #8
Source File: test_problem.py From ProxImaL with MIT License | 4 votes |
def test_problem(self): """Test problem object. """ X = Variable((4, 2)) B = np.reshape(np.arange(8), (4, 2)) * 1. prox_fns = [norm1(X), sum_squares(X, b=B)] prob = Problem(prox_fns) # prob.partition(quad_funcs = [prox_fns[0], prox_fns[1]]) prob.set_automatic_frequency_split(False) prob.set_absorb(False) prob.set_implementation(Impl['halide']) prob.set_solver('admm') prob.solve() true_X = norm1(X).prox(2, B.copy()) self.assertItemsAlmostEqual(X.value, true_X, places=2) prob.solve(solver="pc") self.assertItemsAlmostEqual(X.value, true_X, places=2) prob.solve(solver="hqs", eps_rel=1e-6, rho_0=1.0, rho_scale=np.sqrt(2.0) * 2.0, rho_max=2**16, max_iters=20, max_inner_iters=500, verbose=False) self.assertItemsAlmostEqual(X.value, true_X, places=2) # CG prob = Problem(prox_fns) prob.set_lin_solver("cg") prob.solve(solver="admm") self.assertItemsAlmostEqual(X.value, true_X, places=2) prob.solve(solver="hqs", eps_rel=1e-6, rho_0=1.0, rho_scale=np.sqrt(2.0) * 2.0, rho_max=2**16, max_iters=20, max_inner_iters=500, verbose=False) self.assertItemsAlmostEqual(X.value, true_X, places=2) # Quad funcs. prob = Problem(prox_fns) prob.solve(solver="admm") self.assertItemsAlmostEqual(X.value, true_X, places=2) # Absorbing lin ops. prox_fns = [norm1(5 * mul_elemwise(B, X)), sum_squares(-2 * X, b=B)] prob = Problem(prox_fns) prob.set_absorb(True) prob.solve(solver="admm", eps_rel=1e-6, eps_abs=1e-6) cvx_X = cvx.Variable(4, 2) cost = cvx.sum_squares(-2 * cvx_X - B) + cvx.norm(5 * cvx.mul_elemwise(B, cvx_X), 1) cvx_prob = cvx.Problem(cvx.Minimize(cost)) cvx_prob.solve(solver=cvx.SCS) self.assertItemsAlmostEqual(X.value, cvx_X.value, places=2) prob.set_absorb(False) prob.solve(solver="admm", eps_rel=1e-6, eps_abs=1e-6) self.assertItemsAlmostEqual(X.value, cvx_X.value, places=2) # Constant offsets. prox_fns = [norm1(5 * mul_elemwise(B, X)), sum_squares(-2 * X - B)] prob = Problem(prox_fns) prob.solve(solver="admm", eps_rel=1e-6, eps_abs=1e-6) self.assertItemsAlmostEqual(X.value, cvx_X.value, places=2)
Example #9
Source File: listbalancer.py From doppelganger with Apache License 2.0 | 4 votes |
def balance_cvx(hh_table, A, w, mu=None, verbose_solver=False): """Maximum Entropy allocaion method for a single unit Args: hh_table (numpy matrix): Table of households categorical data A (numpy matrix): Area marginals (controls) w (numpy array): Initial household allocation weights mu (numpy array): Importance weights of marginals fit accuracy verbose_solver (boolean): Provide detailed solver info Returns: (numpy matrix, numpy matrix): Household weights, relaxation factors """ n_samples, n_controls = hh_table.shape x = cvx.Variable(n_samples) if mu is None: objective = cvx.Maximize( cvx.sum_entries(cvx.entr(x) + cvx.mul_elemwise(cvx.log(w.T), x)) ) constraints = [ x >= 0, x.T * hh_table == A, ] prob = cvx.Problem(objective, constraints) prob.solve(solver=cvx.SCS, verbose=verbose_solver) return x.value else: # With relaxation factors z = cvx.Variable(n_controls) objective = cvx.Maximize( cvx.sum_entries(cvx.entr(x) + cvx.mul_elemwise(cvx.log(w.T), x)) + cvx.sum_entries(mu * (cvx.entr(z))) ) constraints = [ x >= 0, z >= 0, x.T * hh_table == cvx.mul_elemwise(A, z.T), ] prob = cvx.Problem(objective, constraints) prob.solve(solver=cvx.SCS, verbose=verbose_solver) return x.value, z.value