How to handle multi-class classification problems in Keras?
In Keras, handling multi-class problems typically involves using softmax activation function and categorical crossentropy loss function. Here is a simple example of a multi-class problem:
from keras.models import Sequential
from keras.layers import Dense
model = Sequential()
model.add(Dense(64, activation='relu', input_shape=(100,)))
model.add(Dense(64, activation='relu'))
model.add(Dense(10, activation='softmax'))
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
# 训练模型
model.fit(X_train, y_train, epochs=10, batch_size=32)
# 评估模型
loss, accuracy = model.evaluate(X_test, y_test)
print('Test accuracy:', accuracy)
In this example, we utilized a neural network with two hidden layers, with the final layer being a softmax layer with 10 categories. During model training, we employed the categorical crossentropy loss function and the Adam optimizer. Lastly, we evaluated the model’s accuracy on the test set.
When dealing with multi-class problems, it is necessary to encode the labels into one-hot encoding, which means converting each category into a vector of the same length as the number of categories, with a value of 1 at the corresponding category position and 0 at all other positions. In Keras, the to_categorical function can be used for this conversion.
from keras.utils import to_categorical
# 将标签进行one-hot编码
y_train = to_categorical(y_train)
y_test = to_categorical(y_test)