简体   繁体   English

Tensorflow 2.0:从 tensorflow keras 导入

[英]Tensorflow 2.0: Import from tensorflow keras

I can't import anything from keras if I import it from tensorflow.如果我从 tensorflow 导入它,我无法从 keras 导入任何东西。 I installed tensorflow 2.0 with pip install tensorflow , and while I'm able to write something like:我安装了 tensorflow 2.0 和pip install tensorflow ,虽然我可以写类似的东西:

import tensorflow as tf
from tensorflow import keras

model = keras.Sequential()

If I try to import Sequential from keras如果我尝试从 keras 导入 Sequential

import tensorflow as tf
from tensorflow import keras
from keras import Sequential

I got Unresolved reference 'keras' .我得到了Unresolved reference 'keras' I've looked into every other post I could find and the information is contradictory, some say you have to install keras separately other says you just need to install tensorflow.我查看了我能找到的所有其他帖子,但信息相互矛盾,有人说你必须单独安装 keras 其他人说你只需要安装 tensorflow。
So far I've tried:到目前为止,我已经尝试过:

from tensorflow.python import keras
from tensorflow.contrib import keras
import tensorflow.keras as keras
from tensorflow.keras import Sequential 

Plus a bunch of combination of the above, none of these work.加上上面的一堆组合,这些都不起作用。
Sorry if it's a dumb question but I've never struggled so much with a simple import before.对不起,如果这是一个愚蠢的问题,但我以前从未在简单的导入方面如此挣扎。

Edit: Additionnal info, I'm on ubuntu 18.04, with Pycharm and a Python 3.6 virtual environment.编辑:附加信息,我在 ubuntu 18.04 上,使用 Pycharm 和 Python 3.6 虚拟环境。

Answer:回答:

It is actually a PyCharm bug: Link here: https://youtrack.jetbrains.com/issue/PY-38220 I tried the snippet of code proposed by @AYI here它实际上是一个 PyCharm 错误:链接在这里: https://youtrack.jetbrains.com/issue/PY-38220我在这里尝试了@AYI 提出的代码片段

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten

example_model = Sequential()
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()

And actually runs normally despite the warning and error displayed by Pycharm !尽管 Pycharm 显示警告和错误,但实际上运行正常! 不合理的pycharm警告和错误高亮

Try in this way should help you "from tensorflow.keras.xxx import xxx"尝试这种方式应该可以帮助您“从 tensorflow.keras.xxx 导入 xxx”

Example of how to import Sequential in tensorflow 2.0:如何在 tensorflow 2.0 中导入 Sequential 的示例:

from tensorflow.keras.models import Sequential

good luck~祝你好运~


Here is the Demo:这是演示:

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten

example_model = Sequential()
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()

模型.摘要

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM