python import as 实例化_python – 将Keras模型集成到TensorFlow中

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值