Keras
model fitting
loss function
validation accuracy
machine learning

How to understand loss, acc, val_loss, val_acc in Keras model fitting?

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Understanding the metrics and losses produced by a Keras model during the fitting process is crucial for evaluating and improving your machine learning models. In Keras, these metrics typically include loss, acc (accuracy), val_loss, and val_acc (validation accuracy). Below, we will explore each of these components in detail and discuss their significance.

Loss

The loss value is a metric that quantifies the difference between your model's predictions and the actual target values during training. It is produced by the loss function specified at the model compilation stage. Common loss functions include Mean Squared Error (MSE) for regression tasks and Categorical Crossentropy for classification tasks. Minimizing this loss is the principal objective of training a model.

Example

For a classification task using sparse categorical crossentropy loss:

python
1model.compile(optimizer='adam', 
2              loss='sparse_categorical_crossentropy', 
3              metrics=['accuracy'])
4
5history = model.fit(X_train, y_train, validation_data=(X_val, y_val), epochs=10)
6
7# Output will display 'loss' and 'val_loss' as part of the fitting result.

Accuracy (Acc)

acc, or accuracy, measures the proportion of true results (both true positives and true negatives) among the total number of cases examined. This metric is straightforward for classification tasks and gives a quick snapshot of how well the model is performing.

Formula

Accuracy is calculated as:

 
(Accuracy) = frac((Number of Correct Predictions))((Total Number of Predictions))

Validation Loss (Val_loss)

val_loss is the same as loss but calculated on a separate validation dataset, which is not used for training the model. Monitoring val_loss helps in understanding if your model is overfitting. Typically, you want to see that both training and validation losses decrease over time.

Overfitting Example

  • During training, a decrease in loss is expected.
  • If val_loss starts increasing while loss keeps decreasing, your model is likely overfitting.

Validation Accuracy (Val_acc)

Similar to acc, val_acc calculates accuracy on the validation dataset. It serves as a generalization measure — a high val_acc indicates that the model performs well on unseen data.

Monitoring Model Performance

Using the history object returned by model.fit(), you can plot these metrics over epochs to visually inspect behavior:

python
1import matplotlib.pyplot as plt
2
3plt.plot(history.history['loss'], label='Training Loss')
4plt.plot(history.history['val_loss'], label='Validation Loss')
5plt.plot(history.history['accuracy'], label='Training Accuracy')
6plt.plot(history.history['val_accuracy'], label='Validation Accuracy')
7plt.xlabel('Epochs')
8plt.ylabel('Loss/Accuracy')
9plt.legend()
10plt.show()

Key Characteristics of Loss and Accuracy

MetricDatasetPurpose
lossTrainingMeasures prediction error for the training data, directly used for backpropagation optimization.
accTrainingMeasures the proportion of correctly predicted observations in the training data.
val_lossValidationEvaluates prediction error on validation data; helps in detecting overfitting when diverging from loss.
val_accValidationIndicates how well the model generalizes to unseen data, useful for performance benchmarking beyond training effectiveness.

Additional Considerations

  • Learning Rate: An inappropriate learning rate may cause loss and accuracy graphs to oscillate or plateau. Tuning the learning rate can ameliorate these issues.
  • Early Stopping: A common technique to avoid overfitting by monitoring val_loss and stopping training when it stops decreasing.
  • Data Quality: Ensure that your validation and training datasets are representative and clean to get accurate metrics.

Understanding these metrics and their implications allows you to fine-tune your models efficiently, leading to models that perform better on unseen data. It is pivotal to interpret these updates in the context of the data and the problem domain to guide necessary adjustments in model architecture or training procedures.


Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
This one is answered in full over here

“Why does training loss keep falling while validation loss starts rising?” is the same question written out properly on Basis Lab, with the course it belongs to beside it. Basis Lab is a separate product from the same team and both are free to read.

Read the answer
ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design