本文整理汇总了Python中scipy.where方法的典型用法代码示例。如果您正苦于以下问题:Python scipy.where方法的具体用法?Python scipy.where怎么用?Python scipy.where使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类scipy
的用法示例。
在下文中一共展示了scipy.where方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: getLeadingEigenvector
# 需要导入模块: import scipy [as 别名]
# 或者: from scipy import where [as 别名]
def getLeadingEigenvector(A, normalized=True, lanczosVecs = 15, maxiter = 1000):
"""Compute normalized leading eigenvector of a given matrix A.
@param A: sparse matrix for which leading eigenvector will be computed
@param normalized: wheter or not to normalize. Default is C{True}
@param lanczosVecs: number of Lanczos vectors to be used in the approximate
calculation of eigenvectors and eigenvalues. This maps to the ncv parameter
of scipy's underlying function eigs.
@param maxiter: scaling factor for the number of iterations to be used in the
approximate calculation of eigenvectors and eigenvalues. The number of iterations
passed to scipy's underlying eigs function will be n*maxiter where n is the
number of rows/columns of the Laplacian matrix.
"""
if _sparse.issparse(A) == False:
raise TypeError("A must be a sparse matrix")
# NOTE: ncv sets additional auxiliary eigenvectors that are computed
# NOTE: in order to be more confident to find the one with the largest
# NOTE: magnitude, see https://github.com/scipy/scipy/issues/4987
w, pi = _sla.eigs( A, k=1, which="LM", ncv=lanczosVecs, maxiter=maxiter)
pi = pi.reshape(pi.size,)
if normalized:
pi /= sum(pi)
return pi
示例2: getAlgebraicConnectivity
# 需要导入模块: import scipy [as 别名]
# 或者: from scipy import where [as 别名]
def getAlgebraicConnectivity(self, lanczosVecs = 15, maxiter = 20):
"""
Returns the algebraic connectivity of the higher-order network.
@param lanczosVecs: number of Lanczos vectors to be used in the approximate
calculation of eigenvectors and eigenvalues. This maps to the ncv parameter
of scipy's underlying function eigs.
@param maxiter: scaling factor for the number of iterations to be used in the
approximate calculation of eigenvectors and eigenvalues. The number of iterations
passed to scipy's underlying eigs function will be n*maxiter where n is the
number of rows/columns of the Laplacian matrix.
"""
Log.add('Calculating algebraic connectivity ... ', Severity.INFO)
L = self.getLaplacianMatrix()
# NOTE: ncv sets additional auxiliary eigenvectors that are computed
# NOTE: in order to be more confident to find the one with the largest
# NOTE: magnitude, see https://github.com/scipy/scipy/issues/4987
w = _sla.eigs( L, which="SM", k=2, ncv=lanczosVecs, return_eigenvectors=False, maxiter = maxiter )
evals_sorted = _np.sort(_np.absolute(w))
Log.add('finished.', Severity.INFO)
return _np.abs(evals_sorted[1])
示例3: get_concentration_functions
# 需要导入模块: import scipy [as 别名]
# 或者: from scipy import where [as 别名]
def get_concentration_functions(composition_table_dict):
meta = composition_table_dict["meta"]
composition_table = Table.from_dict(composition_table_dict["data"])
elements = [col for col in composition_table.columns if col not in meta]
x = composition_table["X"].values
y = composition_table["Y"].values
cats = composition_table["X"].unique()
concentration, conc, d, y_c, functions = {}, {}, {}, {}, RecursiveDict()
for el in elements:
concentration[el] = to_numeric(composition_table[el].values) / 100.0
conc[el], d[el], y_c[el] = {}, {}, {}
if meta["X"] == "category":
for i in cats:
k = "{:06.2f}".format(float(i))
y_c[el][k] = to_numeric(y[where(x == i)])
conc[el][k] = to_numeric(concentration[el][where(x == i)])
d[el][k] = interp1d(y_c[el][k], conc[el][k])
functions[el] = lambda a, b, el=el: d[el][a](b)
else:
functions[el] = interp2d(float(x), float(y), concentration[el])
return functions
示例4: mycount_garrick
# 需要导入模块: import scipy [as 别名]
# 或者: from scipy import where [as 别名]
def mycount_garrick(V):
f=s.zeros((n_bin, n_bin, n_bin))
Vsum=V[:,s.newaxis]+V[s.newaxis,:] # matrix with the sum of the volumes in the bins
for k in xrange(1,(n_bin-1)):
f[:,:,k]=s.where((Vsum<=V[k+1]) & (Vsum>=V[k]), (V[k+1]-Vsum)/(V[k+1]-V[k]),\
f[:,:,k] )
f[:,:,k]=s.where((Vsum<=V[k]) & (Vsum>=V[k-1]),(Vsum-V[k-1])/(V[k]-V[k-1]),\
f[:,:,k])
return f
示例5: pixSeedfillBinary
# 需要导入模块: import scipy [as 别名]
# 或者: from scipy import where [as 别名]
def pixSeedfillBinary(self, Imask, Iseed):
Iseedfill = copy.deepcopy(Iseed)
s = ones((3, 3))
Ijmask, k = ndimage.label(Imask, s)
Ijmask2 = Ijmask * Iseedfill
A = list(unique(Ijmask2))
A.remove(0)
for i in range(0, len(A)):
x, y = where(Ijmask == A[i])
Iseedfill[x, y] = 1
return Iseedfill
示例6: pagerank
# 需要导入模块: import scipy [as 别名]
# 或者: from scipy import where [as 别名]
def pagerank(graph_matrix, n_iter=100, alpha=0.9, tol=1e-6):
n_nodes = graph_matrix.shape[0]
n_edges_per_node = graph_matrix.sum(axis=1)
n_edges_per_node = np.array(n_edges_per_node).flatten()
np.seterr(divide='ignore')
normilize_vector = np.where((n_edges_per_node != 0),
1. / n_edges_per_node, 0)
np.seterr(divide='warn')
normilize_matrix = sp.spdiags(normilize_vector, 0,
*graph_matrix.shape, format='csr')
graph_proba_matrix = normilize_matrix * graph_matrix
teleport_proba = np.repeat(1. / n_nodes, n_nodes)
is_dangling, = scipy.where(normilize_vector == 0)
x_current = teleport_proba
for _ in range(n_iter):
x_previous = x_current.copy()
dangling_total_proba = sum(x_current[is_dangling])
x_current = (
x_current * graph_proba_matrix +
dangling_total_proba * teleport_proba
)
x_current = alpha * x_current + (1 - alpha) * teleport_proba
error = np.abs(x_current - x_previous).mean()
if error < tol:
break
else:
print("PageRank didn't converge")
return x_current
示例7: getFiedlerVectorSparse
# 需要导入模块: import scipy [as 别名]
# 或者: from scipy import where [as 别名]
def getFiedlerVectorSparse(self, normalized = True, lanczosVecs = 15, maxiter = 20):
"""Returns the (sparse) Fiedler vector of the higher-order network. The Fiedler
vector can be used for a spectral bisectioning of the network.
Note that sparse linear algebra for eigenvalue problems with small eigenvalues
is problematic in terms of numerical stability. Consider using the dense version
of this method in this case. Note also that the sparse Fiedler vector might be scaled by
a factor (-1) compared to the dense version.
@param normalized: whether (default) or not to normalize the fiedler vector.
Normalization is done such that the sum of squares equals one in order to
get reasonable values as entries might be positive and negative.
@param lanczosVecs: number of Lanczos vectors to be used in the approximate
calculation of eigenvectors and eigenvalues. This maps to the ncv parameter
of scipy's underlying function eigs.
@param maxiter: scaling factor for the number of iterations to be used in the
approximate calculation of eigenvectors and eigenvalues. The number of iterations
passed to scipy's underlying eigs function will be n*maxiter where n is the
number of rows/columns of the Laplacian matrix.
"""
# NOTE: The transposed matrix is needed to get the "left" eigenvectors
L = self.getLaplacianMatrix()
# NOTE: ncv sets additional auxiliary eigenvectors that are computed
# NOTE: in order to be more confident to find the one with the largest
# NOTE: magnitude, see https://github.com/scipy/scipy/issues/4987
maxiter = maxiter*L.get_shape()[0]
w = _sla.eigs( L, k=2, which="SM", ncv=lanczosVecs, return_eigenvectors=False, maxiter=maxiter )
# compute a sparse LU decomposition and solve for the eigenvector
# corresponding to the second largest eigenvalue
n = L.get_shape()[0]
b = _np.ones(n)
evalue = _np.sort(_np.abs(w))[1]
A = (L[1:n,:].tocsc()[:,1:n] - _sparse.identity(n-1).multiply(evalue))
b[1:n] = A[0,:].toarray()
lu = _sla.splu(A)
b[1:n] = lu.solve(b[1:n])
if normalized:
b /= np.sqrt(np.inner(b, b))
return b
示例8: gen_feature_nodearray
# 需要导入模块: import scipy [as 别名]
# 或者: from scipy import where [as 别名]
def gen_feature_nodearray(xi, feature_max=None):
if feature_max:
assert(isinstance(feature_max, int))
xi_shift = 0 # ensure correct indices of xi
if scipy and isinstance(xi, tuple) and len(xi) == 2\
and isinstance(xi[0], scipy.ndarray) and isinstance(xi[1], scipy.ndarray): # for a sparse vector
index_range = xi[0] + 1 # index starts from 1
if feature_max:
index_range = index_range[scipy.where(index_range <= feature_max)]
elif scipy and isinstance(xi, scipy.ndarray):
xi_shift = 1
index_range = xi.nonzero()[0] + 1 # index starts from 1
if feature_max:
index_range = index_range[scipy.where(index_range <= feature_max)]
elif isinstance(xi, (dict, list, tuple)):
if isinstance(xi, dict):
index_range = xi.keys()
elif isinstance(xi, (list, tuple)):
xi_shift = 1
index_range = range(1, len(xi) + 1)
index_range = filter(lambda j: xi[j-xi_shift] != 0, index_range)
if feature_max:
index_range = filter(lambda j: j <= feature_max, index_range)
index_range = sorted(index_range)
else:
raise TypeError('xi should be a dictionary, list, tuple, 1-d numpy array, or tuple of (index, data)')
ret = (feature_node*(len(index_range)+2))()
ret[-1].index = -1 # for bias term
ret[-2].index = -1
if scipy and isinstance(xi, tuple) and len(xi) == 2\
and isinstance(xi[0], scipy.ndarray) and isinstance(xi[1], scipy.ndarray): # for a sparse vector
for idx, j in enumerate(index_range):
ret[idx].index = j
ret[idx].value = (xi[1])[idx]
else:
for idx, j in enumerate(index_range):
ret[idx].index = j
ret[idx].value = xi[j - xi_shift]
max_idx = 0
if len(index_range) > 0:
max_idx = index_range[-1]
return ret, max_idx
示例9: laplacian_matrix
# 需要导入模块: import scipy [as 别名]
# 或者: from scipy import where [as 别名]
def laplacian_matrix(G, nodelist=None, weight='weight'):
"""Return the Laplacian matrix of G.
The graph Laplacian is the matrix L = D - A, where
A is the adjacency matrix and D is the diagonal matrix of node degrees.
Parameters
----------
G : graph
A NetworkX graph
nodelist : list, optional
The rows and columns are ordered according to the nodes in nodelist.
If nodelist is None, then the ordering is produced by G.nodes().
weight : string or None, optional (default='weight')
The edge data key used to compute each value in the matrix.
If None, then each edge has weight 1.
Returns
-------
L : SciPy sparse matrix
The Laplacian matrix of G.
Notes
-----
For MultiGraph/MultiDiGraph, the edges weights are summed.
See Also
--------
to_numpy_matrix
normalized_laplacian_matrix
"""
import scipy.sparse
if nodelist is None:
nodelist = G.nodes()
A = nx.to_scipy_sparse_matrix(G, nodelist=nodelist, weight=weight,
format='csr')
n,m = A.shape
diags = A.sum(axis=1)
D = scipy.sparse.spdiags(diags.flatten(), [0], m, n, format='csr')
return D - A
示例10: laplacian_matrix
# 需要导入模块: import scipy [as 别名]
# 或者: from scipy import where [as 别名]
def laplacian_matrix(G, nodelist=None, weight='weight'):
"""Returns the Laplacian matrix of G.
The graph Laplacian is the matrix L = D - A, where
A is the adjacency matrix and D is the diagonal matrix of node degrees.
Parameters
----------
G : graph
A NetworkX graph
nodelist : list, optional
The rows and columns are ordered according to the nodes in nodelist.
If nodelist is None, then the ordering is produced by G.nodes().
weight : string or None, optional (default='weight')
The edge data key used to compute each value in the matrix.
If None, then each edge has weight 1.
Returns
-------
L : SciPy sparse matrix
The Laplacian matrix of G.
Notes
-----
For MultiGraph/MultiDiGraph, the edges weights are summed.
See Also
--------
to_numpy_matrix
normalized_laplacian_matrix
"""
import scipy.sparse
if nodelist is None:
nodelist = list(G)
A = nx.to_scipy_sparse_matrix(G, nodelist=nodelist, weight=weight,
format='csr')
n, m = A.shape
diags = A.sum(axis=1)
D = scipy.sparse.spdiags(diags.flatten(), [0], m, n, format='csr')
return D - A
示例11: laplacian_matrix
# 需要导入模块: import scipy [as 别名]
# 或者: from scipy import where [as 别名]
def laplacian_matrix(G, nodelist=None, weight='weight'):
"""Return the Laplacian matrix of G.
The graph Laplacian is the matrix L = D - A, where
A is the adjacency matrix and D is the diagonal matrix of node degrees.
Parameters
----------
G : graph
A NetworkX graph
nodelist : list, optional
The rows and columns are ordered according to the nodes in nodelist.
If nodelist is None, then the ordering is produced by G.nodes().
weight : string or None, optional (default='weight')
The edge data key used to compute each value in the matrix.
If None, then each edge has weight 1.
Returns
-------
L : SciPy sparse matrix
The Laplacian matrix of G.
Notes
-----
For MultiGraph/MultiDiGraph, the edges weights are summed.
See Also
--------
to_numpy_matrix
normalized_laplacian_matrix
"""
import scipy.sparse
if nodelist is None:
nodelist = list(G)
A = nx.to_scipy_sparse_matrix(G, nodelist=nodelist, weight=weight,
format='csr')
n, m = A.shape
diags = A.sum(axis=1)
D = scipy.sparse.spdiags(diags.flatten(), [0], m, n, format='csr')
return D - A