Can't import tensorflow.keras in VS Code

Viewed 15460

I'm running into problems using tensorflow 2 in VS Code. The code executes without a problem, the errors are just related to pylint in VS Code. For example this import from tensorflow.keras.layers import Dense gives a warning "Unable to import 'tensorflow.keras.layers'pylint(import-error)". Importing tensorflow and using tf.keras.layers.Dense does not produce an error. I'm just using a global python environment (3.7.2) on Windows 10, tensorflow is installed via Pip.

6 Answers

The imports that were causing the issue for me:

from tensorflow.keras.models import Model
from tensorflow.keras.layers import Dense

The way I resolved it:

from tensorflow import keras
from keras.models import Model
from keras.layers import Dense

I too faced the same issue. I solved it by installing keras as a new package and then I changed all packages name removing the prefix tensorflow.. So in your case after installing keras you should replace tensorflow.keras.layers with keras.layers

My way to work with that: The problem is related to the custom import system in tf2 (see this issue). A work around for this is possible (Windows, Linux) which basically tricks VS Code to directly import tensorflow_core and don't use the custom lazy loader. If you just want to remove the red lines (as this is only an editor-problem), use

"python.linting.pylintArgs": 
    ["--ignored-modules=tensorflow.keras"]

I solved it by pressing ctrl+shift+P in Visual Studio Code, searching Python: Select Interpreter, and choosing the main environment.

More detailed information can be found here.

I had the same issue. I solved it by installing Keras and directly importing from keras instead from tensorflow.

pip install Keras

from keras.layers import Dense

Its just better to use pycharm instead of vscode. This issue does not exist in pycharm. However, if you are insistent on using vscode, then the import statements have to be changed as follows.

from tensorflow.python.keras import Sequential
from tensorflow.python.keras.layers import Dense
Related