代码之家  ›  专栏  ›  技术社区  ›  NicolaiF

从scipy稀疏矩阵中求n个随机零元

  •  0
  • NicolaiF  · 技术社区  · 8 年前

    我有一个很大的稀疏矩阵,在scipy lil_矩阵格式中,它的大小是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])
    

    我正在寻找一种方法来得到一个长度与非零掩模相同,但有零的掩模…

    1 回复  |  直到 8 年前
        1
  •  2
  •   hilberts_drinking_problem    8 年前

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

    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)]