为什么在流程图中无法使用类似tf op的Keras模型

时间:2019-09-12 17:06:00

标签: python tensorflow keras tf.keras

在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是模型中图层的名称。当我对流程图进行其他更改时,回溯会将错误放入模型的另一层。

2 个答案:

答案 0 :(得分:0)

在尝试通过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})

答案 1 :(得分:0)

感谢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])