【问题标题】:Finding N random zero elements from a scipy sparse matrix从 scipy 稀疏矩阵中找到 N 个随机零元素
【发布时间】:2018-11-12 21:49:41
【问题描述】:

我有一个大的稀疏矩阵,在 scipy lil_matrix 格式中,大小为 281903x281903,它是一个邻接矩阵 https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.lil_matrix.html

我需要一种可靠的方法来获取 N 个为零的索引。我不能只绘制所有零索引然后选择随机索引,因为这会使我的计算机内存不足。有没有一种方法可以识别 N 个随机索引而无需遍历整个数据结构?

我目前通过以下方式获得 10% 的非零索引(Y 是我的稀疏矩阵):

percent = 0.1

oneIdx = Y.nonzero()
numberOfOnes = len(oneIdx[0])
maskLength = int(math.floor(numberOfOnes * percent))
idxOne = np.array(random.sample(range(0,numberOfOnes), maskLength))

maskOne = tuple(np.asarray(oneIdx)[:,idxOne])

我正在寻找获得与非零掩码长度相同但为零的掩码的方法...

【问题讨论】:

  • 有一个nonzero() 方法可以返回所有非零索引。也许您可以品尝一下补品?
  • 这就是我现在正在做的,导致内存错误!
  • 也许我看错了你的问题,我以为你画的是所有的零索引,而不是非零索引。
  • 是的,我正在尝试绘制 N 个随机零索引,但如果我采用所有非零索引 (2312497) 的互补来获取包含零的所有索引 281903 * 281903 = 79466988912 - 2312497 = 79.466.988.912。 python 只是抛出一个内存不足错误
  • 我添加了一个答案。我并不是说显式地构造一个非零值的补集,因为它可能效率低下并且消耗太多内存。但是您可以隐式地对非零元素进行采样。鉴于您的所有值中约有 0.003% 不为零,因此简单的拒绝抽样可能效果很好。

标签: python numpy scipy sparse-matrix


【解决方案1】:

这是一种基于拒绝抽样的方法。根据您示例中的数字,随机统一选择的索引可能为零,因此这将是一种相对有效的方法。

from scipy import sparse

dims = (281903, 281903)

mat = sparse.lil_matrix(dims, dtype=np.int)

for _ in range(1000):
    x, y = np.random.randint(0, dims[0], 2)
    mat[x, y] = 1


def sample_zero_forever(mat):
    nonzero_or_sampled = set(zip(*mat.nonzero()))
    while True:
        t = tuple(np.random.randint(0, mat.shape[0], 2))
        if t not in nonzero_or_sampled:
            yield t
            nonzero_or_sampled.add(t)


def sample_zero_n(mat, n=100):
    itr = sample_zero_forever(mat)
    return [next(itr) for _ in range(n)]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-20
    • 1970-01-01
    • 2017-03-31
    • 2013-11-13
    • 2017-03-26
    • 1970-01-01
    相关资源
    最近更新 更多