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