我尝试在 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
为了数学上的方便,我想将它们转换为 float 。我试试这个:
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'
我错过了什么?谢谢。
最佳答案
您正在使用两个不同的库,它们对 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 docs 中的 astype ):
f = h5py.File('mytestfile.hdf5', 'w')
dset = f.create_dataset("default", (100,))
with dset.astype('float'):
out = dset[:]
out += np.ones((100,))
此问题类似于Creating reference to HDF dataset in H5py using astype
关于python - Python数据导入错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50992080/