Search code examples
pythontensorflowindentation

"unexpected indent" or "object has no attribute 'compile'" errors


I tried using this code from the Tensorflow basic regression tutorial:

def build_model():
  model = keras.Sequential([
    keras.layers.Dense(64, activation=tf.nn.relu, 
                       input_shape=(train_data.shape[1],)),
    keras.layers.Dense(64, activation=tf.nn.relu),
    keras.layers.Dense(1)
  ])

  optimizer = tf.train.RMSPropOptimizer(0.001)

  model.compile(loss='mse',
                optimizer=optimizer,
                metrics=['mae'])
  return model

model = build_model()
model.summary()

But I get an error that says:

>>>   optimizer = tf.train.RMSPropOptimizer(0.001)
  File "<stdin>", line 1
    optimizer = tf.train.RMSPropOptimizer(0.001)
    ^
IndentationError: unexpected indent

If I unindent the optimizer = ... line, the next line gives the same error. If I then unindent the model.compile ... line, I get this:

>>> model.compile(loss='mse',
...                 optimizer=optimizer,
...                 metrics=['mae'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'compile'

...followed by a bunch of other errors, probably resulting from that one.

The other tutorials have worked fine. What is wrong, and how do I fix it?


Solution

  • By this line of the error message

      File "<stdin>", line 1
    

    is evident that you wrote you code directly to the Python interpreter, and by this interpreter's prompt

    >>>
    

    is obvious that you wrote the

      optimizer = tf.train.RMSPropOptimizer(0.001)
    

    as a new command on the highest (module) level, and NOT as a part of your function definition.

    How to fix it:

    You have to write the def build_model(): command after the >>> prompt, and the all other command of this function definition after the ... prompt, with the correct indentations, up to the return model command.

    (After the return model command, press Enter twice for returning to the >>> prompt; then continue writing other commands.)