本文整理汇总了Python中cvxopt.matrix方法的典型用法代码示例。如果您正苦于以下问题:Python cvxopt.matrix方法的具体用法?Python cvxopt.matrix怎么用?Python cvxopt.matrix使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类cvxopt
的用法示例。
在下文中一共展示了cvxopt.matrix方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: lk
# 需要导入模块: import cvxopt [as 别名]
# 或者: from cvxopt import matrix [as 别名]
def lk(E=1.):
"""element stiffness matrix"""
nu = 0.3
k = np.array([0.5 - nu / 6., 0.125 + nu / 8., -0.25 - nu / 12.,
-0.125 + 0.375 * nu, -0.25 + nu / 12., -0.125 - nu / 8., nu / 6.,
0.125 - 0.375 * nu])
KE = E / (1 - nu**2) * np.array([
[k[0], k[1], k[2], k[3], k[4], k[5], k[6], k[7]],
[k[1], k[0], k[7], k[6], k[5], k[4], k[3], k[2]],
[k[2], k[7], k[0], k[5], k[6], k[3], k[4], k[1]],
[k[3], k[6], k[5], k[0], k[7], k[2], k[1], k[4]],
[k[4], k[5], k[6], k[7], k[0], k[1], k[2], k[3]],
[k[5], k[4], k[3], k[2], k[1], k[0], k[7], k[6]],
[k[6], k[3], k[4], k[1], k[2], k[7], k[0], k[5]],
[k[7], k[2], k[1], k[4], k[3], k[6], k[5], k[0]]])
return KE
示例2: fit
# 需要导入模块: import cvxopt [as 别名]
# 或者: from cvxopt import matrix [as 别名]
def fit(self, Xs, Xt):
'''
Fit source and target using KMM (compute the coefficients)
:param Xs: ns * dim
:param Xt: nt * dim
:return: Coefficients (Pt / Ps) value vector (Beta in the paper)
'''
ns = Xs.shape[0]
nt = Xt.shape[0]
if self.eps == None:
self.eps = self.B / np.sqrt(ns)
K = kernel(self.kernel_type, Xs, None, self.gamma)
kappa = np.sum(kernel(self.kernel_type, Xs, Xt, self.gamma) * float(ns) / float(nt), axis=1)
K = matrix(K)
kappa = matrix(kappa)
G = matrix(np.r_[np.ones((1, ns)), -np.ones((1, ns)), np.eye(ns), -np.eye(ns)])
h = matrix(np.r_[ns * (1 + self.eps), ns * (self.eps - 1), self.B * np.ones((ns,)), np.zeros((ns,))])
sol = solvers.qp(K, -kappa, G, h)
beta = np.array(sol['x'])
return beta
示例3: radius
# 需要导入模块: import cvxopt [as 别名]
# 或者: from cvxopt import matrix [as 别名]
def radius(K):
"""evaluate the radius of the MEB (Minimum Enclosing Ball) of examples in
feature space.
Parameters
----------
K : (n,n) ndarray,
the kernel that represents the data.
Returns
-------
r : np.float64,
the radius of the minimum enclosing ball of examples in feature space.
"""
K = validation.check_K(K).numpy()
n = K.shape[0]
P = 2 * matrix(K)
p = -matrix(K.diagonal())
G = -spdiag([1.0] * n)
h = matrix([0.0] * n)
A = matrix([1.0] * n).T
b = matrix([1.0])
solvers.options['show_progress']=False
sol = solvers.qp(P,p,G,h,A,b)
return abs(sol['primal objective'])**.5
示例4: _update_grad
# 需要导入模块: import cvxopt [as 别名]
# 或者: from cvxopt import matrix [as 别名]
def _update_grad(self,Kc, YY, beta, alpha, gamma):
n = self.n_kernels
eb = np.exp(beta)
a,b = [], []
gammaY = gamma['x'].T*YY
for K in self.KL: #optimized for generators
K = matrix(K.numpy().astype(np.double))
a.append( 1.-(alpha['x'].T*matrix(K)*alpha['x'])[0] )
b.append( (gammaY*matrix(K)*gammaY.T)[0] )
ebb, eba = np.dot(eb,b), np.dot(eb,a)
den = np.dot(eb,b)**2
num = [eb[r] * (a[r]*ebb - b[r]*eba) for r in range(n)]
new_beta = np.array([beta[k] - self.learning_rate * (num[k]/den) for k in range(n)])
return new_beta
示例5: cvxopt_matrix
# 需要导入模块: import cvxopt [as 别名]
# 或者: from cvxopt import matrix [as 别名]
def cvxopt_matrix(M):
"""
Convert matrix to CVXOPT format.
Parameters
----------
M : numpy.array
Matrix in NumPy format.
Returns
-------
N : cvxopt.matrix
Matrix in CVXOPT format.
"""
if type(M) is ndarray:
return matrix(M)
elif type(M) is spmatrix or type(M) is matrix:
return M
coo = M.tocoo()
return spmatrix(
coo.data.tolist(), coo.row.tolist(), coo.col.tolist(), size=M.shape)
示例6: projection_in_norm
# 需要导入模块: import cvxopt [as 别名]
# 或者: from cvxopt import matrix [as 别名]
def projection_in_norm(self, x, M):
"""
Projection of x to simplex induced by matrix M. Uses quadratic programming.
"""
m = M.shape[0]
# Constrains matrices
P = opt.matrix(2 * M)
q = opt.matrix(-2 * M * x)
G = opt.matrix(-np.eye(m))
h = opt.matrix(np.zeros((m, 1)))
A = opt.matrix(np.ones((1, m)))
b = opt.matrix(1.)
# Solve using quadratic programming
sol = opt.solvers.qp(P, q, G, h, A, b)
return np.squeeze(sol['x'])
示例7: rebalance
# 需要导入模块: import cvxopt [as 别名]
# 或者: from cvxopt import matrix [as 别名]
def rebalance(self, obs):
"""
Performs portfolio rebalance within environment
:param obs: pandas DataFrame: Environment observation
:return: numpy array: Portfolio vector
"""
n_pairs = obs.columns.levels[0].shape[0]
if self.step:
prev_posit = self.get_portfolio_vector(obs, index=self.reb)
price_relative = self.predict(obs)
return self.update(prev_posit, price_relative)
else:
action = np.ones(n_pairs)
action[-1] = 0
self.sigma = np.matrix(np.eye(n_pairs) / n_pairs ** 2)
return array_normalize(action)
示例8: decide_by_history
# 需要导入模块: import cvxopt [as 别名]
# 或者: from cvxopt import matrix [as 别名]
def decide_by_history(self, x, last_b):
'''
:param x: input matrix
:param last_b: last portfolio
'''
x = self.get_last_rpv(x)
if self.A is None:
self.init_portfolio(x)
# calculate gradient
grad = np.mat(x / np.dot(last_b, x)).T
# update A
self.A += grad * grad.T
# update b
self.b += (1 + 1./self.beta) * grad
# projection of p induced by norm A
pp = self.projection_in_norm(self.delta * self.A.I * self.b, self.A)
return pp * (1 - self.eta) + np.ones(len(x)) / float(len(x)) * self.eta
示例9: calculateA
# 需要导入模块: import cvxopt [as 别名]
# 或者: from cvxopt import matrix [as 别名]
def calculateA(input_,label,C,K): #using cvxopt bag figure out the convex quadratic programming
num = input_.shape[0]
P = cvxopt.matrix(numpy.outer(label,label)*K)
q = cvxopt.matrix(numpy.ones(num)*-1)
A = cvxopt.matrix(label,(1,num))
b = cvxopt.matrix(0.0)
if C is None:
G = cvxopt.matrix(numpy.diag(numpy.ones(num)*-1))
h = cvxopt.matrix(numpy.zeros(num))
else:
temp1 = numpy.diag(numpy.ones(num)*-1)
temp2 = bp.identity(num)
G = cvxopt.matrix(numpy.vstack(temp1,temp2))
temp1 = numpy.zeros(num)
temp2 = numpy.ones(num)*self.C
h = cvxopt.matrix(numpy.hstack(temp1,temp2)) #P\q\A\b\G\h are parameters of cvxopt.solvers.qp() function
solution = cvxopt.solvers.qp(P,q,G,h,A,b) #figure out the model
a = numpy.ravel(solution['x']) #transfer the 'a' into a vector
return a
示例10: _QP
# 需要导入模块: import cvxopt [as 别名]
# 或者: from cvxopt import matrix [as 别名]
def _QP(self, x, y):
# In QP formulation (dual): m variables, 2m+1 constraints (1 equation, 2m inequations)
m = len(y)
print x.shape, y.shape
P = self._kernel(x) * np.outer(y, y)
P, q = matrix(P, tc='d'), matrix(-np.ones((m, 1)), tc='d')
G = matrix(np.r_[-np.eye(m), np.eye(m)], tc='d')
h = matrix(np.r_[np.zeros((m,1)), np.zeros((m,1)) + self.C], tc='d')
A, b = matrix(y.reshape((1,-1)), tc='d'), matrix([0.0])
# print "P, q:"
# print P, q
# print "G, h"
# print G, h
# print "A, b"
# print A, b
solution = solvers.qp(P, q, G, h, A, b)
if solution['status'] == 'unknown':
print 'Not PSD!'
exit(2)
else:
self.alphas = np.array(solution['x']).squeeze()
示例11: min_singular
# 需要导入模块: import cvxopt [as 别名]
# 或者: from cvxopt import matrix [as 别名]
def min_singular(forces, torques, normals, soft_fingers=False, params=None):
""" Min singular value of grasp matrix - measure of wrench that grasp is "weakest" at resisting.
Parameters
----------
forces : 3xN :obj:`numpy.ndarray`
set of forces on object in object basis
torques : 3xN :obj:`numpy.ndarray`
set of torques on object in object basis
normals : 3xN :obj:`numpy.ndarray`
surface normals at the contact points
soft_fingers : bool
whether or not to use the soft finger contact model
params : :obj:`GraspQualityConfig`
set of parameters for grasp matrix and contact model
Returns
-------
float : value of smallest singular value
"""
G = PointGraspMetrics3D.grasp_matrix(forces, torques, normals, soft_fingers)
_, S, _ = np.linalg.svd(G)
min_sig = S[5]
return min_sig
示例12: test_ilp
# 需要导入模块: import cvxopt [as 别名]
# 或者: from cvxopt import matrix [as 别名]
def test_ilp():
"""
Problem defined in:
https://en.wikipedia.org/wiki/Integer_programming#Example
Solution from:
https://stackoverflow.com/questions/33785396/python-the-integer-linear-programming-ilp-function-in-cvxopt-is-not-generati
"""
import cvxopt
from cvxopt import glpk
glpk.options['msg_lev'] = 'GLP_MSG_OFF'
c = cvxopt.matrix([0, -1], tc='d')
G = cvxopt.matrix([[-1, 1], [3, 2], [2, 3], [-1, 0], [0, -1]], tc='d')
h = cvxopt.matrix([1, 12, 12, 0, 0], tc='d')
(status, x) = cvxopt.glpk.ilp(c, G.T, h, I=set([0, 1]))
print (status)
print ("%s, %s" % (str(x[0]), str(x[1])))
print (sum(c.T * x))
示例13: __init__
# 需要导入模块: import cvxopt [as 别名]
# 或者: from cvxopt import matrix [as 别名]
def __init__(self, x, y, model, opts, sample_negative=False):
"""
:param x: np.ndarray
The instance matrix with ALL instances
:param y: np.array
:param model: Aad
:param opts: AadOpts
:param sample_negative: bool
"""
self.x = x
self.y = y
self.model = model
self.opts = opts
self.sample_negative = sample_negative
self.meta = None
示例14: _computeReward
# 需要导入模块: import cvxopt [as 别名]
# 或者: from cvxopt import matrix [as 别名]
def _computeReward(self, reward, transition):
# Compute the reward for the system in one state chosing an action.
# Arguments
# Let S = number of states, A = number of actions
# P could be an array with 3 dimensions or a cell array (1xA),
# each cell containing a matrix (SxS) possibly sparse
# R could be an array with 3 dimensions (SxSxA) or a cell array
# (1xA), each cell containing a sparse matrix (SxS) or a 2D
# array(SxA) possibly sparse
try:
if reward.ndim == 1:
return self._computeVectorReward(reward)
elif reward.ndim == 2:
return self._computeArrayReward(reward)
else:
r = tuple(map(self._computeMatrixReward, reward, transition))
return r
except (AttributeError, ValueError):
if len(reward) == self.A:
r = tuple(map(self._computeMatrixReward, reward, transition))
return r
else:
return self._computeVectorReward(reward)
示例15: __init__
# 需要导入模块: import cvxopt [as 别名]
# 或者: from cvxopt import matrix [as 别名]
def __init__(self, transitions, reward, discount, skip_check=False):
# Initialise a linear programming MDP.
# import some functions from cvxopt and set them as object methods
try:
from cvxopt import matrix, solvers
self._linprog = solvers.lp
self._cvxmat = matrix
except ImportError:
raise ImportError("The python module cvxopt is required to use "
"linear programming functionality.")
# initialise the MDP. epsilon and max_iter are not needed
MDP.__init__(self, transitions, reward, discount, None, None,
skip_check=skip_check)
# Set the cvxopt solver to be quiet by default, but ...
# this doesn't do what I want it to do c.f. issue #3
if not self.verbose:
solvers.options['show_progress'] = False