多输入模型中的ValueError

时间:2020-05-01 08:59:30

标签: keras neural-network functional-programming conv-neural-network valueerror

我正在创建一个多输入模型,其中将CNN模型和LSTM模型连接在一起。 lstm模型包含最近5个事件,而CNN模型包含最后一个事件的图片。两者都经过组织,以使numpy中的每个元素k都匹配5个事件和相应的图片,输出标签也是如此,这是模型应预测的“下一个”事件。

chanDim = -1
inputs = Input(shape=inputShape)
x = inputs
x = Dense(128)(x)
x = Activation("relu")(x)
x = BatchNormalization(axis=chanDim)(x)
x = Dropout(0.3)(x)
x = Flatten()(x)
x = Activation("relu")(x)
x = BatchNormalization(axis=chanDim)(x)
x = Dropout(0.1)(x)
x = Activation("relu")(x)
model_cnn = Model(inputs, x)

这将创建CNN模型,以下代码代表LSTM模型

hidden1 = LSTM(128)(visible)
hidden2 = Dense(64, activation='relu')(hidden1)
output = Dense(10, activation='relu')(hidden2)
model_lstm = Model(inputs=visible, outputs=output)

现在,当我组合这些模型并使用简单的密集层对其进行扩展以对14个类进行多类预测时,所有输入都匹配,因此我可以将(none,10)和(none,10)合并为(没有,对于MLP为20):

x = Dense(14, activation="softmax")(x)
model_mlp = Model(inputs=[model_lstm.input, model_cnn.input], outputs=x)

一切正常,直到我尝试编译模型,这给我一个关于mlp模型最后一个密集层输入的错误:

ValueError:检查目标时出错:预期density_121的形状为(14,),但数组的形状为(1,)

您知道这怎么可能吗?如果您需要更多信息,我们很乐意提供

1 个答案:

答案 0 :(得分:1)

您的目标必须是(无,14)维。使用softmax,您必须对输出进行一键编码

尝试一下:

y = pd.get_dummies(np.concatenate([y_train, y_test])).values
y_train = y[:len(y_train)]
y_test = y[len(y_train):]