【问题标题】:Randomly shuffle a sparse matrix in python在python中随机打乱一个稀疏矩阵
【发布时间】:2012-08-27 04:01:36
【问题描述】:

有没有简单的方法在 python 中打乱稀疏矩阵?

这就是我洗牌非稀疏矩阵的方式:

    index = np.arange(np.shape(matrix)[0])
    np.random.shuffle(index)
    return matrix[index]

如何使用 numpy sparse 做到这一点?

【问题讨论】:

    标签: python numpy sparse-matrix shuffle


    【解决方案1】:

    一个更好的方法是洗牌 CSR 矩阵的索引并获取矩阵的行:

    from random import shuffle
    indices = np.arange(matrix.shape[0]) #gets the number of rows 
    shuffle(indices)
    shuffled_matrix = matrix[list(indices)] 
    

    【讨论】:

      【解决方案2】:

      如果有人希望从稀疏矩阵中随机获取行的子样本,此相关帖子也可能有用:How should I go about subsampling from a scipy.sparse.csr.csr_matrix and a list

      【讨论】:

        【解决方案3】:

        好的,找到了。稀疏格式在打印输出中看起来有点混乱。

            index = np.arange(np.shape(matrix)[0])
            print index
            np.random.shuffle(index)
            return matrix[index, :]
        

        【讨论】:

        • 仅适用于 csr_matrix。我收到一个错误“coo_matrix”对象没有属性“getitem”。
        • 应该注意,这会创建数组的副本,这意味着除非您有足够的 RAM 将两个副本保存在内存中,否则它将无法工作。
        猜你喜欢
        • 1970-01-01
        • 2019-10-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-24
        • 1970-01-01
        • 1970-01-01
        • 2015-04-26
        相关资源
        最近更新 更多