本文整理汇总了Python中numpy.triu_indices方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.triu_indices方法的具体用法?Python numpy.triu_indices怎么用?Python numpy.triu_indices使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.triu_indices方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _do_continue
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import triu_indices [as 别名]
def _do_continue(self, algorithm):
do_continue = self.default.do_continue(algorithm)
# if the default says do not continue just follow that
if not do_continue:
return False
# additionally check for degenerated simplex
else:
X = algorithm.pop.get("X")
# degenerated simplex - get all edges and minimum and maximum length
D = vectorized_cdist(X, X)
val = D[np.triu_indices(len(X), 1)]
min_e, max_e = val.min(), val.max()
# either if the maximum length is very small or the ratio is degenerated
is_degenerated = max_e < 1e-16 or min_e / max_e < 1e-16
return not is_degenerated
示例2: __init__
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import triu_indices [as 别名]
def __init__(self, features, using_cache=False, identity_init=True, eps=1e-3):
super().__init__(features, using_cache)
self.eps = eps
self.lower_indices = np.tril_indices(features, k=-1)
self.upper_indices = np.triu_indices(features, k=1)
self.diag_indices = np.diag_indices(features)
n_triangular_entries = ((features - 1) * features) // 2
self.lower_entries = nn.Parameter(torch.zeros(n_triangular_entries))
self.upper_entries = nn.Parameter(torch.zeros(n_triangular_entries))
self.unconstrained_upper_diag = nn.Parameter(torch.zeros(features))
self._initialize(identity_init)
示例3: ut_dense
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import triu_indices [as 别名]
def ut_dense(preds_ut, diagonal_offset):
"""Construct dense prediction matrix from upper triangular."""
ut_len, num_targets = preds_ut.shape
# infer original sequence length
seq_len = int(np.sqrt(2*ut_len + 0.25) - 0.5)
seq_len += diagonal_offset
# get triu indexes
ut_indexes = np.triu_indices(seq_len, diagonal_offset)
assert(len(ut_indexes[0]) == ut_len)
# assign to dense matrix
preds_dense = np.zeros(shape=(seq_len,seq_len,num_targets), dtype=preds_ut.dtype)
preds_dense[ut_indexes] = preds_ut
# symmetrize
preds_dense += np.transpose(preds_dense, axes=[1,0,2])
return preds_dense
示例4: pairwise_distance_np
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import triu_indices [as 别名]
def pairwise_distance_np(feature, squared=False):
"""Computes the pairwise distance matrix in numpy.
Args:
feature: 2-D numpy array of size [number of data, feature dimension]
squared: Boolean. If true, output is the pairwise squared euclidean
distance matrix; else, output is the pairwise euclidean distance matrix.
Returns:
pairwise_distances: 2-D numpy array of size
[number of data, number of data].
"""
triu = np.triu_indices(feature.shape[0], 1)
upper_tri_pdists = np.linalg.norm(feature[triu[1]] - feature[triu[0]], axis=1)
if squared:
upper_tri_pdists **= 2.
num_data = feature.shape[0]
pairwise_distances = np.zeros((num_data, num_data))
pairwise_distances[np.triu_indices(num_data, 1)] = upper_tri_pdists
# Make symmetrical.
pairwise_distances = pairwise_distances + pairwise_distances.T - np.diag(
pairwise_distances.diagonal())
return pairwise_distances
示例5: _get_lvec
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import triu_indices [as 别名]
def _get_lvec(labels):
"""
Constructs a label vector for an arbitrary number of labels
Assumes that our model is quadratic in the labels
Parameters
----------
labels: numpy ndarray
pivoted label values for one star
Returns
-------
lvec: numpy ndarray
label vector
"""
nlabels = len(labels)
# specialized to second-order model
linear_terms = labels
quadratic_terms = np.outer(linear_terms,
linear_terms)[np.triu_indices(nlabels)]
lvec = np.hstack((linear_terms, quadratic_terms))
return lvec
示例6: compare_ordered
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import triu_indices [as 别名]
def compare_ordered(vals, alpha):
'''simple ordered sequential comparison of means
vals : array_like
means or rankmeans for independent groups
incomplete, no return, not used yet
'''
vals = np.asarray(vals)
alphaf = alpha # Notation ?
sortind = np.argsort(vals)
pvals = vals[sortind]
sortrevind = sortind.argsort()
ntests = len(vals)
#alphacSidak = 1 - np.power((1. - alphaf), 1./ntests)
#alphacBonf = alphaf / float(ntests)
v1, v2 = np.triu_indices(ntests, 1)
#v1,v2 have wrong sequence
for i in range(4):
for j in range(4,i, -1):
print(i,j)
示例7: _hessian_geom
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import triu_indices [as 别名]
def _hessian_geom(self, params):
exog = self.exog
y = self.endog[:,None]
mu = self.predict(params)[:,None]
# for dl/dparams dparams
dim = exog.shape[1]
hess_arr = np.empty((dim, dim))
const_arr = mu*(1+y)/(mu+1)**2
for i in range(dim):
for j in range(dim):
if j > i:
continue
hess_arr[i,j] = np.sum(-exog[:,i,None] * exog[:,j,None] *
const_arr, axis=0)
tri_idx = np.triu_indices(dim, k=1)
hess_arr[tri_idx] = hess_arr.T[tri_idx]
return hess_arr
示例8: _helmert_contrast
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import triu_indices [as 别名]
def _helmert_contrast(self, levels):
n = len(levels)
#http://www.ats.ucla.edu/stat/sas/webbooks/reg/chapter5/sasreg5.htm#HELMERT
#contr = np.eye(n - 1)
#int_range = np.arange(n - 1., 1, -1)
#denom = np.repeat(int_range, np.arange(n - 2, 0, -1))
#contr[np.tril_indices(n - 1, -1)] = -1. / denom
#http://www.ats.ucla.edu/stat/r/library/contrast_coding.htm#HELMERT
#contr = np.zeros((n - 1., n - 1))
#int_range = np.arange(n, 1, -1)
#denom = np.repeat(int_range[:-1], np.arange(n - 2, 0, -1))
#contr[np.diag_indices(n - 1)] = (int_range - 1.) / int_range
#contr[np.tril_indices(n - 1, -1)] = -1. / denom
#contr = np.vstack((contr, -1./int_range))
#r-like
contr = np.zeros((n, n - 1))
contr[1:][np.diag_indices(n - 1)] = np.arange(1, n)
contr[np.triu_indices(n - 1)] = -1
return contr
示例9: _diff_contrast
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import triu_indices [as 别名]
def _diff_contrast(self, levels):
nlevels = len(levels)
contr = np.zeros((nlevels, nlevels-1))
int_range = np.arange(1, nlevels)
upper_int = np.repeat(int_range, int_range)
row_i, col_i = np.triu_indices(nlevels-1)
# we want to iterate down the columns not across the rows
# it would be nice if the index functions had a row/col order arg
col_order = np.argsort(col_i)
contr[row_i[col_order],
col_i[col_order]] = (upper_int-nlevels)/float(nlevels)
lower_int = np.repeat(int_range, int_range[::-1])
row_i, col_i = np.tril_indices(nlevels-1)
# we want to iterate down the columns not across the rows
col_order = np.argsort(col_i)
contr[row_i[col_order]+1, col_i[col_order]] = lower_int/float(nlevels)
return contr
示例10: pairwise_distances
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import triu_indices [as 别名]
def pairwise_distances(feature, squared=True):
"""Computes the pairwise distance matrix in numpy.
Args:
feature: 2-D numpy array of size [number of data, feature dimension]
squared: Boolean. If true, output is the pairwise squared euclidean
distance matrix; else, output is the pairwise euclidean distance matrix.
Returns:
pdists: 2-D numpy array of size
[number of data, number of data].
"""
triu = np.triu_indices(feature.shape[0], 1)
upper_tri_pdists = np.linalg.norm(feature[triu[1]] - feature[triu[0]], axis=1)
if squared:
upper_tri_pdists **= 2.
num_data = feature.shape[0]
pdists = np.zeros((num_data, num_data))
pdists[np.triu_indices(num_data, 1)] = upper_tri_pdists
# Make symmetrical.
pdists = pdists + pdists.T - np.diag(
pdists.diagonal())
return pdists
示例11: test_idxiter
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import triu_indices [as 别名]
def test_idxiter():
n_channels = data.shape[0]
# Upper-triangular part, including diag
idx0, idx1 = np.triu_indices(n_channels)
triu_indices = np.array([np.arange(idx0.size), idx0, idx1])
triu_indices2 = np.array(list(_idxiter(n_channels, include_diag=True)))
# Upper-triangular part, without diag
idx2, idx3 = np.triu_indices(n_channels, 1)
triu_indices_nodiag = np.array([np.arange(idx2.size), idx2, idx3])
triu_indices2_nodiag = np.array(list(_idxiter(n_channels,
include_diag=False)))
assert_almost_equal(triu_indices, triu_indices2.transpose())
assert_almost_equal(triu_indices_nodiag, triu_indices2_nodiag.transpose())
# Upper and lower-triangular parts, without diag
expected = [(i, j) for _, (i, j) in
enumerate(np.ndindex((n_channels, n_channels))) if i != j]
assert_equal(np.array([(i, j) for _, i, j in _idxiter(n_channels,
triu=False)]),
expected)
示例12: pairwise_distance_np
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import triu_indices [as 别名]
def pairwise_distance_np(feature, squared=False):
"""Computes the pairwise distance matrix in numpy.
Args:
feature: 2-D numpy array of size [number of data, feature dimension]
squared: Boolean. If true, output is the pairwise squared euclidean
distance matrix; else, output is the pairwise euclidean distance matrix.
Returns:
pairwise_distances: 2-D numpy array of size
[number of data, number of data].
"""
triu = np.triu_indices(feature.shape[0], 1)
upper_tri_pdists = np.linalg.norm(feature[triu[1]] - feature[triu[0]], axis=1)
if squared:
upper_tri_pdists **= 2.
num_data = feature.shape[0]
pairwise_distances = np.zeros((num_data, num_data))
pairwise_distances[np.triu_indices(num_data, 1)] = upper_tri_pdists
# Make symmetrical.
pairwise_distances = pairwise_distances + pairwise_distances.T - np.diag(
pairwise_distances.diagonal())
return pairwise_distances
示例13: from_tri_2_sym
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import triu_indices [as 别名]
def from_tri_2_sym(tri, dim):
"""convert a upper triangular matrix in 1D format
to 2D symmetric matrix
Parameters
----------
tri: 1D array
Contains elements of upper triangular matrix
dim : int
The dimension of target matrix.
Returns
-------
symm : 2D array
Symmetric matrix in shape=[dim, dim]
"""
symm = np.zeros((dim, dim))
symm[np.triu_indices(dim)] = tri
return symm
示例14: compute_rand_index
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import triu_indices [as 别名]
def compute_rand_index(emb, labels):
"""
https://en.wikipedia.org/wiki/Rand_index
"""
n = len(emb)
k = np.unique(labels).size
m = KMeans(k)
m.fit(emb)
emb_labels = m.predict(emb)
agreements = 0
for i, j in zip(*np.triu_indices(n, 1)):
emb_same = emb_labels[i] == emb_labels[j]
gt_same = labels[i] == labels[j]
if emb_same == gt_same:
agreements += 1
return float(agreements) / (n * (n-1) / 2)
示例15: predict
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import triu_indices [as 别名]
def predict(self, m, s=None, t=None):
D = m.shape[0]
if t is not None:
self.t = t
t = self.t
u, z, I, L = self.u_nominal, self.z_nominal, self.I_, self.L_
if s is None:
s = np.zeros((D, D))
# construct flattened state covariance vector
z_t = tt_.concatenate([m.flatten(), s[self.triu_indices]])
# compute control
u_t = u[t] + I[t] + L[t].dot(z_t - z[t])
# limit the controller output
#u_t = tt.clip(u_t, -self.maxU, self.maxU)
U = u_t.shape[0]
self.t += 1
return u_t, tt_.zeros((U, U)), tt_.zeros((D, U))