Measuring Learnable Structure in Data for Machine Learning
📄 Original paper: From Entropy to Epiplexity: Rethinking Information for Computationally Bounded Intelligence — Marc Finzi, Shikai Qiu, Yiding Jiang, Pavel Izmailov, J. Zico Kolter, and Andrew Gordon Wilson.
Epiplexity is a Python package for measuring the learnable structure in data, distinguishing it from unlearnable noise. Unlike traditional metrics like entropy or perplexity that measure total uncertainty, epiplexity focuses on the information that can actually be learned by computational models.
Epiplexity is a recently proposed metric that addresses limitations in classical information theory when applied to real-world machine learning:
- Entropy/Perplexity: Measures total uncertainty, including random noise
- Epiplexity: Measures learnable structure that a model can actually extract
Comparisons highlighted in the paper:
- Shannon entropy: Quantifies total uncertainty without regard to computational learnability
- Kolmogorov–Smirnov information function (KS statistic): Compares empirical distributions via cumulative differences, but does not isolate learnable structure for bounded models
This distinction is crucial for:
- Data quality assessment
- Model evaluation and comparison
- Understanding learning dynamics
- Detecting overfitting vs. genuine learning
- Geoscience ML applications and beyond
- 🎯 Framework-agnostic core: Works with any ML framework
- 🔧 Ready-to-use wrappers for scikit-learn, TensorFlow/Keras, and PyTorch
- 📊 Prequential evaluation: Predictive sequential coding for online learning
- 🔄 Requential coding: Retrospective sequential coding for teacher-student learning
- 🎓 Knowledge distillation support: Track teacher-student knowledge transfer
- 🧮 Information-theoretic foundations: Based on MDL and compression principles
- 🌍 Designed for scientific ML: Ideal for geoscience, physics, and complex domain applications
pip install epiplexity# For scikit-learn models
pip install epiplexity[sklearn]
# For TensorFlow/Keras models
pip install epiplexity[tensorflow]
# For PyTorch models
pip install epiplexity[pytorch]
# Install all frameworks
pip install epiplexity[all]git clone https://github.com/RichardScottOZ/Epiplexity.git
cd Epiplexity
pip install -e .[dev]from epiplexity import EpiplexityMeter
import numpy as np
# Create meter
meter = EpiplexityMeter()
# During training/evaluation
for X_batch, y_batch in dataloader:
predictions = model.predict(X_batch)
loss = compute_loss(predictions, y_batch)
meter.update(predictions, y_batch, loss)
# Get metrics
summary = meter.summary()
print(f"Epiplexity: {summary.epiplexity:.4f}")
print(f"Perplexity: {summary.perplexity:.2f}")
print(f"Learning efficiency: {summary.learning_efficiency:.2%}")from sklearn.ensemble import RandomForestClassifier
from epiplexity import EpiplexityMeter
from epiplexity.wrappers import SklearnWrapper
# Create meter and wrap your model
meter = EpiplexityMeter()
rf = RandomForestClassifier(n_estimators=100)
model = SklearnWrapper(rf, meter=meter)
# Use like any scikit-learn model
model.fit(X_train, y_train)
accuracy = model.score(X_test, y_test)
# Get epiplexity metrics
summary = model.get_epiplexity_summary()
print(f"Learnable structure captured: {summary.learning_efficiency:.2%}")from tensorflow import keras
from epiplexity.wrappers import TensorFlowWrapper
# Create model
model = keras.Sequential([
keras.layers.Dense(128, activation='relu'),
keras.layers.Dense(10, activation='softmax')
])
# Wrap with epiplexity tracking
wrapper = TensorFlowWrapper(model)
wrapper.compile(optimizer='adam', loss='sparse_categorical_crossentropy')
# Train with automatic tracking
history = wrapper.fit(X_train, y_train, epochs=10, validation_split=0.2)
# Get metrics
summary = wrapper.get_epiplexity_summary()
print(f"Epiplexity: {summary.epiplexity:.4f}")import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from epiplexity.wrappers import PyTorchWrapper
# Create model
model = nn.Sequential(
nn.Linear(784, 128),
nn.ReLU(),
nn.Linear(128, 10)
)
# Wrap with epiplexity tracking
wrapper = PyTorchWrapper(model)
# Train with high-level interface
optimizer = torch.optim.Adam(model.parameters())
loss_fn = nn.CrossEntropyLoss()
history = wrapper.fit(
train_loader,
optimizer,
loss_fn,
epochs=10,
val_loader=val_loader
)
# Get metrics
summary = wrapper.get_epiplexity_summary()
print(f"Epiplexity: {summary.epiplexity:.4f}")
print(f"Learning efficiency: {summary.learning_efficiency:.2%}")The EpiplexitySummary object contains:
epiplexity: Remaining learnable structure in the data (lower = better learning)perplexity: Model's prediction uncertainty (traditional metric)entropy: Shannon entropy of predictionslearning_efficiency: Ratio of learned to total learnable structure (0-1)avg_loss: Average loss per sampletotal_samples: Number of samples processed
- High epiplexity (relative to baseline): Model hasn't learned much structure yet
- Low epiplexity: Model has captured most learnable patterns
- High perplexity, low epiplexity: Data contains mostly noise
- High learning efficiency (>0.7): Model effectively learning from data
- Low learning efficiency (<0.3): Model struggling to learn, or data is noisy
Measure how much learnable structure exists in your dataset before training:
from epiplexity.utils import compute_epiplexity
baseline_loss = 2.5 # Loss with random model
current_loss = 2.3 # Loss with simple model
epiplexity = compute_epiplexity(current_loss, baseline_loss, n_samples)
if epiplexity > baseline_loss * 0.8:
print("Data has high learnable structure - suitable for complex models")
else:
print("Limited learnable structure - simpler models may be better")Compare different model architectures based on learning efficiency:
models = {'simple': model1, 'complex': model2}
results = {}
for name, model in models.items():
wrapper = PyTorchWrapper(model, meter=EpiplexityMeter())
wrapper.fit(train_loader, optimizer, loss_fn, epochs=5)
summary = wrapper.get_epiplexity_summary()
results[name] = summary.learning_efficiency
# Choose model with best learning efficiency
best_model = max(results, key=results.get)Monitor epiplexity to detect when model learns patterns vs. memorizes noise:
# Train with validation tracking
for epoch in range(epochs):
train_loss = train_epoch(...)
val_loss = validate(...)
train_summary = train_meter.summary()
val_summary = val_meter.summary()
# If validation epiplexity increases while training decreases
if (train_summary.epiplexity < val_summary.epiplexity * 0.7):
print("Possible overfitting detected!")Epiplexity is particularly useful for geoscience applications where:
- Data contains inherent noise (measurement errors, natural variability)
- Signal-to-noise ratio varies across datasets
- You need to distinguish learnable geological patterns from random variation
# Example: Mineral exploration data
from epiplexity import EpiplexityMeter
from sklearn.ensemble import GradientBoostingClassifier
meter = EpiplexityMeter()
model = SklearnWrapper(GradientBoostingClassifier(), meter=meter)
# Train on geochemical data
model.fit(geochemical_features, mineral_presence)
summary = meter.summary()
if summary.learning_efficiency > 0.6:
print("Strong geological signal detected - predictions likely reliable")
else:
print("Weak signal - need more data or better features")The package includes several comprehensive examples demonstrating different use cases:
-
basic_example.py- Core functionality without ML frameworks- Framework-agnostic usage
- Simulated learning scenario
- Basic metrics interpretation
-
sklearn_example.py- Scikit-learn integration- Classification and regression examples
- Model comparison
- Wrapper usage patterns
-
tensorflow_example.py- TensorFlow/Keras integration- Classification with Sequential API
- Regression models
- Functional API models
- Custom callbacks
-
pytorch_example.py- PyTorch integration- Classification and regression
- Custom training loops
- High-level fit interface
-
prequential_example.py- Prequential (predictive sequential) evaluation- True prequential evaluation
- Comparison with batch evaluation
- Combining with epiplexity metrics
-
requential_example.py- Requential (retrospective sequential) coding- Teacher-student KL divergence tracking
- Comparison with prequential coding
- Imperfect teacher scenarios
- Based on arxiv:2601.03220
-
distillation_example.py- Knowledge distillation- Teacher model training
- Student model distillation
- Distillation quality metrics
- Model compression analysis
Run any example:
python examples/tensorflow_example.py
python examples/requential_example.py
python examples/distillation_example.pyMain class for tracking epiplexity metrics.
Parameters:
window_size(int): Number of recent samples for estimation (default: 1000)baseline_entropy(float, optional): Baseline entropy for comparison
Methods:
update(predictions, targets, loss): Update meter with new predictionssummary(): Get current metrics asEpiplexitySummaryreset(): Reset meter and return final summarystate_dict(): Get state for checkpointingload_state_dict(state): Load state from checkpoint
Container for epiplexity metrics.
Attributes:
epiplexity: Remaining learnable structureperplexity: Model uncertaintyentropy: Shannon entropylearning_efficiency: Learning effectiveness (0-1)avg_loss: Average loss per sampletotal_samples: Total samples processed
Wraps scikit-learn models with epiplexity tracking.
Wraps Keras models with epiplexity tracking.
Wraps PyTorch models with epiplexity tracking.
compute_entropy(predictions): Compute Shannon entropycompute_shannon_entropy(predictions): Explicit Shannon entropy helpercompute_ks_statistic(sample_a, sample_b): Kolmogorov-Smirnov statisticcompute_perplexity(loss): Convert loss to perplexitycompute_epiplexity(current_loss, baseline_loss, ...): Compute epiplexitycompute_learning_efficiency(...): Compute learning efficiency metric
Prequential evaluation tests predictions before updating the model, simulating true online/streaming scenarios. This is more realistic than batch evaluation as it respects temporal ordering.
from epiplexity.utils import PrequentialEvaluator
# Create evaluator
evaluator = PrequentialEvaluator(window_size=100, base="2")
# Online learning loop
for x, y in data_stream:
# 1. Predict before seeing label
pred = model.predict(x)
# 2. Evaluate prediction (prequential)
loss = evaluator.update(pred, y)
# 3. Now update model with true label
model.learn(x, y)
# Get prequential statistics
stats = evaluator.get_stats()
print(f"Prequential loss: {stats['prequential_loss']:.4f}")
print(f"Code length: {stats['code_length']:.2f} bits")Key benefits:
- Respects temporal order of data
- Tests true online learning capability
- More realistic for streaming scenarios
- Provides code length metrics for compression analysis
Example: See examples/prequential_example.py for detailed demonstrations.
Requential coding measures the cumulative KL divergence between a student model and a teacher model as the student learns sequentially. This quantifies how much information the student absorbs from the teacher's knowledge.
from epiplexity.utils import RequentialEvaluator
# Create evaluator
evaluator = RequentialEvaluator(window_size=100, base="2")
# Teacher-student learning loop
for x in data_stream:
# 1. Get teacher's knowledge
teacher_pred = teacher_model.predict(x)
# 2. Student predicts (before learning)
student_pred = student_model.predict(x)
# 3. Measure KL gap (requential coding)
kl = evaluator.update(student_pred, teacher_pred)
# 4. Student learns from teacher
student_model.learn(x, teacher_pred)
# Get requential statistics
stats = evaluator.get_stats()
print(f"Average KL: {stats['requential_kl']:.4f}")
print(f"Code length: {stats['code_length']:.2f} bits")
print(f"Information gap: {stats['information_gap']:.4f} bits/sample")Key benefits:
- Quantifies knowledge transfer quality
- Measures teacher-student information gap
- Useful for distillation evaluation
- Assesses synthetic data generation quality
Key difference from prequential:
- Prequential: Measures predictive performance (student vs true labels)
- Requential: Measures knowledge gap (student vs teacher distribution)
Example: See examples/requential_example.py for complete demonstrations.
Theory: Based on the epiplexity paper (arxiv:2601.03220), requential coding provides an explicit measure of learnable information transfer in teacher-student setups.
Track how well a student model learns from a teacher model using distillation metrics:
from epiplexity.distillation import DistillationMeter
# Create distillation meter
distill_meter = DistillationMeter(alpha=0.7, temperature=3.0)
# Training loop
for batch in dataloader:
student_preds = student_model(batch)
teacher_preds = teacher_model(batch)
# Track distillation quality
distill_meter.update(
student_predictions=student_preds,
teacher_predictions=teacher_preds,
true_labels=batch.labels,
loss=combined_loss
)
# Get distillation metrics
summary = distill_meter.summary()
print(f"Distillation efficiency: {summary.distillation_efficiency:.2%}")
print(f"Teacher epiplexity: {summary.teacher_epiplexity:.4f}")
print(f"Label epiplexity: {summary.label_epiplexity:.4f}")Key metrics:
- Distillation efficiency: How well student learns from teacher vs. labels
- Teacher epiplexity: Remaining structure in teacher's knowledge
- Label epiplexity: Remaining structure in true labels
- Teacher-student agreement: How well student mimics teacher
Example: See examples/distillation_example.py for a complete PyTorch distillation pipeline.
Use the built-in distillation loss function:
from epiplexity.distillation import compute_distillation_loss
combined_loss, distill_loss, hard_loss = compute_distillation_loss(
student_logits=student_output,
teacher_logits=teacher_output,
true_labels=labels,
alpha=0.7, # Weight for distillation vs hard loss
temperature=3.0 # Softening temperature
)Epiplexity is based on recent research that extends information theory to account for computational constraints:
- Classical entropy assumes infinite computation and memory
- Epiplexity considers what's actually learnable by bounded agents (real ML models)
- Based on MDL (Minimum Description Length) and sequential coding principles
- Separates learnable structure from unlearnable randomness
Sequential Coding Approaches:
This package implements two complementary sequential coding methods described in the epiplexity paper:
-
Prequential Coding (Predictive Sequential):
- Tests each prediction before updating the model
- Measures cumulative prediction loss over time
- Evaluates true online learning capability
- Code length = cumulative cross-entropy loss
-
Requential Coding (Retrospective Sequential):
- Measures KL divergence between student and teacher models
- Quantifies information transfer in teacher-student learning
- Evaluates knowledge distillation quality
- Code length = cumulative KL(teacher || student)
Knowledge Distillation: The distillation utilities use epiplexity metrics to quantify how much learnable structure transfers from teacher to student models, combining both prequential (task performance) and requential (teacher mimicry) perspectives.
Theoretical Foundation: This implementation draws from "From Entropy to Epiplexity: Rethinking Information for Computationally Bounded Intelligence" (arxiv:2601.03220), focusing on practical estimation of learnable structure in real-world datasets.
Contributions are welcome! Areas for contribution:
- Additional framework wrappers
- Improved epiplexity estimation algorithms
- Domain-specific applications
- Documentation and examples
- Bug fixes and performance improvements
MIT License - see LICENSE file for details.
If you use Epiplexity in your research, please cite:
@software{epiplexity2026,
title={Epiplexity: Measuring Learnable Structure in Data},
author={Scott, Richard},
year={2026},
url={https://github.com/RichardScottOZ/Epiplexity}
}Inspired by recent advances in information theory for machine learning and the need for better metrics in scientific ML applications, particularly in geoscience domains.