将值输入 sess.run() 的占位符张量的问题

Issue with feeding value into placeholder tensor for sess.run()

我想获取卷积神经网络中特定输入的中间张量的值。我知道如何在 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 的图像属于 float 类型,我认为这是正确的形状。将建议任何帮助。

您必须使用来自 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)