python - Python数据导入错误

标签 python matlab import dataset

我尝试在 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/

相关文章:

没有 '.' 和 '..' 的 MATLAB 目录

python - 如何将 python 脚本分成几部分并循环导入这些部分?

intellij-idea - 在IntelliJ中复制粘贴时如何导入类?

css - LESS 编译器和相关 @import 引用在 Web Essentials 2012 v2.7 中不起作用

python pandas用数字替换数据框中的字符串

python - 如何提取Matlab的datenum的小数部分?

python - INSTALLED_APPS Django 限制中的唯一名称

algorithm - 递归最小二乘 (RLS) 算法的复杂性

c++ - 我应该在 C++ 之后学习 Python 吗?

python - Pyramid 中的多个数据库