Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tensorflow.keras.layers "unresolved reference" in pycharm

I just installed tensorflow, and am trying to get the basics to work. However, the import statement is underlined in red, with message "unresolved reference 'layers' ". The code does run correctly though.

I've tried some of the suggestions in this question: PyCharm shows unresolved references error for valid code.

However, that question is not about my specific error, and I'm wondering what the cause of my error is, and whether it is just part of a pycharm-level bug, or something related to tensorflow.

My code is:

import tensorflow as tf;
from tensorflow.keras import layers;

It gives the error "unresolved reference 'layers' " on a red jagged underline beneath "layers", with no indication of how to solve it.

like image 930
user637140 Avatar asked Feb 14 '19 08:02

user637140


3 Answers

Pycharm may just recognize the sub-package


(1) package tensorflow's structure :

  ├── tensorflow
        ├── _api
        ├── compiler
        ├── contrib
        ├── core
        ├── examples
        ├── include
        ├── python
        ├── tools
        └── __init__.py

you can import the layer in an absolutely way

from tensorflow._api.v1.keras import layers

then you will get no unresolved reference mark in your pycharm.


(2) in package tensorflow's __init__.py

...
from tensorflow._api.v1 import keras  

# import all packages you want to use in tensorflow level 
# so, you can use `from tensorflow.keras import layers` for keras having been imported

...

then, you can simplely import layers like from tensorflow.keras import layers

But package keras is not the sub-package of tensorflow, so pycharm marked it as unresolved reference, which was not a error

like image 97
jia Jimmy Avatar answered Oct 19 '22 11:10

jia Jimmy


If you are using Tensorflow 2.0, try using this code to load them instead using 'from' and 'import'

import tensorflow
example_model = tensorflow.keras.Sequential()
BatchNormalization = tensorflow.keras.layers.BatchNormalization
Conv2D = tensorflow.keras.layers.Conv2D
MaxPooling2D = tensorflow.keras.layers.MaxPooling2D
Activation = tensorflow.keras.layers.Activation
Flatten = tensorflow.keras.layers.Flatten
Dropout = tensorflow.keras.layers.Dropout
Dense = tensorflow.keras.layers.Dense

##Testing Purpose On PyCharm##
example_model.add(Conv2D(64, (3, 3), activation='relu', padding='same', input_shape=(100, 100, 1)))
example_model.add(MaxPooling2D((2, 2)))
example_model.add(Flatten())
example_model.summary()
like image 40
Azriel Tan Avatar answered Oct 19 '22 10:10

Azriel Tan


You can import the package directly with:

from keras import layers;

There is no need to add "import tensorflow as tf;" and "tensorflow" in the second line.

like image 40
Olatunji Avatar answered Oct 19 '22 09:10

Olatunji