Randomly shuffle a sparse matrix in python

左心房为你撑大大i 提交于 2019-12-30 06:20:31

问题


is there an easy way to shuffle a sparse matrix in python?

This is how I shuffle a non-sparse matrix:

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

How can I do it with numpy sparse?


回答1:


Ok, found it. The sparse format looks a bit confusing in the print-out.

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



回答2:


In case anyone is looking to randomly get a subsample of rows from a sparse matrix, this related post may also be useful: How should I go about subsampling from a scipy.sparse.csr.csr_matrix and a list




回答3:


A better way can be shuffling the index of CSR Matrix and fetching the rows of matrix as such:

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


来源:https://stackoverflow.com/questions/12230527/randomly-shuffle-a-sparse-matrix-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!