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


Python sparse.isspmatrix方法代码示例

本文整理汇总了Python中scipy.sparse.isspmatrix方法的典型用法代码示例。如果您正苦于以下问题:Python sparse.isspmatrix方法的具体用法?Python sparse.isspmatrix怎么用?Python sparse.isspmatrix使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在scipy.sparse的用法示例。


在下文中一共展示了sparse.isspmatrix方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: normalize_adj

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import isspmatrix [as 别名]
def normalize_adj(A, is_sym=True, exponent=0.5):
  """
    Normalize adjacency matrix

    is_sym=True: D^{-1/2} A D^{-1/2}
    is_sym=False: D^{-1} A
  """
  rowsum = np.array(A.sum(1))

  if is_sym:
    r_inv = np.power(rowsum, -exponent).flatten()
  else:
    r_inv = np.power(rowsum, -1.0).flatten()

  r_inv[np.isinf(r_inv)] = 0.

  if sp.isspmatrix(A):
    r_mat_inv = sp.diags(r_inv.squeeze())
  else:
    r_mat_inv = np.diag(r_inv)

  if is_sym:
    return r_mat_inv.dot(A).dot(r_mat_inv)
  else:
    return r_mat_inv.dot(A) 
开发者ID:lrjconan,项目名称:LanczosNetwork,代码行数:27,代码来源:data_helper.py

示例2: safe_onenorm

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import isspmatrix [as 别名]
def safe_onenorm(A):
    """
    Computes the 1-norm of the dense or sparse matrix `A`.

    Parameters
    ----------
    A : ndarray or sparse matrix
        The matrix or vector to take the norm of.

    Returns
    -------
    float
    """
    if _sps.isspmatrix(A):
        return sparse_onenorm(A)
    else:
        return _np.linalg.norm(A, 1) 
开发者ID:pyGSTio,项目名称:pyGSTi,代码行数:19,代码来源:matrixtools.py

示例3: _graph_is_connected

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import isspmatrix [as 别名]
def _graph_is_connected(graph):
    """ Return whether the graph is connected (True) or Not (False)

    Parameters
    ----------
    graph : array-like or sparse matrix, shape: (n_samples, n_samples)
        adjacency matrix of the graph, non-zero weight means an edge
        between the nodes

    Returns
    -------
    is_connected : bool
        True means the graph is fully connected and False means not
    """
    if sparse.isspmatrix(graph):
        # sparse graph, find all the connected components
        n_connected_components, _ = connected_components(graph)
        return n_connected_components == 1
    else:
        # dense graph, find all connected components start from node 0
        return _graph_connected_component(graph, 0).sum() == graph.shape[0] 
开发者ID:PacktPublishing,项目名称:Mastering-Elasticsearch-7.0,代码行数:23,代码来源:spectral_embedding_.py

示例4: _decision_function

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import isspmatrix [as 别名]
def _decision_function(self, X):
        """Decision function of the linear model

        Parameters
        ----------
        X : numpy array or scipy.sparse matrix of shape (n_samples, n_features)

        Returns
        -------
        T : array, shape (n_samples,)
            The predicted decision function
        """
        check_is_fitted(self, 'n_iter_')
        if sparse.isspmatrix(X):
            return safe_sparse_dot(X, self.coef_.T,
                                   dense_output=True) + self.intercept_
        else:
            return super()._decision_function(X)


###############################################################################
# Lasso model 
开发者ID:PacktPublishing,项目名称:Mastering-Elasticsearch-7.0,代码行数:24,代码来源:coordinate_descent.py

示例5: _dense_array

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import isspmatrix [as 别名]
def _dense_array(arr):
        """Converts the input array to dense array.

        Parameters
        ----------
        arr : numpy array or csr_matrix
            The array to be densified.

        Returns
        -------
        array-like
            Dense numpy array representing arr.

        """
        if isspmatrix(arr):
            return arr.todense()
        return arr 
开发者ID:aws,项目名称:sagemaker-scikit-learn-extension,代码行数:19,代码来源:automl_transformer.py

