本文整理汇总了Python中numpy.fill_diagonal方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.fill_diagonal方法的具体用法?Python numpy.fill_diagonal怎么用?Python numpy.fill_diagonal使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.fill_diagonal方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _calc_score
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import fill_diagonal [as 别名]
def _calc_score(self, X):
if isinstance(self.criterion, str):
if self.criterion == "maxmin":
D = cdist(X, X)
np.fill_diagonal(D, np.inf)
return np.min(D)
elif self.criterion == "correlation":
M = np.corrcoef(X.T, rowvar=True)
return -np.sum(np.tril(M, -1) ** 2)
else:
raise Exception("Unknown criterion.")
elif callable(self.criterion):
return self.criterion(X)
else:
raise Exception("Either provide a str or a function as a criterion!")
示例2: geometric_mean_var
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import fill_diagonal [as 别名]
def geometric_mean_var(z):
for row in np.eye(z.shape[1]):
if not np.any(np.all(row == z, axis=1)):
z = np.row_stack([z, row])
n_points, n_dim = z.shape
D = vectorized_cdist(z, z)
np.fill_diagonal(D, np.inf)
k = n_dim - 1
I = D.argsort(axis=1)[:, :k]
first = np.column_stack([np.arange(n_points) for _ in range(k)])
val = gmean(D[first, I], axis=1)
return val.var()
示例3: pyeeg_samp_entropy
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import fill_diagonal [as 别名]
def pyeeg_samp_entropy(X, M, R):
N = len(X)
Em = pyeeg_embed_seq(X, 1, M)[:-1]
A = np.tile(Em, (len(Em), 1, 1))
B = np.transpose(A, [1, 0, 2])
D = np.abs(A - B) # D[i,j,k] = |Em[i][k] - Em[j][k]|
InRange = np.max(D, axis=2) <= R
np.fill_diagonal(InRange, 0) # Don't count self-matches
Cm = InRange.sum(axis=0) # Probability that random M-sequences are in range
Dp = np.abs(np.tile(X[M:], (N - M, 1)) - np.tile(X[M:], (N - M, 1)).T)
Cmp = np.logical_and(Dp <= R, InRange).sum(axis=0)
# Avoid taking log(0)
Samp_En = np.log(np.sum(Cm + 1e-100) / np.sum(Cmp + 1e-100))
return Samp_En
# =============================================================================
# Entropy
# =============================================================================
示例4: _fit
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import fill_diagonal [as 别名]
def _fit(self):
# Versions using sparse matrices
# adj = nx.adjacency_matrix(self._G)
# ident = sparse.identity(len(self._G.nodes)).tocsc()
# sim = inv(ident - adj.multiply(self.beta).T) - ident
# adj = nx.adjacency_matrix(self._G)
# aux = adj.multiply(-self.beta).T
# aux.setdiag(1+aux.diagonal(), k=0)
# sim = inv(aux)
# sim.setdiag(sim.diagonal()-1)
# print(sim.nnz)
# print(adj.nnz)
# Version using dense matrices
adj = nx.adjacency_matrix(self._G)
aux = adj.T.multiply(-self.beta).todense()
np.fill_diagonal(aux, 1+aux.diagonal())
sim = np.linalg.inv(aux)
np.fill_diagonal(sim, sim.diagonal()-1)
return sim
示例5: generate_neg_edges
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import fill_diagonal [as 别名]
def generate_neg_edges(G, testing_edges_num, seed=42):
nnodes = len(G.nodes)
# Make a full graph (matrix of 1)
negG = np.ones((nnodes, nnodes))
np.fill_diagonal(negG, 0.)
# Substract existing edges from full graph
# generates negative graph
original_graph = nx.adj_matrix(G).todense()
negG = negG - original_graph
# get negative edges (nonzero entries)
neg_edges = np.where(negG > 0)
random.seed(seed) # replicability!
rng_edges = random.sample(range(neg_edges[0].size), testing_edges_num)
# return edges in (src, dst) tuple format
return list(zip(
neg_edges[0][rng_edges],
neg_edges[1][rng_edges]
))
示例6: add_noise
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import fill_diagonal [as 别名]
def add_noise(cor, epsilon=None, m=None):
if isinstance(cor, pd.DataFrame):
cor = cor.values
elif isinstance(cor, np.ndarray) is False:
cor = np.array(cor)
n = cor.shape[1]
if epsilon is None:
epsilon = 0.05
if m is None:
m = 2
np.fill_diagonal(cor, 1 - epsilon)
cor = SimulateCorrelationMatrix._generate_noise(cor, n, m, epsilon)
return cor
示例7: constant
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import fill_diagonal [as 别名]
def constant(self):
delta = np.min(self.rho) - 0.01
cormat = np.full((self.nkdim, self.nkdim), delta)
epsilon = 0.99 - np.max(self.rho)
for i in np.arange(self.k):
cor = np.full((self.nk[i], self.nk[i]), self.rho[i])
if i == 0:
cormat[0:self.nk[0], 0:self.nk[0]] = cor
if i != 0:
cormat[np.sum(self.nk[0:i]):np.sum(self.nk[0:i + 1]),
np.sum(self.nk[0:i]):np.sum(self.nk[0:i + 1])] = cor
np.fill_diagonal(cormat, 1 - epsilon)
cormat = self._generate_noise(cormat, self.nkdim, self.M, epsilon)
return cormat
示例8: toepz
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import fill_diagonal [as 别名]
def toepz(self):
cormat = np.zeros((self.nkdim, self.nkdim))
epsilon = (1 - np.max(self.rho)) / (1 + np.max(self.rho)) - .01
for i in np.arange(self.k):
t = np.insert(np.power(self.rho[i], np.arange(1, self.nk[i])), 0, 1)
cor = toeplitz(t)
if i == 0:
cormat[0:self.nk[0], 0:self.nk[0]] = cor
if i != 0:
cormat[np.sum(self.nk[0:i]):np.sum(self.nk[0:i + 1]),
np.sum(self.nk[0:i]):np.sum(self.nk[0:i + 1])] = cor
np.fill_diagonal(cormat, 1 - epsilon)
cormat = self._generate_noise(cormat, self.nkdim, self.M, epsilon)
return cormat
示例9: hub
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import fill_diagonal [as 别名]
def hub(self):
cormat = np.zeros((self.nkdim, self.nkdim))
for i in np.arange(self.k):
cor = toeplitz(self._fill_hub_matrix(self.rho[i, 0], self.rho[i, 1], self.power, self.nk[i]))
if i == 0:
cormat[0:self.nk[0], 0:self.nk[0]] = cor
if i != 0:
cormat[np.sum(self.nk[0:i]):np.sum(self.nk[0:i + 1]),
np.sum(self.nk[0:i]):np.sum(self.nk[0:i + 1])] = cor
tau = (np.max(self.rho[i]) - np.min(self.rho[i])) / (self.nk[i] - 2)
epsilon = 0.08 #(1 - np.min(rho) - 0.75 * np.min(tau)) - 0.01
np.fill_diagonal(cormat, 1 - epsilon)
cormat = self._generate_noise(cormat, self.nkdim, self.M, epsilon)
return cormat
示例10: grad
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import fill_diagonal [as 别名]
def grad(self, inp, cost_grad):
"""
Notes
-----
The gradient is currently implemented for matrices only.
"""
a, val = inp
grad = cost_grad[0]
if (a.dtype.startswith('complex')):
return [None, None]
elif a.ndim > 2:
raise NotImplementedError('%s: gradient is currently implemented'
' for matrices only' %
self.__class__.__name__)
wr_a = fill_diagonal(grad, 0) # valid for any number of dimensions
# diag is only valid for matrices
wr_val = theano.tensor.nlinalg.diag(grad).sum()
return [wr_a, wr_val]
示例11: test_perform
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import fill_diagonal [as 别名]
def test_perform(self):
x = tensor.matrix()
y = tensor.scalar()
f = function([x, y], fill_diagonal(x, y))
for shp in [(8, 8), (5, 8), (8, 5)]:
a = numpy.random.rand(*shp).astype(config.floatX)
val = numpy.cast[config.floatX](numpy.random.rand())
out = f(a, val)
# We can't use numpy.fill_diagonal as it is bugged.
assert numpy.allclose(numpy.diag(out), val)
assert (out == val).sum() == min(a.shape)
# test for 3d tensor
a = numpy.random.rand(3, 3, 3).astype(config.floatX)
x = tensor.tensor3()
y = tensor.scalar()
f = function([x, y], fill_diagonal(x, y))
val = numpy.cast[config.floatX](numpy.random.rand() + 10)
out = f(a, val)
# We can't use numpy.fill_diagonal as it is bugged.
assert out[0, 0, 0] == val
assert out[1, 1, 1] == val
assert out[2, 2, 2] == val
assert (out == val).sum() == min(a.shape)
示例12: perform
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import fill_diagonal [as 别名]
def perform(self, node, inputs, outputs):
# Kalbfleisch and Lawless, J. Am. Stat. Assoc. 80 (1985) Equation 3.4
# Kind of... You need to do some algebra from there to arrive at
# this expression.
(A, gA) = inputs
(out,) = outputs
w, V = scipy.linalg.eig(A, right=True)
U = scipy.linalg.inv(V).T
exp_w = numpy.exp(w)
X = numpy.subtract.outer(exp_w, exp_w) / numpy.subtract.outer(w, w)
numpy.fill_diagonal(X, exp_w)
Y = U.dot(V.T.dot(gA).dot(U) * X).dot(V.T)
with warnings.catch_warnings():
warnings.simplefilter("ignore", numpy.ComplexWarning)
out[0] = Y.astype(A.dtype)
示例13: test_cov_nearest_factor_homog_sparse
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import fill_diagonal [as 别名]
def test_cov_nearest_factor_homog_sparse(self):
d = 100
for dm in 1,2:
# Construct a test matrix with exact factor structure
X = np.zeros((d,dm), dtype=np.float64)
x = np.linspace(0, 2*np.pi, d)
for j in range(dm):
X[:,j] = np.sin(x*(j+1))
mat = np.dot(X, X.T)
np.fill_diagonal(mat, np.diag(mat) + 3.1)
# Fit to dense
rslt = cov_nearest_factor_homog(mat, dm)
mat1 = rslt.to_matrix()
# Fit to sparse
smat = sparse.csr_matrix(mat)
rslt = cov_nearest_factor_homog(smat, dm)
mat2 = rslt.to_matrix()
assert_allclose(mat1, mat2, rtol=0.25, atol=1e-3)
示例14: __init__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import fill_diagonal [as 别名]
def __init__(self, one_body, two_body, constant=0.):
if two_body.dtype != numpy.float:
raise ValueError('Two-body tensor has invalid dtype. Expected {} '
'but was {}'.format(numpy.float, two_body.dtype))
if not numpy.allclose(two_body, two_body.T):
raise ValueError('Two-body tensor must be symmetric.')
if not numpy.allclose(one_body, one_body.T.conj()):
raise ValueError('One-body tensor must be Hermitian.')
# Move the diagonal of two_body to one_body
diag_indices = numpy.diag_indices(one_body.shape[0])
one_body[diag_indices] += two_body[diag_indices]
numpy.fill_diagonal(two_body, 0.)
self.one_body = one_body
self.two_body = two_body
self.constant = constant
示例15: LagrangeGaussLobatto
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import fill_diagonal [as 别名]
def LagrangeGaussLobatto(C,xi):
from Florence.QuadratureRules import GaussLobattoQuadrature
n = C+2
ranger = np.arange(n)
eps = GaussLobattoQuadrature(n)[0][:,0]
A = np.zeros((n,n))
A[:,0] = 1.
for i in range(1,n):
A[:,i] = eps**i
# A1[:,1:] = np.array([eps**i for i in range(1,n)]).T[0,:,:]
RHS = np.zeros((n,n))
np.fill_diagonal(RHS,1)
coeff = np.linalg.solve(A,RHS)
xis = np.ones(n)*xi**ranger
N = np.dot(coeff.T,xis)
# dN = np.einsum('i,ij,i',1+ranger[:-1],coeff[1:,:],xis[:-1])
dN = np.dot(coeff[1:,:].T,xis[:-1]*(1+ranger[:-1]))
return (N,dN,eps)