首页 > 解决方案 > Python中的数据导入错误

问题描述

我正在尝试在 Python 中导入 MNIST 数据集,如下所示:

import h5py
f = h5py.File("mnist.h5")
x_test = f["x_test"]
x_train = f["x_train"]
y_test = f["y_test"]
y_train = f["y_train"]

说的类型,y_train 说 h5py._hl.dataset.Dataset

为了数学上的方便,我想将它们转换为浮点数。我试试这个:

D = x_train.astype(float)
y_train = y_train.astype(float)+np.ones((60000,1));

但我得到了这个回溯:

Traceback (most recent call last):

  File "<ipython-input-14-f3677d523d45>", line 1, in <module>
    y_train = y_train.astype(float)+np.ones((60000,1));

TypeError: unsupported operand type(s) for +: 'AstypeContext' and 'float'

我错过了什么?谢谢。

标签: pythonmatlabimportdataset

解决方案


您正在使用两个不同的库,它们对astype.

如果您在 中执行此操作,则可以执行以下numpy操作:

a = np.array([1, 2, 3])

a = a.astype(float) + np.ones((60000,1))

但是在 h5py 中, astype 是一个不同的函数,并且打算在上下文管理器中使用:

这将引发与您得到的相同的错误:

import h5py
f = h5py.File('mytestfile.hdf5', 'w')
dset = f.create_dataset("default", (100,))
dset.astype(float)  + np.ones((60000,1))

但是下面的代码将起作用(请参阅 h5py 文档中的astype):

f = h5py.File('mytestfile.hdf5', 'w')
dset = f.create_dataset("default", (100,))

with dset.astype('float'):
    out = dset[:]
    out += np.ones((100,))

此问题类似于使用 astype 在 H5py 中创建对 HDF 数据集的引用


推荐阅读