'Colab: Importing old modules from tf.keras 2.4 fails; importing from Keras 2.4 works, but leads to mixing tf and tf.keras

I'm trying to modify a jupyter notebook to run on colab. It's from a somewhat older repo with known compatibility issues for tensorflow/keras versions after ~2.4.X. The non-notebook files import tensorflow from the tensorflow module and Keras from the keras module (and not the tf.keras module).

Downgrading TF and running the model this way leads to an exception commonly attributed to mixing keras and tf.keras imports:

AttributeError: 'ReduceLROnPlateau' object has no attribute '_implements_test_batch_hooks'

Switching all import keras to import tensorflow.keras leads to a different issue, as a selection of imports no longer work:

ModuleNotFoundError: No module named 'tensorflow.keras.objectives'

This error is the same one that led to the keras 2.4 requirement for the package, so I assume something is going wrong. I have also attempted to switch all error-generating tf.keras imports to keras; this brings back the first issue.

Of note, all of tensorflow, keras, and tf.keras are 2.4.0. Any idea what I should do to fix this?



Solution 1:[1]

I have faced with the ModuleNotFound error for keras.objectives while using tf and keras in version 2.8.0, changing the import as from tensorflow.keras.losses instead of from tensorflow.keras.objectives worked for me.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 husofield