跳到内容

save_npz

将稀疏矩阵以 numpy 的 .npz 格式保存到磁盘。注意:这与 scipy 的 save_npz() 不二进制兼容。此二进制格式目前不稳定。它将保存一个只能通过本包的 load_npz() 打开的文件。

参数

名称 类型 描述 默认值
filename stringfile

文件名 (string) 或一个打开的文件 (file-like object),数据将保存到此处。如果文件是 string 或 Path,则在文件名中尚无 .npz 扩展名时,会自动添加此扩展名。

必需
matrix SparseArray

要保存到磁盘的矩阵

必需
compressed bool_

是否以压缩或未压缩模式保存

True

示例

将稀疏矩阵保存到磁盘,并再次加载。

>>> import os
>>> import sparse
>>> import numpy as np
>>> dense_mat = np.array([[[0.0, 0.0], [0.0, 0.70677779]], [[0.0, 0.0], [0.0, 0.86522495]]])
>>> mat = sparse.COO(dense_mat)
>>> mat
<COO: shape=(2, 2, 2), dtype=float64, nnz=2, fill_value=0.0>
>>> sparse.save_npz("mat.npz", mat)
>>> loaded_mat = sparse.load_npz("mat.npz")
>>> loaded_mat
<COO: shape=(2, 2, 2), dtype=float64, nnz=2, fill_value=0.0>
>>> os.remove("mat.npz")
另请参阅
源代码位于 sparse/numba_backend/_io.py
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
def save_npz(filename, matrix, compressed=True):
    """Save a sparse matrix to disk in numpy's `.npz` format.
    Note: This is not binary compatible with scipy's `save_npz()`.
    This binary format is not currently stable. Will save a file
    that can only be opend with this package's `load_npz()`.

    Parameters
    ----------
    filename : string or file
        Either the file name (string) or an open file (file-like object)
        where the data will be saved. If file is a string or a Path, the
        `.npz` extension will be appended to the file name if it is not
        already there
    matrix : SparseArray
        The matrix to save to disk
    compressed : bool
        Whether to save in compressed or uncompressed mode

    Examples
    --------
    Store sparse matrix to disk, and load it again:

    >>> import os
    >>> import sparse
    >>> import numpy as np
    >>> dense_mat = np.array([[[0.0, 0.0], [0.0, 0.70677779]], [[0.0, 0.0], [0.0, 0.86522495]]])
    >>> mat = sparse.COO(dense_mat)
    >>> mat
    <COO: shape=(2, 2, 2), dtype=float64, nnz=2, fill_value=0.0>
    >>> sparse.save_npz("mat.npz", mat)
    >>> loaded_mat = sparse.load_npz("mat.npz")
    >>> loaded_mat
    <COO: shape=(2, 2, 2), dtype=float64, nnz=2, fill_value=0.0>
    >>> os.remove("mat.npz")

    See Also
    --------
    - [`sparse.load_npz`][]
    - [`scipy.sparse.save_npz`][]
    - [`scipy.sparse.load_npz`][]
    - [`numpy.savez`][]
    - [`numpy.load`][]

    """

    nodes = {
        "data": matrix.data,
        "shape": matrix.shape,
        "fill_value": matrix.fill_value,
    }

    if type(matrix) is COO:
        nodes["coords"] = matrix.coords
    elif type(matrix) is GCXS:
        nodes["indices"] = matrix.indices
        nodes["indptr"] = matrix.indptr
        nodes["compressed_axes"] = matrix.compressed_axes

    if compressed:
        np.savez_compressed(filename, **nodes)
    else:
        np.savez(filename, **nodes)