本文整理匯總了Python中numpy.triu_indices_from方法的典型用法代碼示例。如果您正苦於以下問題:Python numpy.triu_indices_from方法的具體用法?Python numpy.triu_indices_from怎麽用?Python numpy.triu_indices_from使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類numpy
的用法示例。
在下文中一共展示了numpy.triu_indices_from方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: _featurize
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import triu_indices_from [as 別名]
def _featurize(self, mol):
"""
Calculate Coulomb matrices for molecules. If extra randomized
matrices are generated, they are treated as if they are features
for additional conformers.
Since Coulomb matrices are symmetric, only the (flattened) upper
triangular portion is returned.
Parameters
----------
mol : RDKit Mol
Molecule.
"""
features = self.coulomb_matrix(mol)
if self.upper_tri:
features = [f[np.triu_indices_from(f)] for f in features]
features = np.asarray(features)
return features
示例2: predict
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import triu_indices_from [as 別名]
def predict(self, output_dir, model_path):
x1d, x2d, name, size, iterator = self.build_input_test()
preds, logits = self.resn(x1d, x2d)
saver = tf.train.Saver()
saver.restore(self.sess, model_path)
self.sess.run(iterator.initializer,
feed_dict={self.input_tfrecord_files:self.dataset.get_chunks(RunMode.TEST)})
while True:
try:
preds_, names_, sizes_, = self.sess.run([preds, name, size])
for pred_, name_, size_ in zip(preds_, names_, sizes_):
pred_ = pred_[:size_, :size_]
#inds = np.triu_indices_from(pred_, k=1)
#pred_[(inds[1], inds[0])] = pred_[inds]
#pred_ = (pred_ + np.transpose(pred_)) / 2.0
output_path = '{}/{}.concat'.format(output_dir, name_)
np.savetxt(output_path, pred_)
except tf.errors.OutOfRangeError:
break
示例3: get_triangle
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import triu_indices_from [as 別名]
def get_triangle(hic_matrix, cut, window_len, return_mean=False):
"""
like get_cut_weight which is the 'diamond' representing the counts
from a region -window_len to +window_len from the given bin position (cut):
"""
if cut < 0 or cut > hic_matrix.matrix.shape[0]:
return None
left_idx, right_idx = get_idx_of_bins_at_given_distance(hic_matrix, cut, window_len)
def remove_lower_triangle(matrix):
"""
remove all values in the lower triangle of a matrix
"""
return matrix[np.triu_indices_from(matrix)].A1
edges_left = remove_lower_triangle(hic_matrix.matrix[left_idx:cut, :][:, left_idx:cut].todense())
edges_right = remove_lower_triangle(hic_matrix.matrix[cut:right_idx, :][:, cut:right_idx].todense())
# if cut > 1000:
# import ipdb;ipdb.set_trace()
return np.concatenate([edges_left, edges_right])
示例4: from_sym_2_tri
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import triu_indices_from [as 別名]
def from_sym_2_tri(symm):
"""convert a 2D symmetric matrix to an upper
triangular matrix in 1D format
Parameters
----------
symm : 2D array
Symmetric matrix
Returns
-------
tri: 1D array
Contains elements of upper triangular matrix
"""
inds = np.triu_indices_from(symm)
tri = symm[inds]
return tri
示例5: test_rbfize
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import triu_indices_from [as 別名]
def test_rbfize():
X = np.random.normal(size=(20, 4))
dists = euclidean_distances(X)
median = np.median(dists[np.triu_indices_from(dists, k=1)])
rbf = RBFize(gamma=.25)
res = rbf.fit_transform(dists)
assert not hasattr(res, 'median_')
assert np.allclose(res, np.exp(-.25 * dists ** 2))
rbf = RBFize(gamma=.25, squared=True)
res = rbf.fit_transform(dists)
assert np.allclose(res, np.exp(-.25 * dists))
rbf = RBFize(gamma=4, scale_by_median=True)
res = rbf.fit_transform(dists)
assert np.allclose(rbf.median_, median)
assert np.allclose(res, np.exp((-4 * median**2) * dists ** 2))
rbf = RBFize(gamma=4, scale_by_median=True, squared=True)
res = rbf.fit_transform(dists)
assert np.allclose(rbf.median_, median)
assert np.allclose(res, np.exp((-4 * median) * dists))
示例6: fit
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import triu_indices_from [as 別名]
def fit(self, X, y=None):
'''
If scale_by_median, find :attr:`median_`; otherwise, do nothing.
Parameters
----------
X : array
The raw pairwise distances.
'''
X = check_array(X)
if self.scale_by_median:
self.median_ = np.median(X[np.triu_indices_from(X, k=1)],
overwrite_input=True)
elif hasattr(self, 'median_'):
del self.median_
return self
示例7: get_net_vectors
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import triu_indices_from [as 別名]
def get_net_vectors(subject_list, kind, atlas_name="aal"):
"""
subject_list : the subject short IDs list
kind : the kind of connectivity to be used, e.g. lasso, partial correlation, correlation
atlas_name : name of the atlas used
returns:
matrix : matrix of connectivity vectors (num_subjects x num_connections)
"""
# This is an alternative implementation
networks = load_all_networks(subject_list, kind, atlas_name=atlas_name)
# Get Fisher transformed matrices
norm_networks = [np.arctanh(mat) for mat in networks]
# Get upper diagonal indices
idx = np.triu_indices_from(norm_networks[0], 1)
# Get vectorised matrices
vec_networks = [mat[idx] for mat in norm_networks]
# Each subject should be a row of the matrix
matrix = np.vstack(vec_networks)
return matrix
示例8: __init__
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import triu_indices_from [as 別名]
def __init__(
self, relative_rates, equilibrium_frequencies=None, root_distribution=None
):
alleles = _ACGT_ALLELES
assert len(relative_rates) == 6
if equilibrium_frequencies is None:
equilibrium_frequencies = [0.25, 0.25, 0.25, 0.25]
if root_distribution is None:
root_distribution = equilibrium_frequencies
transition_matrix = np.zeros((4, 4))
# relative_rates: [A->C, A->G,A->T,C->G,C->T,G->T]
tri_upper = np.triu_indices_from(transition_matrix, k=1)
transition_matrix[tri_upper] = relative_rates
transition_matrix += transition_matrix.T
transition_matrix *= equilibrium_frequencies
row_sums = transition_matrix.sum(axis=1)
transition_matrix = transition_matrix / max(row_sums)
row_sums = transition_matrix.sum(axis=1, dtype="float64")
np.fill_diagonal(transition_matrix, 1.0 - row_sums)
super().__init__(alleles, root_distribution, transition_matrix)
示例9: tangent_space
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import triu_indices_from [as 別名]
def tangent_space(covmats, Cref):
"""Project a set of covariance matrices in the tangent space according to the given reference point Cref
:param covmats: Covariance matrices set, Ntrials X Nchannels X Nchannels
:param Cref: The reference covariance matrix
:returns: the Tangent space , a matrix of Ntrials X (Nchannels*(Nchannels+1)/2)
"""
Nt, Ne, Ne = covmats.shape
Cm12 = invsqrtm(Cref)
idx = numpy.triu_indices_from(Cref)
T = numpy.empty((Nt, Ne * (Ne + 1) / 2))
coeffs = (
numpy.sqrt(2) *
numpy.triu(
numpy.ones(
(Ne,
Ne)),
1) +
numpy.eye(Ne))[idx]
for index in range(Nt):
tmp = numpy.dot(numpy.dot(Cm12, covmats[index, :, :]), Cm12)
tmp = logm(tmp)
T[index, :] = numpy.multiply(coeffs, tmp[idx])
return T
示例10: untangent_space
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import triu_indices_from [as 別名]
def untangent_space(T, Cref):
"""Project a set of Tangent space vectors in the manifold according to the given reference point Cref
:param T: the Tangent space , a matrix of Ntrials X (Nchannels*(Nchannels+1)/2)
:param Cref: The reference covariance matrix
:returns: A set of Covariance matrix, Ntrials X Nchannels X Nchannels
"""
Nt, Nd = T.shape
Ne = int((numpy.sqrt(1 + 8 * Nd) - 1) / 2)
C12 = sqrtm(Cref)
idx = numpy.triu_indices_from(Cref)
covmats = numpy.empty((Nt, Ne, Ne))
covmats[:, idx[0], idx[1]] = T
for i in range(Nt):
covmats[i] = numpy.diag(numpy.diag(covmats[i])) + numpy.triu(
covmats[i], 1) / numpy.sqrt(2) + numpy.triu(covmats[i], 1).T / numpy.sqrt(2)
covmats[i] = expm(covmats[i])
covmats[i] = numpy.dot(numpy.dot(C12, covmats[i]), C12)
return covmats
示例11: _fractal_correlation_Corr_Dim
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import triu_indices_from [as 別名]
def _fractal_correlation_Corr_Dim(embedded, r_vals, dist):
"""References
-----------
- `Corr_Dim <https://github.com/jcvasquezc/Corr_Dim>`_
"""
ED = dist[np.triu_indices_from(dist, k=1)]
Npairs = (len(embedded[1, :])) * ((len(embedded[1, :]) - 1))
corr = np.zeros(len(r_vals))
for i, r in enumerate(r_vals):
N = np.where(((ED < r) & (ED > 0)))
corr[i] = len(N[0]) / Npairs
omit_pts = 1
k1 = omit_pts
k2 = len(r_vals) - omit_pts
r_vals = r_vals[k1:k2]
corr = corr[k1:k2]
return r_vals, corr
# =============================================================================
# Utilities
# =============================================================================
示例12: _exec
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import triu_indices_from [as 別名]
def _exec(self):
M = np.zeros((self.labels.size, self.labels.size))
with closing(Pool(processes=self.n_threads)) as pool:
values = pool.map(self._partial_mutinf,
combinations(self.labels, 2))
pool.terminate()
idx = np.triu_indices_from(M)
M[idx] = values
return M + M.T - np.diag(M.diagonal())
示例13: test_tensor_iterator
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import triu_indices_from [as 別名]
def test_tensor_iterator():
a = np.arange(16).reshape((4, 4))
test_tensor = Tensor(tensor=a)
assert np.allclose(test_tensor.data, a)
assert test_tensor.size == 16
assert isinstance(test_tensor.basis, Bijection)
a_triu = a[np.triu_indices_from(a)]
a_tril = a[np.tril_indices_from(a)]
counter = 0
for val, idx in test_tensor.utri_iterator():
assert val == a[tuple(idx)]
assert val == a_triu[counter]
counter += 1
assert counter == 4 * (4 + 1) / 2
counter = 0
for val, idx in test_tensor.ltri_iterator():
assert val == a[tuple(idx)]
assert val == a_tril[counter]
counter += 1
assert counter == 4 * (4 + 1) / 2
counter = 0
for val, idx in test_tensor.all_iterator():
assert val == a[tuple(idx)]
counter += 1
assert np.allclose(test_tensor.vectorize(), a.reshape((-1, 1), order='C'))
with pytest.raises(TypeError):
list(test_tensor._iterator('blah'))
示例14: test_simple_hessenberg_trafo
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import triu_indices_from [as 別名]
def test_simple_hessenberg_trafo():
# Made up discrete time TF
G = Transfer([1., -8., 28., -58., 67., -30.],
poly([1, 2, 3., 2, 3., 4, 1 + 1j, 1 - 1j]), dt=0.1)
H, _ = hessenberg_realization(G, compute_T=1, form='c', invert=1)
assert_(not np.any(H.a[triu_indices_from(H.a, k=2)]))
assert_(not np.any(H.b[:-1, 0]))
H = hessenberg_realization(G, form='o', invert=1)
assert_(not np.any(H.c[0, :-1]))
assert_(not np.any(H.a.T[triu_indices_from(H.a, k=2)]))
示例15: lowertosymmetric
# 需要導入模塊: import numpy [as 別名]
# 或者: from numpy import triu_indices_from [as 別名]
def lowertosymmetric(a, copy=False):
a = np.copy(a) if copy else a
idxs = np.triu_indices_from(a)
a[idxs] = a[(idxs[1], idxs[0])]