本文へスキップ
SDK Version: 2.5.0

Evaluator

The Evaluator in DX-ModelZoo is an abstract class that encapsulates model evaluation logic. It performs inference through a session and computes metrics.

Module: dx_modelzoo.evaluator

EvaluatorBase​

The abstract base class that all evaluators inherit from.

Constructor​

class EvaluatorBase(ABC):
def __init__(
self,
session: SessionBase,
dataset: DatasetBase,
workers: int = 12,
batch_size: int = 1,
)
ParameterTypeDescription
sessionSessionBaseInference session
datasetDatasetBaseEvaluation dataset
workersintNumber of DataLoader workers (default: 12)
batch_sizeintBatch size (default: 1)

Properties and Configuration Methods​

@property
def postprocessing(self) -> Callable
"""Currently configured postprocessing pipeline"""

def set_preprocessing(self, preprocessing) -> None
"""Set the preprocessing pipeline on the dataset"""

def set_postprocessing(self, postprocessing) -> None
"""Set the postprocessing pipeline"""

def make_loader(self) -> DataLoader
"""Create a DataLoader instance"""

Context properties (set externally):

PropertyTypeDescription
model_namestrModel name
dataset_namestrDataset name
profile_namestrProfile name

Running Evaluation​

def eval(self) -> dict

Runs evaluation and returns the results. Automatically selects Sync or Async mode based on whether the session supports asynchronous execution.

results = evaluator.eval()
# {
# "model": "resnet50_224x224",
# "metrics": [{"name": "Top-1", "metric_value": 69.76}, ...],
# "fps": 624.7,
# "elapsed_time": 82
# }

Abstract Methods (Must Be Implemented by Subclasses)​

Concrete evaluator subclasses must implement the following 5 methods:

init_metrics​

@abstractmethod
def init_metrics(self) -> Any

Initializes the metrics state. Called once before the evaluation loop begins.

# Example: Classification
def init_metrics(self):
return {"correct_top1": 0, "correct_top5": 0, "total": 0}

extract_inputs​

@abstractmethod
def extract_inputs(self, batch_data: Any) -> Any

Extracts model inputs from batch data. Converts the batch returned by the DataLoader into the format expected by the session.

# Example: Extract only images from an (images, labels) batch
def extract_inputs(self, batch_data):
images, labels = batch_data
return images

process_batch_result​

@abstractmethod
def process_batch_result(
self,
batch_data: Any,
output: Any,
metrics_state: Any,
) -> Any

Processes the result of a single batch and updates the metrics state.

output is already postprocessed

EvaluatorBase calls postprocess_output() before process_batch_result() and passes the result in as output. Calling self.postprocessing(output) again applies the pipeline twice, which corrupts metrics for non-idempotent steps (or raises on an unexpected input shape).

The per-batch order is: extract_inputs → run_inference → postprocess_output → process_batch_result.

# Example: Update Top-1/Top-5 accuracy
def process_batch_result(self, batch_data, output, metrics_state):
images, labels = batch_data
predictions = output # already postprocessed

for pred, label in zip(predictions, labels):
if pred["top1"] == label:
metrics_state["correct_top1"] += 1
if label in pred["top5"]:
metrics_state["correct_top5"] += 1
metrics_state["total"] += 1

return metrics_state

compute_final_metrics​

@abstractmethod
def compute_final_metrics(self, metrics_state: Any) -> dict

Computes the final metrics. Called once after the evaluation loop completes.

# Example
def compute_final_metrics(self, metrics_state):
total = metrics_state["total"]
return {
"metrics": [
{"name": "Top-1", "metric_value": metrics_state["correct_top1"] / total * 100},
{"name": "Top-5", "metric_value": metrics_state["correct_top5"] / total * 100},
]
}

format_progress_desc​

@abstractmethod
def format_progress_desc(self, metrics_state: Any, current_fps: float) -> str

Generates the string to display in the progress bar.

# Example
def format_progress_desc(self, metrics_state, current_fps):
total = metrics_state["total"] or 1
acc = metrics_state["correct_top1"] / total * 100
return f"Top-1: {acc:.2f}% | {current_fps:.1f} fps"

Sync / Async Mode​

The Evaluator automatically selects the mode based on the session type:

def _eval_sync(self):
metrics = self.init_metrics()
for batch in dataloader:
inputs = self.extract_inputs(batch)
output = self.session.run(inputs) # Synchronous inference
metrics = self.process_batch_result(batch, output, metrics)
return self.compute_final_metrics(metrics)
  • Requirement: OnnxRuntimeSession
  • Processes batches sequentially

