TensorFlow:使用不同的输入张量重新运行网络?

TensorFlow: Rerun network with a different input tensor?

假设我在 TensorFlow 中有一个典型的 CNN 模型。

def inference(images):
    # images: 4D tensor of [batch_size, IMAGE_SIZE, IMAGE_SIZE, 3] size.
    conv_1 = conv_layer(images, 64, 7, 2)
    pool_2 = pooling_layer(conv_1, 2, 2)
    conv_3 = conv_layer(pool_2, 192, 3, 1)
    pool_4 = pooling_layer(conv_3, 2, 2)
    ...
    conv_28 = conv_layer(conv_27, 1024, 3, 1)
    fc_29 = fc_layer(conv_28, 512)
    fc_30 = fc_layer(fc_29, 4096)
    return fc_30

典型的前向传球可以这样完成:

images = input()
logits = inference(images)
output = sess.run([logits])

现在假设我的 input 函数现在 returns 一对参数,left_imagesright_images(立体相机)。我想 运行 right_imagesconv_28left_imagesfc_30。所以像这样

images = tf.placeholder(tf.float32, [batch_size, IMAGE_SIZE, IMAGE_SIZE, 3])
left_images, right_images = input()
conv_28, fc_30 = inference(images)
right_images_val = sess.run([conv_28], feed_dict={images: right_images})
left_images_val = sess.run([fc_30], feed_dict={images: left_images})

但是失败了

TypeError: The value of a feed cannot be a tf.Tensor object. Acceptable feed values include Python scalars, strings, lists, or numpy ndarrays.

我想避免必须评估 inputs 然后将其反馈给 TensorFlow。使用不同的参数调用 inference 两次也不会起作用,因为像 conv_layer 这样的函数会创建变量。

是否可以用不同的输入张量重新运行网络?

Tensorflow shared Variables 就是您要找的。在推理中将 tf.Variable 的所有调用替换为 tf.get_variable()。那么你可以 运行:

images_left, images_right = input()
with tf.variable_scope("logits") as scope:
    logits_left = inference(images_left)
    scope.reuse_variables()
    logits_right = inference(images_right)
output = sess.run([logits_left, logits_right])

在第二次推理调用中不再创建变量。左右图像使用相同的权重进行处理。另请查看我的 Tensorflow CNN training toolkit (Look at training 代码)。我利用这种技术在同一个 TensorFlow 图中 运行 验证和前向训练。