示例6: test_csr_to_sps

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import isspmatrix [as 别名]
def test_csr_to_sps():
    # initialize sparse matrix
    mat = np.random.randn(10, 5)
    mat[mat <= 0] = 0
    # get COO
    smat = sps.coo_matrix(mat)
    # make sure it's sparse
    assert smat.nnz == np.sum(mat > 0)

    csr = lm.CSR.from_coo(smat.row, smat.col, smat.data, shape=smat.shape)
    assert csr.nnz == smat.nnz
    assert csr.nrows == smat.shape[0]
    assert csr.ncols == smat.shape[1]

    smat2 = csr.to_scipy()
    assert sps.isspmatrix(smat2)
    assert sps.isspmatrix_csr(smat2)

    for i in range(csr.nrows):
        assert smat2.indptr[i] == csr.rowptrs[i]
        assert smat2.indptr[i+1] == csr.rowptrs[i+1]
        sp = smat2.indptr[i]
        ep = smat2.indptr[i+1]
        assert all(smat2.indices[sp:ep] == csr.colinds[sp:ep])
        assert all(smat2.data[sp:ep] == csr.values[sp:ep]) 
开发者ID:lenskit,项目名称:lkpy,代码行数:27,代码来源:test_matrix_csr.py

示例7: _decision_function

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import isspmatrix [as 别名]
def _decision_function(self, X):
        """Decision function of the linear model

        Parameters
        ----------
        X : numpy array or scipy.sparse matrix of shape (n_samples, n_features)

        Returns
        -------
        T : array, shape (n_samples,)
            The predicted decision function
        """
        check_is_fitted(self, 'n_iter_')
        if sparse.isspmatrix(X):
            return safe_sparse_dot(X, self.coef_.T,
                                   dense_output=True) + self.intercept_
        else:
            return super(ElasticNet, self)._decision_function(X)


###############################################################################
# Lasso model 
开发者ID:nccgroup,项目名称:Splunking-Crime,代码行数:24,代码来源:coordinate_descent.py

示例8: _check_b

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import isspmatrix [as 别名]
def _check_b(self, A, b):
        if sp.isspmatrix(b):
            warnings.warn('PyPardiso requires the right-hand side b to be a dense array for maximum efficiency', 
                          SparseEfficiencyWarning)
            b = b.todense()
        
        # pardiso expects fortran (column-major) order if b is a matrix
        if b.ndim == 2:
            b = np.asfortranarray(b)
        
        if b.shape[0] != A.shape[0]:
            raise ValueError("Dimension mismatch: Matrix A {} and array b {}".format(A.shape, b.shape))
            
        if b.dtype != np.float64:
            if b.dtype in [np.float16, np.float32, np.int16, np.int32, np.int64]:
                warnings.warn("Array b's data type was converted from {} to float64".format(str(b.dtype)), 
                              PyPardisoWarning)
                b = b.astype(np.float64)
            else:
                raise TypeError('Dtype {} for array b is not supported'.format(str(b.dtype)))
        
        return b 
开发者ID:haasad,项目名称:PyPardisoProject,代码行数:24,代码来源:pardiso_wrapper.py

示例9: _graph_is_connected

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import isspmatrix [as 别名]
def _graph_is_connected(graph):
    """
    Return whether the graph is connected (True) or Not (False)

    Parameters
    ----------
    graph : array-like or sparse matrix, shape: (n_samples, n_samples)
        adjacency matrix of the graph, non-zero weight means an edge
        between the nodes

    Returns
    -------
    is_connected : bool
        True means the graph is fully connected and False means not
    """
    if sparse.isspmatrix(graph):
        # sparse graph, find all the connected components
        n_connected_components, _ = connected_components(graph)
        return n_connected_components == 1
    else:
        # dense graph, find all connected components start from node 0
        return _graph_connected_component(graph, 0).sum() == graph.shape[0] 
开发者ID:mmp2,项目名称:megaman,代码行数:24,代码来源:spectral_embedding.py

示例10: affinity_matrix

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import isspmatrix [as 别名]
def affinity_matrix(self, adjacency_matrix):
        A = check_array(adjacency_matrix, dtype=float, copy=True,
                        accept_sparse=['csr', 'csc', 'coo'])

        if isspmatrix(A):
            data = A.data
        else:
            data = A

        # in-place computation of
        # data = np.exp(-(data / radius) ** 2)
        data **= 2
        data /= -self.radius ** 2
        np.exp(data, out=data)

        if self.symmetrize:
            A = self._symmetrize(A)

        # for sparse, need a true zero on the diagonal
        # TODO: make this more efficient?
        if isspmatrix(A):
            A.setdiag(1)

        return A 
