【问题标题】:keras.utils.to_categorical() - name keras not definedkeras.utils.to_categorical() - 名称 keras 未定义
【发布时间】:2021-07-21 19:51:52
【问题描述】:

我正在从Keras website 运行用于多层感知器 (MLP) 的测试脚本,以进行多类 softmax 分类。在 jupyter notebook 中运行时出现错误“未定义名称 '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)

这是错误信息:

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

【问题讨论】:

  • 可能是import keras?还是from keras.utils import to_categorical
  • @devforfu 两者都有效!请张贴作为答案我可以想象我不会是唯一有这个问题的人。

标签: python keras


【解决方案1】:
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.optimizers import SGD

从上面,您只在keras 中导入了以下子模块

  • keras.models
  • keras.layers
  • keras.optimizers

但这不会像keras这样自动导入外部模块 或其他子模块keras.utils

所以,你可以做任何一个

import keras
import keras.utils
from keras import utils as np_utils

from keras import utils as np_utils 是使用最广泛的。

特别是import keras 不是一个好习惯,因为导入更高的模块并不一定会导入它的子模块(尽管它在 Keras 中有效)

例如,

import urllib 不一定要导入urllib.request,因为如果有这么多大的子模块,每次都导入它的所有子模块是低效的。

编辑: 随着 Tensorflow 2 的引入,keras.utils 等 keras 子模块现在应该导入为

from tensorflow.keras import utils as np_utils

【讨论】:

    【解决方案2】:

    虽然这是一个老问题,但尚未更新访问 to_categorical 函数的最新方法。

    这个函数现在已经打包在 np_utils 中了。

    正确的访问方式是:

    from keras.utils.np_utils import to_categorical
    

    【讨论】:

      【解决方案3】:

      一般方式:

      from keras.utils import to_categorical
      Y_train = to_categorical(y_train, num_classes)
      

      具体方式:

      from keras.utils import to_categorical
      
      print(to_categorical(1, 2))
      print(to_categorical(0, 2))
      

      会输出

      [0. 1.]
      [1. 0.]
      

      【讨论】:

        【解决方案4】:

        这对我有用:

        import tensorflow as tf
        from keras import utils as np_utils 
        
         y_train =  tf.keras.utils.to_categorical(y_train, num_classes)
         y_test = tf.keras.utils.to_categorical(y_test, num_classes)
        

        【讨论】:

          猜你喜欢
          • 2022-07-03
          • 1970-01-01
          • 2018-12-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-09-29
          相关资源
          最近更新 更多