# Further Training for Number Recognition ## Scope This guide is only about the number-recognition pipeline in this repository. It does not cover face recognition, face detection, identity matching, or the separate FaceAI system. The application uses two Darknet networks: 1. `models/detection.cfg` and `models/detection.weights` find a number/text region in the full image. This is a one-class detector. 2. `models/recognition.cfg` and `models/recognition.weights` find individual digit boxes inside that region. The ten classes are `0` through `9`, and the application orders detections by horizontal position to build the number. The recognizer is a legacy Darknet YOLO `region` network with a 140x120 input, five anchors, ten classes, and 75 output filters (`5 * (4 + 1 + 10)`). The region detector is separate: it uses a 416x416 input and one class. The .NET engine loads both `.cfg` and `.weights` files directly through OpenCvSharp; it does not currently have a training command or training-data pipeline. ## Modernize the Format or the Model There are two different kinds of modernization. They have different costs and should be evaluated separately. ### Convert the Existing Model for Inference The current weights may be exportable to ONNX, a portable model format that can be consumed by runtimes such as ONNX Runtime or OpenCV DNN. This changes how the existing model is deployed; it does not change what it learned. Conversion by itself will not add font or background coverage, and it is not guaranteed to make inference faster. The recognizer uses Darknet's legacy `[region]` output. Confirm that the chosen export/conversion path supports this exact network and preserves its outputs. The current application interprets YOLO-style boxes, combines objectness and class scores, applies NMS, and maps class IDs to digits. A converted model may need a different output decoder, even if its predictions are equivalent. Keep the original `.cfg` and `.weights` as the reference and rollback option. ### Replace the Architecture A newer detector can still predict one box per digit, preserving the current left-to-right assembly contract, or a sequence-recognition model can predict a whole number directly. These are model changes, not file conversions. Existing weights generally cannot be loaded as weights for a different architecture; plan to train the replacement from a compatible pretrained checkpoint or from scratch using the annotated data described above. Replacing the architecture also requires updating the .NET inference path: input preprocessing, model loading, output decoding, confidence handling, and possibly the class/sequence decoding logic. A whole-number sequence model has a different output contract from ten separate digit classes and cannot be plugged into `RecognizeDigits` without changing that code. Keep the region detector and recognizer as separate decisions unless evidence supports replacing both. ### Measure Before Choosing Neither ONNX conversion nor a newer architecture guarantees better speed. The digit recognizer processes small 140x120 crops, so the full-image detector, image loading, number-crop count, CPU/GPU choice, and runtime overhead can be significant parts of total latency. Compare candidates on the actual deployment hardware and the same held-out images. Record warm and cold-start time, median and tail end-to-end latency, throughput for the expected workload, and recognition metrics by font and background. Compare CPU and GPU separately if both are supported; GPU is not automatically faster for small or single-crop workloads. A low-risk modernization experiment is: 1. Freeze a representative test set and record the current model's accuracy and end-to-end timing. 2. Try converting only the digit recognizer first, leaving the region detector and application behavior unchanged. Keep the converted files and any new decoder isolated from the production model. 3. Compare per-crop predictions and full-image number results, then benchmark end-to-end latency on the target hardware. Treat output mismatches as a compatibility issue to investigate, not as an acceptable conversion detail. 4. If conversion does not meet the speed or portability goal, or accuracy is the priority, evaluate a newly trained architecture on the same data and test set. Include the engineering and retraining cost in the comparison. 5. Promote a candidate only if it meets pre-agreed accuracy and performance requirements, and retain the original model for rollback. ## Decide Which Network Needs Training First inspect actual inference inputs and outputs. Enable crop saving with `ModelConfiguration.EnableCropSaving` and collect representative images from the conditions that are failing. The saved crops show what the digit recognizer actually receives. - If a crop contains the complete number but digits are missed or confused, improve the digit recognizer dataset and fine-tune `recognition.weights`. - If the region detector misses the number or returns a crop that cuts digits off, improve the full-image detector dataset and train `detection.weights`. - If both happen, evaluate and train the networks separately, then validate the combined pipeline. Do not assume that changing only the recognizer fixes bad crops. Different fonts primarily affect the digit recognizer. New backgrounds can affect both networks: full-image backgrounds affect region detection, while backgrounds visible inside the cropped number affect digit recognition. ## Build the Digit Dataset Create a versioned dataset of number-region crops that resemble the crops passed to `RecognizeDigits`. Include real examples from every supported font, print style, size, color, background, camera, and capture condition. Include examples that currently work as well as the new difficult cases, so fine-tuning does not erase existing capabilities. For every crop, draw one tight bounding box around each visible digit and assign its class ID. Use the standard Darknet YOLO label format, one line per digit: ```text class_id center_x center_y width height ``` The four box values are normalized to the image dimensions and range from 0 to 1. Keep the class mapping fixed and identical everywhere: ```text 0 -> 0 1 -> 1 2 -> 2 3 -> 3 4 -> 4 5 -> 5 6 -> 6 7 -> 7 8 -> 8 9 -> 9 ``` Use a matching image and label filename, for example `crop-001.jpg` and `crop-001.txt`. Include negative crops with no digits if the selected Darknet training setup supports empty annotations. These teach the detector not to invent numbers from background texture, logos, or nearby text. Do not label letters or punctuation as digits; the current output contract only represents the ten digit classes. Split data into training, validation, and a held-out test set by original photograph, event, location, or capture session, not by randomly splitting near-duplicate crops. Keep the test set untouched during training. Balance the digits and report results separately by font and background so a strong overall score cannot hide one failing group. Synthetic examples can add font and background coverage. Render digits using the target fonts and plausible sizes, colors, spacing, perspective, blur, lighting, compression, and noise, and generate matching boxes automatically. Keep synthetic examples visually close to real captures and retain real images in validation and test sets. Avoid transformations that do not occur in the application, such as arbitrary rotations if numbers are expected to be read left-to-right. ## Fine-Tune the Digit Recognizer 1. Record a baseline by running the current model on the fixed test set. Keep both per-crop digit predictions and end-to-end number strings. 2. Verify that the existing recognition weights load with the exact `recognition.cfg`. Their training origin and provenance are not documented here, so confirm compatibility and baseline quality before using them as a starting checkpoint. Preserve the original files unchanged. 3. Pin a Darknet source revision/build that can train this legacy `[region]` architecture. Do not assume a current Darknet build or a YOLOv3/YOLOv4 training recipe is compatible. 4. Create a separate training config and Darknet data files for the digit dataset. The names file must list `0` through `9` in that exact order. Set the training and validation image lists and a dedicated checkpoint/backup directory. 5. Preserve the recognizer architecture and inference contract: ten classes, five anchors, 140x120 input, and 75 filters before the `[region]` layer. Choose batch size, subdivisions, learning schedule, and training duration for the available hardware and dataset; do not blindly reuse the config's existing schedule. Keep checkpoints and logs separate from `models/` while training. 6. Fine-tune from the verified existing recognition weights when compatible. Monitor validation results and retain the best checkpoint, not merely the last one. If anchors are recalculated, update the matching config and preserve the required output shape. 7. Evaluate the candidate on the untouched test set and compare it with the baseline. Inspect confusing pairs such as `0`/`O`-like glyphs, `1`/`7`, and `3`/`8`, plus missed and duplicate digit boxes. The application preprocesses recognizer inputs at 140x120, scales pixel values by 1/255, and swaps red/blue channels before inference. Training crops and evaluation should use the same aspect-ratio behavior and color-channel convention. At inference, the engine combines objectness and class probability, applies its confidence and NMS thresholds, and concatenates digit classes from left to right. Training metrics alone do not verify this complete behavior. ## Train the Number-Region Detector Only When Needed The region detector needs a different dataset: full input images with a box around each complete number/text region, using the single `number-region` class. Its labels must not be per-digit labels. Keep the detector's one-class architecture consistent: its YOLO heads use one class and 18 filters (`3 * (4 + 1 + 1)`). Use the same held-out full images to measure whether the complete region is found and contains every digit. Train and evaluate this model independently from the digit recognizer. A background change can require detector retraining even when the cropped digits are already recognized correctly. ## Validate and Integrate a Candidate Evaluate both individual digit crops and full images. Record at least: - Per-digit precision, recall, and class confusion. - Exact whole-number accuracy and character error rate. - Region-detection recall and the rate of incomplete or incorrect crops. - False positive numbers on images/crops with no target number. - Results grouped by font, background, image quality, and capture source. Choose acceptance thresholds before training. Compare old and new weights on the same test set, including examples from previously supported conditions. Check the .NET end-to-end path on representative files with CPU inference; also check GPU inference if it is a deployment mode. Tune confidence/NMS settings only after checking the model, and record any threshold changes separately. For promotion, package the candidate `.weights` with its exact matching `.cfg` and keep the original pair available for rollback. Point only the relevant `ModelConfiguration` paths at the candidate pair. Keep the digit class order identical to `NumberClasses`; no label or application-code change should be needed when the ten digit classes and network output shape remain unchanged. Load the pair with `NumberRecognitionEngine` and verify the actual full-image pipeline before replacing any deployed model. Keep a training record with the dataset version and split lists, annotation rules, augmentation settings, Darknet revision/build, exact training command, starting checkpoint, config, logs, selected checkpoint, evaluation report, and hashes of the promoted files. Store candidate files separately until they pass the acceptance checks. ## Current Repository Gap The repository currently contains the inference configs and weights, but no annotated training dataset, dataset manifests, Darknet training environment, or repeatable training/evaluation scripts. The existing `scripts/py_diag.py` is a diagnostic helper, not a trainer. The steps above define the required workflow; making it repeatable will require adding a versioned dataset specification and training/evaluation tooling. Do not replace the checked-in weights until that workflow and its test-set comparison are in place.