2

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

ColBeseder
  • 3,579
  • 3
  • 28
  • 45
  • 1
    You shouldn't use pickle to save the model. Tensorflow has explicit save methods to save the model as a h5 model or tensorflow model. See: https://www.tensorflow.org/guide/keras/save_and_serialize even converting to ONNX should be a safer/better option than using pickle. – stateMachine May 24 '23 at 02:22

2 Answers2

2

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')
ColBeseder
  • 3,579
  • 3
  • 28
  • 45
1

Actually, the same error happens using the keras save and load_model. I found this entry on the keras GitHub page:

https://github.com/keras-team/keras/issues/18278

This indicates that on M1/M2 Macs, keras reverts to the legacy optimizers, and that version of Adam does not have a build() function. I've tried other optimizers, but they appear to have this issue as well.

I have not found a solution yet...

  • found another reference: https://stackoverflow.com/questions/72964800/what-is-the-proper-way-to-install-tensorflow-on-apple-m1-in-2022 – user2824214 Aug 19 '23 at 21:52
  • This indicates that tensorflow2.11 has an incompatibility with tensorflow-metal on M1/M2 Macs, which is related to the version of numpy. The workaround is either to downgrade to tensorflow 2.10 or figure out the needed version of numpy ( numpy >=1.23.2,<1.23.3 apparently, which is only available via conda). Trying that out over the next few days – user2824214 Aug 19 '23 at 21:58