Computing model accuracy is a crucial step during Keras-based model training, as it helps us understand the model's performance on both the training and validation sets. Below, I will illustrate how to obtain model accuracy in Keras using a simple example.
Step 1: Import necessary libraries
First, we import the required libraries, including Keras:
pythonimport keras from keras.models import Sequential from keras.layers import Dense from keras.datasets import mnist from keras.utils import to_categorical
Step 2: Load and preprocess data
Next, we load and preprocess the data. For example, using the MNIST handwritten digit dataset:
python(x_train, y_train), (x_test, y_test) = mnist.load_data() # Normalize x_train = x_train.reshape(60000, 784).astype('float32') / 255 x_test = x_test.reshape(10000, 784).astype('float32') / 255 # Convert labels to one-hot encoding y_train = to_categorical(y_train, 10) y_test = to_categorical(y_test, 10)
Step 3: Build the model
Then, we build a simple fully connected neural network model:
pythonmodel = Sequential([ Dense(512, activation='relu', input_shape=(784,)), Dense(256, activation='relu'), Dense(10, activation='softmax') ])
Step 4: Compile the model
During model compilation, we set accuracy as the evaluation metric:
pythonmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
Step 5: Train the model
Train the model and monitor accuracy during training:
pythonhistory = model.fit(x_train, y_train, epochs=10, batch_size=128, validation_data=(x_test, y_test))
Step 6: Evaluate the model
Finally, we evaluate the model's accuracy on the test set:
pythontest_loss, test_acc = model.evaluate(x_test, y_test) print(f"Test set accuracy: {test_acc}")
By following these steps, we can observe both training and validation accuracy at the end of each training epoch, and after training completes, we can directly obtain the model's accuracy on the test set using the evaluation function.
This method helps us understand how the model performs on unseen data. By comparing training and validation accuracy, we can also detect potential overfitting issues. I hope this example helps you understand how to obtain model accuracy in Keras.