本文整理汇总了Python中cvxpy.sum_entries方法的典型用法代码示例。如果您正苦于以下问题:Python cvxpy.sum_entries方法的具体用法?Python cvxpy.sum_entries怎么用?Python cvxpy.sum_entries使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类cvxpy
的用法示例。
在下文中一共展示了cvxpy.sum_entries方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: solve_spectral
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import sum_entries [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
示例2: solve_sdr
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import sum_entries [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
示例3: linear_softmax_reg
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import sum_entries [as 别名]
def linear_softmax_reg(X, Y, params):
m, n = X.shape[0], X.shape[1]
Theta = cp.Variable(n, len(params['d']))
f = cp.sum_entries(cp.log_sum_exp(X*Theta, axis=1) -
cp.sum_entries(cp.mul_elemwise(Y, X*Theta), axis=1)) / m
lam = 1e-5 # regularization
cp.Problem(cp.Minimize(f + lam * cp.sum_squares(Theta)), []).solve()
Theta = np.asarray(Theta.value)
return Theta
# Optimize expected value of inventory allocation
示例4: loss
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import sum_entries [as 别名]
def loss(self, A, U): return cp.sum_entries(cp.huber(cp.Constant(A) - U, self.a))
示例5: reg
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import sum_entries [as 别名]
def reg(self, X): return 1e10*cp.sum_entries(cp.neg(X))
示例6: get_C_hat_transpose
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import sum_entries [as 别名]
def get_C_hat_transpose():
probs = []
net.eval()
for batch_idx, (data, target) in enumerate(train_gold_deterministic_loader):
# we subtract 10 because we added 10 to gold so we could identify which example is gold in train_phase2
data, target = V(data.cuda(), volatile=True),\
V((target - num_classes).cuda(), volatile=True)
# forward
output = net(data)
pred = F.softmax(output)
probs.extend(list(pred.data.cpu().numpy()))
probs = np.array(probs, dtype=np.float32)
C_hat = np.zeros((num_classes, num_classes))
for label in range(num_classes):
indices = np.arange(len(train_data_gold.train_labels))[
np.isclose(np.array(train_data_gold.train_labels) - num_classes, label)]
C_hat[label] = np.mean(probs[indices], axis=0, keepdims=True)
import cvxpy
base_rate_clean = [0] * num_classes
base_rate_corr = [0] * num_classes
for label in range(num_classes):
base_rate_clean[label] = sum(np.array(train_data_gold.train_labels) == label)
base_rate_corr[label] = sum(np.array(train_data_silver.train_labels) == label)
base_rate_clean = np.array(base_rate_clean).reshape((1,-1)) / len(train_data_gold.train_labels)
base_rate_corr = np.array(base_rate_corr).reshape((1,-1)) / len(train_data_silver.train_labels)
print(base_rate_clean)
print(base_rate_corr)
C_hat_better = cvxpy.Variable(num_classes,num_classes)
objective = cvxpy.Minimize(
1e-2*cvxpy.sum_squares(C_hat_better - C_hat)/num_classes +
cvxpy.sum_squares(base_rate_clean * C_hat_better - base_rate_corr))
constraints = [0 <= C_hat_better, C_hat_better <= 1, 1 == cvxpy.sum_entries(C_hat_better, axis=1)]
prob = cvxpy.Problem(objective, constraints)
prob.solve()
C_hat = np.array(C_hat_better.value)
return C_hat.T.astype(np.float32)
示例7: balance_cvx
# 需要导入模块: import cvxpy [as 别名]
# 或者: from cvxpy import sum_entries [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