当前位置: 首页>>代码示例>>Python>>正文


Python scipy.where方法代码示例

本文整理汇总了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 
开发者ID:IngoScholtes,项目名称:pathpy,代码行数:27,代码来源:HigherOrderNetwork.py

示例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]) 
开发者ID:IngoScholtes,项目名称:pathpy,代码行数:27,代码来源:HigherOrderNetwork.py

示例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 
开发者ID:materialsproject,项目名称:MPContribs,代码行数:29,代码来源:pre_submission.py

示例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 
开发者ID:ActiveState,项目名称:code,代码行数:12,代码来源:recipe-576547.py

示例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 
开发者ID:OCR-D,项目名称:ocrd_anybaseocr,代码行数:13,代码来源:ocrd_anybaseocr_tiseg.py

示例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 
开发者ID:itdxer,项目名称:neupy,代码行数:39,代码来源:pagerank.py

示例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 
开发者ID:IngoScholtes,项目名称:pathpy,代码行数:46,代码来源:HigherOrderNetwork.py

示例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 
开发者ID:AudioVisualEmotionChallenge,项目名称:AVEC2018,代码行数:49,代码来源:liblinear.py

示例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 
开发者ID:SpaceGroupUCL,项目名称:qgisSpaceSyntaxToolkit,代码行数:44,代码来源:laplacianmatrix.py

示例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 
开发者ID:holzschu,项目名称:Carnets,代码行数:44,代码来源:laplacianmatrix.py

示例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 
开发者ID:aws-samples,项目名称:aws-kube-codesuite,代码行数:44,代码来源:laplacianmatrix.py


注:本文中的scipy.where方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。