【问题标题】:Keras Tutorial Error: NameError: name 'layers' is not definedKeras 教程错误:NameError:未定义名称“层”
【发布时间】:2018-12-23 04:34:01
【问题描述】:

我正在尝试遵循this Keras 教程,但是使用命令python3 test.py 编译时遇到以下错误:

Traceback (most recent call last):
  File "test.py", line 13, in <module>
    layers.Dense(64, activation='sigmoid')
NameError: name 'layers' is not defined

我的代码如下:

import tensorflow as tf
from tensorflow import keras

model = keras.Sequential()
# Adds a densely-connected layer with 64 units to the model:
model.add(keras.layers.Dense(64, activation='relu'))
# Add another:
model.add(keras.layers.Dense(64, activation='relu'))
# Add a softmax layer with 10 output units:
model.add(keras.layers.Dense(10, activation='softmax'))

# Create a sigmoid layer:
layers.Dense(64, activation='sigmoid')

# A linear layer with L1 regularization of factor 0.01 applied to the kernel matrix:
layers.Dense(64, kernel_regularizer=keras.regularizers.l1(0.01))
# A linear layer with L2 regularization of factor 0.01 applied to the bias vector:
layers.Dense(64, bias_regularizer=keras.regularizers.l2(0.01))

# A linear layer with a kernel initialized to a random orthogonal matrix:
layers.Dense(64, kernel_initializer='orthogonal')

Python 版本:3.6.6

操作系统:MacOS High Sierra

我也是在命令行(tensorflow)$环境中做这一切的。

【问题讨论】:

  • 你很可能打算写model.add(keras.layers....etc)。
  • @LucaCappelletti 我直接从tensorflow.org/guide/keras 复制了它(参见“配置层”部分。)
  • 是的,它解释了它在 model.add 中的作用。没必要。
  • 你可以考虑阅读the keras documentation上的keras教程。
  • @LucaCappelletti 哦,好的,我很抱歉!这对我来说似乎是一个更好的起点。感谢您的帮助。 :) 我会留下这个,以防万一将来另一个新手感到困惑。

标签: python python-3.x tensorflow keras keras-layer


【解决方案1】:

怎么了

首先,python 向您发出信号,名称为 layers 的对象不在脚本范围内。

但实际的错误是代码是从 TensorFlow's Keras documentation 复制出来的,但在文档中,代码的第二部分仅用于解释 model.add(...) 调用中实例化的内容。

所以只需删除所有以layers 开头的代码,因为它只是一个解释。

import tensorflow as tf
from tensorflow import keras

model = keras.Sequential()
# Adds a densely-connected layer with 64 units to the model:
model.add(keras.layers.Dense(64, activation='relu'))
# Add another:
model.add(keras.layers.Dense(64, activation='relu'))
# Add a softmax layer with 10 output units:
model.add(keras.layers.Dense(10, activation='softmax'))

进一步阅读

您应该考虑在Keras Documentation 上了解Keras。

【讨论】:

    【解决方案2】:

    对我来说,使用 from tensorflow.keras import layers 导入图层就可以了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-13
      • 1970-01-01
      • 2016-03-11
      相关资源
      最近更新 更多