我想有效地创建以下维(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))发布于 2018-01-31 18:40:00
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>我不会声称这是有效的。hstack和vstack使用bmat (检查它们的代码)。bmat收集所有块的coo属性,并将它们(带有偏移)连接到一个新的coo_matrix调用的输入中(同样,代码是可读的)。因此,您可以通过直接使用bmat,甚至直接使用coo属性来避免一些中间转换。但是hstack和vstack是相对直观的。
https://stackoverflow.com/questions/48542640
复制相似问题