首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >重塑枕叶csr矩阵

重塑枕叶csr矩阵
EN

Stack Overflow用户
提问于 2018-04-29 15:21:23
回答 2查看 3.3K关注 0票数 0

我如何有效地重塑和scipy.sparse csr_matrix?

我需要在末尾加零行。使用:

代码语言:javascript
复制
from scipy.sparse import csr_matrix
data = [1,2,3,4,5,6]
col = [0,0,0,1,1,1]
row = [0,1,2,0,1,2]
a = csr_matrix((data, (row, col)))
a.reshape(3,5)

我知道这个错误:

代码语言:javascript
复制
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.5/dist-packages/scipy/sparse/base.py", line 129, in reshape
self.__class__.__name__)
NotImplementedError: Reshaping not implemented for csr_matrix.
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-04-29 16:38:51

如果您能够尽早发现问题,只需包含一个形状参数:

代码语言:javascript
复制
In [48]: a = csr_matrix((data, (row, col)))
In [49]: a
Out[49]: 
<3x2 sparse matrix of type '<class 'numpy.int64'>'
    with 6 stored elements in Compressed Sparse Row format>
In [50]: a = csr_matrix((data, (row, col)),shape=(3,5))
In [51]: a
Out[51]: 
<3x5 sparse matrix of type '<class 'numpy.int64'>'
    with 6 stored elements in Compressed Sparse Row format>
In [52]: a.A
Out[52]: 
array([[1, 4, 0, 0, 0],
       [2, 5, 0, 0, 0],
       [3, 6, 0, 0, 0]], dtype=int64)

你也可以把hstack放在便携板上。确保这是稀疏版本:

代码语言:javascript
复制
In [59]: z = sparse.coo_matrix(np.zeros((3,3)))
In [60]: z
Out[60]: 
<3x3 sparse matrix of type '<class 'numpy.float64'>'
    with 0 stored elements in COOrdinate format>
In [61]: sparse.hstack((a,z))
Out[61]: 
<3x5 sparse matrix of type '<class 'numpy.float64'>'
    with 6 stored elements in COOrdinate format>
In [62]: _.A
Out[62]: 
array([[1., 4., 0., 0., 0.],
       [2., 5., 0., 0., 0.],
       [3., 6., 0., 0., 0.]])

hstack使用sparse.bmat。它结合了两个数组的coo属性,并生成了一个新的coo矩阵。

票数 3
EN

Stack Overflow用户

发布于 2018-04-29 16:19:42

reshape()方法将与接近释放的ciply1.1中的csr_matrix对象一起工作。同时,您可以在Reshape sparse matrix efficiently, Python, SciPy 0.12上尝试代码来重塑稀疏矩阵。

但是,您的示例不起作用,因为您正在尝试将具有形状(3,2)的数组重塑为具有形状(3,5)的数组。链接到上面和稀疏reshape()方法的代码遵循与numpy数组的reshape()方法相同的规则:不能更改数组的总大小。

如果您想要更改总大小,您最终将能够使用resize()方法(该方法是就地操作的),但这也是ciply1.1的一个新特性,因此尚未发布。

相反,您可以构建新的稀疏矩阵,如下所示:

代码语言:javascript
复制
In [57]: b = csr_matrix((a.data, a.indices, a.indptr), shape=(3, 5))

In [58]: b.shape
Out[58]: (3, 5)

In [59]: b.A
Out[59]: 
array([[1, 4, 0, 0, 0],
       [2, 5, 0, 0, 0],
       [3, 6, 0, 0, 0]], dtype=int64)
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50088190

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档