python - 在tensorflow代码中使用keras层

标签 python tensorflow keras

假设我有一个简单的神经网络,其中有一个输入层和一个用 tensorflow 编程的卷积层:

  # Input Layer
  input_layer = tf.reshape(features["x"], [-1, 28, 28, 1])

  # Convolutional Layer #1
  conv1 = tf.layers.conv2d(
      inputs=input_layer,
      filters=32,
      kernel_size=[5, 5],
      padding="same",
      activation=tf.nn.relu)

我省略了功能的网络定义的任何其他部分。

如果我想在这个卷积层之后添加一个 LSTM 层,我必须制作卷积层 TimeDistributed (用keras的语言)然后把TimeDistributed层的输出放到LSTM中。

Tensorflow 提供对 tf.keras.layers 中的 keras 层的访问.我可以直接在 tensorflow 代码中使用 keras 图层吗?如果是这样,如何?我也可以使用 tf.keras.layers.lstm 吗? LSTM 层的实现?

总的来说:是否可以混合使用纯 tensorflow 代码和 keras 代码,我可以使用 tf.keras.layers 吗?

最佳答案

是的,这是可能的。

同时导入 TensorFlow 和 Keras,并将您的 Keras session 链接到 TF one:

import tensorflow as tf
import keras
from keras import backend as K

tf_sess = tf.Session()
K.set_session(tf_sess)

现在,在您的模型定义中,您可以像这样混合 TF 和 Keras 层:

# Input Layer
input_layer = tf.reshape(features["x"], [-1, 28, 28, 1])

# Convolutional Layer #1
conv1 = tf.layers.conv2d(
    inputs=input_layer,
    filters=32,
    kernel_size=[5, 5],
    padding="same",
    activation=tf.nn.relu)

# Flatten conv output
flat = tf.contrib.layers.flatten(conv1)

# Fully-connected Keras layer
layer2_dense = keras.layers.Dense(128, activation='relu')(flat)

# Fully-connected TF layer (output)
output_preds = tf.layers.dense(layer2_dense, units=10)

这个答案来自a Keras blog弗朗索瓦·肖莱 (Francois Chollet) 发表。

关于python - 在tensorflow代码中使用keras层,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47167630/

相关文章:

python - 为什么发送字符串并关闭套接字后会有 TCP RST 数据包

python - zip_safe 仅与蛋格式相关吗?

python - 在 Python 中将 LaTex 表读入数组

tensorflow - 原因: image not found tensorflow GPU

python - Keras 和 LSTM 中的二元分类

keras - 检查语言模型的复杂度

python - 如何在 uwsgi 中使用 nginx UWSGI_SETENV 获取 env_vars

python - tensorflow 程序陷入变量中

python - TensorFlow:整合神经网络的输出

python - keras.backend.function() with updates=None 不会更新有状态模型的状态吗?