Save / load scipy array,sparse csr_matrix

A csr_matrix has 3 data attributes that matter: .data.indices, and .indptr. All are simple ndarrays, so numpy.save will work on them. Save the three arrays with numpy.save or numpy.savez, load them back with numpy.load, and then recreate the sparse matrix object with:

new_csr = csr_matrix((data, indices, indptr), shape=(M, N))



def save_sparse_csr(filename,array):

        np.savez(filename,data = array.data ,indices=array.indices,indptr =array.indptr, shape=array.shape )


def load_sparse_csr(npzfilename):
        loader = np.load(npzfilename)
        return csr_matrix((  loader['data'], loader['indices'], loader['indptr']),shape = loader['shape'])


def save_ids_array(filename,array):
        np.savez(filename+'.ids',data = array)


def load_ids_array(npzfilename):
        loader = np.load(npzfilename)
        return loader['data']
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章