How to Log Keras Loss Output to a File
Last Updated :
23 Jul, 2025
Monitoring the training process of a machine learning model is crucial for understanding its performance over time. When working with Keras, one of the most effective ways to track this is by logging the loss output to a file. This not only allows you to keep a record of the training progress but also provides valuable insights for further tuning and optimization. In this article, we'll walk through the process of logging Keras loss output to a file using the CSVLogger
callback, a built-in feature in Keras.
Why Log Loss Output?
Logging the loss output during training has several benefits:
- Performance Monitoring: Track how well your model is learning over epochs.
- Troubleshooting: Detect issues such as overfitting or underfitting by analyzing the loss curve.
- Experiment Documentation: Keep a record of different training runs for future reference or comparison.
- Post-Training Analysis: Perform in-depth analysis on the loss values to understand the model’s behavior.
Using CSVLogger Callback
Using CSVLogger callback in Keras we can log epoch results to a CSV file. This is most simple and easy method to keep track of the loss and other metrics during training.
Syntax
from keras.callbacks import CSVLogger
csv_logger = CSVLogger('training.log', append=True)
Step-by-Step Implementation
Below is a step-by-step guide to logging Keras loss output to a file using a simple Keras model.
1. Import Necessary Libraries
Start by importing the required libraries and modules:
import keras
from keras.models import Sequential
from keras.layers import Dense, Input
from keras.callbacks import CSVLogger
import numpy as np
Here, we import Keras modules to build the model, layers for defining the architecture, and CSVLogger
for logging. We also use NumPy to generate some sample data for demonstration.
2. Define the Model
Next, define a simple Keras model using the Sequential API. This model consists of an input layer, two hidden dense layers with ReLU activation, and an output layer with softmax activation.
# Define a simple model
model = Sequential([
Input(shape=(100,)),
Dense(64, activation='relu'),
Dense(64, activation='relu'),
Dense(10, activation='softmax')
])
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
This model is compiled with the Adam optimizer and categorical cross-entropy as the loss function, which is common for multi-class classification tasks.
3. Create a CSV Logger Callback
The CSVLogger
callback is a built-in Keras callback that automatically logs loss, accuracy, and other metrics to a CSV file after each epoch. You can set it up as follows:
# Create CSVLogger callback
csv_logger = CSVLogger('training.log', append=True)
The append=True
argument ensures that the logger appends to the file if it already exists, instead of overwriting it.
4. Generate Sample Data
For the purpose of this demonstration, we’ll create some random sample data. In a real scenario, you would replace this with your actual dataset.
# Create sample data for demonstration (Replace with your actual data)
x_train = np.random.rand(1000, 100)
y_train = np.random.rand(1000, 10)
x_val = np.random.rand(200, 100)
y_val = np.random.rand(200, 10)
Here, x_train
and y_train
represent the training data and labels, while x_val
and y_val
represent the validation data and labels.
5. Train the Model and Log the Loss
Now, you can train the model and use the CSVLogger
to log the training process:
# Train the model
model.fit(x_train, y_train, epochs=10, validation_data=(x_val, y_val), callbacks=[csv_logger])
print("Training completed. Check 'training.log' for details.")
During training, Keras will log the loss, accuracy, validation loss, and validation accuracy after each epoch into the training.log
file.
Complete Code
Python
import keras
from keras.models import Sequential
from keras.layers import Dense, Input
from keras.callbacks import CSVLogger
import numpy as np
# Define a simple model
model = Sequential([
Input(shape=(100,)),
Dense(64, activation='relu'),
Dense(64, activation='relu'),
Dense(10, activation='softmax')
])
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
# Create CSVLogger callback
csv_logger = CSVLogger('training.log', append=True)
# Create sample data for demonstration (Replace with your actual data)
x_train = np.random.rand(1000, 100)
y_train = np.random.rand(1000, 10)
x_val = np.random.rand(200, 100)
y_val = np.random.rand(200, 10)
# Train the model
model.fit(x_train, y_train, epochs=10, validation_data=(x_val, y_val), callbacks=[csv_logger])
print("Training completed. Check 'training.log' for details.")
Output:
Epoch 1/10
32/32 ━━━━━━━━━━━━━━━━━━━━ 1s 9ms/step - accuracy: 0.0963 - loss: 12.9074 - val_accuracy: 0.1000 - val_loss: 20.8755
Epoch 2/10
32/32 ━━━━━━━━━━━━━━━━━━━━ 0s 3ms/step - accuracy: 0.0996 - loss: 23.6421 - val_accuracy: 0.1050 - val_loss: 38.4615
Epoch 3/10
32/32 ━━━━━━━━━━━━━━━━━━━━ 0s 3ms/step - accuracy: 0.1206 - loss: 45.8963 - val_accuracy: 0.0950 - val_loss: 67.9421
Epoch 4/10
32/32 ━━━━━━━━━━━━━━━━━━━━ 0s 3ms/step - accuracy: 0.1003 - loss: 78.6446 - val_accuracy: 0.1150 - val_loss: 120.0951
Epoch 5/10
32/32 ━━━━━━━━━━━━━━━━━━━━ 0s 3ms/step - accuracy: 0.0923 - loss: 136.6691 - val_accuracy: 0.0800 - val_loss: 181.1774
Epoch 6/10
32/32 ━━━━━━━━━━━━━━━━━━━━ 0s 2ms/step - accuracy: 0.0815 - loss: 196.4902 - val_accuracy: 0.1000 - val_loss: 238.5413
Epoch 7/10
32/32 ━━━━━━━━━━━━━━━━━━━━ 0s 3ms/step - accuracy: 0.0923 - loss: 245.0914 - val_accuracy: 0.0900 - val_loss: 270.6060
Epoch 8/10
32/32 ━━━━━━━━━━━━━━━━━━━━ 0s 3ms/step - accuracy: 0.1010 - loss: 285.1187 - val_accuracy: 0.1000 - val_loss: 305.6728
Epoch 9/10
32/32 ━━━━━━━━━━━━━━━━━━━━ 0s 3ms/step - accuracy: 0.1091 - loss: 307.4221 - val_accuracy: 0.1000 - val_loss: 314.3473
Epoch 10/10
32/32 ━━━━━━━━━━━━━━━━━━━━ 0s 3ms/step - accuracy: 0.0955 - loss: 305.7090 - val_accuracy: 0.0750 - val_loss: 260.9680
Training completed. Check 'training.log' for details.
Review the Logged Data
After the training is complete, you can open the training.log
file to review the logged data. The file will contain records similar to the following:
Each row corresponds to an epoch, showing the accuracy, loss, validation accuracy, and validation loss.
Conclusion
Logging Keras loss output to a file is a straightforward process using the CSVLogger
callback. This method provides a simple yet powerful way to monitor and analyze your model's performance throughout the training process. By logging the loss and other metrics, you can keep a detailed record of your experiments, making it easier to diagnose issues, optimize your model, and document your findings.
Whether you are working on a simple model or a complex deep learning architecture, keeping track of the loss output is essential for successful model development.
Similar Reads
Deep Learning Tutorial Deep Learning is a subset of Artificial Intelligence (AI) that helps machines to learn from large datasets using multi-layered neural networks. It automatically finds patterns and makes predictions and eliminates the need for manual feature extraction. Deep Learning tutorial covers the basics to adv
5 min read
Deep Learning Basics
Introduction to Deep LearningDeep Learning is transforming the way machines understand, learn and interact with complex data. Deep learning mimics neural networks of the human brain, it enables computers to autonomously uncover patterns and make informed decisions from vast amounts of unstructured data. How Deep Learning Works?
7 min read
Artificial intelligence vs Machine Learning vs Deep LearningNowadays many misconceptions are there related to the words machine learning, deep learning, and artificial intelligence (AI), most people think all these things are the same whenever they hear the word AI, they directly relate that word to machine learning or vice versa, well yes, these things are
4 min read
Deep Learning Examples: Practical Applications in Real LifeDeep learning is a branch of artificial intelligence (AI) that uses algorithms inspired by how the human brain works. It helps computers learn from large amounts of data and make smart decisions. Deep learning is behind many technologies we use every day like voice assistants and medical tools.This
3 min read
Challenges in Deep LearningDeep learning, a branch of artificial intelligence, uses neural networks to analyze and learn from large datasets. It powers advancements in image recognition, natural language processing, and autonomous systems. Despite its impressive capabilities, deep learning is not without its challenges. It in
7 min read
Why Deep Learning is ImportantDeep learning has emerged as one of the most transformative technologies of our time, revolutionizing numerous fields from computer vision to natural language processing. Its significance extends far beyond just improving predictive accuracy; it has reshaped entire industries and opened up new possi
5 min read
Neural Networks Basics
What is a Neural Network?Neural networks are machine learning models that mimic the complex functions of the human brain. These models consist of interconnected nodes or neurons that process data, learn patterns and enable tasks such as pattern recognition and decision-making.In this article, we will explore the fundamental
12 min read
Types of Neural NetworksNeural networks are computational models that mimic the way biological neural networks in the human brain process information. They consist of layers of neurons that transform the input data into meaningful outputs through a series of mathematical operations. In this article, we are going to explore
7 min read
Layers in Artificial Neural Networks (ANN)In Artificial Neural Networks (ANNs), data flows from the input layer to the output layer through one or more hidden layers. Each layer consists of neurons that receive input, process it, and pass the output to the next layer. The layers work together to extract features, transform data, and make pr
4 min read
Activation functions in Neural NetworksWhile building a neural network, one key decision is selecting the Activation Function for both the hidden layer and the output layer. It is a mathematical function applied to the output of a neuron. It introduces non-linearity into the model, allowing the network to learn and represent complex patt
8 min read
Feedforward Neural NetworkFeedforward Neural Network (FNN) is a type of artificial neural network in which information flows in a single direction i.e from the input layer through hidden layers to the output layer without loops or feedback. It is mainly used for pattern recognition tasks like image and speech classification.
6 min read
Backpropagation in Neural NetworkBack Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
Deep Learning Models
Deep Learning Frameworks
TensorFlow TutorialTensorFlow is an open-source machine-learning framework developed by Google. It is written in Python, making it accessible and easy to understand. It is designed to build and train machine learning (ML) and deep learning models. It is highly scalable for both research and production.It supports CPUs
2 min read
Keras TutorialKeras high-level neural networks APIs that provide easy and efficient design and training of deep learning models. It is built on top of powerful frameworks like TensorFlow, making it both highly flexible and accessible. Keras has a simple and user-friendly interface, making it ideal for both beginn
3 min read
PyTorch TutorialPyTorch is an open-source deep learning framework designed to simplify the process of building neural networks and machine learning models. With its dynamic computation graph, PyTorch allows developers to modify the networkâs behavior in real-time, making it an excellent choice for both beginners an
7 min read
Caffe : Deep Learning FrameworkCaffe (Convolutional Architecture for Fast Feature Embedding) is an open-source deep learning framework developed by the Berkeley Vision and Learning Center (BVLC) to assist developers in creating, training, testing, and deploying deep neural networks. It provides a valuable medium for enhancing com
8 min read
Apache MXNet: The Scalable and Flexible Deep Learning FrameworkIn the ever-evolving landscape of artificial intelligence and deep learning, selecting the right framework for building and deploying models is crucial for performance, scalability, and ease of development. Apache MXNet, an open-source deep learning framework, stands out by offering flexibility, sca
6 min read
Theano in PythonTheano is a Python library that allows us to evaluate mathematical operations including multi-dimensional arrays efficiently. It is mostly used in building Deep Learning Projects. Theano works way faster on the Graphics Processing Unit (GPU) rather than on the CPU. This article will help you to unde
4 min read
Model Evaluation
Deep Learning Projects