猿问

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

我有一个包含 m 行和数组作为值的数组,它们指示列的索引并限制为一个大数 n。例如:

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

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


守候你守候我
浏览 196回答 1
1回答

繁星coding

您的数据已经接近 csr 格式,所以我建议使用它:import numpy as npfrom scipy import sparsefrom itertools import chain# create an example&nbsp; &nbsp;&nbsp;m, n = 20, 10X = np.random.random((m, n)) < 0.1Y = [list(np.where(y)[0]) for y in X]# construct the sparse matrixindptr = 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)&nbsp; &nbsp;&nbsp;S = sparse.csr_matrix((data, indices, indptr), (m, n))# or&nbsp; &nbsp;&nbsp;S = sparse.csr_matrix((data, indices, indptr))# checkassert np.all(S==X)
随时随地看视频慕课网APP

相关分类

Python
我要回答