'Import "tensorflow.keras" could not be resolved after upgrading to TensorFlow 2.8.0

TensorFlow 2.8 was recently released and I installed it as soon as it was out. I really need it for support of higher NumPy versions and a few new features. However, after installing it in my conda environment with

python3 -m pip install --upgrade tensorflow

neither PyCharm nor VSCode can no longer resolve the import from tensorflow.keras import ....

The imports themselves seem to work at runtime, but because the import cannot be resolved I can't make use of code completion, visualizing signatures of functions and etc. Has anybody encountered a similar issue?

everything was working with TF 2.7 - the version I had before.

Note: I'm using Python 3.8

Vs Code enter image description here

PyCharm enter image description here

I tried to check the versions through the PyCharm interpreter tab and this is what I saw. For some reason PyCharm isn't aware that there are versions after 2.0 (I have the latest version of pip installed in that environment). I'm guessing this is related, but not sure what to do with that.

enter image description here



Solution 1:[1]

I had the same problem and resolved it by importing it as

from tensorflow.python.keras.layers import Dense

Solution 2:[2]

I see the problem in Google Colab as well. Although running the code works just fine. It's just an IDE complaint that supposedly it cannot find the imports. Very strange. I hope someone from the TensorFlow team gives feedback soon.

Could not be resolved error

Solution 3:[3]

This has been a pattern as this post in GitHub shows. I'm getting the same. Ignoring it since the code still runs, but would rather not have the yellow. I hope someone from tensorflow can chime in. :)

Solution 4:[4]

This is a bug in the current version of tensorflow, as discussed in this issue.

You can work around it by either

  1. modifying the file site-packages/tensorflow/__init__.py as described in this answer from the referenced issue or
  2. using import keras.api._v2.keras as keras since this seems to be the exact package tensorflow loads itself. (Though you need to reference the protected member _v2 here, which is against python conventions.)

The reason here is that tensorflow tries to load the keras module in a lazy fashion, which means that it holds only a reference to the module until the module is used. Only then the keras module will be actually loaded. Therefore IDEs only know about the reference tensorflow holds to the keras module and not its content.

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 buddemat
Solution 2 Jazon Samillano
Solution 3 user18324275
Solution 4 TomS