[英]Keras Tutorial Error: NameError: name 'layers' is not defined
I am trying to follow this Keras tutorial, but I encounter the following error when compiling using the command python3 test.py
:我正在尝试遵循此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
My code is as follows:我的代码如下:
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 version: 3.6.6 Python版本:3.6.6
Operating System: MacOS High Sierra操作系统:MacOS High Sierra
I am also doing this all in the command line (tensorflow)$
environment.我也在命令行
(tensorflow)$
环境中执行所有这些操作。
First of all, python is signalling you that an object with name layers
is not present within the scope of the script.首先,python 向您发出信号,表示脚本范围内不存在具有名称
layers
的对象。
But the actual error is that the code was copied out of the TensorFlow's Keras documentation , but in the documentation the second part of the code serves only to explain what is being instantiated within the model.add(...)
call.但实际的错误是代码是从TensorFlow 的 Keras 文档中复制出来的,但在文档中,代码的第二部分仅用于解释在
model.add(...)
调用中实例化的model.add(...)
。
So just drop all the code that begins with layers
, as it is just an explanation.所以只需删除所有以
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'))
You should consider learning about Keras on the Keras Documentation .您应该考虑在Keras 文档中了解Keras 。
对我来说,使用from tensorflow.keras import layers
完成了这项工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.