The Pointer
The Pointer

Reputation: 2386

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:

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

Operating System: MacOS High Sierra

I am also doing this all in the command line (tensorflow)$ environment.

Upvotes: 5

Views: 33807

Answers (2)

Codehauk
Codehauk

Reputation: 63

For me importing layers with from tensorflow.keras import layers did the job.

Upvotes: 6

Luca Cappelletti
Luca Cappelletti

Reputation: 2545

What is wrong

First of all, python is signalling you that an object with name layers is not present within the scope of the script.

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.

So just drop all the code that begins with layers, as it is just an explanation.

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'))

Further readings

You should consider learning about Keras on the Keras Documentation.

Upvotes: 8

Related Questions