将 scipy 稀疏矩阵存储为 HDF5

2024-04-03

我想以 HDF5 格式压缩和存储一个巨大的 Scipy 矩阵。我该怎么做呢?我尝试过以下代码:

a = csr_matrix((dat, (row, col)), shape=(947969, 36039))
f = h5py.File('foo.h5','w')    
dset = f.create_dataset("init", data=a, dtype = int, compression='gzip')

我遇到这样的错误,

TypeError: Scalar datasets don't support chunk/filter options
IOError: Can't prepare for writing data (No appropriate function for conversion path)

我无法将其转换为 numpy 数组,因为会出现内存溢出。最好的方法是什么?


csr 矩阵将其值存储在 3 个数组中。它不是数组或数组子类,所以h5py无法直接保存。您能做的最好的事情就是保存属性,并在加载时重新创建矩阵:

In [248]: M = sparse.random(5,10,.1, 'csr')
In [249]: M
Out[249]: 
<5x10 sparse matrix of type '<class 'numpy.float64'>'
    with 5 stored elements in Compressed Sparse Row format>
In [250]: M.data
Out[250]: array([ 0.91615298,  0.49907752,  0.09197862,  0.90442401,  0.93772772])
In [251]: M.indptr
Out[251]: array([0, 0, 1, 2, 3, 5], dtype=int32)
In [252]: M.indices
Out[252]: array([5, 7, 5, 2, 6], dtype=int32)
In [253]: M.data
Out[253]: array([ 0.91615298,  0.49907752,  0.09197862,  0.90442401,  0.93772772])

coo格式有data, row, col属性,基本相同(dat, (row, col))你用来创建你的a.

In [254]: M.tocoo().row
Out[254]: array([1, 2, 3, 4, 4], dtype=int32)

The new save_npz函数的作用是:

arrays_dict = dict(format=matrix.format, shape=matrix.shape, data=matrix.data)
if matrix.format in ('csc', 'csr', 'bsr'):
    arrays_dict.update(indices=matrix.indices, indptr=matrix.indptr)
...
elif matrix.format == 'coo':
    arrays_dict.update(row=matrix.row, col=matrix.col)
...
np.savez(file, **arrays_dict)

换句话说,它收集字典中的相关属性并使用savez创建 zip 存档。

可以使用相同类型的方法h5py文件。更多相关内容save_npz在最近的一个 SO 问题中,包含源代码的链接。

scipy.sparse 中缺少 save_npz 方法 https://stackoverflow.com/questions/43014503/save-npz-method-missing-from-scipy-sparse

看看你是否可以让这个工作。如果你可以创建一个csr矩阵,您可以从其属性(或coo等价物)。如果需要,我可以制作一个工作示例。

csr 到 h5py 的示例

import numpy as np
import h5py
from scipy import sparse

M = sparse.random(10,10,.2, 'csr')
print(repr(M))

print(M.data)
print(M.indices)
print(M.indptr)

f = h5py.File('sparse.h5','w')
g = f.create_group('Mcsr')
g.create_dataset('data',data=M.data)
g.create_dataset('indptr',data=M.indptr)
g.create_dataset('indices',data=M.indices)
g.attrs['shape'] = M.shape
f.close()

f = h5py.File('sparse.h5','r')
print(list(f.keys()))
print(list(f['Mcsr'].keys()))

g2 = f['Mcsr']
print(g2.attrs['shape'])

M1 = sparse.csr_matrix((g2['data'][:],g2['indices'][:],
    g2['indptr'][:]), g2.attrs['shape'])
print(repr(M1))
print(np.allclose(M1.A, M.A))
f.close()

生产

1314:~/mypy$ python3 stack43390038.py 
<10x10 sparse matrix of type '<class 'numpy.float64'>'
    with 20 stored elements in Compressed Sparse Row format>
[ 0.13640389  0.92698959 ....  0.7762265 ]
[4 5 0 3 0 2 0 2 5 6 7 1 7 9 1 3 4 6 8 9]
[ 0  2  4  6  9 11 11 11 14 19 20]
['Mcsr']
['data', 'indices', 'indptr']
[10 10]
<10x10 sparse matrix of type '<class 'numpy.float64'>'
    with 20 stored elements in Compressed Sparse Row format>
True

首席运营官替代方案

Mo = M.tocoo()
g = f.create_group('Mcoo')
g.create_dataset('data', data=Mo.data)
g.create_dataset('row', data=Mo.row)
g.create_dataset('col', data=Mo.col)
g.attrs['shape'] = Mo.shape

g2 = f['Mcoo']
M2 = sparse.coo_matrix((g2['data'], (g2['row'], g2['col'])),
   g2.attrs['shape'])   # don't need the [:]
# could also use sparse.csr_matrix or M2.tocsr()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 scipy 稀疏矩阵存储为 HDF5 的相关文章

