简体   繁体   English

Keras 多分类器 ANN 中的 Argmax

[英]Argmax in a Keras multiclassifier ANN

I am trying to code a 5 class classifier ANN, and this code return this error:我正在尝试编写一个 5 class 分类器 ANN,并且此代码返回此错误:

    classifier = Sequential()
    
    classifier.add(Dense(units=10, input_dim=14, kernel_initializer='uniform', activation='relu'))
    
    classifier.add(Dense(units=6, kernel_initializer='uniform', activation='relu'))
    
    classifier.add(Dense(units=5, kernel_initializer='uniform', activation='softmax'))
    
    classifier.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
    
    RD_Model = classifier.fit(X_train,y_train, batch_size=10 , epochs=10, verbose=1)


File "c:\Program Files\Python310\lib\site-packages\keras\backend.py", line 5119, in categorical_crossentropy
        target.shape.assert_is_compatible_with(output.shape)
    ValueError: Shapes (None, 1) and (None, 5) are incompatible

I figured this is caused because I have a probability matrix instead of an actual output, so I have been trying to apply an argmax, but haven't figured a way我认为这是因为我有一个概率矩阵而不是实际的 output,所以我一直在尝试应用 argmax,但还没有想出办法

Can someone help me out?有人可以帮我吗?

Have you tried applying:您是否尝试过申请:

tf.keras.backend.argmax()

You can define a lambda layer using the following:您可以使用以下命令定义lambda layer

from keras.layer import Lambda
from keras import backend as K

def argmax_layer(input):
  return K.argmax(input, axis=-1)

Keras provides two paradigms for defining a model topology. Keras提供了两种用于定义 model 拓扑的范例。 The code you are using uses the Sequential API .您正在使用的代码使用Sequential API You might have to revert to the Functional API .您可能必须恢复到Functional API

input_layer = Input(shape=(14,))
layer_1 = Dense(10, activation="relu")(input_layer)
layer_2 = Dense(6, activation="relu")(layer_1)
layer_3 = argmax_layer()(layer_2 )
output_layer= Dense(5, activation="linear")(layer_3 )

model = Model(inputs=input_layer, outputs=output_layer)

model.compile(optimizer='adam',
               loss='categorical_crossentropy', metrics=['accuracy'])

Another option would be to instantiate an inherited class of a Keras Layer .另一种选择是实例化Keras Layer的继承 class 。 https://www.tutorialspoint.com/keras/keras_customized_layer.htm https://www.tutorialspoint.com/keras/keras_customized_layer.htm

As Dr. Snoopy mentioned, it was indeed a problem of one-hot encoding... I missed to do that, resulting in my model not working.正如史努比博士所说,这确实是单热编码的问题......我错过了这样做,导致我的 model 无法正常工作。

So I just one hot encoded it:所以我只对它进行了一次热编码:

encoder = LabelEncoder()
encoder.fit(y_train)
encoded_Y = encoder.transform(y_train)
# convert integers to dummy variables (i.e. one hot encoded)
dummy_y = np_utils.to_categorical(encoded_Y)

And it worked after using dummy_y.它在使用 dummy_y 后起作用。 Thank you for your help.谢谢您的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM