【问题标题】:Keras backend function: InvalidArgumentErrorKeras 后端函数:InvalidArgumentError
【发布时间】:2018-12-10 21:29:38
【问题描述】:

我无法让keras.backend.function 正常工作。我正在尝试关注这篇文章:

How to calculate prediction uncertainty using Keras?

在这篇文章中,他们创建了一个函数f

f = K.function([model.layers[0].input],[model.layers[-1].output]) #(I actually simplified the function a little bit).

在我的神经网络中,我有 3 个输入。当我尝试计算 f([[3], [23], [0.0]]) 时,出现此错误:

InvalidArgumentError: You must feed a value for placeholder tensor 'input_3' with dtype float and shape [?,1]
 [[{{node input_3}} = Placeholder[dtype=DT_FLOAT, shape=[?,1], _device="/job:localhost/replica:0/task:0/device:CPU:0"]

现在我知道在我的模型中使用[[3], [23], [0.0]] 作为输入不会在测试阶段给我带来错误。谁能告诉我哪里出错了?

如果重要的话,这就是我的模型的样子:

home_in = Input(shape=(1,))
away_in = Input(shape=(1,))
time_in = Input(shape = (1,))
embed_home = Embedding(input_dim = in_dim, output_dim = out_dim, input_length = 1)
embed_away = Embedding(input_dim = in_dim, output_dim = out_dim, input_length = 1)
embedding_home = Flatten()(embed_home(home_in))
embedding_away = Flatten()(embed_away(away_in))
keras.backend.set_learning_phase(1) #this will keep dropout on during the testing phase
model_layers = Dense(units=2)\
    (Dropout(0.3)\
    (Dense(units=64, activation = "relu")\
    (Dropout(0.3)\
    (Dense(units=64, activation = "relu")\
    (Dropout(0.3)\
    (Dense(units=64, activation = "relu")\
    (concatenate([embedding_home, embedding_away, time_in]))))))))
model = Model(inputs=[home_in, away_in, time_in], outputs=model_layers)`

【问题讨论】:

  • 感谢您@today 的更新回复,我的代码现在可以工作了。我还想提一下,我在张量流 (tf.keras) 中从 keras 切换到了 keras 库,并且我的代码立即运行,没有任何错误。

标签: python machine-learning keras neural-network


【解决方案1】:

您定义的函数仅使用其中一个输入层(即model.layers[0].input)作为其输入。相反,它必须使用所有输入才能运行模型。该模型有 inputsoutputs 属性,您可以使用它们来包含所有输入和输出,并且不那么冗长:

f = K.function(model.inputs, model.outputs)

更新:所有输入数组的形状必须为(num_samples, 1)。因此,您需要传递列表列表(例如[[3]])而不是列表(例如[3]):

outs = f([[[3]], [[23]], [[0.0]]])

【讨论】:

  • 感谢您的回复!不幸的是,现在我得到了错误:InvalidArgumentError: ConcatOp : Ranks of all input tensors should match: shape[0] = [1,16] vs. shape[2] = [1] [[{{node concatenate_1/concat}} = ConcatV2[N=3, T=DT_FLOAT, Tidx=DT_INT32, _device="/job:localhost/replica:0/task:0/device:CPU:0"](flatten_1/Reshape, flatten_2/Reshape, _arg_input_3_0_2, concatenate_1/concat/axis)]]"
猜你喜欢
  • 2018-10-10
  • 2023-03-22
  • 2018-12-26
  • 2018-08-06
  • 1970-01-01
  • 2017-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多