Python 如何在 Tensorflow 中从 tf.keras 导入 keras?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47262955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 18:06:49  来源:igfitidea点击:

How to import keras from tf.keras in Tensorflow?

pythontensorflowdeep-learningkeras

提问by GeorgeOfTheRF

import tensorflow as tf
import tensorflow 

from tensorflow import keras
from keras.layers import Dense

I am getting the below error

我收到以下错误

from keras.layers import Input, Dense
Traceback (most recent call last):

  File "<ipython-input-6-b5da44e251a5>", line 1, in <module>
    from keras.layers import Input, Dense

ModuleNotFoundError: No module named 'keras'

How do I solve this?

我该如何解决这个问题?

Note: I am using Tensorflow version 1.4

注意:我使用的是 Tensorflow 1.4 版

回答by Mihail Burduja

Use the keras module from tensorflow like this:

像这样使用 tensorflow 中的 keras 模块:

import tensorflow as tf

import tensorflow as tf

Import classes

导入类

from tensorflow.python.keras.layers import Input, Dense

from tensorflow.python.keras.layers import Input, Dense

or use directly

或者直接使用

dense = tf.keras.layers.Dense(...)

dense = tf.keras.layers.Dense(...)

EDIT Tensorflow 2

编辑张量流 2

from tensorflow.keras.layers import Input, Dense

from tensorflow.keras.layers import Input, Dense

and the rest stays the same.

其余保持不变。

回答by Ramesh Kamath

Try from tensorflow.python import keras

尝试 from tensorflow.python import keras

with this, you can easily change keras dependent code to tensorflow in one line change.

有了这个,您可以在一行更改中轻松地将 keras 依赖代码更改为 tensorflow。

You can also try from tensorflow.contrib import keras. This works on tensorflow 1.3

你也可以试试from tensorflow.contrib import keras。这适用于 tensorflow 1.3

Edited: for tensorflow 1.10and aboveyou can use import tensorflow.keras as kerasto get keras in tensorflow.

编辑:对于tensorflow 1.10及更高版本,您可以使用import tensorflow.keras as keras在 tensorflow 中获取 keras。

回答by Ruthwik

To make it simple I will take the two versions of the code in keras and tf.keras. The example here is a simple Neural Network Model with different layers in it.

为简单起见,我将采用 keras 和 tf.keras 中的两个版本代码。这里的例子是一个简单的神经网络模型,其中包含不同的层。

In Keras(v2.1.5)

Keras(v2.1.5)

from keras.models import Sequential
from keras.layers import Dense

def get_model(n_x, n_h1, n_h2):
    model = Sequential()
    model.add(Dense(n_h1, input_dim=n_x, activation='relu'))
    model.add(Dense(n_h2, activation='relu'))
    model.add(Dropout(0.5))
    model.add(Dense(4, activation='softmax'))
    model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
    print(model.summary())
    return model

In tf.keras(v1.9)

tf.keras(v1.9)

import tensorflow as tf

def get_model(n_x, n_h1, n_h2):
    model = tf.keras.Sequential()
    model.add(tf.keras.layers.Dense(n_h1, input_dim=n_x, activation='relu'))
    model.add(tf.keras.layers.Dense(n_h2, activation='relu'))
    model.add(tf.keras.layers.Dropout(0.5))
    model.add(tf.keras.layers.Dense(4, activation='softmax'))
    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
    print(model.summary())

    return model

or it can be imported the following way instead of the above-mentioned way

或者它可以通过以下方式导入而不是上述方式

from tensorflow.keras.layers import Dense

The official documentation of tf.keras

tf.keras官方文档

Note: TensorFlow Version is 1.9

注意:TensorFlow 版本为 1.9

回答by Timbus Calin

Update for everybody coming to check why tensorflow.kerasis not visible in PyCharm.

为每个来检查为什么tensorflow.kerasPyCharm.

Starting from TensorFlow 2.0, only PyCharm versions > 2019.3 are able to recognise tensorflowand kerasinside tensorflow (tensorflow.keras) properly.

从 TensorFlow 2.0 开始,只有 PyCharm 版本 > 2019.3能够正确识别tensorflowkeras内部 tensorflow ( tensorflow.keras)。

Also, it is recommended(by Francois Chollet) that everybody switches to tensorflow.kerasin place of plain keras.

此外,建议(由 Francois Chollet)每个人都切换到tensorflow.keras代替普通keras

回答by Shaina Raza

Its not quite fine to downgrade everytime, you may need to make following changes as shown below:

每次都降级不太好,您可能需要进行以下更改,如下所示:

Tensorflow

张量流

import tensorflow as tf

将张量流导入为 tf

#Keras
from tensorflow.keras.models import Sequential, Model, load_model, save_model
from tensorflow.keras.callbacks import ModelCheckpoint
from tensorflow.keras.layers import Dense, Activation, Dropout, Input, Masking, TimeDistributed, LSTM, Conv1D, Embedding
from tensorflow.keras.layers import GRU, Bidirectional, BatchNormalization, Reshape
from tensorflow.keras.optimizers import Adam

from tensorflow.keras.layers import Reshape, Dropout, Dense,Multiply, Dot, Concatenate,Embedding
from tensorflow.keras import optimizers
from tensorflow.keras.callbacks import ModelCheckpoint

The point is that instead of using

关键是,而不是使用

from keras.layers import Reshape, Dropout, Dense,Multiply, Dot, Concatenate,Embedding

you need to add

你需要添加

from tensorflow.keras.layers import Reshape, Dropout, Dense,Multiply, Dot, Concatenate,Embedding

回答by pfRodenas

I have a similar problem importing those libs. I am using Anaconda Navigator 1.8.2 with Spyder 3.2.8.

我在导入这些库时遇到了类似的问题。我将 Anaconda Navigator 1.8.2 与 Spyder 3.2.8 一起使用。

My code is the following:

我的代码如下:

import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
import math

#from tf.keras.models import Sequential  # This does not work!
from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.layers import InputLayer, Input
from tensorflow.python.keras.layers import Reshape, MaxPooling2D
from tensorflow.python.keras.layers import Conv2D, Dense, Flatten

I get the following error:

我收到以下错误:

from tensorflow.python.keras.models import Sequential

ModuleNotFoundError: No module named 'tensorflow.python.keras'

I solve this erasing tensorflow.python

我解决了这个擦除 tensorflow.python

With this code I solve the error:

使用此代码,我解决了错误:

import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
import math

#from tf.keras.models import Sequential  # This does not work!
from keras.models import Sequential
from keras.layers import InputLayer, Input
from keras.layers import Reshape, MaxPooling2D
from keras.layers import Conv2D, Dense, Flatten

回答by Umair Qadir

this worked for me in tensorflow==1.4.0

这在 tensorflow==1.4.0 中对我有用

from tensorflow.python import keras

从 tensorflow.python 导入 keras

回答by soheila zangeneh

I had the same problem with Tensorflow 2.0.0 in PyCharm. PyCharm did not recognize tensorflow.keras; I updated my PyCharm and the problem was resolved!

我在 PyCharm 中使用 Tensorflow 2.0.0 时遇到了同样的问题。PyCharm 无法识别 tensorflow.keras;我更新了我的 PyCharm,问题解决了!