扩展(添加行或列)一个 scipy.sparse 矩阵 [英] expanding (adding a row or column) a scipy.sparse matrix

查看:30
本文介绍了扩展(添加行或列)一个 scipy.sparse 矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个来自 scipy.sparse 的 NxN 矩阵 M(lil_matrix 或 csr_matrix),我想将其设为 (N+1)xN,其中 M_modified[i,j] = M[i,j] 为 0 <=我<对于所有 j,N(以及所有 j)和 M[N,j] = 0.基本上,我想在 M 的底部添加一行零并保留矩阵的其余部分.有没有办法在不复制数据的情况下做到这一点?

Suppose I have a NxN matrix M (lil_matrix or csr_matrix) from scipy.sparse, and I want to make it (N+1)xN where M_modified[i,j] = M[i,j] for 0 <= i < N (and all j) and M[N,j] = 0 for all j. Basically, I want to add a row of zeros to the bottom of M and preserve the remainder of the matrix. Is there a way to do this without copying the data?

推荐答案

我认为没有什么方法可以真正避免复制.这两种类型的稀疏矩阵在内部都将它们的数据存储为 Numpy 数组(在 csr 的数据和索引属性中以及在 lil 的数据和行属性中)并且 Numpy 数组不能扩展.

I don't think that there is any way to really escape from doing the copying. Both of those types of sparse matrices store their data as Numpy arrays (in the data and indices attributes for csr and in the data and rows attributes for lil) internally and Numpy arrays can't be extended.

更新更多信息:

LIL 确实代表链接列表,但当前的实现并不完全符合名称.用于 datarows 的 Numpy 数组都是对象类型.这些数组中的每个对象实际上都是 Python 列表(当所有值在一行中都为零时为空列表).Python 列表并不完全是链接列表,但由于 O(1) 查找,它们有点接近并且坦率地说是更好的选择.就我个人而言,我并没有立即看到在这里使用 Numpy 对象数组而不仅仅是 Python 列表的意义.您可以相当轻松地将当前的 lil 实现更改为使用 Python 列表,这将允许您在不复制整个矩阵的情况下添加一行.

LIL does stand for LInked List, but the current implementation doesn't quite live up to the name. The Numpy arrays used for data and rows are both of type object. Each of the objects in these arrays are actually Python lists (an empty list when all values are zero in a row). Python lists aren't exactly linked lists, but they are kind of close and quite frankly a better choice due to O(1) look-up. Personally, I don't immediately see the point of using a Numpy array of objects here rather than just a Python list. You could fairly easily change the current lil implementation to use Python lists instead which would allow you to add a row without copying the whole matrix.

这篇关于扩展(添加行或列)一个 scipy.sparse 矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