【问题标题】:Cannot execute sess.run after loading model in TensorFlow在 TensorFlow 中加载模型后无法执行 sess.run
【发布时间】:2018-09-13 01:29:07
【问题描述】:

我用来加载模型的代码:

graph1 = tf.get_default_graph()
with graph1.as_default():
  with tf.Session(graph=graph1) as sess:
    tf.saved_model.loader.load(sess,[tag_constants.SERVING],'/mnist/mnist_saved_model/')

    x = graph1.get_tensor_by_name("x:0")
    y = graph1.get_tensor_by_name("y:0")
    keep_prob = graph1.get_tensor_by_name("keep_prob:0")
    aug_img = graph1.get_tensor_by_name("aug_img:0")
    logits = graph1.get_tensor_by_name("logits/BiasAdd:0")

    feats = sess.run(logits,feed_dict={x:img,keep_prob:1.0})
    print feats

sess.runwith tf.Session(graph=graph1) as sess 块内调用时执行良好

但是在使用 Jupyter Notebook 时,当我尝试在上述代码下方的另一个单元格中的另一个图像上分别执行 sess.run 时:

with tf.Session(graph=graph1) as sess:
  feats = sess.run(logits,feed_dict={x:img,keep_prob:1.0})

然后我得到一个错误

FailedPreconditionError: Attempting to use uninitialized value conv2/kernel

为什么我不能在除第一段代码之外的其他地方执行sess.run

如何加载模型并从代码中的任何位置调用它?

【问题讨论】:

    标签: tensorflow


    【解决方案1】:

    这样做:

    graph1 = tf.get_default_graph()
    sess = tf.Session(graph=graph1)
    with graph1.as_default():
      tf.saved_model.loader.load(sess,[tag_constants.SERVING],'/mnist/mnist_saved_model/')
    
      x = graph1.get_tensor_by_name("x:0")
      y = graph1.get_tensor_by_name("y:0")
      keep_prob = graph1.get_tensor_by_name("keep_prob:0")
      aug_img = graph1.get_tensor_by_name("aug_img:0")
      logits = graph1.get_tensor_by_name("logits/BiasAdd:0")
    
      feats = sess.run(logits,feed_dict={x:img,keep_prob:1.0})
      print feats
    

    然后只运行这一行:

    feats = sess.run(logits,feed_dict={x:img,keep_prob:1.0})
    print feats
    

    不用再sess = tf.Session(graph=graph1)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-24
      • 1970-01-01
      • 2022-08-10
      • 1970-01-01
      • 2020-05-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多