【问题标题】:How does "scipy.sparse.issparse" work? It always return "False"“scipy.sparse.issparse”是如何工作的?它总是返回“假”
【发布时间】:2014-02-25 17:30:14
【问题描述】:

本文使用scipy.sparse.issparse

Is it possible to specify your own distance function using scikit-learn K-Means Clustering?

但是,我不知道它是如何工作的。我已经找到了文件,它是空的。 http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.issparse.html

from scipy.sparse import issparse

issparse([0, 0, 0])
>> False

issparse([[1, 0, 0], [0, 0, 0]])
>> False

它总是返回False。我怎样才能让它返回True

【问题讨论】:

    标签: python scipy


    【解决方案1】:

    This page 定义 spmatrix 类

    class spmatrix(object):
        """ This class provides a base class for all sparse matrices.
    

    在页面底部,将issparse定义为

    def isspmatrix(x):
        return isinstance(x, spmatrix)
    
    issparse = isspmatrix
    

    所以,如果我没看错的话,当xspmatrix 的一个实例时,issparse 为真。

    【讨论】:

      【解决方案2】:

      issparse 与输入有多少元素无关。相反,scipy.sparse 定义了许多为表示稀疏矩阵而优化的类型,issparse 确定输入是否为稀疏矩阵对象。

      In [1]: import scipy.sparse
      
      In [2]: scipy.sparse.issparse(scipy.sparse.bsr_matrix([[1, 0], [0, 1]]))                          
      Out[2]: True
      

      【讨论】:

        【解决方案3】:

        该函数仅测试变量是否是spmatrix 的子类。例如il_matrixdok_matrix

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-12-29
          • 2020-08-02
          • 1970-01-01
          • 2014-05-06
          • 2020-08-05
          • 2019-09-20
          • 2021-02-15
          • 1970-01-01
          相关资源
          最近更新 更多