python - 将 vlen 与 h5py 一起使用时出现莫名其妙的行为

标签 python numpy hdf5 h5py

我正在使用 h5py 构建数据集。因为我想存储具有不同 #of rows 维度的数组,所以我使用 h5py special_type vlen。但是,我遇到了无法解释的行为,也许你能帮助我理解正在发生的事情:

>>>> import h5py
>>>> import numpy as np
>>>> fp = h5py.File(datasource_fname, mode='w') 
>>>> dt = h5py.special_dtype(vlen=np.dtype('float32'))
>>>> train_targets = fp.create_dataset('target_sequence', shape=(9549, 5,), dtype=dt)
>>>> test
Out[130]: 
array([[ 0.,  1.,  1.,  1.,  0.,  1.,  1.,  0.,  1.,  0.,  0.],
       [ 1.,  0.,  0.,  0.,  1.,  0.,  0.,  1.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  1.,  1.]])
>>>> train_targets[0] = test
>>>> train_targets[0]
Out[138]: 
array([ array([ 0.,  1.,  0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.,  1.], dtype=float32),
        array([ 1.,  0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.,  1.,  0.], dtype=float32),
        array([ 0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.,  1.,  0.,  0.], dtype=float32),
        array([ 0.,  0.,  1.,  0.,  0.,  0.,  0.,  1.,  0.,  0.,  0.], dtype=float32),
        array([ 0.,  1.,  0.,  0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.], dtype=float32)], dtype=object)

我确实希望 train_targets[0] 具有这种形状,但是我无法识别数组中的行。他们似乎完全困惑,但它是一致的。我的意思是,每次我尝试上面的代码时,train_targets[0] 看起来都一样。

澄清一下:我的 train_targets 中的第一个元素(在本例中为 test)的形状为 (5,11),但是第二个元素元素的形状可能是 (5,38),这就是我使用 vlen 的原因。

谢谢你的帮助

垫子

最佳答案

我觉得

train_targets[0] = test

已将您的(11,5) 数组作为F 有序数组存储在一行train_targets 中。根据 (9549,5) 形状,这是一行 5 个元素。因为它是 vlen,所以每个元素都是一个长度为 11 的一维数组。

这就是您在 train_targets[0] 中得到的结果 - 一个包含 5 个数组的数组,每个形状 (11,),其值取自 test(顺序 F)。

所以我认为有 2 个问题 - 2d 形状意味着什么,以及 vlen 允许什么。


我的 h5py 版本是 v2.3 之前的版本,所以我只得到字符串 vlen。但我怀疑您的问题可能是 vlen 仅适用于一维数组,可以说是字节字符串的扩展。

shape=(9549, 5,) 中的 5test.shape 中的 5 有什么关系吗?我认为不是,至少不是 numpyh5py 看到的。

当我按照字符串 vlen 示例创建文件时:

>>> f = h5py.File('foo.hdf5')
>>> dt = h5py.special_dtype(vlen=str)
>>> ds = f.create_dataset('VLDS', (100,100), dtype=dt)

然后做:

ds[0]='this one string'

然后查看 ds[0],我得到一个包含 100 个元素的对象数组,每个元素都是这个字符串。也就是说,我设置了一整行ds

ds[0,0]='another'

是只设置一个元素的正确方法。

vlen 是“可变长度”,而不是“可变形状”。而 https://www.hdfgroup.org/HDF5/doc/TechNotes/VLTypes.html文档对此并不完全清楚,我认为你可以存储形状为 (11,)(38,) 的一维数组和 vlen,但不是二维的。


实际上,train_targets 输出重现为:

In [54]: test1=np.empty((5,),dtype=object)
In [55]: for i in range(5):
    test1[i]=test.T.flatten()[i:i+11]

它是从转置(F 顺序)中获取的 11 个值,但针对每个子数组进行了移位。

关于python - 将 vlen 与 h5py 一起使用时出现莫名其妙的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30543791/

相关文章:

python - 将数据集转换为 HDF5 数据集

python - 在pycharm中运行nupichelloworld

python - 带索引数组的索引多维数组

python - 在 Python 中,如何对嵌套的整数列表 : [[1, 0]、[1,1]、[1,0]] → [3,1] 进行数值求和

Python Pandas - 将行添加到空数据框

python - 将 Numpy 数组保存为图像(说明)

python - 隔离 3d 数据点的策略

c++ - 将 H5::CompType 初始化为类的静态成员

python - 为什么 setup_requires 不能为 numpy 正常工作?

python - h5py:如何组织 HDF5 文件以有效读取混合数据类型对象