当前位置: 首页>>代码示例>>Python>>正文


Python cvxpy.mul_elemwise方法代码示例

本文整理汇总了Python中cvxpy.mul_elemwise方法的典型用法代码示例。如果您正苦于以下问题:Python cvxpy.mul_elemwise方法的具体用法?Python cvxpy.mul_elemwise怎么用?Python cvxpy.mul_elemwise使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在cvxpy的用法示例。


在下文中一共展示了cvxpy.mul_elemwise方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_inpaint_func_tv

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import mul_elemwise [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 
开发者ID:AshishBora,项目名称:ambient-gan,代码行数:23,代码来源:measure_utils.py

示例2: solve_spectral

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import mul_elemwise [as 别名]
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 
开发者ID:cvxgrp,项目名称:qcqp,代码行数:32,代码来源:qcqp.py

示例3: solve_sdr

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import mul_elemwise [as 别名]
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 
开发者ID:cvxgrp,项目名称:qcqp,代码行数:31,代码来源:qcqp.py

示例4: __str__

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import mul_elemwise [as 别名]
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)
# 
开发者ID:powerscorinne,项目名称:GLRM,代码行数:12,代码来源:loss.py

示例5: loss

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import mul_elemwise [as 别名]
def loss(self, A, U): return cp.sum_entries(cp.pos(ones(A.shape)-cp.mul_elemwise(cp.Constant(A), U))) 
开发者ID:powerscorinne,项目名称:GLRM,代码行数:3,代码来源:loss.py

示例6: _initialize_probs

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import mul_elemwise [as 别名]
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) 
开发者ID:powerscorinne,项目名称:GLRM,代码行数:33,代码来源:glrm.py

示例7: test_problem

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import mul_elemwise [as 别名]
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) 
开发者ID:comp-imaging,项目名称:ProxImaL,代码行数:61,代码来源:test_problem.py

示例8: balance_cvx

# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import mul_elemwise [as 别名]
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 
开发者ID:replicahq,项目名称:doppelganger,代码行数:51,代码来源:listbalancer.py


注:本文中的cvxpy.mul_elemwise方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。