首页 文章

将Keras模型集成到TensorFlow中

提问于
浏览
7

我试图在TensorFlow代码中使用预先训练的Keras模型,如this Keras blog post中第II节:使用带有TensorFlow的Keras模型中所述 .

我想使用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需要显式初始化所有变量 . 但这只是猜测 .

2 回答

  • 6

    作为@ P-Gn答案的补充,如果你坚持明确创建一个新的会话(比如你正在阅读的教程),你应该把这些行:

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

    在创建模型之前(即 model = VGG16(...) ),然后使用创建的会话,如:

    with sess.as_defualt():
        output = sess.run(features, feed_dict={inputs: images})
    
  • 2

    TLDR

    使用Keras时,

    • 如果可以,请避免使用 Session (本着不可知的Keras精神)

    • 否则使用Keras处理 Sessiontf.keras.backend.get_session .

    • 使用Keras' set_session 进行高级用途(例如,当您需要分析或设备放置时)并且在程序的早期阶段 - 与"pure" Tensorflow中的常规做法和良好用法相反 .

    更多关于此事

    必须先初始化变量才能使用它们 . 实际上,它比那更微妙:变量必须初始化 in the 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
    

    因此, model 中的变量未初始化不应该出乎意料,因为您在 sess 之前创建了模型 .

    但是, VGG16 不仅会为模型变量(使用 tf.global_variables_initializer 调用的变量)创建初始化操作,而且实际上会调用它们 . 问题是, Session

    好吧,既然您在构建模型时没有存在,Keras为您创建了一个默认模式,您可以使用 tf.keras.backend.get_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用户通常首先构建图形,然后在冻结图形之后实例化会话 .

    Keras与框架无关,并且在构造阶段之间没有这种内置的区别 - 特别是,我们在这里了解到Keras可以在图形构建期间很好地实例化Session .

    出于这个原因,当使用Keras时,我建议不要自己管理 tf.Session 而是依赖 tf.keras.backend.get_session 如果你需要处理需要 tf.Session 的TensorFlow特定代码 .

相关问题