python - 将 Keras 模型集成到 TensorFlow 中

标签 python tensorflow keras deep-learning vgg-net

我正在尝试在 TensorFlow 代码中使用预训练的 Keras 模型,如 this Keras blog post 中所述在第二部分:将 Keras 模型与 TensorFlow 结合使用。

我想使用 Keras 中可用的预训练 VGG16 网络从图像中提取卷积特征映射,并在其上添加我自己的 TensorFlow 代码。所以我这样做了:

import tensorflow as tf
from tensorflow.python.keras.applications.vgg16 import VGG16, preprocess_input
from tensorflow.python.keras import backend as K

# images = a NumPy array containing 8 images

model = VGG16(include_top=False, weights='imagenet')
inputs = tf.placeholder(shape=images.shape, dtype=tf.float32)
inputs = preprocess_input(inputs)
features = model(inputs)

with tf.Session() as sess:
    K.set_session(sess)
    output = sess.run(features, feed_dict={inputs: images})
    print(output.shape)

但是,这给了我一个错误:

FailedPreconditionError: Attempting to use uninitialized value block1_conv1_2/kernel
     [[Node: block1_conv1_2/kernel/read = Identity[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:GPU:0"](block1_conv1_2/kernel)]]
     [[Node: vgg16_1/block5_pool/MaxPool/_3 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device_incarnation=1, tensor_name="edge_132_vgg16_1/block5_pool/MaxPool", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]

相反,如果我在运行网络之前运行初始化操作:

with tf.Session() as sess:
    K.set_session(sess)
    tf.global_variables_initializer().run()
    output = sess.run(features, feed_dict={inputs: images})
    print(output.shape)

然后我得到预期的输出:

(8, 11, 38, 512)

我的问题是,在运行 tf.global_variables_initializer() 时,变量是随机初始化的还是使用 ImageNet 权重初始化的?我问这个是因为上面引用的博客文章没有提到在使用预训练的 Keras 模型时需要运行初始化器,这确实让我感到有点不安。

我怀疑它确实使用了 ImageNet 权重,并且它需要运行初始化程序只是因为 TensorFlow 要求所有变量都被显式初始化。但这只是一个猜测。

最佳答案

长篇小说

使用 Keras 时,

  1. 尽可能避免使用Session(本着不可知论者 Keras 的精神)
  2. 否则通过 tf.keras.backend.get_session 使用 Keras 处理的 Session
  3. 将 Keras 的 set_session 用于高级用途(例如,当您需要分析或设备放置时)并在您的程序的早期使用——这与“纯”Tensorflow 中的常见做法和良好用法相反。

更多信息

变量必须在使用前进行初始化。实际上,它比这更微妙:变量必须在它们被使用的 session 中被初始化。让我们看一下这个例子:

import tensorflow as tf

x = tf.Variable(0.)

with tf.Session() as sess:
    tf.global_variables_initializer().run()
    # x is initialized -- no issue here
    x.eval()
    
with tf.Session() as sess:
    x.eval()
    # Error -- x was never initialized in this session, even though
    # it has been initialized before in another session

因此,模型 中的变量未初始化也就不足为奇了,因为您在sess 之前创建了模型。

但是,VGG16 不仅为模型变量(您使用 tf.global_variables_initializer 调用的变量)创建初始化操作,而且实际上确实 调用他们。问题是,在哪个 Session 中?

好吧,由于在您构建模型时不存在,Keras 为您创建了一个默认值,您可以使用 tf.keras.backend.get_session() 恢复它。使用此 session 现在可以按预期工作,因为变量已在此 session 中初始化:

with tf.keras.backend.get_session() as sess:
    K.set_session(sess)
    output = sess.run(features, feed_dict={inputs: images})
    print(output.shape)

请注意,您还可以创建自己的 Session 并通过 keras.backend.set_session 将其提供给 Keras — 这正是您所做的。但是,正如这个例子所示,Keras 和 TensorFlow 有着不同的思维方式。

TensorFlow 用户通常会首先构建一个图,然后实例化一个 Session,也许在卡住图之后。

Keras 与框架无关,并且在构建阶段之间没有这种内置的区别——特别是,我们在这里了解到,Keras 很可能在图构建期间 实例化 session 。

因此,在使用 Keras 时,我建议不要自己管理 tf.Session,而是在需要时依赖 tf.keras.backend.get_session处理需要 tf.Session 的 TensorFlow 特定代码。

关于python - 将 Keras 模型集成到 TensorFlow 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51107527/

相关文章:

Python3 : ImportError: No module named '_ctypes' when using Value from module multiprocessing

python - 如何从 Python 调用 Rust 异步方法?

python - 验证精度卡住,精度低

python - 具有多个特征的 RNN 的数据形状/格式

tensorflow - 用于 360 度预测的 keras 损失函数

python - Pandas - 如何用 NaN 替换这些异常值

python - 如何在单个图中绘制多个seaborn.distplot

python - Keras:使用更大的训练集更新模型

python - 计算图图像中的名称使用(TensorBoard)

python - Keras 2, TypeError : can't pickle _thread. 锁定对象