Search code examples
tensorflowkeras

ImportError : import segmentation_models as sm


So i want to import segmentation_models as sm and i try to pip install using this :

pip install segmentation-models

Then i want to import it using this :

import segmentation_models as sm

And i get this error :

---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
/usr/local/lib/python3.10/dist-packages/segmentation_models/__init__.py in <module>
     97 try:
---> 98     set_framework(_framework)
     99 except ImportError:

12 frames
ModuleNotFoundError: No module named 'tensorflow.keras'

During handling of the above exception, another exception occurred:

ImportError                               Traceback (most recent call last)
/usr/local/lib/python3.10/dist-packages/keras/saving/saving_lib.py in <module>
     31 from keras import losses
     32 from keras.engine import base_layer
---> 33 from keras.optimizers import optimizer
     34 from keras.saving.serialization_lib import ObjectSharingScope
     35 from keras.saving.serialization_lib import deserialize_keras_object

ImportError: cannot import name 'optimizer' from 'keras.optimizers' (/usr/local/lib/python3.10/dist-packages/keras/optimizers.py)

FYI i already install tensorflow and keras, and here is the version of it :

tensorflow                       2.12.0
keras                            2.12.0

Can someone tell me what did i do wrong?


Solution

  • There is nothing wrong we did in the code. It is perfectly fine.

    It is just that the latest Segmentation Models version happens to be 1.0.1 which dates way back in Jan 2020 when Keras version was 2.10.

    Keras, however kept itself updated from time to time and now Keras won't support importing some of its modules which are automatically imported when we import segmentation models.

    The solution to overcome the Import Error lies in downgrading Keras to its version compatible with segmentation-models 1.0.1.

    I tried the same and it worked.

    Here is the code for your reference :

    pip install keras==2.10
    import tensorflow as tf
    from tensorflow import keras
    

    Check version

    keras.__version__
    

    Output :

    2.10.0
    

    Install segmentation models

    pip install segmentation-models==1.0.1
    

    Output :

    Segmentation Models: using `keras` framework.
    

    I hope this works for you as well.