3

I've been facing this attribute error, any ideas how I can solve it?

def model(input_shape):
   model = keras.Sequential()
   model.add(keras.layers.LSTM(64, input_shape=(1,9), return_sequences=True))
   model.add(keras.layers.LSTM(64))
   model.add(keras.layers.Dense(64, activation='relu'))
   model.add(keras.layers.Dropout(0.3))
   model.add(keras.layers.Dense(10, activation='softmax'))
   return model

model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

model.summary()
AttributeError                            Traceback (most recent call last)
Input In [67], in <cell line: 1>()
----> 1 model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
      2 model.summary()

AttributeError: 'function' object has no attribute 'compile'

2 Answers 2

2

The function and variable have the same name, causing the issue. You can either rename the variable or the function.

def model(input_shape):
   model = keras.Sequential()
   model.add(keras.layers.LSTM(64, input_shape=(1,9), return_sequences=True))
   model.add(keras.layers.LSTM(64))

   model.add(keras.layers.Dense(64, activation='relu'))
   model.add(keras.layers.Dropout(0.3))
   
   model.add(keras.layers.Dense(10, activation='softmax'))

   return model

my_model = model() # your initializer
my_model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
my_model.summary()
Sign up to request clarification or add additional context in comments.

1 Comment

It's worth noting that you don't have to rename either of these. model = model() is perfectly valid. You just wouldn't be able to call the model function anymore.
0

You've used the word model as a name for a function. That is permissible (because model is not a reserved word in Python), but it means that when you use model.compile(), the interpreter assumes you want to call an attribute of what you called "model", and there is no such attribute there. Solution: Give the function another name so that the word "model" only refers to the model object, which has a compile method you can call. Or, conversely, use "model" for the function if you want to, but then give the model another name, and call compile() on that.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.