How to measure dataset sufficiency for image classification

This guide provides a beginner friendly how-to guide to anayze an image classification model’s hypothetical performance.

Estimated time to complete: 10 minutes

Relevant ML stages: Model Development

Relevant personas: ML Engineer

What you’ll do

  • Evaluate an image classification model’s performance with the MNIST dataset

  • Define a custom evaluation function with metrics of interest

  • Project the model’s performance over increasing sample sizes

What you’ll learn

  • Learn to evaluate a model’s limits for different metrics with the MNIST dataset

  • Learn to determine how many samples are required to reach specific performance thresholds

Problem Statement

For machine learning tasks, often we would like to evaluate the performance of a model on a small, preliminary dataset. In situations where data collection is expensive, we would like to extrapolate hypothetical performance out to a larger dataset.

DataEval has introduced a method projecting performance via sufficiency curves.

When to use

The Sufficiency class should be used when you would like to extrapolate hypothetical performance. For example, if you have a small dataset, and would like to know if it is worthwhile to collect more data.

What you will need

  1. A particular model architecture.

  2. Metric(s) that we would like to evaluate.

  3. A dataset of interest.

  4. A Python environment with the following packages installed:

    • tabulate

Setting up

Let’s import the required libraries needed to set up a minimal working example

import os
from collections.abc import Sequence
from typing import Any, cast

import dataeval_plots as dep
import numpy as np
import plotly.io as pio
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchmetrics
from IPython.display import display  # noqa: A004
from maite_datasets.image_classification import MNIST
from numpy.typing import NDArray
from tabulate import tabulate
from torch.utils.data import DataLoader, Subset
from torch.utils.data import Dataset as TorchDataset

from dataeval import config
from dataeval.performance import Sufficiency
from dataeval.protocols import Dataset, DatumMetadata
from dataeval.selection import Limit, Select

DatumType = tuple[NDArray[np.number[Any]], NDArray[np.number[Any]], DatumMetadata]

# Set seed for reproducibility
config.set_seed(0, all_generators=True)

# Set hardware based on system
device = "cuda" if torch.cuda.is_available() else "cpu"
config.set_device(device=device)

# Additional reproducibility and printing options
np.set_printoptions(formatter={"float": lambda x: f"{x:0.4f}"})
torch.set_float32_matmul_precision("high")
torch._dynamo.config.suppress_errors = True
torch.use_deterministic_algorithms(True)
os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8"

# Use plotly to render plots
dep.set_default_backend("plotly")

# Use the notebook renderer so JS is embedded
pio.renderers.default = "notebook"

Load data and create model

Before calculating the sufficiency of a dataset, the dataset must be loaded and the model architecture defined. We will walk through these in the following steps.

Loading MNIST data

Load the MNIST data and split it into training and test datasets. For this notebook, we will use subsets of the training (2500) and test (500) data.

# Configure the dataset transforms

transforms = [
    lambda x: x / 255.0,  # scale to [0, 1]
    lambda x: x.astype(np.float32),  # convert to float32
]

# Download the mnist dataset and apply the transforms and subset the data
train_ds = Select(MNIST(root="./data", image_set="train", transforms=transforms,download=True),selections=[Limit(2500)])  # fmt: skip # noqa: E501
test_ds = Select(MNIST(root="./data", image_set="test", transforms=transforms, download=True), selections=[Limit(500)])

Creating a PyTorch model

Next, we define the network architecture that will be trained and then evaluated throughout the sufficiency calculation.

# Define our network architecture
class Net(nn.Module):
    def __init__(self):
        super().__init__()
        self.conv1 = nn.Conv2d(1, 6, 5)
        self.conv2 = nn.Conv2d(6, 16, 5)
        self.fc1 = nn.Linear(6400, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 10)

    def forward(self, x):
        x = F.relu(self.conv1(x))
        x = F.relu(self.conv2(x))
        x = torch.flatten(x, 1)  # flatten all dimensions except batch
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x


# Compile the model (cast sets the type to Net as compile returns an Unknown)
model: Net = cast(Net, torch.compile(Net().to(device)))

Strategy Protocols

Training and evaluation functions are heavily dependent on the hyperparameters defined by a user. These can include metrics, loss functions, optimizers, model architectures, input sizes, etc.

