[英]Keras output single value through argmax
I'm trying to build a really simple neural network in Keras: 我正在努力在Keras建立一个非常简单的神经网络:
model = Sequential()
model.add(Dense(40, input_dim=186, activation='relu', name='x'))
model.add(Dense(3, activation='softmax'))
This works, and outputs a three-dimensional vector (eg 0 1 0
). 这有效,并输出三维矢量(例如
0 1 0
)。 I'd like to add a layer that uses argmax to send out a single value, rather than this vector. 我想添加一个使用argmax发送单个值的图层,而不是这个向量。
I figured this would work: 我认为这样可行:
model.add(Lambda(lambda x: K.cast(K.argmax(x), dtype='float32')))
But this throws (5962 is the number of training samples): 但这次抛出(5962是训练样本的数量):
ValueError: Error when checking target: expected lambda_1 to have 1 dimensions, but got array with shape (5962, 3)
How would I achieve this? 我怎么做到这一点?
Note that I'd like this in the model as an actual ArgMax layer, similar to TensorFlow's ArgMax . 请注意,我在模型中将此视为实际的ArgMax层,类似于TensorFlow的ArgMax 。
Thanks to @today for pointing me in the right direction. 感谢@today指出我正确的方向。 You should add the layer after training and all is fine:
您应该在训练后添加图层并且一切正常:
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')
This will now have added the ArgMax layer to the model! 现在,这将把ArgMax图层添加到模型中!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.