本文整理汇总了Python中numpy.diag方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.diag方法的具体用法?Python numpy.diag怎么用?Python numpy.diag使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.diag方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_bitmap_mask_resize
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diag [as 别名]
def test_bitmap_mask_resize():
# resize with empty bitmap masks
raw_masks = dummy_raw_bitmap_masks((0, 28, 28))
bitmap_masks = BitmapMasks(raw_masks, 28, 28)
resized_masks = bitmap_masks.resize((56, 72))
assert len(resized_masks) == 0
assert resized_masks.height == 56
assert resized_masks.width == 72
# resize with bitmap masks contain 1 instances
raw_masks = np.diag(np.ones(4, dtype=np.uint8))[np.newaxis, ...]
bitmap_masks = BitmapMasks(raw_masks, 4, 4)
resized_masks = bitmap_masks.resize((8, 8))
assert len(resized_masks) == 1
assert resized_masks.height == 8
assert resized_masks.width == 8
truth = np.array([[[1, 1, 0, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 0, 0, 0, 0], [0, 0, 1, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 1, 0, 0], [0, 0, 0, 0, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 0, 1, 1]]])
assert (resized_masks.masks == truth).all()
示例2: classical_mds
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diag [as 别名]
def classical_mds(self, D):
'''
Classical multidimensional scaling
Parameters
----------
D : square 2D ndarray
Euclidean Distance Matrix (matrix containing squared distances between points
'''
# Apply MDS algorithm for denoising
n = D.shape[0]
J = np.eye(n) - np.ones((n,n))/float(n)
G = -0.5*np.dot(J, np.dot(D, J))
s, U = np.linalg.eig(G)
# we need to sort the eigenvalues in decreasing order
s = np.real(s)
o = np.argsort(s)
s = s[o[::-1]]
U = U[:,o[::-1]]
S = np.diag(s)[0:self.dim,:]
self.X = np.dot(np.sqrt(S),U.T)
示例3: spectrum_analysis
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diag [as 别名]
def spectrum_analysis(model,n,spec):
"""
sepctrum analysis
params:
n: number of modes to use\n
spec: a list of tuples (period,acceleration response)
"""
freq,mode=eigen_mode(model,n)
M_=np.dot(mode.T,model.M)
M_=np.dot(M_,mode)
K_=np.dot(mode.T,model.K)
K_=np.dot(K_,mode)
C_=np.dot(mode.T,model.C)
C_=np.dot(C_,mode)
d_=[]
for (m_,k_,c_) in zip(M_.diag(),K_.diag(),C_.diag()):
sdof=SDOFSystem(m_,k_)
T=sdof.omega_d()
d_.append(np.interp(T,spec[0],spec[1]*m_))
d=np.dot(d_,mode)
#CQC
return d
示例4: __init__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diag [as 别名]
def __init__(self):
"""Initialize variable used by Kalman Filter class
Args:
None
Return:
None
"""
self.dt = 0.005 # delta time
self.A = np.array([[1, 0], [0, 1]]) # matrix in observation equations
self.u = np.zeros((2, 1)) # previous state vector
# (x,y) tracking object center
self.b = np.array([[0], [255]]) # vector of observations
self.P = np.diag((3.0, 3.0)) # covariance matrix
self.F = np.array([[1.0, self.dt], [0.0, 1.0]]) # state transition mat
self.Q = np.eye(self.u.shape[0]) # process noise matrix
self.R = np.eye(self.b.shape[0]) # observation noise matrix
self.lastResult = np.array([[0], [255]])
示例5: train
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diag [as 别名]
def train(self):
if (self.status != 'init'):
print("Please load train data and init W first.")
return self.W
self.status = 'train'
original_X = self.train_X[:, 1:]
K = utility.Kernel.kernel_matrix(self, original_X)
I = np.diag(np.ones(self.data_num))
inverse_part = np.linalg.inv(self.lambda_p * I + K)
self.beta = np.dot(inverse_part, self.train_Y)
return self.W
示例6: _eigen_components
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diag [as 别名]
def _eigen_components(self):
components = [(0, np.diag([1, 1, 1, 0, 1, 0, 0, 1]))]
nontrivial_part = np.zeros((3, 3), dtype=np.complex128)
for ij, w in zip([(1, 2), (0, 2), (0, 1)], self.weights):
nontrivial_part[ij] = w
nontrivial_part[ij[::-1]] = w.conjugate()
assert np.allclose(nontrivial_part, nontrivial_part.conj().T)
eig_vals, eig_vecs = np.linalg.eigh(nontrivial_part)
for eig_val, eig_vec in zip(eig_vals, eig_vecs.T):
exp_factor = -eig_val / np.pi
proj = np.zeros((8, 8), dtype=np.complex128)
nontrivial_indices = np.array([3, 5, 6], dtype=np.intp)
proj[nontrivial_indices[:, np.newaxis], nontrivial_indices] = (
np.outer(eig_vec.conjugate(), eig_vec))
components.append((exp_factor, proj))
return components
示例7: test_rhf_func_gen
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diag [as 别名]
def test_rhf_func_gen():
rhf_objective, molecule, parameters, _, _ = make_h6_1_3()
ansatz, energy, _ = rhf_func_generator(rhf_objective)
assert np.isclose(molecule.hf_energy, energy(parameters))
ansatz, energy, _, opdm_func = rhf_func_generator(
rhf_objective, initial_occ_vec=[1] * 3 + [0] * 3, get_opdm_func=True)
assert np.isclose(molecule.hf_energy, energy(parameters))
test_opdm = opdm_func(parameters)
u = ansatz(parameters)
initial_opdm = np.diag([1] * 3 + [0] * 3)
final_odpm = u @ initial_opdm @ u.T
assert np.allclose(test_opdm, final_odpm)
result = rhf_minimization(rhf_objective, initial_guess=parameters)
assert np.allclose(result.x, parameters)
示例8: adjacencyToLaplacian
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diag [as 别名]
def adjacencyToLaplacian(W):
"""
adjacencyToLaplacian: Computes the Laplacian from an Adjacency matrix
Input:
W (np.array): adjacency matrix
Output:
L (np.array): Laplacian matrix
"""
# Check that the matrix is square
assert W.shape[0] == W.shape[1]
# Compute the degree vector
d = np.sum(W, axis = 1)
# And build the degree matrix
D = np.diag(d)
# Return the Laplacian
return D - W
示例9: normalizeAdjacency
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diag [as 别名]
def normalizeAdjacency(W):
"""
NormalizeAdjacency: Computes the degree-normalized adjacency matrix
Input:
W (np.array): adjacency matrix
Output:
A (np.array): degree-normalized adjacency matrix
"""
# Check that the matrix is square
assert W.shape[0] == W.shape[1]
# Compute the degree vector
d = np.sum(W, axis = 1)
# Invert the square root of the degree
d = 1/np.sqrt(d)
# And build the square root inverse degree matrix
D = np.diag(d)
# Return the Normalized Adjacency
return D @ W @ D
示例10: normalizeLaplacian
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diag [as 别名]
def normalizeLaplacian(L):
"""
NormalizeLaplacian: Computes the degree-normalized Laplacian matrix
Input:
L (np.array): Laplacian matrix
Output:
normL (np.array): degree-normalized Laplacian matrix
"""
# Check that the matrix is square
assert L.shape[0] == L.shape[1]
# Compute the degree vector (diagonal elements of L)
d = np.diag(L)
# Invert the square root of the degree
d = 1/np.sqrt(d)
# And build the square root inverse degree matrix
D = np.diag(d)
# Return the Normalized Laplacian
return D @ L @ D
示例11: get_ma_dist
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diag [as 别名]
def get_ma_dist(A, B):
Y = A.copy()
X = B.copy()
S = np.cov(X.T)
try:
SI = np.linalg.inv(S)
except:
print("Singular Matrix: using np.linalg.pinv")
SI = np.linalg.pinv(S)
mu = np.mean(X, axis=0)
diff = Y - mu
Dct_c = np.diag(diff @ SI @ diff.T)
return Dct_c
示例12: fit
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diag [as 别名]
def fit(self, X, y=None):
"""Compute the mean, whitening and dewhitening matrices.
Parameters
----------
X : array-like with shape [n_samples, n_features]
The data used to compute the mean, whitening and dewhitening
matrices.
"""
X = check_array(X, accept_sparse=None, copy=self.copy,
ensure_2d=True)
X = as_float_array(X, copy=self.copy)
self.mean_ = X.mean(axis=0)
X_ = X - self.mean_
cov = np.dot(X_.T, X_) / (X_.shape[0]-1)
U, S, _ = linalg.svd(cov)
s = np.sqrt(S.clip(self.regularization))
s_inv = np.diag(1./s)
s = np.diag(s)
self.whiten_ = np.dot(np.dot(U, s_inv), U.T)
self.dewhiten_ = np.dot(np.dot(U, s), U.T)
return self
示例13: SpectralClustering
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diag [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_
示例14: class_accuracy
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diag [as 别名]
def class_accuracy(prediction, label):
cf = confusion_matrix(prediction, label)
cls_cnt = cf.sum(axis=1)
cls_hit = np.diag(cf)
cls_acc = cls_hit / cls_cnt.astype(float)
mean_cls_acc = cls_acc.mean()
return cls_acc, mean_cls_acc
示例15: invertFast
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import diag [as 别名]
def invertFast(A, d):
"""
given an array A of shape d x k and a d x 1 vector d, computes (A * A.T + diag(d)) ^{-1}
Checked.
"""
assert(A.shape[0] == d.shape[0])
assert(d.shape[1] == 1)
k = A.shape[1]
A = np.array(A)
d_vec = np.array(d)
d_inv = np.array(1 / d_vec[:, 0])
inv_d_squared = np.dot(np.atleast_2d(d_inv).T, np.atleast_2d(d_inv))
M = np.diag(d_inv) - inv_d_squared * np.dot(np.dot(A, np.linalg.inv(np.eye(k, k) + np.dot(A.T, mult_diag(d_inv, A)))), A.T)
return M