【发布时间】:2018-07-04 05:00:12
【问题描述】:
【问题讨论】:
标签: python-3.x keras
【问题讨论】:
标签: python-3.x keras
您可以在 keras 中导入to_categorical,如下所示。
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)
【讨论】:
尝试从keras.utils 导入np_utils 并像这样使用
from keras.utils import np_utils
np_utils.to_categorical(y_train, num_classes)
【讨论】:
您在导入 python 模块时遵循了错误的做法。您应该采用以下任一做法:
从 keras.utils.np_utils 导入到_categorical
y_train = to_categorical(y_train, num_classes)
y_test = to_categorical(y_test, num_classes)
OR
从 keras.utils 导入 np_utils
y_train = np_utils.to_categorical(y_train, num_classes)
y_test = np_utils.to_categorical(y_test, num_classes)
您只能调用已导入的模块/函数。说,如果你使用,
from keras.utils.np_utils import to_categorical
这意味着您正在从 keras.utils.np_utils 包中导入 to_categorical 函数。因此,您只能调用 to_categorical 函数。但是您尝试调用未导入的 keras.utils.to_categorical。另外,不能直接导入
to_categorical 从 utils 而不首先导入 np_utils。
经验法则:如果您输入 from X import Y,这意味着您必须照原样调用 Y() 而不是 X.Y()。这样做是多余的,也是错误的。
提示:您无需在 to_categorical 中将 num_classes 作为参数提及。 Python 解释器会智能地为你做这件事。
【讨论】: