python - 有效地初始化一个 numpy 稀疏矩阵
问题描述
我有一个以 m 行和数组作为值的数组,它指示列的索引并限制为一个大数 n。例如:
Y = [[1,34,203,2032],...,[2984]]
现在我想要一种有效的方法来初始化一个稀疏 numpy 矩阵 X,其维度为 m,n,值对应于 Y(X[i,j] = 1,如果 j 在 Y[i] 中,则 = 0)。
解决方案
您的数据已经接近 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)
推荐阅读
- azure - 如果接收 Azure Function 停止,ServiceBus 如何保证 FIFO 顺序?
- jpa - 将 Spring 的订单从 Pageable 转换为 JPA 订单
- visual-studio - 将此规则代码实现到我的函数输出
- html - 设置高度的建筑网格
- python - Python:在数据框中移动一个单元格
- scala - 在 Scala 中使用类型 lambdas 和更高类型的类型:如何让编译器正确推断类型?
- sql - 由于空值,使用 Case 语句更新失败
- firebase - cordova-plugin-firebase 如何删除 crashlytics?
- javascript - Javascript 文件的 MIME 类型错误 - VS Code/Live 服务器 - Firefox/Console
- angular - 在 Jasmine 中对 MatDialog 进行单元测试时无法读取未定义的属性“afterClosed”