乐闻世界logo
搜索文章和话题

How to get accuracy of model using keras?

1个答案

1

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:

python
import 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:

python
model = 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:

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

Step 5: Train the model

Train the model and monitor accuracy during training:

python
history = 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:

python
test_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.

2024年8月12日 10:47 回复

你的答案