Keras API Reference 📖
Complete API reference for MLPotion's Keras components.
Auto-Generated Documentation
This page is automatically populated with API documentation from the source code.
Extensibility
These components are built using protocol-based design, making MLPotion easy to extend. Want to add new data sources, training methods, or integrations? See Contributing Guide.
Data Loading
mlpotion.frameworks.keras.data.loaders
Keras data loaders.
Classes
CSVDataLoader
dataclass
Bases: DataLoader[CSVSequence]
Loader for CSV files into a Keras-ready Sequence.
This class provides a high-level interface for loading data from CSV files into a
CSVSequence compatible with Keras models. It handles file globbing, reading,
column selection, and label separation.
Attributes:
| Name | Type | Description |
|---|---|---|
file_pattern |
str
|
Glob pattern matching the CSV files to load (e.g., "data/*.csv"). |
batch_size |
int
|
Number of samples per batch in the resulting sequence. |
column_names |
list[str] | None
|
List of column names to use as features. If None, all columns except the label are used. |
label_name |
str | None
|
Name of the column to use as labels. If None, no labels are returned (inference mode). |
shuffle |
bool
|
Whether to shuffle the data between epochs. |
dtype |
np.dtype | str
|
Data type to use for the loaded data (default: "float32"). |
Example
import keras
from mlpotion.frameworks.keras.data.loaders import CSVDataLoader
# Define a simple model
model = keras.Sequential([
keras.layers.Dense(10, input_shape=(5,), activation='relu'),
keras.layers.Dense(1, activation='sigmoid')
])
model.compile(optimizer='adam', loss='binary_crossentropy')
# Create loader
loader = CSVDataLoader(
file_pattern="data/train_*.csv",
label_name="target_class",
batch_size=64,
shuffle=True
)
# Load data
train_sequence = loader.load()
# Train model
model.fit(train_sequence, epochs=10)
Functions
load
load() -> CSVSequence
Load CSV files and return a CSVSequence.
Returns:
| Type | Description |
|---|---|
CSVSequence
|
CSVSequence that can be passed directly to |
Raises:
| Type | Description |
|---|---|
DataLoadingError
|
If files cannot be found or read. |
Source code in mlpotion/frameworks/keras/data/loaders.py
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 | |
CSVSequence
CSVSequence(
features: np.ndarray,
labels: np.ndarray | None,
batch_size: int = 32,
shuffle: bool = True,
dtype: np.dtype | str = "float32",
) -> None
Bases: Sequence
Keras Sequence for CSV data backed by NumPy arrays.
This class implements the keras.utils.Sequence interface, allowing it to be used directly
with model.fit(), model.evaluate(), and model.predict(). It handles data batching
and shuffling efficiently in memory.
Attributes:
| Name | Type | Description |
|---|---|---|
features |
np.ndarray
|
The feature data as a 2D NumPy array. |
labels |
np.ndarray | None
|
The label data as a NumPy array, or None if not available. |
batch_size |
int
|
The size of each data batch. |
shuffle |
bool
|
Whether to shuffle the data at the end of each epoch. |
dtype |
np.dtype | str
|
The data type of the features and labels. |
Example
from mlpotion.frameworks.keras.data.loaders import CSVSequence
import numpy as np
# Create dummy data
X = np.random.rand(100, 10)
y = np.random.randint(0, 2, 100)
# Create sequence
sequence = CSVSequence(
features=X,
labels=y,
batch_size=32,
shuffle=True
)
# Use in training
model.fit(sequence, epochs=5)
Source code in mlpotion/frameworks/keras/data/loaders.py
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 | |
Functions
__getitem__
__getitem__(idx: int) -> Any
Get batch by index.
Returns:
| Type | Description |
|---|---|
Any
|
|
Any
|
|
Source code in mlpotion/frameworks/keras/data/loaders.py
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 | |
__len__
__len__() -> int
Number of batches per epoch.
Source code in mlpotion/frameworks/keras/data/loaders.py
89 90 91 92 | |
on_epoch_end
on_epoch_end() -> None
Shuffle indices between epochs if enabled.
Source code in mlpotion/frameworks/keras/data/loaders.py
115 116 117 118 | |
Training
mlpotion.frameworks.keras.training.trainers
Classes
ModelTrainer
dataclass
Bases: ModelTrainerProtocol[Model, Sequence]
Generic trainer for Keras 3 models.
This class implements the ModelTrainerProtocol for Keras models, providing a standardized
interface for training. It wraps the standard model.fit() method but adds flexibility
and consistency checks.
It supports:
- Automatic model compilation if compile_params are provided.
- Handling of various data formats (tuples, dicts, generators).
- Standardized return format (dictionary of history metrics).
Example
import keras
import numpy as np
from mlpotion.frameworks.keras import ModelTrainer
# Prepare data
X_train = np.random.rand(100, 10)
y_train = np.random.randint(0, 2, 100)
# Define model
model = keras.Sequential([
keras.layers.Dense(1, activation='sigmoid')
])
# Initialize trainer
trainer = ModelTrainer()
# Train
history = trainer.train(
model=model,
data=(X_train, y_train),
compile_params={
"optimizer": "adam",
"loss": "binary_crossentropy",
"metrics": ["accuracy"]
},
fit_params={
"epochs": 5,
"batch_size": 32,
"verbose": 1
}
)
print(history['loss'])
Functions
train
train(
model: Model,
dataset: Any,
config: ModelTrainingConfig,
validation_dataset: Any | None = None,
) -> TrainingResult[Model]
Train a Keras model using the provided dataset and configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model |
Model
|
The Keras model to train. |
required |
dataset |
Any
|
The training data. Can be a tuple |
required |
config |
ModelTrainingConfig
|
Configuration object containing training parameters. |
required |
validation_dataset |
Any | None
|
Optional validation data. |
None
|
Returns:
| Type | Description |
|---|---|
TrainingResult[Model]
|
TrainingResult[Model]: An object containing the trained model, training history, and metrics. |
Source code in mlpotion/frameworks/keras/training/trainers.py
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 | |
Evaluation
mlpotion.frameworks.keras.evaluation.evaluators
Classes
ModelEvaluator
dataclass
Bases: ModelEvaluatorProtocol[Model, Sequence]
Generic evaluator for Keras 3 models.
This class implements the ModelEvaluatorProtocol for Keras models. It wraps the
model.evaluate() method to provide a consistent evaluation interface.
It ensures that the evaluation result is always returned as a dictionary of metric names to values, regardless of how the model was compiled or what arguments were passed.
Example
import keras
import numpy as np
from mlpotion.frameworks.keras import ModelEvaluator
# Prepare data
X_test = np.random.rand(20, 10)
y_test = np.random.randint(0, 2, 20)
# Define model
model = keras.Sequential([
keras.layers.Dense(1, activation='sigmoid')
])
# Initialize evaluator
evaluator = ModelEvaluator()
# Evaluate
metrics = evaluator.evaluate(
model=model,
data=(X_test, y_test),
compile_params={
"optimizer": "adam",
"loss": "binary_crossentropy",
"metrics": ["accuracy"]
},
eval_params={"batch_size": 32}
)
print(metrics) # {'loss': 0.693..., 'accuracy': 0.5...}
Functions
evaluate
evaluate(
model: Model,
dataset: Any,
config: ModelEvaluationConfig,
) -> EvaluationResult
Evaluate a Keras model on the given data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model |
Model
|
The Keras model to evaluate. |
required |
dataset |
Any
|
The evaluation data. Can be a tuple |
required |
config |
ModelEvaluationConfig
|
Configuration object containing evaluation parameters. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
EvaluationResult |
EvaluationResult
|
An object containing the evaluation metrics. |
Source code in mlpotion/frameworks/keras/evaluation/evaluators.py
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 | |
Persistence
mlpotion.frameworks.keras.deployment.persistence
Classes
ModelPersistence
ModelPersistence(
path: str | Path, model: Model | None = None
) -> None
Bases: ModelPersistenceProtocol[Model]
Persistence helper for Keras models.
This class manages saving and loading of Keras models. It supports standard Keras
formats (.keras, .h5) and SavedModel directories. It also integrates with
ModelInspector to provide model metadata upon loading.
Attributes:
| Name | Type | Description |
|---|---|---|
path |
Path
|
The file path for the model artifact. |
model |
Model | None
|
The Keras model instance (optional). |
Example
import keras
from mlpotion.frameworks.keras import ModelPersistence
# Define model
model = keras.Sequential([keras.layers.Dense(1)])
# Save
saver = ModelPersistence(path="models/my_model.keras", model=model)
saver.save()
# Load
loader = ModelPersistence(path="models/my_model.keras")
loaded_model, metadata = loader.load(inspect=True)
print(metadata['parameters'])
Source code in mlpotion/frameworks/keras/deployment/persistence.py
44 45 46 | |
Attributes
model
property
writable
model: Model | None
Currently attached Keras model (may be None before loading).
path
property
writable
path: Path
Filesystem path where the model is saved/loaded.
Functions
load
load(
*, inspect: bool = True, **kwargs: Any
) -> tuple[Model, dict[str, Any] | None]
Load a Keras model from disk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inspect |
bool
|
Whether to inspect the loaded model and return metadata. |
True
|
**kwargs |
Any
|
Additional arguments passed to |
{}
|
Returns:
| Type | Description |
|---|---|
Model
|
tuple[Model, dict[str, Any] | None]: A tuple containing the loaded model and |
dict[str, Any] | None
|
optional inspection metadata. |
Raises:
| Type | Description |
|---|---|
ModelPersistenceError
|
If the model file cannot be found or loaded. |
Source code in mlpotion/frameworks/keras/deployment/persistence.py
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 | |
save
save(overwrite: bool = True, **kwargs: Any) -> None
Save the attached model to disk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
overwrite |
bool
|
Whether to overwrite the file if it already exists. |
True
|
**kwargs |
Any
|
Additional arguments passed to |
{}
|
Raises:
| Type | Description |
|---|---|
ModelPersistenceError
|
If no model is attached or if the file exists and |
Source code in mlpotion/frameworks/keras/deployment/persistence.py
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 | |
Export
mlpotion.frameworks.keras.deployment.exporters
Classes
ModelExporter
Bases: ModelExporterProtocol[Model]
Generic exporter for Keras 3 models.
This class implements ModelExporterProtocol and supports exporting Keras models
to various formats, including native Keras formats (.keras, .h5) and inference
formats like TensorFlow SavedModel or ONNX (via model.export).
It also supports creating export archives with custom endpoints using keras.export.ExportArchive.
Example
import keras
from mlpotion.frameworks.keras import ModelExporter
model = keras.Sequential([keras.layers.Dense(1)])
exporter = ModelExporter()
# Export as standard Keras file
exporter.export(model, "models/model.keras")
# Export for serving (TF SavedModel)
exporter.export(model, "models/serving", export_format="tf_saved_model")
Functions
export
export(model: Model, path: str, **kwargs: Any) -> None
Export a Keras model to disk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model |
Model
|
The Keras model to export. |
required |
path |
str
|
The destination path or directory. |
required |
**kwargs |
Any
|
Additional export options:
- |
{}
|
Raises:
| Type | Description |
|---|---|
ModelExporterError
|
If export fails. |
Source code in mlpotion/frameworks/keras/deployment/exporters.py
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 | |
Model Inspection
mlpotion.frameworks.keras.models.inspection
Classes
ModelInspector
dataclass
Bases: ModelInspectorProtocol[ModelLike]
Inspector for Keras models.
This class analyzes Keras models to extract metadata such as input/output shapes, parameter counts, layer details, and signatures. It is useful for validating models before training or deployment, and for generating model reports.
Attributes:
| Name | Type | Description |
|---|---|---|
include_layers |
bool
|
Whether to include detailed information about each layer. |
include_signatures |
bool
|
Whether to include model signatures (if available). |
Example
import keras
from mlpotion.frameworks.keras import ModelInspector
model = keras.Sequential([keras.layers.Dense(1, input_shape=(10,))])
inspector = ModelInspector()
info = inspector.inspect(model)
print(f"Total params: {info['parameters']['total']}")
print(f"Inputs: {info['inputs']}")
Functions
inspect
inspect(model: ModelLike) -> dict[str, Any]
Inspect a Keras model and return structured metadata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model |
ModelLike
|
The Keras model to inspect. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: A dictionary containing model metadata:
- |
Source code in mlpotion/frameworks/keras/models/inspection.py
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 | |
See the Keras Guide for usage examples