h5py矩阵存储精度

问题描述 投票:1回答:1

我想使用Python3-h5py将矩阵存储到.HDF5格式我的问题是,当我将初始数据与从HDF5文件中提取的数据进行比较时,我得到了惊人的差异。

import numpy
import h5py

# Create a vector of float64 values between 0 and 1
A = numpy.array(range(16384+1))/(16384+1)

# Save the corresponding float16 array to a HDF5 file
Fid = h5py.File("Output/Test.hdf5","w")
Group01 = Fid.create_group("Group")
Group01.create_dataset("Data", data=A, dtype='f2')
# Group01.create_dataset("Data", data=A.astype(numpy.float16), dtype='f2')# Use that line to avoid the bug
Fid.flush()
Fid.close()

# Read the HDF5 file
Fid = h5py.File("Output/Test.hdf5",'r')
B = Fid["Group/Data"][:]
Fid.close()

# Compare float64 and float16 Values
print(A[8192])
print(B[8192])
print("")
print(A[8192+1])
print(B[8192+1])
print("")
print(A[16384])
print(B[16384])

给:

0.499969484284
0.25

0.500030515716
0.5

0.999938968569
0.5

有时我得到的差异大约是“0.00003”,有时是“0.4999”。通常情况下,我应该总是得到“0.00003”,它与float16舍入有关,介于0和1之间。但是“0.4999”值确实是意料之外的,我注意到它发生在接近幂的值上。 2(例如“~1 / 2”将存储为“~1 / 4”)。

这是h5py包中的错误吗?

提前致谢,

斯特凡,

[Xubuntu 17.09 64bits + python3-h5py v2.7.1-2 + python3 v3.6.3-0ubuntu2]

python-3.x numpy floating-point precision h5py
1个回答
1
投票

我不完全确定这可以被视为一个答案,但我终于以一个小小的规避摆脱了我的问题。

总结一下,看起来有一个“h5py v2.7.1-2”的错误

使用h5py存储数组时,请勿使用以下命令:

`Group01.create_dataset("Data", data=A, dtype='f2')# Buggy command`

但反而 :

`Group01.create_dataset("Data", data=A.astype(numpy.float16), dtype='f2')`
© www.soinside.com 2019 - 2024. All rights reserved.