从行列表(稀疏向量)创建稀疏矩阵

时间:2018-01-31 12:50:12

标签: python python-3.x scipy sparse-matrix

我想有效地创建以下维度(s, n1+n2)的稀疏矩阵:

v0 v1 
v0 v2 
v0 v3 
 ... 
v0 vs

给出稀疏向量v0 (1, n1)和稀疏向量列表(1, n2) l = [v1, ... , vs]

我曾尝试使用coo_matrix(),但它没有成功,因为它似乎只有在你有密集向量时才有效:

left = coo_matrix(np.repeat(v0, s))
right = coo_matrix(l)
m = hstack((left, right))

修改1:

我找到了一种似乎效率不高的解决方法:

right = vstack([x for x in l])
left = vstack([v0 for i in range(len(l))])
m = hstack((left, right))

编辑2:

这是一个帮助您了解情况的示例(不起作用)。

from scipy.sparse import random, coo_matrix
from numpy import repeat

s = 10
n1 = 3
n2 = 5

v0 = random(1, n1)
l = [random(1, n2) for i in range(s)]

left = coo_matrix(repeat(v0, s))
right = coo_matrix(l)
m = hstack((left, right))

1 个答案:

答案 0 :(得分:1)

In [1]: from scipy import sparse

In [2]: s, n1, n2 = 10,3,5
In [3]: v0 = sparse.random(1, n1)
In [4]: v0
Out[4]: 
<1x3 sparse matrix of type '<class 'numpy.float64'>'
    with 0 stored elements in COOrdinate format>
In [5]: l = [sparse.random(1, n2) for i in range(s)]
In [6]: l
Out[6]: 
[<1x5 sparse matrix of type '<class 'numpy.float64'>'
    with 0 stored elements in COOrdinate format>,
  ...
 <1x5 sparse matrix of type '<class 'numpy.float64'>'
    with 0 stored elements in COOrdinate format>]

而不是np.repeat使用sparse.vstack来创建一堆V0份副本

In [7]: V0 = sparse.vstack([v0]*s)
In [8]: V0
Out[8]: 
<10x3 sparse matrix of type '<class 'numpy.float64'>'
    with 0 stored elements in COOrdinate format>

同样将n2矩阵列表转换为一个矩阵:

In [10]: V1 = sparse.vstack(l)
In [11]: V1
Out[11]: 
<10x5 sparse matrix of type '<class 'numpy.float64'>'
    with 0 stored elements in COOrdinate format>

现在加入他们:

In [12]: m = sparse.hstack((V0,V1))
In [13]: m
Out[13]: 
<10x8 sparse matrix of type '<class 'numpy.float64'>'
    with 0 stored elements in COOrdinate format>

我没有声称对此有效。 hstackvstack使用bmat(查看他们的代码)。 bmat收集所有块的coo属性,并将它们(带偏移量)连接到新coo_matrix调用的输入中(同样,代码是可读的)。因此,您可以直接使用bmat,甚至直接使用coo属性来避免某些中间转换。但hstackvstack相对直观。

相关问题