开发者ID:mmp2,项目名称:megaman,代码行数:26,代码来源:affinity.py

示例11: convert_to_adjacency_matrix

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import isspmatrix [as 别名]
def convert_to_adjacency_matrix(matrix):
    """
    Converts transition matrix into adjacency matrix

    :param matrix: The matrix to be converted
    :returns: adjacency matrix
    """
    for i in range(matrix.shape[0]):
        
        if isspmatrix(matrix):
            col = find(matrix[:,i])[2]
        else:
            col = matrix[:,i].T.tolist()[0]

        coeff = max( Fraction(c).limit_denominator().denominator for c in col )
        matrix[:,i] *= coeff

    return matrix 
开发者ID:GuyAllard,项目名称:markov_clustering,代码行数:20,代码来源:modularity.py

示例12: delta_matrix

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import isspmatrix [as 别名]
def delta_matrix(matrix, clusters):
    """
    Compute delta matrix where delta[i,j]=1 if i and j belong
    to same cluster and i!=j
    
    :param matrix: The adjacency matrix
    :param clusters: The clusters returned by get_clusters
    :returns: delta matrix
    """
    if isspmatrix(matrix):
        delta = dok_matrix(matrix.shape)
    else:
        delta = np.zeros(matrix.shape)

    for i in clusters :
        for j in permutations(i, 2):
            delta[j] = 1

    return delta 
开发者ID:GuyAllard,项目名称:markov_clustering,代码行数:21,代码来源:modularity.py

示例13: add_self_loops

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import isspmatrix [as 别名]
def add_self_loops(matrix, loop_value):
    """
    Add self-loops to the matrix by setting the diagonal
    to loop_value
    
    :param matrix: The matrix to add loops to
    :param loop_value: Value to use for self-loops
    :returns: The matrix with self-loops
    """
    shape = matrix.shape
    assert shape[0] == shape[1], "Error, matrix is not square"

    if isspmatrix(matrix):
        new_matrix = matrix.todok()
    else:
        new_matrix = matrix.copy()

    for i in range(shape[0]):
        new_matrix[i, i] = loop_value

    if isspmatrix(matrix):
        return new_matrix.tocsc()

    return new_matrix 
开发者ID:GuyAllard,项目名称:markov_clustering,代码行数:26,代码来源:mcl.py

示例14: prune

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import isspmatrix [as 别名]
def prune(matrix, threshold):
    """
    Prune the matrix so that very small edges are removed.
    The maximum value in each column is never pruned.
    
    :param matrix: The matrix to be pruned
    :param threshold: The value below which edges will be removed
    :returns: The pruned matrix
    """
    if isspmatrix(matrix):
        pruned = dok_matrix(matrix.shape)
        pruned[matrix >= threshold] = matrix[matrix >= threshold]
        pruned = pruned.tocsc()
    else:
        pruned = matrix.copy()
        pruned[pruned < threshold] = 0

    # keep max value in each column. same behaviour for dense/sparse
    num_cols = matrix.shape[1]
    row_indices = matrix.argmax(axis=0).reshape((num_cols,))
    col_indices = np.arange(num_cols)
    pruned[row_indices, col_indices] = matrix[row_indices, col_indices]

    return pruned 
开发者ID:GuyAllard,项目名称:markov_clustering,代码行数:26,代码来源:mcl.py

示例15: get_clusters

# 需要导入模块: from scipy import sparse [as 别名]
# 或者: from scipy.sparse import isspmatrix [as 别名]
def get_clusters(matrix):
    """
    Retrieve the clusters from the matrix
    
    :param matrix: The matrix produced by the MCL algorithm
    :returns: A list of tuples where each tuple represents a cluster and
              contains the indices of the nodes belonging to the cluster
    """
    if not isspmatrix(matrix):
        # cast to sparse so that we don't need to handle different 
        # matrix types
        matrix = csc_matrix(matrix)

    # get the attractors - non-zero elements of the matrix diagonal
    attractors = matrix.diagonal().nonzero()[0]

    # somewhere to put the clusters
    clusters = set()

    # the nodes in the same row as each attractor form a cluster
    for attractor in attractors:
        cluster = tuple(matrix.getrow(attractor).nonzero()[1].tolist())
        clusters.add(cluster)

    return sorted(list(clusters)) 
开发者ID:GuyAllard,项目名称:markov_clustering,代码行数:27,代码来源:mcl.py


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