问题
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.
回答1:
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
来源:https://stackoverflow.com/questions/54686336/tensorflow-keras-layers-unresolved-reference-in-pycharm