Search code examples
tensorflowmachine-learningkerasraspberry-piraspberry-pi4

ValueError: Unknown optimizer: Custom>Adam| Adam Optimizer on Raspberry Pi (TensorFlow 2.5.0rc0)


I am a learning machine learning and I want to apply it on a raspberry pi. I have RPi 4b running on:

NAME="Raspbian GNU/Linux"  
VERSION_ID="11"
VERSION="11 (bullseye)"
with armv7l architecture
I have installed tensorflow and it's version is 2.5.0-rc0.

I am trying to load my model I trained in colab which uses Adam optimizer however I get this result whenever I try to load it:

ValueError: Unknown optimizer: Custom\>Adam. Please ensure this object is passed to the \`custom_objects\` argument. See <https://www.tensorflow.org/guide/keras/save_and_serialize#registering_the_custom_object> for details.
import librosa
import numpy as np
import tensorflow as tf
from tensorflow.keras.optimizers import Adam
import simpleaudio as sa

# Load the trained ML model
with tf.device('/cpu:0'):
   model = tf.keras.models.load_model('/home/pi/Desktop/project/pineapplemodeltwoclassbs16e75.h5')

What could I do to resolve the error?

I have tried adding this:

# Define the custom Adam optimizer
class CustomAdam(Adam):
    pass
# Register the custom optimizer
tf.keras.utils.get_custom_objects().update({'CustomAdam': CustomAdam})
# Load the trained ML model
with tf.device('/cpu:0'):
    model = tf.keras.models.load_model('/home/pi/Desktop/project/pineapplemodeltwoclassbs16e75.h5', custom_objects={'CustomAdam': CustomAdam})

and still resulted in the same error.

I also tried this:

# Load the Adam optimizer from the tensorflow.keras.optimizers module
Adam = tf.keras.optimizers.Adam

# Load the trained ML model
with tf.device('/cpu:0'):
    model = tf.keras.models.load_model('/home/pi/Desktop/project/pineapplemodeltwoclassbs16e75.h5', custom_objects={'Adam': Adam})

and still the same result.


Solution

  • According to the documentation:

    Keras saves models by inspecting their architectures. This technique saves everything:

    • The weight values
    • The model's architecture
    • The model's training configuration (what you pass to the .compile() method)
    • The optimizer and its state, if any (this enables you to restart training where you left off)

    Keras is not able to save the v1.x optimizers (from tf.compat.v1.train) since they aren't compatible with checkpoints. For v1.x optimizers, you need to re-compile the model after loading—losing the state of the optimizer.

    Since Adam Optimizer is a v1.x optimizer, you might need to re-compile your model. If you're not using the loaded model for training, you don't need to re-compile it. Just set the parameter compile=False when calling load_model.

    For example: load_model('file.h5', compile=False)