To allow the Sufficiency class to handle this situation, DataEval uses Protocols. Sufficiency requires two specific protocols called TrainingStrategy and EvaluationStrategy.
Below we will define the strategies that align with this notebook and combine them into a Sufficiency.Config that can be given to the Sufficiency class.

Training strategy

class MNISTTrainingStrategy:
    def train(self, model: nn.Module, dataset: Dataset[DatumType], indices: Sequence[int]):
        # Defined only for this testing scenario
        criterion = torch.nn.CrossEntropyLoss().to(device)
        optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.9)
        epochs = 10

        # Define the dataloader for training
        dataloader = DataLoader(Subset(cast(TorchDataset, dataset), indices), batch_size=8)

        for epoch in range(epochs):
            for batch in dataloader:
                # Load data/images to device
                X = torch.Tensor(batch[0]).to(device)
                # Load one-hot encoded targets/labels to device
                y = torch.argmax(torch.asarray(batch[1], dtype=torch.int).to(device), dim=1)
                # Zero out gradients
                optimizer.zero_grad()
                # Forward propagation
                outputs = model(X)
                # Compute loss
                loss = criterion(outputs, y)
                # Back prop
                loss.backward()
                # Update weights/parameters
                optimizer.step()

Evaluation strategy

class MNISTEvaluationStrategy:
    def evaluate(self, model: nn.Module, dataset: Dataset[DatumType]) -> dict[str, float]:
        # Metrics of interest
        metrics = {
            "Accuracy": torchmetrics.Accuracy(task="multiclass", num_classes=10).to(device),
            "AUROC": torchmetrics.AUROC(task="multiclass", num_classes=10).to(device),
            "TPR at 0.5 Fixed FPR": torchmetrics.ROC(task="multiclass", average="macro", num_classes=10).to(device),
        }
        result = {}
        # Set model layers into evaluation mode
        model.eval()
        dataloader = DataLoader(cast(TorchDataset, dataset), batch_size=8)
        # Tell PyTorch to not track gradients, greatly speeds up processing
        with torch.no_grad():
            for batch in dataloader:
                # Load data/images to device
                X = torch.Tensor(batch[0]).to(device)
                # Load one-hot encoded targets/labels to device
                y = torch.argmax(torch.asarray(batch[1], dtype=torch.int).to(device), dim=1)
                preds = model(X)
                for metric in metrics.values():
                    metric.update(preds, y)
            # Compute ROC curve
            false_positive_rate, true_positive_rate, _ = metrics["TPR at 0.5 Fixed FPR"].compute()
            # determine interval to examine
            desired_rate = 0.5
            closest_desired_index = torch.argmin(torch.abs(false_positive_rate - desired_rate)).item()
            # return corresponding tpr value
            result["TPR at 0.5 Fixed FPR"] = true_positive_rate[closest_desired_index].cpu()
            result["Accuracy"] = metrics["Accuracy"].compute().cpu()
            result["AUROC"] = metrics["AUROC"].compute().cpu()
        return result

Sufficiency config

Do not forget to initialize your strategy classes!

mnist_config = Sufficiency.Config(
    training_strategy=MNISTTrainingStrategy(),
    evaluation_strategy=MNISTEvaluationStrategy(),
    runs=5,
    substeps=10,
)

Initialize sufficiency metric

Attach the custom training and evaluation functions to the Sufficiency metric and define the number of models to train in parallel (stability), as well as the number of steps along the learning curve to evaluate.

# Instantiate sufficiency metric
suff = Sufficiency(
    model=model,
    train_ds=train_ds,
    test_ds=test_ds,
    config=mnist_config,
)

Evaluate Sufficiency

Now we can evaluate the metric to train the models and produce the learning curve.

# Train & test model
output = suff.evaluate()
/builds/jatic/aria/dataeval/.nox/docs/lib/python3.13/site-packages/torch/cuda/__init__.py:734: UserWarning:

Can't initialize NVML
/builds/jatic/aria/dataeval/.nox/docs/lib/python3.13/site-packages/torch/cuda/__init__.py:734: UserWarning: Can't initialize NVML
  warnings.warn("Can't initialize NVML")
