为什么我不能在我的流程图中使用像 tf op 这样的 Keras 模型

Why can't I use a Keras model like an tf op in my flow graph

我正在尝试在 tf 会话中的计算流程图中的某处使用我预训练的 keras 模型,所以我尝试了这个简化的图,但我仍然遇到相同的错误。

model = load_model('models/vtcnn3.h5')

input = tf.placeholder(tf.float32,shape=(1,*x_test.shape[1:]))
output = model(input)

sess = tf.compat.v1.Session()

guess_0 = sess.run(output, {input:x_test[0:1]} )

当会话运行时,我得到一个很大的回溯,最终显示

tensorflow.python.framework.errors_impl.FailedPreconditionError: Error while reading resource variable dense2/kernel from Container: localhost. This could mean that the variable was uninitialized. Not found: Container localhost does not exist. (Could not find resource: localhost/dense2/kernel)
     [[node sequential/dense2/MatMul/ReadVariableOp (defined at code/soq.py:114) ]]

Errors may have originated from an input operation.
Input Source operations connected to node sequential/dense2/MatMul/ReadVariableOp:
 dense2/kernel (defined at code/soq.py:111)

Original stack trace for 'sequential/dense2/MatMul/ReadVariableOp':
  File "code/soq.py", line 114, in <module>
    output = model(input)
  File "/Users/yaba/miniconda3/envs/cs1/lib/python3.7/site-packages/tensorflow/python/keras/engine/base_layer.py", line 634, in __call__
    outputs = call_fn(inputs, *args, **kwargs)
.
.
.
.

dense2 是我模型中图层的名称。当我对流程图进行其他更改时,回溯将错误放入模型的不同层。

在尝试通过 Keras 模型 运行 输入之前,您需要初始化变量。以下代码适用于 tensorflow==1.14.0

import tensorflow as tf

model = tf.keras.applications.ResNet50()

init_op = tf.global_variables_initializer()
with tf.compat.v1.Session() as sess:
    random_image, _ = sess.run([tf.random.normal(shape=[1, 224, 224, 3]), init_op])
    outputs = sess.run(model.output, feed_dict={model.input:random_image})

感谢 Srihari Humbardwadi 提供的初始化答案,它修复了我遇到的错误,但现在网络的输出与我使用 model.predict(...) 时不同!

如果您想从文件中加载 Keras 模型并在 Tensorflow 图中使用它,您必须将 tf.Session() 设置到 Keras 后端,然后初始化变量,然后加载 Keras 模型,如下所示

sess = tf.Session()

# make sure keras has the same session as this code BEFORE initializing
tf.keras.backend.set_session(sess)

# Do this BEFORE loading a keras model
init_op = tf.global_variables_initializer()
sess.run(init_op)


model = models.load_model('models/vtcnn3.h5')


input = tf.placeholder(tf.float32,shape=(1,*x_test.shape[1:]))
output = model(input)


guess_0 = sess.run(output, feed_dict={input:x_test[0:1]} )

现在 guess_0 与您

的操作相同
model = models.load_model('models/vtcnn3.h5')
guess_0 = model.predict(x_test[0:1])