随机推荐

  • 无法使用 Google Drive api 复制 Google 幻灯片文件

    我想复制我的谷歌驱动器中存在的现有模板 ppt 然后我想将占位符文本更改为其他文本 这就是我正在尝试的 from google oauth2 import service account import googleapiclient dis
  • 如何从 django 数据库中下载 blob 字段中的数据?

    我有一个表 其中有一个包含一些数据的 blob 列 我如何在 django 中下载 blob 内容 我尝试了提到的解决方案here https stackoverflow com questions 4915397 django blob
  • 如何在 Python 中测试 Web API 限制

    我想使用 Python 测试给定站点的 Web API 限制 此 API 限制允许每个 IP 在 Y 秒内最多发出 X 个请求 我希望能够测试此限制的可靠性 特别是在边界情况下 X 1 请求 X 1 请求 你能建议一个好方法吗 我会编写一个
  • 如何在 Vue JS SPA 中进行开放图图像?

    我正在尝试在我的 VueJS 单页应用程序中包含开放图形图像 https developers facebook com tools debug https developers facebook com tools debug 给我这个链
  • 模糊测试(框架)Web应用程序?

    是否有可以对 Web 应用程序执行模糊测试的框架 我知道Selenium and WebDriver用于为 Web 应用程序构建测试 但我对内置模糊测试的库 框架或项目特别感兴趣 因此我不需要重新发明轮子 例如 我可以从以下功能中受益 随机
  • `.create()` 方法默认不支持可写嵌套字段。

    关于 DRF 中与中间模型的多对多关系的序列化 我有一个大问题 如果请求方法是 get 则一切正常 但是当我尝试将数据发布或放置到 API 时 我收到以下错误 Traceback most recent call last File Lib
  • ASP.NET MVC4 捆绑单个文件

    有没有办法使用 MVC4 中的新捆绑功能来捆绑单个文件 我知道捆绑单个文件没有多大意义 但我想使用服务器端缩小并让 MVC 在 URL 末尾附加哈希以用于缓存目的 我已经尝试过 Scripts Url Scripts myscript js
  • iOS7 中非消耗性产品的服务器端收据验证和 transactionReceipt 弃用

    我正在从以前的 iOS 移植一个工作应用程序 但在处理新的应用程序内购买收据时遇到了问题 我们现在的工作方式是从SKPaymentTransaction对象并将其发送到服务器进行验证 从我从其他问题中收集到的信息来看 收据现在似乎保存在一个
  • Android studio 1.4 和矢量图像

    今天我将android studio更新到1 4版本 我在变更日志中看到 您也可以为 api Error Execution failed for task app transformClassesWithDexForDebug gt co
  • Eclipse Java IDE JUnit5:junit.jupiter.api.Assertions 不可访问

    我对整个编程很陌生 但这是我的问题 我曾经通过右键单击项目在 Eclipse 中添加 JUnit 测试用例 然后添加新增 gt JUnit 测试用例 目前 我无法实现任何测试方法 因为 Eclipse 在线告诉我 import static
  • FPDF/FPDI 错误:致命错误:找不到类“setasign\Fpdi\FpdfTpl”

    我正在尝试为现有的 PDF 文档添加水印 这个错误在过去两天一直困扰着我 我的 FPDI 库位于 fpdi src 中 fpdf 库位于 fpdf 中 引发错误的文件是 Fpdi php 第 27 行 以下是前 30 行
  • Java 中的 tan() 返回一个奇怪的值

    我的代码将一个以弧度为单位的角度传递给cos tan and sin 一切似乎都工作正常 除了晒黑90 这给出了值16331239353195370由于某些奇怪的原因 示例代码 import java text DecimalFormat
  • 当最小 SDK 从 21 增加到 24 时,APK 大小增加了 35mb

    最近 我们将支持的最小 SDK 从 API 21 提高到了 24 显然 这一变化导致我们的 APK 大小从 65mb 增加到 103mb 从Android studio中的APK分析中 我们可以看到所有的 so文件的大小基本上都增加了一倍
  • 替换 Java 中的静态引用方法

    我有一个如下所示的类 其方法仅返回一个字符串 但我想修改它从另一个类返回的内容 而无需自己对其进行硬编码 public class Name public static String getName return MyName 有什么办法可
  • 协议中的公共默认初始化

    我有这个代码 public protocol MyProtocol init public extension MyProtocol public init self init public final class MyClass MyPr
  • 如何处理“intrin.h:没有这样的文件或目录”?

    include
  • 深层路由的 webpack HistoryApiFallback 配置

    webpack dev server 可以设置为将您发送回 index html 并找到单个路由的脚本 例如http localhost 4301 sdr http localhost 4301 sdr但是当您放入更深的路线 或末尾带有 的
  • Mercurial 和 Notepad++ 集成

    Notepad 是否有插件可以与 Mercurial 和 TortoiseHg 集成 如果将以下内容添加到我们的配置文件中 您可以使用 Notepad 打开文件 tortoisehg editor
  • 在用户交互之前,GoogleMap 不会加载详细地图

    我正在 android 上编写一个应用程序 它将显示谷歌地图的地图 当我启动应用程序时 地图以当前位置为中心 当我使用animateCamera 我可以看到整个世界的放大动画 直到它聚焦于当前位置 问题是我需要触摸地图才能使地图以我期望的缩
  • 将 scipy 稀疏矩阵存储为 HDF5

    我想以 HDF5 格式压缩和存储一个巨大的 Scipy 矩阵 我该怎么做呢 我尝试过以下代码 a csr matrix dat row col shape 947969 36039 f h5py File foo h5 w dset f c