python 转储和加载稀疏矩阵https://stackoverflow.com/questions/11129429/storing-numpy-sparse-matrix-in-hdf5-pyt

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 转储和加载稀疏矩阵https://stackoverflow.com/questions/11129429/storing-numpy-sparse-matrix-in-hdf5-pyt相关的知识,希望对你有一定的参考价值。

import tables as tb
from numpy import array
from scipy import sparse


def store_sparse_mat(path, name, m, separator='__'):
    if (m.__class__ not in [sparse.csr.csr_matrix, sparse.csc.csc_matrix]):
        raise TypeError("This code only works for csr/csc matrices")
    with tb.openFile(path, 'a') as f:
        for par in ('data', 'indices', 'indptr', 'shape'):
            full_name = '%s%s%s' % (name, separator, par)
            try:
                n = getattr(f.root, full_name)
                n._f_remove()
            except AttributeError:
                pass

            arr = array(getattr(m, par))
            atom = tb.Atom.from_dtype(arr.dtype)
            ds = f.createCArray(f.root, full_name, atom, arr.shape)
            ds[:] = arr


def load_sparse_mat(
        path, name, type_=sparse.csr.csr_matrix, separator='__', default=None):
    if (type_ not in [sparse.csr.csr_matrix, sparse.csc.csc_matrix]):
        raise TypeError("This code only works for csr/csc matrices")
    if not os.path.isfile(path):
        return default
    with tb.openFile(path) as f:
        pars = []
        for par in ('data', 'indices', 'indptr', 'shape'):
            try:
                arr = getattr(f.root, '%s%s%s' % (name, separator, par))
            except AttributeError:
                return default
            r = arr.read()
            pars.append(r)
        m = type_(tuple(pars[:3]), shape=pars[3])
        return m

以上是关于python 转储和加载稀疏矩阵https://stackoverflow.com/questions/11129429/storing-numpy-sparse-matrix-in-hdf5-pyt的主要内容,如果未能解决你的问题,请参考以下文章

将一个 numpy 稀疏矩阵转储到 libsvm 后形状不一样

将使用-v7.3(HDF5)保存的Matlab稀疏矩阵加载到Python中并对其进行操作

稠密矩阵怎么转成稀疏矩阵 python

将稀疏 scipy 矩阵加载到现有的 numpy 密集矩阵中

Python的稀疏矩阵和参数保存 save/load

pyspark:将稀疏局部矩阵转换为 RDD