Python keras.utils.to_categorical() - 名称 keras 未定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44054082/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
keras.utils.to_categorical() - name keras not defined
提问by xjtc55
I am running the test script from the Keras websitefor Multilayer Perceptron (MLP) for multi-class softmax classification. Running in the jupyter notebook I get the error "name 'keras' is not defined". This may be a simple python syntax problem that I am not keen to, however this code comes straight from keras so I expect it should work as is. I have run other neural nets using keras, so I am pretty sure that I have installed everything (installed keras using anaconda). Can anyone help? I have included both the code and the error at the bottom. Thanks!
我正在运行Keras 网站上的测试脚本,用于多层感知器 (MLP) 以进行多类 softmax 分类。在 jupyter 笔记本中运行时,我收到错误“名称 'keras' 未定义”。这可能是一个我不喜欢的简单 python 语法问题,但是这段代码直接来自 keras,所以我希望它可以按原样工作。我已经使用 keras 运行过其他神经网络,所以我很确定我已经安装了所有东西(使用 anaconda 安装了 keras)。任何人都可以帮忙吗?我在底部包含了代码和错误。谢谢!
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.optimizers import SGD
# Generate dummy data
import numpy as np
x_train = np.random.random((1000, 20))
y_train = keras.utils.to_categorical(np.random.randint(10, size=(1000, 1)), num_classes=10)
x_test = np.random.random((100, 20))
y_test = keras.utils.to_categorical(np.random.randint(10, size=(100, 1)), num_classes=10)
model = Sequential()
# Dense(64) is a fully-connected layer with 64 hidden units.
# in the first layer, you must specify the expected input data shape:
# here, 20-dimensional vectors.
model.add(Dense(64, activation='relu', input_dim=20))
model.add(Dropout(0.5))
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(10, activation='softmax'))
sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='categorical_crossentropy',
optimizer=sgd,
metrics=['accuracy'])
model.fit(x_train, y_train,
epochs=20,
batch_size=128)
score = model.evaluate(x_test, y_test, batch_size=128)
This is the error message:
这是错误消息:
NameError Traceback (most recent call last)
<ipython-input-1-6d8174e3cf2a> in <module>()
6 import numpy as np
7 x_train = np.random.random((1000, 20))
----> 8 y_train = keras.utils.to_categorical(np.random.randint(10, size=(1000, 1)), num_classes=10)
9 x_test = np.random.random((100, 20))
10 y_test = keras.utils.to_categorical(np.random.randint(10, size=(100, 1)), num_classes=10)
NameError: name 'keras' is not defined
回答by Mo K
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.optimizers import SGD
From above, you only imported following submodules in keras
从上面,您只导入了以下子模块 keras
keras.models
keras.layers
keras.optimizers
keras.models
keras.layers
keras.optimizers
But this does not automatically import the outer module like keras
or other submodules keras.utils
但这不会像keras
或其他子模块一样自动导入外部模块keras.utils
So, you can do either one
所以,你可以做任何一个
import keras
import keras.utils
from keras import utils as np_utils
but from keras import utils as np_utils
is the most widely used.
但from keras import utils as np_utils
使用最广泛。
Especially import keras
is not a good practice because importing the higher module does not necessarily import its submodules (though it works in Keras)
特别import keras
是不是一个好习惯,因为导入更高的模块并不一定导入它的子模块(尽管它在 Keras 中有效)
For example,
例如,
import urllib
does not necessarily import urllib.request
because if there are so many big submodules, it's inefficient to import all of its submodules every time.
import urllib
不一定要导入,urllib.request
因为如果有这么多大的子模块,每次都导入它的所有子模块效率很低。
EDIT:With the introduction of Tensorflow 2, keras submodules such as keras.utils
should now be imported as
编辑:随着 Tensorflow 2 的引入,keras.utils
现在应该将keras 子模块导入为
from tensorflow.keras import utils as np_utils
回答by prosti
General way:
一般方式:
from keras.utils import to_categorical
Y_train = to_categorical(y_train, num_classes)
Concrete way:
具体方式:
from keras.utils import to_categorical
print(to_categorical(1, 2))
print(to_categorical(0, 2))
Will output
会输出
[0. 1.]
[1. 0.]