# Print out sufficiency output in a table format
formatted = {"Steps": output.steps, **output.averaged_measures}
print(tabulate(formatted, headers=list(formatted), tablefmt="pretty"))
+-------+----------------------+---------------------+--------------------+
| Steps | TPR at 0.5 Fixed FPR |      Accuracy       |       AUROC        |
+-------+----------------------+---------------------+--------------------+
|  25   |   0.75251145362854   | 0.16440000385046005 | 0.7067711114883423 |
|  41   |  0.8947786331176758  |  0.487199991941452  | 0.8450579285621643 |
|  69   |  0.9608144164085388  | 0.6375999927520752  | 0.9154425740242005 |
|  116  |  0.9741832971572876  | 0.7051999926567077  | 0.9376469254493713 |
|  193  |  0.9896627306938172  | 0.7928000092506409  | 0.9667350649833679 |
|  322  |  0.9947847247123718  | 0.8463999986648559  | 0.9784429788589477 |
|  538  |  0.9941036224365234  |  0.878000009059906  | 0.9826449871063232 |
|  898  |  0.9990697383880616  | 0.9055999994277955  | 0.9911015510559082 |
| 1498  |         1.0          | 0.9184000015258789  | 0.9941145896911621 |
| 2500  |         1.0          | 0.9404000043869019  | 0.9958232641220093 |
+-------+----------------------+---------------------+--------------------+
# Print out projected output values
projection = output.project([1000, 2500, 5000])
projected = {"Steps": projection.steps, **projection.averaged_measures}
print(tabulate(projected, list(projected), tablefmt="pretty"))
+-------+----------------------+--------------------+--------------------+
| Steps | TPR at 0.5 Fixed FPR |      Accuracy      |       AUROC        |
+-------+----------------------+--------------------+--------------------+
| 1000  |  0.9973934522809914  | 0.9051458770087063 | 0.9893293597214722 |
| 2500  |  0.9977025834573092  | 0.9220204218466752 | 0.9914244677165256 |
| 5000  |  0.9977573633858183  | 0.9283103006028888 | 0.9920041957770291 |
+-------+----------------------+--------------------+--------------------+
for name, values in output.averaged_measures.items():
    print(abs(values[-1] - projection.averaged_measures[name][-2]))
0.0022974165426907778
0.018379582540226647
0.004398796405483685
# Plot the output using dataeval-plots library
for plot in dep.plot(output, backend="plotly"):
    display(plot)

Results

Using these learning curves, we can project performance under much larger datasets (with the same models).

Predicting sample requirements

We can also predict the amount of training samples required to achieve specific performance thresholds.

Let’s say we wanted to see how many samples are needed to hit 90%, 93%, and 99% accuracy, area under the receiver operating characteristic, and true positive rate at a fixed false positive rate of 0.5.

# Initialize the array of desired thresholds to apply to all metrics
desired_values = np.array([0.90, 0.93, 0.99])
metrics = ["Accuracy", "AUROC", "TPR at 0.5 Fixed FPR"]
evaluated_metrics = {}

for metric in metrics:
    evaluated_metrics[metric] = desired_values
# Evaluate the learning curve to infer the needed amount of training data
samples_needed = output.inv_project(evaluated_metrics)
# Print the amount of needed data needed to achieve the thresholds
for metric, samples in samples_needed.items():
    print(f"{metric}")
    for index, sample_size in enumerate(samples):
        print(
            f"To achieve {int(evaluated_metrics[metric][index] * 100)}% {metric},"
            f" {int(sample_size)} samples are needed."
        )
    print()
Accuracy
To achieve 90% Accuracy, 836 samples are needed.
To achieve 93% Accuracy, 6670 samples are needed.
To achieve 99% Accuracy, -1 samples are needed.

AUROC
To achieve 90% AUROC, 62 samples are needed.
To achieve 93% AUROC, 85 samples are needed.
To achieve 99% AUROC, 1219 samples are needed.

TPR at 0.5 Fixed FPR
To achieve 90% TPR at 0.5 Fixed FPR, 42 samples are needed.
To achieve 93% TPR at 0.5 Fixed FPR, 52 samples are needed.
To achieve 99% TPR at 0.5 Fixed FPR, 179 samples are needed.

With a value of “-1” samples, the projection shows that given the current model, hitting an accuracy of 99% is improbable.