Skip to main content

A library for computing true training loss in Keras models without regularization effects.

Project description

trueloss

trueloss is a Python library designed to compute and plot the true training loss and accuracy of a Keras classification model without regularization effects. The purpose of creating this library is to address the discrepancy between the training loss displayed in Keras. This discrepancy can lead to misleading conclusions about model performance. trueloss allows you to gain a clearer understanding of your model's true performance on the training data.

When training machine learning models, the total training loss usually includes a base loss term and a regularization loss term.The base loss is problem-specific, guiding model predictions (e.g., Cross-Entropy Loss for classification, Mean Squared Error (MSE) for regression). But during testing there is no regularization term added to the base loss. Mathematically, this is represented as:

  1. During Training:

$$ \text{Training Loss} = \text{Base Loss} + \text{Regularization Loss} $$

$$ \text{Training Loss} (\mathcal{L}{\text{training}}) = \mathcal{L}{\text{base}} + \lambda |\theta|^2 $$

  1. During testing:

$$ \text{Testing Loss} = \text{Base Loss} $$

$$ \text{Testing Loss} (\mathcal{L}{\text{testing}}) = \mathcal{L}{\text{base}} $$

Currently this version only supports classification models.

Features

  • Computes the true training loss and accuracy without regularization effects.
  • Plots training and validation loss and accuracy curves.
  • Seamlessly integrates with Keras, using the same fit method parameters and defaults.
  • Ensures the model instance and history object work normally, with the addition of base_loss and base_accuracy in the training history.

Installation

Install the library using pip:

pip install trueloss

Usage

Basic Usage

First, import the necessary libraries and the trueloss class:

import tensorflow as tf
from trueloss import trueloss

Creating and Compiling a Model

Create and compile your Keras model as usual:

model = tf.keras.models.Sequential([
    tf.keras.layers.Dense(64, activation='relu', input_shape=(784,)),
    tf.keras.layers.Dense(10, activation='softmax')
])

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

Training the Model with trueloss

Create an instance of the trueloss class and train your model using the fit method. The parameters for fit are exactly the same as those for the Keras fit method, with the same defaults. This ensures seamless integration with Keras.

# Initialize the trueloss instance with the model
true_loss_instance = trueloss(model=model, plot=True)

# Train the model
history = true_loss_instance.fit(x_train, y_train, 
                                 validation_data=(x_val, y_val),
                                 epochs=10, 
                                 batch_size=32, 
                                 verbose=1)

Important Notes

  1. Model Instance Behavior:

    • The model instance will behave normally, even when fitted using true_loss_instance.fit().
    • You can use the model for predictions, evaluations, and other tasks just as you would with a standard Keras model.
  2. Training History:

    • The training history object returned by the fit method is the same as the Keras history object.
    • The only addition is history.history['base_loss'] and history.history['base_accuracy'], which log the true training loss and accuracy.
  3. Verbose Output:

    • The verbose output during training will be the same as the Keras fit method.

Plotting Only

If you only want to plot the training and validation curves without fitting the model, you can initialize the trueloss class without a model and use the plot_fn method directly:

# Initialize the trueloss instance without a model
true_loss_instance = trueloss(plot=True)

# Assuming you have a history object from previous training
true_loss_instance.plot_fn(history)

Example

Here is a complete example of how to use the trueloss library:

import tensorflow as tf
from trueloss import trueloss

# Load and preprocess the data
(x_train, y_train), (x_val, y_val) = tf.keras.datasets.mnist.load_data()
x_train, x_val = x_train / 255.0, x_val / 255.0

# Create and compile the model
model = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(input_shape=(28, 28)),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dropout(0.2),
    tf.keras.layers.Dense(10, activation='softmax')
])

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

# Initialize the trueloss instance
true_loss_instance = trueloss(model=model, plot=True)

# Train the model
history = true_loss_instance.fit(x_train, y_train, 
                                 validation_data=(x_val, y_val),
                                 epochs=10, 
                                 batch_size=32, 
                                 verbose=1)

You can also visit this notebook for an example.

Contributing

Contributions are welcome! If you have any improvements, suggestions, or bug fixes, please feel free to open an issue or submit a pull request.

License

This project is licensed under the MIT License. See the LICENSE file for details.

Contact

For questions, feedback, or support, please reach out via GitHub issues or email me(Siddique Abusaleh) at trueloss.py@gmail.com.

Acknowledgements

This library is built on top of Keras and TensorFlow. We thank the contributors of these libraries for their excellent work.

Citation

If you find this library useful in your research, please consider citing it:

@misc{trueloss,
  author = {Siddique Abusaleh},
  title = {trueloss: A library for computing true training loss in Keras models},
  year = {2024},
  publisher = {GitHub},
  journal = {GitHub repository},
  howpublished = {\url{https://github.com/trueloss/trueloss}}
}

By using trueloss, you can gain deeper insights into your model's true performance on the training data while enjoying the seamless integration with Keras.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

trueloss-0.1.4.tar.gz (5.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

trueloss-0.1.4-py3-none-any.whl (5.5 kB view details)

Uploaded Python 3

File details

Details for the file trueloss-0.1.4.tar.gz.

File metadata

  • Download URL: trueloss-0.1.4.tar.gz
  • Upload date:
  • Size: 5.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.2

File hashes

Hashes for trueloss-0.1.4.tar.gz
Algorithm Hash digest
SHA256 9dc53802667d236babee19c074d9f0ae8f05abc9febfd2016e3b2f56219faa38
MD5 8507e6a4b2cd8faabf1870de2c420c6e
BLAKE2b-256 6c0da75dde27c48870da69dc131bb37bee695495ba7e70cd023f580cd8a80734

See more details on using hashes here.

File details

Details for the file trueloss-0.1.4-py3-none-any.whl.

File metadata

  • Download URL: trueloss-0.1.4-py3-none-any.whl
  • Upload date:
  • Size: 5.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.2

File hashes

Hashes for trueloss-0.1.4-py3-none-any.whl
Algorithm Hash digest
SHA256 fef10430fe01bb614f561413469a3633273513f0bf1394e105beacdac78ac92b
MD5 5a9757dc5243e646027f64295bc73a3b
BLAKE2b-256 8d18da408620afc90b3d62c68441612a97804f37d774761536ffeae8716bd379

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page