# Methods

## Objective and outputs

The project estimates malignancy and delineates the index lesion in selected breast ultrasound images. Classification and segmentation are independent supervised tasks, with separate model weights. Localization is a bounding box derived from the largest predicted mask component.

## Data boundaries

BUS-BRA uses `Case` as the patient group, `ID` as the image identifier and `Pathology` as the binary diagnosis. All images from a group remain in one partition. BrEaST uses `Classification` and the index-tumor annotation; additional lesions are metadata, not automatically labeled malignant or included in the index target. Four normal images are described individually outside the binary lesion metrics.

Preparation verifies image/mask geometry and source counts. Auditing uses grayscale pixel SHA-256 plus pHash candidates at Hamming distance ≤4. Confirmed duplicates connect groups before splitting; pending reviews block splitting. The pinned data have no exact duplicate groups or perceptual candidates at this threshold. This is not proof that every related acquisition has been found.

The diagnosis-stratified BUS-BRA split uses seed 2026, intended fractions 70/15/15 and a second holdout seed 2027. It contains 744/160/160 cases and 1,307/286/282 images. Training weights are `1 / number_of_images_in_case`. BrEaST is excluded from fitting, selection, thresholds and calibration. The released cohorts have been inspected during project development; their held-out scores are descriptive evidence, not a blinded prospective test.

## Preprocessing

Complete images are converted to grayscale, repeated into RGB and normalized with ImageNet means `(0.485, 0.456, 0.406)` and standard deviations `(0.229, 0.224, 0.225)`. Letterbox resizing uses bilinear interpolation for images and nearest-neighbor for target masks. Padding does not enter segmentation loss. Model input is image-only: masks, case names, BI-RADS, device and diagnostic metadata are not predictor channels. No reference-derived crop is used.

Training augmentation uses horizontal flip probability 0.5, rotation ±7°, translation up to 4% of the square, scale 0.9–1.1 and independent brightness/contrast multipliers 0.9–1.1. Image and mask/valid-region affine geometry are coordinated. Validation and inference do not augment. The affine transformation does not deliberately crop around an annotated lesion.

## Networks and finite configuration search

The classifier is TorchVision ResNet18 with ImageNet `IMAGENET1K_V1` initialization, global average pooling and one linear logit. The segmenter is a ResNet18 or ResNet34 encoder with a U-Net-style decoder. Five decoder blocks use channels 128, 64, 32, 16 and 16, nearest-neighbor upsampling and two convolution/batch-normalization/ReLU layers. Four blocks concatenate encoder features at matching scales. Nearest-neighbor upsampling supports the requested deterministic CUDA backward path. One final convolution produces the mask logit.

| Candidate | Task | Encoder | Square input | Batch |
| --- | --- | --- | ---: | ---: |
| `classification_224` | classification | ResNet18 | 224 | 16 |
| `classification_384` | classification | ResNet18 | 384 | 8 |
| `segmentation_224` | segmentation | ResNet18 | 224 | 16 |
| `segmentation_384` | segmentation | ResNet18 | 384 | 8 |
| `segmentation_resnet34_384` | segmentation | ResNet34 | 384 | 8 |

Each candidate trains with seed 17. Classification maximizes validation **AP per case**, averaging image probabilities before scoring. Segmentation maximizes validation **native-resolution Dice per case**, after unpadding and restoration of float32 probabilities. Checkpoint ties retain the earliest epoch. Configuration ties prefer lower resolution, then the smaller encoder, then lexical candidate name. Scores, epochs, configurations and checkpoint checksums are saved in `selection.json` before held-out inference. Batch size changes with resolution, so this is a comparison of complete configurations, not a controlled causal estimate of resolution alone.

Both selected configurations also train with seeds 29 and 43. The seed-17 search fit is reused, giving five candidate fits plus four repeats: nine neural fits. All three selected-model seeds enter the results. Seed 17 is the default for inspection, irrespective of test performance. Validation is reused for checkpoint and configuration selection, so its scores are optimistic development estimates.

## Optimization and loss

AdamW uses encoder learning rate `1e-4`, head/decoder rate `1e-3`, weight decay `1e-4`, and default betas `(0.9, 0.999)`. Cosine annealing decays each rate to zero over 50 epochs. Maximum training is 50 epochs, with early stopping after 10 epochs without primary validation-metric improvement. Training uses CUDA automatic mixed precision; loss reductions use float32, and validation/evaluation use float32.

