A lightweight library to help with training neural networks in PyTorch.
—
Core base classes and exception types used throughout PyTorch Ignite. These provide fundamental functionality and error handling for the library's components.
Foundation classes that provide common functionality across Ignite components.
class Serializable:
"""
Mixin class for objects that can be serialized and deserialized.
Provides state_dict() and load_state_dict() methods for saving and loading
object state, following PyTorch conventions.
"""
def state_dict(self):
"""
Get object state dictionary for serialization.
Returns:
dict: State dictionary containing object state
"""
def load_state_dict(self, state_dict):
"""
Load object state from state dictionary.
Parameters:
- state_dict: dictionary containing object state
"""Custom exception types for specific error conditions in PyTorch Ignite.
class NotComputableError(RuntimeError):
"""
Raised when a metric cannot be computed due to insufficient data or invalid state.
This exception is typically raised by metrics when:
- No data has been accumulated yet
- Invalid data types or shapes are encountered
- Mathematical operations cannot be completed (e.g., division by zero)
"""
passfrom ignite.base import Serializable
class CustomHandler(Serializable):
def __init__(self, param1, param2):
self.param1 = param1
self.param2 = param2
self.internal_state = 0
def state_dict(self):
return {
'param1': self.param1,
'param2': self.param2,
'internal_state': self.internal_state
}
def load_state_dict(self, state_dict):
self.param1 = state_dict['param1']
self.param2 = state_dict['param2']
self.internal_state = state_dict['internal_state']
# Save handler state
handler = CustomHandler("value1", 42)
state = handler.state_dict()
# Load handler state
new_handler = CustomHandler("", 0)
new_handler.load_state_dict(state)from ignite.metrics import Accuracy
from ignite.exceptions import NotComputableError
# Create metric
accuracy = Accuracy()
try:
# Try to compute without any data
result = accuracy.compute()
except NotComputableError:
print("Cannot compute accuracy - no data accumulated yet")
# Add some data first
accuracy.update((torch.tensor([1, 0]), torch.tensor([1, 1])))
result = accuracy.compute() # Now it works
print(f"Accuracy: {result}")class SerializableStateDict:
"""Type hint for serializable state dictionaries."""
passInstall with Tessl CLI
npx tessl i tessl/pypi-pytorch-ignite