python - Keras 教程错误 : NameError: name 'layers' is not defined

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

我正在尝试关注 this Keras tutorial,但是在使用命令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)$ 环境中完成这一切。

最佳答案

怎么了

首先,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 .

关于python - Keras 教程错误 : NameError: name 'layers' is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51348085/

相关文章:

python - 如何将 @tf.function 与 Keras 顺序 API 一起使用?

python - python re regex在\\之后分割。 os.linesep用于空白和不空白

python - 生成小数点后一位数字的浮点型随机数

python - 无法使用下划线对 unicode 字符串进行切片/索引

python - Python 中的地理库问题

python - 梯度如何通过 tf.py_func

tensorflow - softmax 忽略负标签(就像 caffe)

python - 无法打开骑行Python27

python - 如何使用并行化 Python 代码在集群上使用多个节点/核心

python - 子函数的自定义打印函数 yield