从磁盘加载 NumPy 的 .npz
格式的稀疏矩阵。注意:这与 SciPy 的 save_npz()
输出不进行二进制兼容。此二进制格式目前不稳定。仅加载本包保存的文件。
参数
名称 |
类型 |
描述 |
默认值 |
filename
|
类文件对象、字符串或 pathlib.Path
|
要读取的文件。类文件对象必须支持 seek() 和 read() 方法。
|
必需
|
返回值
示例
有关用法示例,请参阅 sparse.save_npz
。
另请参阅
源代码位于 sparse/numba_backend/_io.py
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132 | def load_npz(filename):
"""Load a sparse matrix in numpy's `.npz` format from disk.
Note: This is not binary compatible with scipy's `save_npz()`
output. This binary format is not currently stable.
Will only load files saved by this package.
Parameters
----------
filename : file-like object, string, or pathlib.Path
The file to read. File-like objects must support the
`seek()` and `read()` methods.
Returns
-------
SparseArray
The sparse matrix at path `filename`.
Examples
--------
See [`sparse.save_npz`][] for usage examples.
See Also
--------
- [`sparse.save_npz`][]
- [`scipy.sparse.save_npz`][]
- [`scipy.sparse.load_npz`][]
- [`numpy.savez`][]
- [`numpy.load`][]
"""
with np.load(filename) as fp:
try:
coords = fp["coords"]
data = fp["data"]
shape = tuple(fp["shape"])
fill_value = fp["fill_value"][()]
return COO(
coords=coords,
data=data,
shape=shape,
sorted=True,
has_duplicates=False,
fill_value=fill_value,
)
except KeyError:
pass
try:
data = fp["data"]
indices = fp["indices"]
indptr = fp["indptr"]
comp_axes = fp["compressed_axes"]
shape = tuple(fp["shape"])
fill_value = fp["fill_value"][()]
return GCXS(
(data, indices, indptr),
shape=shape,
fill_value=fill_value,
compressed_axes=comp_axes,
)
except KeyError as e:
raise RuntimeError(f"The file {filename!s} does not contain a valid sparse matrix") from e
|