PyCharm cannot import tensorflow.keras

I am working with the tensorflow-implementation from Keras and I can use it without issues, however, my IDE thinks that the keras submodule in tf does not exist. I am using anaconda where I install tensorflow and all my other libraries. I make sure that I select the right interpreter in PyCharm (all my other obscure libraries are imported without issue) and the base module from tf is imported without any problem (I get autocomplete etc.) but when I import "tensorflow.keras" the IDE complains that it cannot find the reference 'keras'. As said above, executing the files works without problem. Is there a way to tell the PyCharm that there is actually a keras submodule?

PyCharm 2018.3.3 (Community Edition)
Build #PC-183.5153.39, built on January 9, 2019
JRE: 1.8.0_152-release-1343-b26 amd64
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Linux 4.15.0-43-generic

 

7 comments

Hi,

As a first troubleshooting step, can you try to find where the keras module is physically located in your packages directories, and check if this directory is present in the sys.path of your interpreter?

Also, please try to open python console and do the import from there.

0

I have the same problem. I use virtualenv and it is in "env" directory. From PyCharm's Python Console it works, though the completion is not as expected.

The code works with the following import:

from tensorflow.keras import backend as K
from tensorflow.keras.layers import Lambda, Input, Flatten
from tensorflow.keras.models import Model

But PyCharm shows "Unresolved reference" error.

My workaround is this:

import tensorflow as tf
keras = tf.keras
K = keras.backend
KL = keras.layers
Lambda, Input, Flatten = KL.Lambda, KL.Input, KL.Flatten
Model = keras.Model

 

0

Hey Adam,

Yes, I can reproduce the issue, but please note that it's expected in some limited cases. The tooltip for that inspection says:

"This inspection detects names that should resolve but don't. Due to dynamic dispatch and duck typing, this is possible in a limited but useful number of cases. Top-level and class-level items are supported better than instance items."

So another workaround would be to disable that inspection.

0

Hi Andrey,


That import is working from python console in PyCharm. 

I think yesterday (but sadly not today) my PyCharm was able to resolve this reference.

0

I've found workaround. 

Instead of

from tensorflow.keras import layers

do import it as:

from tensorflow._api.v1.keras import layers
0

Same error here, cannot autocomplete in code but work fine in python console, the work arounds posted here didn't help. I'm using tensorflow 2.0 btw. 

0

In tensorflow 2.0 you can import keras using

`from tensorflow.python import keras`

and it will autocomplete

1

Please sign in to leave a comment.