[英]Most effective way to compute the pairwise minimum between a numpy array and a csr_matrix
我有一个形状为(1, 1000)
的 numpy 数组V
。 我还有一个形状为(100000, 1000)
的 csr_matrix M
。 对于M
每一行m
,我想计算V
和m
之间的成对最小值,并将所有结果存储在一个新矩阵中,并且我想高效地完成它。 最终结果也应该是一个形状为(100000, 1000)
的矩阵。
我考虑/尝试过的一些方法:
M
每一行。 这有效,但速度很慢。M
转换为矩阵: numpy.minimum(V, M.toarray())
这需要大量内存。numpy.minimum(V, M)
不起作用。 我收到一条错误消息: Comparing a sparse matrix with a scalar less than zero using >= is inefficient
。在不占用太多内存或时间的情况下,有什么好的和有效的方法可以做到这一点?
如果v
中的值是非负的,这是一个简洁的方法,应该比循环每一行快得多:
import numpy as np
from scipy.sparse import csr_matrix
def rowmin(M, v):
# M must be a csr_matrix, and v must be a 1-d numpy array with
# length M.shape[1]. The values in v must be nonnegative.
if np.any(v < 0):
raise ValueError('v must not contain negative values.')
# B is a CSR matrix with the same sparsity pattern as M, but its
# data values are from v:
B = csr_matrix((v[M.indices], M.indices, M.indptr))
return M.minimum(B)
为了允许v
负值,此修改有效,但是当v
具有负值时会生成警告,因为将负值复制到B
中时必须更改B
的稀疏模式。 (警告可以用多几行代码消除。) v
许多负值可能会显着降低性能。
def rowmin(M, v):
# M must be a csr_matrix, and v must be a 1-d numpy array with
# length M.shape[1].
# B is a CSR matrix with the same sparsity pattern as M, but its
# data values are from v:
B = csr_matrix((v[M.indices], M.indices, M.indptr))
# If there are negative values in v, include them in B.
negmask = v < 0
if np.any(negmask):
negindices = negmask.nonzero()[0]
B[:, negindices] = v[negindices]
return M.minimum(B)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.