将二进制数据加载到 NumPy 数组

Loading the binary data to a NumPy array

我无法读取二进制文件。我有一个 NumPy 数组,

data = array([[ 0.        ,  0.        ,  7.821725  ],
              [ 0.05050505,  0.        ,  7.6358337 ],
              [ 0.1010101 ,  0.        ,  7.453858  ],
              ...,
              [ 4.8989897 ,  5.        , 16.63227   ],
              [ 4.949495  ,  5.        , 16.88153   ],
              [ 5.        ,  5.        , 17.130795  ]], dtype=float32)

我把这个数组以二进制格式写入了一个文件。

file = open('model_binary', 'wb')
data.tofile(file)

现在,我无法从保存的二进制文件中取回数据。我尝试使用 numpy.fromfile() 但它对我没有用。

file = open('model_binary', 'rb')
data = np.fromfile(file)

当我打印数据时,我得到了 [0.00000000e+00 2.19335211e-13 8.33400000e+04 ... 2.04800049e+03 2.04800050e+03 5.25260241e+07] 这绝对不是我想要的。

我运行下面的代码来检查文件中的内容,

for line in file:
    print(line)
    break

我得到了 b'\x00\x00\x00\x00\......\c1\x07@\x00\x00\x00\x00S\xc5{@j\xfd\n' 的输出,我认为它是二进制格式。

我想从保存的二进制文件中取回数组。任何帮助将不胜感激。

正如凯文所说,添加数据类型是必需的。您可能还需要重塑(您的示例中有 3 列。所以

file = open('model_binary', 'rb')
data = fromfile(file, dtype=np.float32).reshape((-1,3))

应该适合你。

顺便说一句,我认为 np.save 确实 保存为二进制格式,应该避免这些问题。