首页 文章

有效地初始化一个numpy稀疏矩阵

提问于
浏览
0

我有一个数组,其中m行和数组作为值,它指示列的索引并且限制为大数n . 例如:

Y = [[1,34,203,2032],...,[2984]]

现在我想要一种有效的方法来初始化具有维度m,n的稀疏numpy矩阵X和对应于Y的值(X [i,j] = 1,如果j在Y [i]中,否则= 0) .

1 回答

  • 1

    您的数据已接近csr格式,因此我建议使用:

    import numpy as np
    from scipy import sparse
    from itertools import chain
    
    # create an example    
    m, n = 20, 10
    X = np.random.random((m, n)) < 0.1
    Y = [list(np.where(y)[0]) for y in X]
    
    # construct the sparse matrix
    indptr = np.fromiter(chain((0,), map(len, Y)), int, len(Y) + 1).cumsum()
    indices = np.fromiter(chain.from_iterable(Y), int, indptr[-1])
    data = np.ones_like(indices)    
    S = sparse.csr_matrix((data, indices, indptr), (m, n))
    # or    
    S = sparse.csr_matrix((data, indices, indptr))
    
    # check
    assert np.all(S==X)
    

相关问题