【问题标题】:Keras output single value through argmaxKeras通过argmax输出单个值
【发布时间】:2019-06-21 13:44:18
【问题描述】:

我正在尝试在 Keras 中构建一个非常简单的神经网络:

model = Sequential()
model.add(Dense(40, input_dim=186, activation='relu', name='x'))
model.add(Dense(3, activation='softmax'))

这可行,并输出一个三维向量(例如0 1 0)。我想添加一个使用 argmax 发送单个值的层,而不是这个向量。

我认为这会起作用:

model.add(Lambda(lambda x: K.cast(K.argmax(x), dtype='float32')))

但这会抛出(5962是训练样本的数量):

ValueError: Error when checking target: expected lambda_1 to have 1 dimensions, but got array with shape (5962, 3)

我将如何实现这一目标?

请注意,我希望在模型中将此作为实际的 ArgMax 层,类似于 TensorFlow's ArgMax

【问题讨论】:

  • 你不能在训练阶段这样做,因为.argmax 不是一个可微的操作。但是,错误告诉您您提供的标签的形状为(num_samples, 3),但Lambda 层的输出形状为(num_samples, 1)
  • @today,这是有道理的,但是 TensorFlow 怎么能做到这一点呢?例如。 here 它在模型定义中显示argmax 层...

标签: python keras


【解决方案1】:

感谢@today 为我指明了正确的方向。您应该在 训练之后添加层,一切都很好:

model = Sequential()
model.add(Dense(40, input_dim=186, activation='relu', name='x'))
model.add(Dense(classes, activation='softmax'))

model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(X_train, Y_train, batch_size=50, epochs=100, validation_data=(X_test, Y_test))
model.add(Lambda(lambda x: K.cast(K.argmax(x), dtype='float32'), name='y_pred'))
model.save('data/trained.h5')

这将把 ArgMax 层添加到模型中!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-25
    • 2019-07-24
    相关资源
    最近更新 更多