【问题标题】:Initialize a numpy sparse matrix efficiently有效地初始化一个 numpy 稀疏矩阵
【发布时间】:2018-12-09 05:45:40
【问题描述】:

我有一个以 m 行和数组作为值的数组,它表示列的索引,并且以大数 n 为界。 例如:

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

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

【问题讨论】:

  • 什么是“稀疏 numpy 矩阵”?或者你想要一个 scipy 矩阵,比如scipy.sparse.coo_matrix
  • 对不起,我想要一个像 scipy.sparse.coo_matrix 这样的矩阵。
  • 这里没有问题..
  • 制作coo 矩阵的规范方法是使用(data, (i,j)) 输入。你的 Y 如果展平应该作为 j 参数工作。 data 将等效大小为 1 的数组。 i 然后需要成为行索引,根据需要进行复制。

标签: python numpy scipy sparse-matrix adjacency-list


【解决方案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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-07
    • 2017-07-20
    • 1970-01-01
    • 2021-11-25
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多