本文整理汇总了Python中numpy.flatnonzero方法的典型用法代码示例。如果您正苦于以下问题:Python numpy.flatnonzero方法的具体用法?Python numpy.flatnonzero怎么用?Python numpy.flatnonzero使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类numpy
的用法示例。
在下文中一共展示了numpy.flatnonzero方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_clusters
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import flatnonzero [as 别名]
def get_clusters(C):
nonassigned = list(range(len(C)))
clusters = []
while nonassigned:
queue = {nonassigned[0]}
clusters.append([])
while queue:
node = queue.pop()
clusters[-1].append(node)
nonassigned.remove(node)
queue.update(n for n in np.flatnonzero(C[node]) if n in nonassigned)
C = np.zeros_like(C)
for cluster in clusters:
for i in cluster:
C[i, cluster] = True
return clusters, C
示例2: pinv
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import flatnonzero [as 别名]
def pinv(A, log=lambda _: None):
U, D, V = np.linalg.svd(A)
thre = 1e3
thre_log = 1e8
gaps = D[:-1] / D[1:]
try:
n = np.flatnonzero(gaps > thre)[0]
except IndexError:
n = len(gaps)
else:
gap = gaps[n]
if gap < thre_log:
log('Pseudoinverse gap of only: {:.1e}'.format(gap))
D[n + 1 :] = 0
D[: n + 1] = 1 / D[: n + 1]
return U.dot(np.diag(D)).dot(V)
示例3: _minor_reduce
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import flatnonzero [as 别名]
def _minor_reduce(self, ufunc):
"""Reduce nonzeros with a ufunc over the minor axis when non-empty
Warning: this does not call sum_duplicates()
Returns
-------
major_index : array of ints
Major indices where nonzero
value : array of self.dtype
Reduce result for nonzeros in each major_index
"""
major_index = np.flatnonzero(np.diff(self.indptr))
value = ufunc.reduceat(self.data,
downcast_intp_index(self.indptr[major_index]))
return major_index, value
#######################
# Getting and Setting #
#######################
示例4: test_incidence2
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import flatnonzero [as 别名]
def test_incidence2():
# Check that the cumulative incidence functions for all competing
# risks sum to the complementary survival function.
np.random.seed(2423)
n = 200
time = -np.log(np.random.uniform(size=n))
status = np.random.randint(0, 3, size=n)
ii = np.argsort(time)
time = time[ii]
status = status[ii]
ci = CumIncidenceRight(time, status)
statusa = 1*(status >= 1)
sf = SurvfuncRight(time, statusa)
x = 1 - sf.surv_prob
y = (ci.cinc[0] + ci.cinc[1])[np.flatnonzero(statusa)]
assert_allclose(x, y)
示例5: vb_elbo_grad
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import flatnonzero [as 别名]
def vb_elbo_grad(self, vb_mean, vb_sd):
"""
Returns the gradient of the model's evidence lower bound (ELBO).
"""
fep_mean, vcp_mean, vc_mean = self._unpack(vb_mean)
fep_sd, vcp_sd, vc_sd = self._unpack(vb_sd)
tm, tv = self._lp_stats(fep_mean, fep_sd, vc_mean, vc_sd)
def h(z):
u = tm + np.sqrt(tv)*z
x = np.zeros_like(u)
ii = np.flatnonzero(u > 0)
uu = u[ii]
x[ii] = 1 / (1 + np.exp(-uu))
ii = np.flatnonzero(u <= 0)
uu = u[ii]
x[ii] = np.exp(uu) / (1 + np.exp(uu))
return -x
return self.vb_elbo_grad_base(
h, tm, tv, fep_mean, vcp_mean, vc_mean, fep_sd, vcp_sd, vc_sd)
示例6: covariance_matrix
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import flatnonzero [as 别名]
def covariance_matrix(self, endog_expval, index):
if self.grid:
return self.covariance_matrix_grid(endog_expval, index)
j1, j2 = np.tril_indices(len(endog_expval))
dx = np.abs(self.time[index][j1] - self.time[index][j2])
ii = np.flatnonzero((0 < dx) & (dx <= self.max_lag))
j1 = j1[ii]
j2 = j2[ii]
dx = dx[ii]
cmat = np.eye(len(endog_expval))
cmat[j1, j2] = self.dep_params[dx - 1]
cmat[j2, j1] = self.dep_params[dx - 1]
return cmat, True
示例7: test_default_time
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import flatnonzero [as 别名]
def test_default_time(self):
# Check that the time defaults work correctly.
endog, exog, group = load_data("gee_logistic_1.csv")
# Time values for the autoregressive model
T = np.zeros(len(endog))
idx = set(group)
for ii in idx:
jj = np.flatnonzero(group == ii)
T[jj] = lrange(len(jj))
family = Binomial()
va = Autoregressive()
md1 = GEE(endog, exog, group, family=family, cov_struct=va)
mdf1 = md1.fit()
md2 = GEE(endog, exog, group, time=T, family=family,
cov_struct=va)
mdf2 = md2.fit()
assert_almost_equal(mdf1.params, mdf2.params, decimal=6)
assert_almost_equal(mdf1.standard_errors(),
mdf2.standard_errors(), decimal=6)
示例8: update_data
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import flatnonzero [as 别名]
def update_data(self):
"""
Gibbs update of the missing data values.
"""
for ix in self.patterns:
i = ix[0]
ix_miss = np.flatnonzero(self.mask[i, :])
ix_obs = np.flatnonzero(~self.mask[i, :])
mm = self.mean[ix_miss]
mo = self.mean[ix_obs]
voo = self.cov[ix_obs, :][:, ix_obs]
vmm = self.cov[ix_miss, :][:, ix_miss]
vmo = self.cov[ix_miss, :][:, ix_obs]
r = self.data[ix, :][:, ix_obs] - mo
cm = mm + np.dot(vmo, np.linalg.solve(voo, r.T)).T
cv = vmm - np.dot(vmo, np.linalg.solve(voo, vmo.T))
cs = np.linalg.cholesky(cv)
u = np.random.normal(size=(len(ix), len(ix_miss)))
self.data[np.ix_(ix, ix_miss)] = cm + np.dot(u, cs.T)
示例9: transform
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import flatnonzero [as 别名]
def transform(self, X):
"""Transform X.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Returns
-------
X_new : array-like, shape (n_samples, n_components)
"""
check_is_fitted(self, 'X_fit_')
# Compute centered gram matrix between X and training data X_fit_
K = self._centerer.transform(self._get_kernel(X, self.X_fit_))
# scale eigenvectors (properly account for null-space for dot product)
non_zeros = np.flatnonzero(self.lambdas_)
scaled_alphas = np.zeros_like(self.alphas_)
scaled_alphas[:, non_zeros] = (self.alphas_[:, non_zeros]
/ np.sqrt(self.lambdas_[non_zeros]))
# Project with a scalar product between K and the scaled eigenvectors
return np.dot(K, scaled_alphas)
示例10: get_data_by_id
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import flatnonzero [as 别名]
def get_data_by_id(self, ids):
""" Helper for getting current data values from stored identifiers
:param float|list ids: ids for which data are requested
:return: the stored ids
:rtype: np.ndarray
"""
if self.ids is None:
raise ValueError("IDs not stored in node {}".format(self.name))
if self.data is None:
raise ValueError("No data in node {}".format(self.name))
ids = np.array(ids, ndmin=1, copy=False)
found_items = np.in1d(ids, self.ids)
if not np.all(found_items):
raise ValueError("Cannot find {} among {}".format(ids[np.logical_not(found_items)],
self.name))
idx = np.empty(len(ids), dtype='int')
for k, this_id in enumerate(ids):
if self.ids.ndim > 1:
idx[k] = np.flatnonzero(np.all(self.ids == this_id, axis=1))[0]
else:
idx[k] = np.flatnonzero(self.ids == this_id)[0]
return np.array(self.data, ndmin=1)[idx]
示例11: subset_test
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import flatnonzero [as 别名]
def subset_test(lin_op):
""" Test that subsetting a linear operator produces the correct outputs.
:param LinearOperator lin_op: the linear operator
"""
sub_idx = np.random.rand(lin_op.shape[0], 1) > 0.5
# make sure at least one element included
sub_idx[np.random.randint(0, len(sub_idx))] = True
sub_idx = np.flatnonzero(sub_idx)
sub_lin_op = undertest.get_subset_lin_op(lin_op, sub_idx)
# test projection to subset of indices
x = np.random.randn(lin_op.shape[1], np.random.randint(1, 3))
np.testing.assert_array_almost_equal(sub_lin_op * x, (lin_op * x)[sub_idx, :])
# test back projection from subset of indices
y = np.random.randn(len(sub_idx), np.random.randint(1, 3))
z = np.zeros((lin_op.shape[0], y.shape[1]))
z[sub_idx] = y
np.testing.assert_array_almost_equal(sub_lin_op.rmatvec(y), lin_op.rmatvec(z))
示例12: test_get_data_by_id
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import flatnonzero [as 别名]
def test_get_data_by_id(self):
dim, data, cpd, ids = self.gen_data()
node = undertest.Node(name='test node', data=data, cpd=cpd, ids=ids)
# test setting of ids
np.testing.assert_array_equal(node.ids, ids)
# test for one id
idx = np.random.randint(0, dim)
np.testing.assert_array_equal(node.get_data_by_id(ids[idx]).ravel(), node.data[idx])
# test for a random set of ids
ids_subset = np.random.choice(ids, dim, replace=True)
np.testing.assert_array_equal(node.get_data_by_id(ids_subset),
[node.data[np.flatnonzero(ids == x)[0]] for x in ids_subset])
# test for all ids
self.assertEqual(node.get_all_data_and_ids(), {x: node.get_data_by_id(x) for x in ids})
# test when data are singleton
dim, _, cpd, ids = self.gen_data(dim=1)
node = undertest.Node(name='test node', data=1, cpd=cpd, ids=ids)
self.assertEqual(node.get_all_data_and_ids(), {x: node.get_data_by_id(x) for x in ids})
示例13: fill_nan
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import flatnonzero [as 别名]
def fill_nan(data):
"""
Returns the timeseries where any gaps (represented by NaN) are
filled, using a linear approximation between the neighbors.
Gaps at the beginning or end are filled with the first resp. last
valid entry
:param data: The timeseries data as a numeric sequence
:return: The filled timeseries as array
"""
# All data indices
x = np.arange(len(data))
# Valid data indices
xp = np.flatnonzero(np.isfinite(data))
# Valid data
fp = remove_nan(data)
# Interpolate missing values
return np.interp(x, xp, fp)
示例14: computeNonzeroRows
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import flatnonzero [as 别名]
def computeNonzeroRows(S, Nl = 'all'):
"""
computeNonzeroRows: Find the position of the nonzero elements of each
row of a matrix
Input:
S (np.array): matrix
Nl (int or 'all'): number of rows to compute the nonzero elements; if
'all', then Nl = S.shape[0]. Rows are counted from the top.
Output:
nonzeroElements (list): list of size Nl where each element is an array
of the indices of the nonzero elements of the corresponding row.
"""
# Find the position of the nonzero elements of each row of the matrix S.
# Nl = 'all' means for all rows, otherwise, it will be an int.
if Nl == 'all':
Nl = S.shape[0]
assert Nl <= S.shape[0]
# Save neighborhood variable
neighborhood = []
# For each of the selected nodes
for n in range(Nl):
neighborhood += [np.flatnonzero(S[n,:])]
return neighborhood
示例15: _one_sample_positive_class_precisions
# 需要导入模块: import numpy [as 别名]
# 或者: from numpy import flatnonzero [as 别名]
def _one_sample_positive_class_precisions(self, scores, truth):
"""Calculate precisions for each true class for a single sample.
Args:
scores: np.array of (num_classes,) giving the individual classifier scores.
truth: np.array of (num_classes,) bools indicating which classes are true.
Returns:
pos_class_indices: np.array of indices of the true classes for this sample.
pos_class_precisions: np.array of precisions corresponding to each of those
classes.
"""
num_classes = scores.shape[0]
pos_class_indices = np.flatnonzero(truth > 0)
# Only calculate precisions if there are some true classes.
if not len(pos_class_indices):
return pos_class_indices, np.zeros(0)
# Retrieval list of classes for this sample.
retrieved_classes = np.argsort(scores)[::-1]
# class_rankings[top_scoring_class_index] == 0 etc.
class_rankings = np.zeros(num_classes, dtype=np.int)
class_rankings[retrieved_classes] = range(num_classes)
# Which of these is a true label?
retrieved_class_true = np.zeros(num_classes, dtype=np.bool)
retrieved_class_true[class_rankings[pos_class_indices]] = True
# Num hits for every truncated retrieval list.
retrieved_cumulative_hits = np.cumsum(retrieved_class_true)
# Precision of retrieval list truncated at each hit, in order of pos_labels.
precision_at_hits = (
retrieved_cumulative_hits[class_rankings[pos_class_indices]] /
(1 + class_rankings[pos_class_indices].astype(np.float)))
return pos_class_indices, precision_at_hits