【发布时间】:2016-10-29 11:11:16
【问题描述】:
为了创建scipy sparse matrix,我有一个数组或行和列索引I 和J 以及一个数据数组V。我用它们在COO format 中构造一个矩阵,然后将其转换为CSR,
matrix = sparse.coo_matrix((V, (I, J)), shape=(n, n))
matrix = matrix.tocsr()
我有一组行索引,唯一的条目应该是对角线上的1.0。到目前为止,我通过I,找到所有需要擦除的索引,然后这样做:
def find(lst, a):
# From <http://stackoverflow.com/a/16685428/353337>
return [i for i, x in enumerate(lst) if x in a]
# wipe_rows = [1, 55, 32, ...] # something something
indices = find(I, wipe_rows) # takes too long
I = numpy.delete(I, indices).tolist()
J = numpy.delete(J, indices).tolist()
V = numpy.delete(V, indices).tolist()
# Add entry 1.0 to the diagonal for each wipe row
I.extend(wipe_rows)
J.extend(wipe_rows)
V.extend(numpy.ones(len(wipe_rows)))
# construct matrix via coo
这没问题,但find 往往需要一段时间。
关于如何加快速度的任何提示? (也许以 COO 或 CSR 格式擦除行是一个更好的主意。)
【问题讨论】:
标签: python scipy sparse-matrix