Python 3.x Keras.utils无法导入

Python 3.x Keras.utils无法导入,python-3.x,keras,Python 3.x,Keras,下图显示了在CIFAR小型图像数据集上训练简单的深层CNN(卷积神经网络)的部分代码。 我已导入,导入keras.utils(以红色突出显示) 但是,我仍然得到以下错误: 您可以将导入keras中的_category,如下所示 from keras.utils.np_utils import to_categorical Y = [1, 2, 1, 2, 3, 4, 1] Y = to_categorical(Y) print(Y) # output array([[0., 1., 0

下图显示了在CIFAR小型图像数据集上训练简单的深层CNN(卷积神经网络)的部分代码。 我已导入,导入keras.utils(以红色突出显示)

但是,我仍然得到以下错误:


您可以将
导入keras中的_category
,如下所示

from keras.utils.np_utils import to_categorical
Y = [1, 2, 1, 2, 3, 4, 1]

Y = to_categorical(Y)

print(Y)

# output
array([[0., 1., 0., 0., 0.],
       [0., 0., 1., 0., 0.],
       [0., 1., 0., 0., 0.],
       [0., 0., 1., 0., 0.],
       [0., 0., 0., 1., 0.],
       [0., 0., 0., 0., 1.],
       [0., 1., 0., 0., 0.]], dtype=float32)
它可以使用如下所示

from keras.utils.np_utils import to_categorical
Y = [1, 2, 1, 2, 3, 4, 1]

Y = to_categorical(Y)

print(Y)

# output
array([[0., 1., 0., 0., 0.],
       [0., 0., 1., 0., 0.],
       [0., 1., 0., 0., 0.],
       [0., 0., 1., 0., 0.],
       [0., 0., 0., 1., 0.],
       [0., 0., 0., 0., 1.],
       [0., 1., 0., 0., 0.]], dtype=float32)

导入python模块的做法是错误的。您应该采取以下任一做法:

从keras.utils.np\u utils导入到\u category

y_列=到分类(y_列,数量类)
y_测试=to_分类(y_测试,num_类)

从keras.utils导入np_utils

y_列=np_utils.to_categorical(y_列,num_类)
y_测试=np_utils.to_范畴(y_测试,num_类)

只能调用已导入的模块/函数。比如,如果您使用,
从keras.utils.np_utils导入到_category
这意味着您正在从keras.utils.np\u utils包导入到\u category函数。因此,您只能调用来实现_category函数。但是您试图调用keras.utils.to\u category,这不是导入的。此外,您不能直接导入 utils到\u category而不首先导入np\u utils

经验法则:如果您从X导入Y中键入,这意味着您必须按原样调用Y(),而不是X.Y()。这样做是多余的,也是错误的


提示:您不需要在to\u category中提到num\u classes作为参数。Python解释器将智能地为您执行此操作。

尝试从
keras.utils
导入
np_utils
,并像这样使用

from keras.utils import np_utils
np_utils.to_categorical(y_train, num_classes)