Classification loss is binary cross-entropy with logits. Segmentation loss is `0.5 × BCE + 0.5 × DiceLoss`. BCE averages valid pixels; soft Dice is computed separately for each image, excluding padding, with smoothing `1e-6`. Batch loss is the case-weighted image mean normalized by the sum of weights in the batch. Recorded epoch losses use a global weighted mean across all batches. Primary validation scores give each case equal weight.

`best.pt` is the selected checkpoint. `last.pt` stores model, optimizer, scheduler, AMP scaler, Python/NumPy/PyTorch/CUDA RNGs, loader generators, early-stop state and configuration. Resume requires the same configuration and manifest/split checksums. Deterministic algorithms are requested; exact numerical identity across different hardware/library versions is not assumed.

## Baselines

The prevalence control is the training-case malignant fraction. The spatial control averages resized training masks with inverse image-per-case weights and uses threshold 0.5 after restoration to the image grid. Both use 224-pixel preparation. They measure what can be obtained without image-dependent inference.

The frozen baseline extracts ResNet18 ImageNet features at 224 pixels. `StandardScaler` and logistic regression fit training images with case weights normalized to mean one. Regularization candidates are `C = 0.01, 0.1, 1, 10`; validation case AP selects the highest score, with smaller C preferred in ties. The logistic baseline has one execution and no neural training-seed interval.

## Evaluation and calibration

Classification uses the arithmetic mean of original image probabilities per case. Metrics are AP, AUROC, sensitivity, specificity, precision, F1, balanced accuracy, MCC, Brier score and confusion matrix. The validation Youden J threshold maximizes sensitivity + specificity − 1; ties prefer greater sensitivity and then lower threshold. Test decisions and threshold-0.5 results are both saved. AP concerns malignancy and must be interpreted with prevalence.

Temperature scaling fits negative log likelihood on validation logits of the **case-mean probability**. It is a secondary analysis; primary ranking metrics and Brier scores retain original probabilities. The corresponding calibrated threshold is the transformed validation threshold, rather than a new test-fitted cutoff.

Segmentation restores float32 probability maps to native dimensions with bilinear interpolation, then thresholds at 0.5. No component removal or test-dependent area filter is applied. Dice and IoU are computed per image, averaged within each case and then across cases. Reported medians and tenth percentiles concern case means. An empty prediction on a nonempty lesion scores zero. Empty references have no Dice/IoU; normal-image predicted area is reported separately.

Boxes use the largest predicted 8-connected component and the bounding extent of the complete index-lesion reference. Coordinates are `[x1, y1, x2, y2]` with exclusive maxima. Reported success averages image-level box IoU ≥0.5 indicators within a case, then across cases. It is conditional localization, without a detection AP or FROC claim.

## Uncertainty and errors

Intervals use 2,000 percentile bootstrap replicates, seed 2026, resampling cases rather than images or pixels. Classification resampling is stratified by diagnosis and conditions on observed prevalence; segmentation uses ordinary case bootstrap. Paired comparisons resample the same cases for both models and every fixed seed, then average seed-specific differences. Training seeds are neither resampled nor treated as additional patients. Training-seed standard deviation is separate from patient sampling intervals. Intervals exclude model/threshold selection, split and annotation uncertainty; baseline comparisons are exploratory without multiplicity adjustment.

Error selection is deterministic: up to three false-negative and three false-positive cases ordered by case-probability severity and patient ID, represented by their most erroneous image; segmentation shows six lowest image-Dice predictions with image-ID tie-breaks. Stratified summaries include diagnosis, device, relative lesion size and additional annotations. Small subgroups and one-class ranking metrics are kept descriptive or undefined. Neither overlays nor subgroup averages establish causal explanations.

## Evidence and implementation choices

ImageNet initialization and residual networks follow He et al.; spatial decoding and skip connections follow U-Net. Dataset units and annotation semantics follow the original dataset descriptors. Case-level reporting, calibration and task-appropriate metrics follow CLAIM 2024 and Metrics Reloaded principles. The split seed/fractions, decoder widths, candidate sizes, optimizer settings, augmentation ranges, metric selection rules and default inspection seed are this project's engineering choices, not literature-established clinical recommendations. Sources are in [RESEARCH.md](references.md).