Built-in Evaluators​

The following evaluators are available out of the box:

Registry NameTaskKey Metrics
image_classificationClassificationTop-1, Top-5
anomaly_detectionAnomaly DetectionAUROC, F1
object_detectionObject DetectionmAP
3d_object_detection3D Object Detection3D AP
oriented_object_detectionOriented Object DetectionmAP
instance_segmentationInstance SegmentationmAP
zero_shot_instance_segmentationZero-shot Instance SegmentationmAP
face_detectionFace DetectionAP / FROC
face_landmarkFace LandmarkNME
face_recognitionFace RecognitionAccuracy
face_attributeFace AttributeAccuracy
hand_detectionHand DetectionAP
hand_landmarkHand LandmarkNME
depth_estimationDepth Estimationδ<1.25, RMSE
image_denoisingImage DenoisingPSNR
low_light_enhancementLow-light EnhancementPSNR, SSIM
pose_estimationPose EstimationAP, AR
pose_estimation_topdownTop-down Pose EstimationAP, AR
person_attributePerson AttributemA
person_segmentationPerson SegmentationmIoU
person_reidPerson Re-identificationRank-1, mAP
semantic_segmentationSemantic SegmentationmIoU
panoptic_driving_perceptionPanoptic Driving PerceptionDetection + segmentation metrics
visual_place_recognitionVisual Place RecognitionRetrieval metrics
image_retrievalImage RetrievalTop-1, Top-5 retrieval accuracy
image_mattingImage MattingSAD, MSE
keypoint_detectionKeypoint DetectionMatching / repeatability metrics
mainbody_detectionMainbody DetectionAP
super_resolutionSuper ResolutionPSNR
zero_shot_image_classificationZero-shot Image ClassificationTop-1
object_pose_estimationObject Pose EstimationADD / ADD-S / PnP metrics

Design Principles​

The Evaluator architecture follows a strict separation of concerns:

LayerResponsibilityExample
Postprocessing (custom_ops.py)Convert raw model output → standardized formatDecode heatmap → keypoints
EvaluatorConsume standardized data → compute metricsKeypoints → COCO AP

Rules:

  • Evaluators must not contain model-specific decoding logic.
  • Model-specific transforms belong in custom_ops.py (registered with POSTPROCESSING_REGISTRY).
  • Common operations (NMS, TopK) remain in the shared postprocessing/ module.

Standardized Data Formats​

TaskPostprocessor Output
Feature Extraction(keypoints [N,2], descriptors [N,D])
Pose Estimation (Top-Down)(keypoints [17,2], scores [17])
Text DetectionList[np.ndarray] — polygons [4,2]
Text Recognitionstr — decoded text
Face Detection (BlazeFace)np.ndarray [N, 5] (x1, y1, x2, y2, score)
Instance Segmentationnp.ndarray [N, H, W] binary masks
Anomaly Detectionfloat — anomaly score

Writing a Custom Evaluator​

Register a custom evaluator with EVALUATOR_REGISTRY as follows:

from dx_modelzoo.evaluator import EVALUATOR_REGISTRY, EvaluatorBase

@EVALUATOR_REGISTRY.register("my_evaluator")
class MyEvaluator(EvaluatorBase):
def init_metrics(self):
return {"total_error": 0.0, "count": 0}

def extract_inputs(self, batch_data):
inputs, targets = batch_data
return inputs

def process_batch_result(self, batch_data, output, metrics_state):
_, targets = batch_data
predictions = output # already postprocessed by the base evaluator
error = np.mean(np.abs(predictions - targets))
metrics_state["total_error"] += error
metrics_state["count"] += 1
return metrics_state

def compute_final_metrics(self, metrics_state):
mae = metrics_state["total_error"] / metrics_state["count"]
return {"metrics": [{"name": "MAE", "metric_value": mae}]}

def format_progress_desc(self, metrics_state, current_fps):
count = metrics_state["count"] or 1
mae = metrics_state["total_error"] / count
return f"MAE: {mae:.4f} | {current_fps:.1f} fps"
evaluator:
type: my_evaluator
Keep Evaluators Pure

If your evaluator needs to decode model-specific output formats, put that logic in a custom_ops.py file in the model directory instead. The evaluator should only consume the decoded result and compute metrics.