Search code examples
pythontensorflowkeraspickle

AttributeError: 'Adam' object has no attribute 'build' during unpickling


I'm training a Keras model and saving it for later use using pickle.

When I unpickle I get this error:

AttributeError: 'Adam' object has no attribute 'build'

Here's the code:

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
import pickle

model = Sequential()
model.add(Dense(32, activation='relu', input_shape=(3,)))
model.add(Dense(1, activation='linear'))  # Use linear activation for regression
model.compile(loss='mean_squared_error', optimizer='adam')

pickle.dump(model, open("m.pkl", 'wb'))
loadedModel = pickle.load(open("m.pkl", 'rb'))

I get this error with TensorFlow 2.11.x and 2.13.0-rc0 on MacOS M1


Solution

  • Instead of pickling, you should save the model using h5. This solves the issue:

    from keras.models import load_model
    
    model.save('m.h5')
    loadedModel = load_model('m.h5')