本文整理匯總了Python中numpy.matmul方法的典型用法代碼示例。如果您正苦於以下問題:Python numpy.matmul方法的具體用法?Python numpy.matmul怎麽用?Python numpy.matmul使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類numpy
的用法示例。
在下文中一共展示了numpy.matmul方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: _BtDB
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import matmul [as 別名]
def _BtDB(self,s,r):
"""
dot product of B^T, D, B
params:
s,r:natural position of evalue point.2-array.
returns:
3x3 matrix.
"""
print(self._B(s,r).transpose(2,0,1).shape)
print(
np.matmul(
np.dot(self._B(s,r).T,self._D),
self._B(s,r).transpose(2,0,1)).shape
)
print(self._D.shape)
return np.matmul(np.dot(self._B(s,r).T,self._D),self._B(s,r).transpose(2,0,1)).transpose(1,2,0)
示例2: DataProjection
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import matmul [as 別名]
def DataProjection(X, r, type='NormalProj'):
Xp = None
D, N = X.shape
if r == 0:
Xp = X
else:
if type == 'PCA':
isEcon = False
if D > N:
isEcon = True
U, S, V = np.linalg.svd(X.T, full_matrices=isEcon)
Xp = U[:, 0:r].T
if type == 'NormalProj':
normP = (1.0 / math.sqrt(r)) * np.random.randn(r * D, 1)
PrN = normP.reshape(r, D, order='F')
Xp = np.matmul(PrN, X)
if type == 'BernoulliProj':
bp = np.random.rand(r * D, 1)
Bp = (1.0 / math.sqrt(r)) * (bp >= .5) - (1.0 / math.sqrt(r)) * (bp < .5)
PrB = Bp.reshape(r, D, order='F')
Xp = np.matmul(PrB, X)
return Xp
示例3: SpectralClustering
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import matmul [as 別名]
def SpectralClustering(CKSym, n):
# This is direct port of JHU vision lab code. Could probably use sklearn SpectralClustering.
CKSym = CKSym.astype(float)
N, _ = CKSym.shape
MAXiter = 1000 # Maximum number of iterations for KMeans
REPlic = 20 # Number of replications for KMeans
DN = np.diag(np.divide(1, np.sqrt(np.sum(CKSym, axis=0) + np.finfo(float).eps)))
LapN = identity(N).toarray().astype(float) - np.matmul(np.matmul(DN, CKSym), DN)
_, _, vN = np.linalg.svd(LapN)
vN = vN.T
kerN = vN[:, N - n:N]
normN = np.sqrt(np.sum(np.square(kerN), axis=1))
kerNS = np.divide(kerN, normN.reshape(len(normN), 1) + np.finfo(float).eps)
km = KMeans(n_clusters=n, n_init=REPlic, max_iter=MAXiter, n_jobs=-1).fit(kerNS)
return km.labels_
示例4: _evaluate
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import matmul [as 別名]
def _evaluate(self, X, out, *args, **kwargs):
if self.w == 0:
X1 = X[:, 0]
X2 = X[:, 1]
else:
# If rotated, we rotate it back by applying the inverted rotation matrix to X
Y = np.array([np.matmul(self.IRM, x) for x in X])
X1 = Y[:, 0]
X2 = Y[:, 1]
a, b, c = self.a, self.b, self.c
t1_hat = sign(X1) * ceil((abs(X1) - a - c / 2) / (2 * a + c))
t2_hat = sign(X2) * ceil((abs(X2) - b / 2) / b)
one = ones(len(X))
t1 = sign(t1_hat) * min(np.vstack((abs(t1_hat), one)), axis=0)
t2 = sign(t2_hat) * min(np.vstack((abs(t2_hat), one)), axis=0)
p1 = X1 - t1 * c
p2 = X2 - t2 * b
f1 = (p1 + a) ** 2 + p2 ** 2
f2 = (p1 - a) ** 2 + p2 ** 2
out["F"] = np.vstack((f1, f2)).T
示例5: _calc_pareto_set
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import matmul [as 別名]
def _calc_pareto_set(self, n_pareto_points=500):
# The SYM-PART test problem has 9 equivalent Pareto subsets.
h = int(n_pareto_points / 9)
PS = zeros((h * 9, self.n_var))
cnt = 0
for row in [-1, 0, 1]:
for col in [1, 0, -1]:
X1 = np.linspace(row * self.c - self.a, row * self.c + self.a, h)
X2 = np.tile(col * self.b, h)
PS[cnt * h:cnt * h + h, :] = np.vstack((X1, X2)).T
cnt = cnt + 1
if self.w != 0:
# If rotated, we apply the rotation matrix to PS
# Calculate the rotation matrix
RM = np.array([
[cos(self.w), -sin(self.w)],
[sin(self.w), cos(self.w)]
])
PS = np.array([np.matmul(RM, x) for x in PS])
return PS
示例6: overlap_ni
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import matmul [as 別名]
def overlap_ni(me, sp1,R1, sp2,R2, **kw):
"""
Computes overlap for an atom pair. The atom pair is given by a pair of species indices
and the coordinates of the atoms.
Args:
sp1,sp2 : specie indices, and
R1,R2 : respective coordinates in Bohr, atomic units
Result:
matrix of orbital overlaps
The procedure uses the numerical integration in coordinate space.
"""
from pyscf.nao.m_ao_matelem import build_3dgrid
from pyscf.nao.m_ao_eval_libnao import ao_eval_libnao as ao_eval #_libnao
grids = build_3dgrid(me, sp1, R1, sp2, R2, **kw)
ao1 = ao_eval(me.ao1, R1, sp1, grids.coords)
ao1 = ao1 * grids.weights
ao2 = ao_eval(me.ao2, R2, sp2, grids.coords)
overlaps = np.einsum("ij,kj->ik", ao1, ao2) # overlaps = np.matmul(ao1, ao2.T)
return overlaps
示例7: get_3d_box_batch
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import matmul [as 別名]
def get_3d_box_batch(box_size, heading_angle, center):
''' box_size: [x1,x2,...,xn,3]
heading_angle: [x1,x2,...,xn]
center: [x1,x2,...,xn,3]
Return:
[x1,x3,...,xn,8,3]
'''
input_shape = heading_angle.shape
R = roty_batch(heading_angle)
l = np.expand_dims(box_size[...,0], -1) # [x1,...,xn,1]
w = np.expand_dims(box_size[...,1], -1)
h = np.expand_dims(box_size[...,2], -1)
corners_3d = np.zeros(tuple(list(input_shape)+[8,3]))
corners_3d[...,:,0] = np.concatenate((l/2,l/2,-l/2,-l/2,l/2,l/2,-l/2,-l/2), -1)
corners_3d[...,:,1] = np.concatenate((h/2,h/2,h/2,h/2,-h/2,-h/2,-h/2,-h/2), -1)
corners_3d[...,:,2] = np.concatenate((w/2,-w/2,-w/2,w/2,w/2,-w/2,-w/2,w/2), -1)
tlist = [i for i in range(len(input_shape))]
tlist += [len(input_shape)+1, len(input_shape)]
corners_3d = np.matmul(corners_3d, np.transpose(R, tuple(tlist)))
corners_3d += np.expand_dims(center, -2)
return corners_3d
示例8: rotate_molecule
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import matmul [as 別名]
def rotate_molecule(path, target_path, count=10):
# Load dataset
mols = Chem.SDMolSupplier(path)
rotated_mols = []
print("Loaded {} Molecules from {}".format(len(mols), path))
print("Rotating Molecules...")
for mol in mols:
for _ in range(count):
for atom in mol.GetAtoms():
atom_idx = atom.GetIdx()
pos = list(mol.GetConformer().GetAtomPosition(atom_idx))
pos_rotated = np.matmul(random_rotation_matrix(), pos)
mol.GetConformer().SetAtomPosition(atom_idx, pos_rotated)
rotated_mols.append(mol)
w = Chem.SDWriter(target_path)
for m in rotated_mols:
if m is not None:
w.write(m)
print("Saved {} Molecules to {}".format(len(rotated_mols), target_path))
示例9: backward
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import matmul [as 別名]
def backward(self, Z, O, E, W):
outdim = W.shape[-1]
time, batch, zdim = Z.shape
indim = zdim - outdim
bwO = self.actfn.backward(O)
for t in range(time-1, -1, -1):
E[t] *= bwO[t]
deltaZ = np.dot(E[t], W.T)
E[t-1] += deltaZ[:, indim:] if t else 0.
dX = E[:, :, :indim]
nablaW = np.matmul(Z.transpose(0, 2, 1), E).sum(axis=0)
nablab = E.sum(axis=(0, 1))
return dX, nablaW, nablab
示例10: valid
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import matmul [as 別名]
def valid(A, F):
im, ic, iy, ix = A.shape
nf, fc, fy, fx = F.shape
# fx, fy, fc, nf = F.shape
recfield_size = fx * fy * fc
oy, ox = iy - fy + 1, ix - fx + 1
rfields = np.zeros((im, oy*ox, recfield_size))
Frsh = F.reshape(nf, recfield_size)
if fc != ic:
err = "Supplied filter (F) is incompatible with supplied input! (X)\n"
err += "input depth: {} != {} :filter depth".format(ic, fc)
raise ValueError(err)
for i, sy, sx in ((idx, shy, shx) for shx in range(ox) for shy in range(oy) for idx in range(im)):
rfields[i][sy*ox + sx] = A[i, :, sy:sy+fy, sx:sx+fx].ravel()
# output = np.zeros((im, oy*ox, nf))
# for m in range(im):
# output[m] = np.dot(rfields[m], Frsh.T)
output = np.matmul(rfields, Frsh.T)
output = output.transpose((0, 2, 1)).reshape((im, nf, oy, ox))
return output
示例11: _parse_gufunc_signature
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import matmul [as 別名]
def _parse_gufunc_signature(signature):
"""
Parse string signatures for a generalized universal function.
Arguments
---------
signature : string
Generalized universal function signature, e.g., ``(m,n),(n,p)->(m,p)``
for ``np.matmul``.
Returns
-------
Tuple of input and output core dimensions parsed from the signature, each
of the form List[Tuple[str, ...]].
"""
if not re.match(_SIGNATURE, signature):
raise ValueError(
'not a valid gufunc signature: {}'.format(signature))
return tuple([tuple(re.findall(_DIMENSION_NAME, arg))
for arg in re.findall(_ARGUMENT, arg_list)]
for arg_list in signature.split('->'))
示例12: test_basic_property
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import matmul [as 別名]
def test_basic_property(self):
# Check A = L L^H
shapes = [(1, 1), (2, 2), (3, 3), (50, 50), (3, 10, 10)]
dtypes = (np.float32, np.float64, np.complex64, np.complex128)
for shape, dtype in itertools.product(shapes, dtypes):
np.random.seed(1)
a = np.random.randn(*shape)
if np.issubdtype(dtype, np.complexfloating):
a = a + 1j*np.random.randn(*shape)
t = list(range(len(shape)))
t[-2:] = -1, -2
a = np.matmul(a.transpose(t).conj(), a)
a = np.asarray(a, dtype=dtype)
c = np.linalg.cholesky(a)
b = np.matmul(c, c.transpose(t).conj())
assert_allclose(b, a,
err_msg="{} {}\n{}\n{}".format(shape, dtype, a, c),
atol=500 * a.shape[0] * np.finfo(dtype).eps)
示例13: dictionary_update
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import matmul [as 別名]
def dictionary_update(self, Y: np.ndarray):
# iterate rows
D = self.dictionary.matrix
n, K = D.shape
for k in range(K):
wk = np.nonzero(self.alphas[k, :])[0]
if len(wk) == 0:
continue
D[:, k] = 0
g = np.transpose(self.alphas)[wk, k]
d = np.matmul(Y[:, wk], g) - np.matmul(D, self.alphas[:, wk]).dot(g)
d = d / np.linalg.norm(d)
g = np.matmul(Y[:, wk].T, d) - np.transpose(np.matmul(D, self.alphas[:, wk])).dot(d)
D[:, k] = d
self.alphas[k, wk] = g.T
self.dictionary = Dictionary(D)
示例14: rgb2ycbcr
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import matmul [as 別名]
def rgb2ycbcr(img, only_y=True):
'''same as matlab rgb2ycbcr
only_y: only return Y channel
Input:
uint8, [0, 255]
float, [0, 1]
'''
in_img_type = img.dtype
img.astype(np.float32)
if in_img_type != np.uint8:
img *= 255.
# convert
if only_y:
rlt = np.dot(img, [65.481, 128.553, 24.966]) / 255.0 + 16.0
else:
rlt = np.matmul(img, [[65.481, -37.797, 112.0], [128.553, -74.203, -93.786],
[24.966, 112.0, -18.214]]) / 255.0 + [16, 128, 128]
if in_img_type == np.uint8:
rlt = rlt.round()
else:
rlt /= 255.
return rlt.astype(in_img_type)
示例15: ycbcr2rgb
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import matmul [as 別名]
def ycbcr2rgb(img):
'''same as matlab ycbcr2rgb
Input:
uint8, [0, 255]
float, [0, 1]
'''
in_img_type = img.dtype
img.astype(np.float32)
if in_img_type != np.uint8:
img *= 255.
# convert
rlt = np.matmul(img, [[0.00456621, 0.00456621, 0.00456621], [0, -0.00153632, 0.00791071],
[0.00625893, -0.00318811, 0]]) * 255.0 + [-222.921, 135.576, -276.836]
if in_img_type == np.uint8:
rlt = rlt.round()
else:
rlt /= 255.
return rlt.astype(in_img_type)