【问题标题】:Unable to convert a sparse matrix to a dense one无法将稀疏矩阵转换为密集矩阵
【发布时间】:2015-11-07 00:05:54
【问题描述】:

我有 GxGy 两个稀疏类型的 coo 矩阵。

我对它们执行以下操作:

A = np.hstack((Gx.transpose(),Gy.transpose()))
B = np.vstack((Gx,Gy))

L = np.dot(A,B)

我想可视化解决方案,C所以我使用了C.toarray()和C.todense(),但答案如下:

In [391]: C
Out[391]: 
  array([ <16x16 sparse matrix of type '<type 'numpy.float64'>'
with 64 stored elements in Compressed Sparse Row format>], dtype=object)


In [392]: C.toarray() 
Traceback (most recent call last):
   File "<ipython-input-390-86c90f8dce51>", line 1, in <module>
    C.toarray()
AttributeError: 'numpy.ndarray' object has no attribute 'toarray'

如何才能看到矩阵C 的密集形式?

【问题讨论】:

    标签: python numpy sparse-matrix


    【解决方案1】:

    发件人:

    array([ <16x16 sparse matrix of type '<type 'numpy.float64'>'
    

    以压缩稀疏行格式存储 64 个元素>],dtype=object)

    我推断C 是一个具有dtype=object 的1 元素密集数组。那一个元素是一个稀疏矩阵。

    所以我期待

     C[0].toarray()  
    

    会起作用。正如错误所说,numpy 数组没有 toarray 方法。但在这种情况下,它的元素会。

    由于GxGy 是稀疏的,那么您需要使用hstackvstack 的稀疏版本,而不是numpy 版本。检查AB 的类型。我是那些是 numpy 数组,而不是稀疏矩阵。


    看看当我将np.hstack 与几个稀疏矩阵一起使用时会发生什么:

    In [70]: M=sparse.csr_matrix([[0,1,2],[2,3,4]])
    In [71]: np.hstack([M,M])
    /usr/lib/python3/dist-packages/scipy/sparse/compressed.py:298: SparseEfficiencyWarning: Comparing sparse matrices using >= and <= is inefficient, using <, >, or !=, instead.
      "using <, >, or !=, instead.", SparseEfficiencyWarning)
    Out[71]: 
    array([ <2x3 sparse matrix of type '<class 'numpy.int32'>'
        with 5 stored elements in Compressed Sparse Row format>,
           <2x3 sparse matrix of type '<class 'numpy.int32'>'
        with 5 stored elements in Compressed Sparse Row format>], dtype=object)
    

    结果不是稀疏的,而是密集的 2 个稀疏元素。

    【讨论】:

      猜你喜欢
      • 2023-04-10
      • 2021-11-25
      • 2017-07-02
      • 2013-03-07
      • 1970-01-01
      • 2016-06-25
      • 1970-01-01
      • 2014-03-06
      • 2018-01-19
      相关资源
      最近更新 更多