【问题标题】:Issue with feeding value into placeholder tensor for sess.run()sess.run() 将值输入占位符张量的问题
【发布时间】:2020-10-28 15:06:45
【问题描述】:

我想获得卷积神经网络中特定输入的中间张量的值。我知道如何在 keras 中做到这一点,即使我已经使用 keras 训练了模型,我将继续使用 tensorflow 构建和训练模型。因此,我想摆脱像 K.function(input_layer, output_layer) 这样相当简单的东西,而是使用 tensorflow。我相信我应该使用占位符值,例如以下方法:

with tf.compat.v1.Session(graph=tf.Graph()) as sess:
    loaded_model = tf.keras.models.load_model(filepath)
    graph = tf.compat.v1.get_default_graph()  
    images = tf.compat.v1.placeholder(tf.float32, shape=(None, 28, 28, 1)) # To specify input at MNIST images
    output_tensor = graph.get_tensor_by_name(tensor_name) # tensor_name is 'dense_1/MatMul:0'
    output = sess.run([output_tensor], feed_dict={images: x_test[0:1]}) # x_test[0:1] is of shape (1, 28, 28, 1)
    print(output)

但是,我收到sess.run() 行的以下错误消息:Invalid argument: You must feed a value for placeholder tensor 'conv2d_2_input' with dtype float and shape [?,28,28,1]。我不确定为什么会收到此消息,因为用于feed_dict 的图像是浮点类型,并且我认为是正确的形状。任何帮助都会被建议。

【问题讨论】:

    标签: tensorflow keras conv-neural-network placeholder sess.run


    【解决方案1】:

    您必须使用 Keras 模型中的输入张量,而不是制作自己的新占位符,否则会与模型的其余部分断开连接:

    with tf.Graph().as_default(), tf.compat.v1.Session() as sess:
        # Load model
        loaded_model = tf.keras.models.load_model(filepath)
        # Take model input tensor
        images = loaded_model.input
        # Take output of the second layer (index 1)
        output_tensor = loaded_model.layers[1].output
        # Evaluate
        output = sess.run(output_tensor, feed_dict={images: x_test[0:1]})
        print(output)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-23
      • 2014-01-03
      • 2017-05-22
      • 2018-02-01
      • 2012-02-06
      • 1970-01-01
      • 2020-02-07
      • 2014-08-03
      相关资源
      最近更新 更多