CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-keras

Multi-backend deep learning framework that provides a unified, high-level API for building and training neural networks across JAX, TensorFlow, PyTorch, and OpenVINO backends.

Pending
Overview
Eval results
Files

saving.mddocs/

Model Saving and Serialization

Keras provides comprehensive functionality for saving and loading models and weights, along with serialization utilities for custom objects and configurations.

Capabilities

Model Persistence

Core functions for saving and loading complete models including architecture, weights, and training configuration.

def save_model(model, filepath, overwrite=True, save_format=None, **kwargs):
    """
    Save a model to a file.
    
    Parameters:
    - model: Keras model instance to save  
    - filepath: Path where to save the model
    - overwrite: Whether to overwrite existing file (default: True)
    - save_format: Format to save in ('keras', 'h5', or 'tf') (default: None)
    - **kwargs: Additional arguments for specific formats
    
    Returns:
    None
    """

def load_model(filepath, custom_objects=None, compile=True, safe_mode=True):
    """
    Load a model from a file.
    
    Parameters:
    - filepath: Path to the saved model file
    - custom_objects: Optional dict mapping names to custom classes/functions
    - compile: Whether to compile the model after loading (default: True)
    - safe_mode: Whether to load in safe mode (default: True)
    
    Returns:
    Keras model instance
    """

Weight Management

Functions for saving and loading only the weights of a model without the architecture.

def save_weights(model, filepath, overwrite=True, save_format=None, **kwargs):
    """
    Save model weights to a file.
    
    Parameters:
    - model: Keras model instance
    - filepath: Path where to save the weights
    - overwrite: Whether to overwrite existing file (default: True)
    - save_format: Format to save in ('keras', 'h5', or 'tf') (default: None)
    - **kwargs: Additional arguments for specific formats
    
    Returns:
    None
    """

def load_weights(model, filepath, skip_mismatch=False, by_name=False, **kwargs):
    """
    Load model weights from a file.
    
    Parameters:
    - model: Keras model instance to load weights into
    - filepath: Path to the saved weights file
    - skip_mismatch: Whether to skip mismatched layers (default: False)
    - by_name: Whether to load weights by layer name (default: False)
    - **kwargs: Additional arguments for specific formats
    
    Returns:
    None
    """

Object Registration and Serialization

System for registering and managing custom objects for serialization compatibility.

def register_keras_serializable(package='Custom', name=None):
    """
    Decorator to register a class/function for Keras serialization.
    
    Parameters:
    - package: Package name for the registered object (default: 'Custom')
    - name: Name to register object under (default: class/function name)
    
    Returns:
    Decorator function
    """

def get_custom_objects():
    """
    Get the current custom object registry.
    
    Returns:
    Dict mapping names to custom objects
    """

def get_registered_name(obj):
    """
    Get the registered name for a Keras object.
    
    Parameters:
    - obj: Object to get registered name for
    
    Returns:
    String name or None if not registered
    """

def get_registered_object(name, custom_objects=None, module_objects=None):
    """
    Get a registered object by name.
    
    Parameters:
    - name: Name of the registered object
    - custom_objects: Optional custom object dict
    - module_objects: Optional module object dict
    
    Returns:
    The registered object
    """

class CustomObjectScope:
    """
    Context manager for providing custom objects during deserialization.
    
    Usage:
    ```python
    with CustomObjectScope({'custom_fn': my_custom_function}):
        model = keras.saving.load_model('my_model.keras')
    ```
    """
    def __init__(self, custom_objects):
        """
        Initialize the custom object scope.
        
        Parameters:
        - custom_objects: Dict mapping names to custom objects
        """
    
    def __enter__(self):
        """Enter the context manager."""
    
    def __exit__(self, *args):
        """Exit the context manager."""

def custom_object_scope(custom_objects):
    """
    Create a custom object scope context manager.
    
    Parameters:
    - custom_objects: Dict mapping names to custom objects
    
    Returns:
    CustomObjectScope instance
    """

Keras Object Serialization

Low-level serialization utilities for Keras objects and configurations.

def serialize_keras_object(obj):
    """
    Serialize a Keras object to a JSON-compatible dict.
    
    Parameters:
    - obj: Keras object to serialize
    
    Returns:
    Dict representation of the object
    """

def deserialize_keras_object(config, custom_objects=None, **kwargs):
    """
    Deserialize a Keras object from a config dict.
    
    Parameters:
    - config: Dict configuration of the object
    - custom_objects: Optional dict of custom objects
    - **kwargs: Additional arguments for deserialization
    
    Returns:
    Deserialized Keras object
    """

File Editing Utilities

Tools for editing saved Keras model files without full loading.

class KerasFileEditor:
    """
    Utility for editing Keras model files without full loading.
    
    Usage:
    ```python
    editor = KerasFileEditor('model.keras')
    editor.inspect()  # View model structure
    editor.close()
    ```
    """
    def __init__(self, filepath):
        """
        Initialize the file editor.
        
        Parameters:
        - filepath: Path to the Keras model file
        """
    
    def inspect(self):
        """
        Inspect the model structure without loading.
        
        Returns:
        Dict with model information
        """
    
    def close(self):
        """Close the file editor."""

Usage Examples

Basic Model Saving and Loading

import keras
from keras import saving

# Create and train a model
model = keras.Sequential([
    keras.layers.Dense(64, activation='relu', input_shape=(784,)),
    keras.layers.Dense(10, activation='softmax')
])

model.compile(optimizer='adam', loss='sparse_categorical_crossentropy')

# Save the complete model
saving.save_model(model, 'my_model.keras')

# Load the model
loaded_model = saving.load_model('my_model.keras')

# Save only weights
saving.save_weights(model, 'my_weights.weights.h5')

# Load weights into existing model
new_model = keras.Sequential([
    keras.layers.Dense(64, activation='relu', input_shape=(784,)),
    keras.layers.Dense(10, activation='softmax')
])
saving.load_weights(new_model, 'my_weights.weights.h5')

Custom Objects

import keras
from keras import saving

@saving.register_keras_serializable()
def custom_activation(x):
    return keras.ops.tanh(x) * 0.5

# Use custom activation in model
model = keras.Sequential([
    keras.layers.Dense(64, activation=custom_activation),
    keras.layers.Dense(10, activation='softmax')
])

# Save model with custom objects
saving.save_model(model, 'model_with_custom.keras')

# Load with custom object scope
with saving.CustomObjectScope({'custom_activation': custom_activation}):
    loaded_model = saving.load_model('model_with_custom.keras')

# Or register globally
custom_objects = saving.get_custom_objects()
custom_objects['my_custom_activation'] = custom_activation

Serialization Utilities

import keras
from keras import saving

# Serialize a layer
layer = keras.layers.Dense(64, activation='relu')
config = saving.serialize_keras_object(layer)

# Deserialize the layer
new_layer = saving.deserialize_keras_object(config)

# File inspection
editor = saving.KerasFileEditor('my_model.keras')
info = editor.inspect()
print(info)
editor.close()

File Formats

Keras supports multiple saving formats:

  • .keras: Native Keras format (recommended)
  • .h5: HDF5 format for compatibility
  • .pb: TensorFlow SavedModel format

The native .keras format is recommended for new projects as it provides the most comprehensive support for all Keras features.

Install with Tessl CLI

npx tessl i tessl/pypi-keras

docs

activations.md

applications.md

data-utils.md

index.md

initializers.md

layers.md

models.md

operations.md

random.md

regularizers.md

saving.md

training.md

tile.json