Search code examples
pythontensorflowkerasimporterror

optree ImportError when trying to use tensorflow.keras.models


I have installed tensorflow and keras via pip and want to use it, but the following import is failing:

from tensorflow import keras
from tensorflow.keras.models import Sequential #This line fails

The error:

  File "...AppData\Local\Programs\Python\Python39\lib\site-packages\keras\src\tree\__init__.py", line 1, in <module>
    from keras.src.tree.tree_api import assert_same_structure
  File ""...AppData\Local\Programs\Python\Python39\lib\site-packages\keras\src\tree\tree_api.py", line 10, in <module>
    raise ImportError(
ImportError: To use Keras, you need to have `optree` installed. Install it via `pip install optree`

I checked that optree is installed, tried to reinstall it but no luck. Does anyone face this issue?

Versions:

  • Tensforflow 2.16.1
  • Keras 3.3.3
  • Optree 0.11.0

Solution

  • Finally, the following commands helped me:

    pip uninstall keras
    pip uninstall tensorflow
    pip cache purge
    pip install tensorflow --ignore-installed --user
    

    I have two suggestions of RC:

    • I firstly installed keras, tensorflow was installed after that
    • "--user" helped to solve some permission issue