使用 Keras 模型时出现 "You must feed a value for placeholder tensor" 错误

Getting "You must feed a value for placeholder tensor" error when using Keras model

我试图在 Keras 中实现一个模型,但遇到了以下错误:

You must feed a value for placeholder tensor

这是我的模型:

def create_base_network(input_shape, out_dims):
    model = Sequential()
    model.add(Conv2D(32, kernel_size=(3, 3),
                     activation='relu',
                     input_shape=input_shape))
    model.add(Conv2D(64, (3, 3), activation='relu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))
    model.add(Dropout(0.25))
    model.add(Flatten())
    model.add(Dense(128, activation='relu'))
    model.add(Dropout(0.5))
    model.add(Dense(out_dims, activation='linear'))

    return model

input_shape=(28,28,3)
anchor_in = Input(shape=input_shape)
pos_in = Input(shape=input_shape)
neg_in = Input(shape=input_shape)

base_network = create_base_network(input_shape, 128)
anchor_out = base_network(anchor_in)
pos_out = base_network(pos_in)
neg_out = base_network(neg_in)

merged = concatenate([anchor_out, pos_out, neg_out], axis=-1)

model = Model(inputs=[anchor_in, pos_in, neg_in], outputs=merged)    

然后我尝试使用以下方法从顺序模型中获取输出:

seq_fun = K.function([model.layers[0].input, model.layers[1].input, model.layers[2].input], [model.layers[3].get_output_at(0)])
seq_output = seq_fun([a, p, n])[0]

此输入来自生成器,其形式为 numpy 数组,每个数组都具有所需的形状。然后错误信息是:

InvalidArgumentError: You must feed a value for placeholder tensor 'conv2d_1_input' with dtype float and shape [?,28,28,3]
 [[{{node conv2d_1_input}} = Placeholder[dtype=DT_FLOAT, shape=[?,28,28,3], _device="/job:localhost/replica:0/task:0/device:GPU:0"]()]]
 [[{{node dense_2/BiasAdd/_175}} = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device_incarnation=1, tensor_name="edge_102_dense_2/BiasAdd", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]

我真的不知道发生了什么。

您创建的顺序模型有 4 个输出节点。索引为零的那个,即 get_output_at(0),是直接输入的结果,其他三个是使用您定义的输入层之一输入时的输出。显然第一个没有连接到你定义的输入层,因此你得到错误:

You must feed a value for placeholder tensor ...

因此您需要指定其他三个输出节点(索引 1、2 或 3)作为自定义函数的输出:

seq_fun = K.function([model.layers[0].input, model.layers[1].input, model.layers[2].input], 
                      [model.layers[3].get_output_at(i)])  # i must be 1, 2 or 3

作为旁注,您可以使用模型的 inputs 属性更简洁地定义自定义函数:

seq_fun = K.function(model.inputs, [model.layers[3].get_output_at(i)])

重新安装 tensorflow==1.11.0 和 keras==2.1.2 对我有用。