
A patient being investigated for suspected endometriosis arrives with a pelvic MRI scan. Another patient has a transvaginal ultrasound video instead. A research team wants both collections to improve its classifier, but there is no matching scan and video for each person. A study by Yuan Zhang and colleagues asks whether training can benefit from both imaging methods while testing needs only the examination already available.
Learning from two examinations without requiring both
The attraction of multimodal medical AI is easy to understand. Different examinations reveal different aspects of the same clinical problem. The practical difficulty is that a dataset may contain many examples of each examination without containing paired examples from the same patients. An architecture designed around complete pairs can become unusable precisely where imaging access is uneven.
Zhang and colleagues address this situation in their paper on unpaired multimodal training and single modality testing, published in Computerized Medical Imaging and Graphics, volume 124, article 102575. The work became available online on 29 May 2025. Its collaborators include researchers and clinicians associated with the University of Adelaide, the University of Surrey, MBZUAI, and other institutions listed in the paper.
The research question is narrower than whether combining two scans is always better. The model learns from separate MRI and ultrasound collections, then receives one modality for a test case. Its job is to transfer useful information through training without demanding an extra examination at inference. This makes it relevant to the Medical AI collection and to research on systems that must work with incomplete inputs.
The most useful reading of this paper separates three contributions. Pretraining supplies an MRI representation that a small labeled dataset could not easily teach from scratch. Localization removes irrelevant image content. Fusion supplies information from another modality through label matched training. Their combined result matters, but their individual roles matter just as much when deciding what to reproduce.
The clinical target needs a precise name
The Pouch of Douglas, often shortened to POD, is the space between the uterus and rectum. The study focuses on obliteration of that space. In its ultrasound data, the relevant signal is the sliding sign, a dynamic assessment of movement between pelvic structures. This is a specific imaging task rather than a comprehensive inventory of every possible endometriosis lesion.
That distinction protects readers from an easy misunderstanding. A classifier trained for POD obliteration is not automatically a general endometriosis screening test. A negative output for this target cannot, by itself, establish that endometriosis is absent elsewhere. Nor does the paper establish a treatment decision rule based on its output.
Label direction is particularly important for anyone implementing the method. Positive POD obliteration corresponds to a negative sliding sign in the paper’s setup. A positive sliding sign instead corresponds to the opposite class. A programmer who pairs raw positive labels across modalities without checking their clinical meanings could join examples with opposing targets.
The study builds on Maicas and colleagues’ 2021 paper, Deep learning to diagnose pouch of Douglas obliteration with ultrasound sliding sign, published in Reproduction and Fertility, and Zhang and colleagues’ 2023 work on distilling ultrasound knowledge into MRI. Both appear in the supplied paper’s references. The new contribution combines automatic localization with a model that can accept either modality, rather than requiring separate modality specific classifiers selected by hand.
Unpaired does not mean unlabeled or unrelated
The training examples do not need to come from the same person, but they do need a shared clinical label. An MRI volume labeled for POD obliteration is paired with an ultrasound video whose sliding sign annotation represents that same state. The partner video is selected randomly from the appropriate class. This is supervised matching at the class level, not anatomical registration between examinations.
That choice creates opportunities and limits. Repeated pairings can expose an MRI example to different ultrasound examples from its class, encouraging the classifier to use information associated with the shared target. It cannot teach exact correspondence between one patient’s anatomy in MRI and that patient’s anatomy in ultrasound, because such correspondence is not present in the training pairs.
Class agreement also does not make the populations interchangeable. Referral patterns, acquisition procedures, disease severity, and annotation processes could differ across the two collections. These are potential sources of dataset bias to investigate, not measured explanations for the reported gains. The paper does not provide an external evaluation that resolves them.
For a faithful experiment, patient splitting must happen before random pairing. Both members of every training pair must belong to their respective training partitions. Otherwise, a method can appear to transfer useful knowledge when it has actually reused held out information. This is an implementation requirement for a sound follow up study, not an allegation that the published evaluation did so.
A related design question appears in our article on fusion with incomplete clinical data. The shared issue is what the model can reasonably learn when some inputs are unavailable. The datasets, targets, and evaluation designs are different, so their scores should not be compared as if they measure the same task.
Three stages before the final prediction
Give MRI a useful starting representation
The MRI branch begins with a three dimensional masked autoencoder. Each volume is divided into cubes of 8 × 8 × 8 voxels. A random fraction of cubes is hidden, and the network learns to reconstruct their contents from the visible cubes. The method follows the masked autoencoder approach cited to He and colleagues, with the three dimensional adaptation connected to Butler and colleagues’ earlier endometriosis work.
The encoder contains 12 transformer blocks and produces embeddings of dimension 768. An eight block transformer decoder supports reconstruction. The study tests several masking fractions, with 0.7 producing its strongest reported MRI AUC among the tested settings. That finding applies to this experiment and should not be interpreted as a universal optimum for medical MRI.
The pretraining collection contains 8984 pelvic T2 MRI scans from females aged 18 to 45. The scans come from a hospital database with varied acquisition locations and protocols. They provide unlabeled visual material for learning representations. They are not 8984 independently labeled endometriosis cases, and their size should not be used to inflate the apparent size of the supervised diagnostic evaluation.
Find the relevant region automatically
The classification target occupies a relatively small part of a whole pelvic scan. The authors therefore train a uterus segmentation model and use its predicted mask to select a surrounding region for classification. The purpose is not to claim that the uterus alone contains every useful sign. The crop includes padding intended to retain the neighboring region relevant to POD assessment.
The localization model combines a classification objective with voxel level binary cross entropy for segmentation. Manual uterus masks are needed during training. At test time, the predicted mask replaces manual localization. This is a reduction in manual intervention at inference, not an annotation free training method.
Crop geometry deserves more attention than it often receives. The authors describe padding based on distances relevant to the posterior uterus, POD boundary, cervix, and rectum. A generic crop that tightly hugs the uterus could remove neighboring information needed by the classifier. A generic crop that is too large could dilute the benefit of localization. Exact reproduction needs the anatomical padding specification, not just the words automatic crop.
Prepare the ultrasound branch and then combine features
The TVUS branch uses a ResNet architecture with factorized spatial and temporal convolutions, written as ResNet(2+1)D. It is first pretrained on Kinetics-400 and then trained on sliding sign videos. Its representation has dimension 512. A linear projection maps the MRI representation from 768 to 512 before the two branches enter fusion.
During fusion training, the ultrasound classifier is frozen. This design tries to preserve a strong existing TVUS representation while MRI learning benefits from the combined training arrangement. A frozen encoder does not guarantee unchanged final TVUS performance, however. The final output depends on the fusion weights and classifier as well as the encoder, and those parts can still change.
The paper reports 195 epochs for MRI pretraining, 200 for segmentation, and 90 for multimodal training. MRI pretraining required 98 hours on three RTX 3090 GPUs. Fusion training used an RTX A6000. These are useful reminders that simple deployment inputs do not imply a small training effort or make the full experiment directly comparable to a short notebook demonstration.
What the uncertainty module actually computes
Each branch feeds a Random Network Prediction module. One network has fixed random weights. Another network learns to predict its outputs from the branch embedding. Their squared prediction discrepancy becomes an uncertainty score. The underlying cross modal random network prediction approach is attributed to Wang and colleagues’ ECCV 2022 paper in the source references.
The intuition is that familiar embeddings are easier for the predictor to approximate, while unfamiliar embeddings may produce larger discrepancy. A blank input representing a missing modality is expected to be less familiar. This is a representation based signal, not a calibrated probability that a diagnosis is wrong. The distinction matters because a normalized number can look more clinically interpretable than the experiment establishes.
Let e denote a modality embedding, f the fixed random network, and g the learned predictor. The following equations follow the paper’s scalar uncertainty construction, with M for MRI and U for ultrasound.
The two values sum to one when the denominator is positive. They express relative discrepancy between the branches. If both branches are unfamiliar to a similar degree, their normalized values can still look balanced. The normalization alone therefore does not indicate that either input is trustworthy in an absolute sense.
The fusion equation is easy to misread. The MRI embedding is amplified using ultrasound uncertainty, and the ultrasound embedding is amplified using MRI uncertainty. A residual term keeps each original embedding present.
Under this equation, each scaling factor lies between one and two. The mechanism amplifies one branch relative to the other. It does not multiply an unreliable branch by zero. If a blank input produces a nonzero embedding through network biases or normalization, that embedding can still reach the final concatenation. The downstream classifier must learn how to handle it.
This is an interpretation of the written equation, not an additional experimental finding. It suggests useful future comparisons with explicit availability masks and direct suppression of missing branches. Such alternatives would need to be evaluated fairly, with the same encoders, data splits, and training budget.
The loss functions connect the stages
The masked autoencoder minimizes reconstruction error over hidden cubes. Its objective should not be diluted with visible cubes that were already available to the encoder. In the expression below, L is the number of masked cubes and K is the number of pretraining volumes.
The ultrasound pretraining objective is ordinary classification cross entropy. The uterus localization objective combines classification cross entropy and average binary cross entropy over voxels, with the segmentation weight set to 0.2 in the reported experiment. These losses serve different purposes. Neither a low reconstruction loss nor a visually plausible uterus mask establishes diagnostic usefulness by itself.
The prediction networks are fitted to the fixed random networks with a squared discrepancy objective and a parameter penalty. Fusion is optimized with classification cross entropy after concatenating the modified embeddings. The paper describes alternating optimization of the RNP objective and the multimodal classification objective.
A numerical implementation needs a denominator safeguard when both discrepancies approach zero. That safeguard is an engineering choice rather than a new scientific contribution. It should preserve a sensible fallback, such as equal relative weights, and be documented so readers can distinguish the reported method from the details added to make a runnable implementation.
Training for an examination that may be missing
At test time, the absent modality is represented by zeros. The MRI only path sends a blank video into the ultrasound branch. The ultrasound only path sends a blank volume into the MRI branch. The model still contains both branches even though only one carries the patient’s examination.
Training includes examples in which one modality is replaced by zeros. At least one modality remains real in every pair. This condition should be implemented explicitly. Drawing independent dropout decisions without a constraint can accidentally remove both inputs, producing training examples outside the described setup.
Table 7 reports the strongest MRI setting with MRI missing rate zero and TVUS missing rate 0.2. That setting also yields TVUS AUC of 0.8921. Other absence settings shift the balance between modalities. The training recipe is therefore a tradeoff rather than evidence that one universal dropout setting simultaneously optimizes both test paths.
The prose names two parameters for absence proportions, but its example reverses their apparent modality association. A reproducible implementation should name the probabilities directly as MRI absence and TVUS absence, and use the explicit Table 7 headings to document the intended setting. Silent reliance on an ambiguous letter can change the experiment.
The results are strongest when the baselines stay visible
The main labeled MRI collection contains 127 T2 SPACE pelvic scans, including 57 with POD obliteration. The TVUS collection contains 749 short videos, including 103 cases corresponding to POD obliteration. These are separate collections. They should not be added together and described as a single paired patient cohort.
The study uses stratified cross validation with five folds and reports mean AUC and AUPRC with standard deviations across folds. AUC measures ranking performance over thresholds. It is not the proportion of patients correctly classified at a chosen threshold. AUPRC describes a different aspect of ranking and is sensitive to the class composition of the evaluated data.
| Method | MRI AUC | MRI AUPRC | TVUS AUC | TVUS AUPRC |
|---|---|---|---|---|
| Pretrained MRI transformer | 0.7252 ± 0.0684 | 0.7380 ± 0.0585 | Not applicable | Not applicable |
| Independent TVUS model | Not applicable | Not applicable | 0.9238 ± 0.0253 | 0.8788 ± 0.0347 |
| Plain concatenation | 0.7510 ± 0.0709 | 0.7505 ± 0.0495 | 0.9076 ± 0.0347 | 0.8738 ± 0.0358 |
| Knowledge distillation | 0.7541 ± 0.0751 | 0.7524 ± 0.0632 | Not applicable | Not applicable |
| GMU | 0.6889 ± 0.1210 | 0.6948 ± 0.1073 | 0.9066 ± 0.0476 | 0.8605 ± 0.0621 |
| MGCA | 0.7314 ± 0.0855 | 0.7349 ± 0.0667 | 0.8963 ± 0.0453 | 0.8699 ± 0.0539 |
| Modal mixup | 0.7492 ± 0.0738 | 0.7465 ± 0.0658 | 0.6666 ± 0.2974 | 0.6651 ± 0.1418 |
| ADAPT | 0.7457 ± 0.0607 | 0.7567 ± 0.0506 | 0.9065 ± 0.0272 | 0.8666 ± 0.0372 |
| Proposed method | 0.8023 ± 0.0505 | 0.8134 ± 0.0477 | 0.8921 ± 0.0342 | 0.8599 ± 0.0313 |
These are reported research results, not independently reproduced measurements. Standard deviations across folds are not confidence intervals.
The proposed model improves MRI AUC from the pretrained MRI baseline of 0.7252 to 0.8023. Plain concatenation achieves 0.7510. Those comparisons are more informative about the added fusion method than contrasting the final model only with a transformer trained from scratch. All of these main baseline comparisons use automatic MRI cropping, according to the experimental description.
The MRI comparison with the pretrained baseline has a reported AUC p value of 0.011 and AUPRC p value of 0.006 under the authors’ one sided paired tests. These are the reported test results, not independent reanalyses. Interpretation should account for the small number of folds, overlapping cross validation training sets, and multiple comparisons. No new confidence interval or corrected p value is inferred here.
For TVUS, the independent model achieves AUC 0.9238 and the proposed method achieves 0.8921. The two sided paired test reports p equal to 0.109. Failure to reject a difference is not an equivalence test and does not establish a clinically acceptable performance margin. The safest summary is improved MRI ranking with a numerically lower TVUS result whose difference was not statistically significant in this analysis.
Two discrepancies between the abstract and the tables
The abstract presents the MRI change from 0.4755 to 0.8023 while describing the former as not automatically focused on the uterus. Table 5 instead labels the 0.4755 baseline as a transformer with segmentation and without MAE pretraining. The truly uncropped proposed method is a different row, with AUC 0.5355.
This distinction changes the explanation of the gain. The move from 0.4755 to the final result combines changes in representation learning and fusion. The direct localization comparison is 0.5355 without segmentation based cropping versus 0.8023 with it. The article follows the detailed ablation table and calls out the inconsistency rather than silently choosing whichever story sounds more impressive.
The abstract also describes TVUS AUC 0.8921 as being maintained under either single modality or multimodal training. Tables 1 and 5 give 0.9238 for the independent TVUS baseline and 0.8921 for the proposed method. These detailed values support a qualified claim of comparable performance under the authors’ statistical test, not numerical equality.
There is a smaller reporting difference in MRI fold variability. Tables 1 and 5 report standard deviation 0.0505 for the final AUC, while Tables 6 and 7 list 0.0502 for corresponding settings. The main comparison below follows Tables 1 and 5. The discrepancy is recorded rather than repaired with an invented explanation.
Localization deserves its own error analysis
The ablation from 0.5355 without automatic cropping to 0.8023 with cropping indicates that region selection is central to this pipeline. A sophisticated fusion module cannot compensate for every irrelevant or poorly framed voxel in a whole pelvic scan. The result makes a practical case for testing the input region before adding more elaborate feature interactions.
However, the paper presents segmentation visualizations without a numerical segmentation performance table in the main article. The visual examples help explain the localization mechanism but cannot quantify how frequently crops omit useful tissue. A useful extension would connect localization error directly with classification error, rather than reporting attractive masks and diagnostic scores separately.
The crop also depends on orientation and resampling. The study reorients MRI volumes into a RAS coordinate system, resamples to 1 mm isotropic spacing, and resizes volumes to 64 × 128 × 128. A padding value in voxels means something different before and after resizing. Reproduction needs to specify the coordinate system in which the crop is created.
Our discussion of segmentation quality and downstream prediction provides a related reason to examine this connection. The relevant question here is not whether the uterus outline looks convincing. It is whether localization reliably retains the evidence required for POD classification in unseen cases.
The clinical translation gap
A cross validation result establishes behavior under a defined research protocol. It does not establish the value of introducing the classifier into a hospital workflow. The authors themselves identify external evaluation as future work. The study does not report a prospective trial showing shorter diagnostic delays, better patient outcomes, or safer treatment selection.
Before any clinical use, a development team would need to specify the intended role of the output. Supporting image review, prioritizing cases, and making a diagnosis impose different requirements. The present research does not supply a validated operating threshold, a complete assessment of calibration, or evidence that a negative output can safely end further investigation.
External validation should cover acquisition differences and the intended patient population. The MRI cohort is limited to ages 18 to 45 in the dataset description. Performance outside that population is not established here. Ultrasound also depends on how a video is acquired, so a model that performs well on a particular collection may struggle with different probe movement, image framing, or equipment.
Another unresolved issue is the reference standard. A reproduction or clinical validation effort should document how labels were assigned, which clinical information was available to annotators, and whether all patients were verified consistently. The dataset section reports the target counts, but readers should not infer a complete uniform verification pathway from those counts alone.
The reported inference time of 54.374 milliseconds and parameter count of 148.446 million describe a research implementation under its measurement conditions. They do not include proof that a complete clinical workflow, including acquisition, preprocessing, localization, review, and reporting, runs at that speed. Regulatory clearance or clinical deployment approval is not established by this study.
What researchers can test next
The first priority is a controlled sequence of comparisons. Reproduce MRI pretraining before measuring fusion. Hold localization fixed while comparing fusion modules. Use identical patient partitions for all methods, and preserve the distinction between training labels and test inputs. The paper provides useful ablations, but a follow up should also isolate implementation choices that remain underdescribed.
For uncertainty, inspect raw prediction discrepancies as well as normalized weights. Test real but corrupted images in addition to perfectly blank inputs. An unavailable modality and a low quality available modality are not the same problem. A module that recognizes zeros may still assign misleading confidence to a motion degraded or poorly acquired examination.
For missing input handling, compare residual amplification with explicit modality availability indicators under a fixed training budget. Report both MRI only and TVUS only outcomes rather than selecting whichever improves. If preserving TVUS performance is a design goal, evaluate it using an appropriate prespecified margin and study design rather than interpreting a nonsignificant difference as proof.
These are editorial research recommendations drawn from the architecture and evaluation, not experiments already performed by the authors. The distinction matters. A useful explainer should make the next test clearer without quietly converting a plausible improvement into a demonstrated capability.
Limits on data access and reproducibility
The paper’s data availability statement is explicit.
“The authors do not have permission to share data.”
Zhang and colleagues, data availability statement
That restriction prevents an independent reader from reproducing the clinical results using a publicly downloadable version of the study data. The article does not identify an official code repository that can be confidently linked here. No substitute dataset or fabricated repository address is presented as if it were the original resource.
Several architectural details also require clarification for an exact reproduction. The paper specifies the broad MRI encoder and decoder depths, the feature dimensions, training stages, and loss equations, but does not fully specify the RNP network architecture or all crop geometry. The interaction between RNP training and zero filled samples deserves clarification because predictor fitting on missing inputs could change their discrepancy over time.
The paper reports ethics approvals and discloses funding, relevant professional relationships, and a pending patent. Those disclosures belong in the reader’s assessment of the work, but they do not by themselves validate or invalidate the experiments. The substantive limitation remains that clinical generalization cannot be independently established from the reported internal folds.
What this approach contributes
The main achievement is a training strategy that can use two separately collected imaging modalities while allowing one examination at test time. It addresses a practical data problem without requiring patient matched MRI and TVUS throughout the training collection. That flexibility is useful even though the current evaluation remains limited.
The conceptual contribution is not simply concatenating two feature vectors. The pipeline combines representation pretraining, anatomically motivated localization, deliberate missing input exposure, and relative uncertainty informed feature amplification. The ablation results show why its success should be understood as a coordinated pipeline rather than attributed to one module.
The same design question appears in other medical applications where paired examinations are scarce. The idea of sharing class related information across unpaired datasets may transfer. The particular label mapping, crop, missingness rates, and performance values will not transfer automatically. Each new application needs its own clinical target and evaluation.
The remaining limits are substantial. The MRI labeled sample is small, the ultrasound performance is numerically lower after fusion, the uncertainty estimates are not established as calibrated clinical risk, and external validation is absent. The article’s strongest results are promising research evidence rather than a substitute for a deployment study.
A productive next step is to test the pipeline on genuinely independent data while making the preprocessing, crop rules, uncertainty module, and evaluation code fully inspectable. The goal should be reliable evidence for a defined clinical role. Learning from more than one modality becomes valuable when the resulting prediction remains trustworthy with the single examination a patient actually has.
Complete executable PyTorch reference
The implementation below covers masked MRI pretraining, joint localization losses, a factorized video backbone, random network prediction, class matched pairing, modality dropout, fusion training, and evaluation with either test modality. A small CPU smoke test runs every training stage and both inference paths. It also checks patch reconstruction, frozen random targets, frozen TVUS parameters and normalization statistics, and uncertainty normalization.
This is an independent research reference, not the authors’ code and not an exact reproduction of their results. The code identifies choices that the paper does not fully specify, including RNP dimensions, transformer pooling, the video stem, and demonstration crop padding. No study weights or private images are included. Tiny synthetic inputs make the smoke test practical, while the configuration exposes the larger MRI dimensions reported in the paper.
For real experiments, obtain authorized data, create patient disjoint partitions before pairing, perform the documented orientation and intensity preprocessing, and load compatible pretrained video weights. Train localization on each training fold and crop held out images using that fold’s trained localizer. The example does not manufacture clinical accuracy from random inputs or claim that its custom video implementation can load the original study’s unspecified checkpoints.
Open the full PyTorch implementation and runnable smoke test
"""Executable research reference inspired by Zhang et al. (2025).
Not official code and not a reproduction of the reported clinical scores.
Requires Python 3.10+ and PyTorch. Run this file for a tiny CPU smoke test.
Real inputs must be de-identified, patient-disjoint and preprocessed outside
this example. MRI [B,1,D,H,W], TVUS [B,1,T,H,W], masks matching MRI.
All labels use 1=POD obliteration. Invert a 1=positive sliding-sign label.
The paper's private data, pretrained weights, exact RNP architecture and
anatomical crop padding are unavailable. Explicit choices are listed below.
"""
from dataclasses import dataclass
from copy import deepcopy
import torch
from torch import nn
from torch.nn import functional as F
from torch.utils.data import Dataset, DataLoader
@dataclass
class Config:
shape: tuple = (64, 128, 128)
patch: int = 8
embed: int = 768
enc_depth: int = 12
dec_dim: int = 384 # Reference choice, not specified in paper.
dec_depth: int = 8
heads: int = 12 # Reference choice.
fusion_dim: int = 512
video_width: int = 64
rnp_hidden: int = 256 # Reference choice, not reported RNP dimensions.
rnp_out: int = 128
rnp_l2: float = 1.0 # Explicit coefficient for written Eq. (4).
mask_ratio: float = 0.7
roi_alpha: float = 0.2
drop_mri: float = 0.0
drop_tvus: float = 0.2
crop_pad: tuple = (8, 8, 8) # Demonstration only; validate anatomically.
def transformer(dim, depth, heads):
block = nn.TransformerEncoderLayer(dim, heads, 4 * dim, dropout=0.0,
activation='gelu', batch_first=True,
norm_first=True)
return nn.TransformerEncoder(block, depth, norm=nn.LayerNorm(dim),
enable_nested_tensor=False)
class MRIModel(nn.Module):
"""MAE plus joint uterus segmentation and classification heads.
Learned position tables, mean pooling and linear voxel head are reference
choices. The paper does not fully specify those implementation details.
"""
def __init__(self, cfg):
super().__init__()
self.cfg = cfg
p = cfg.patch
if any(s % p for s in cfg.shape):
raise ValueError('Each MRI dimension must be divisible by patch')
self.grid = tuple(s // p for s in cfg.shape)
self.n = self.grid[0] * self.grid[1] * self.grid[2]
self.input = nn.Linear(p ** 3, cfg.embed)
self.pos = nn.Parameter(torch.randn(1, self.n, cfg.embed) * .02)
self.encoder = transformer(cfg.embed, cfg.enc_depth, cfg.heads)
self.bridge = nn.Linear(cfg.embed, cfg.dec_dim)
self.dpos = nn.Parameter(torch.randn(1, self.n, cfg.dec_dim) * .02)
self.mask_token = nn.Parameter(torch.zeros(1, 1, cfg.dec_dim))
self.decoder = transformer(cfg.dec_dim, cfg.dec_depth, cfg.heads)
self.reconstruct = nn.Linear(cfg.dec_dim, p ** 3)
self.segment = nn.Linear(cfg.dec_dim, p ** 3)
self.classify = nn.Linear(cfg.embed, 2)
def patches(self, x):
b, c, d, h, w = x.shape
p = self.cfg.patch
if c != 1 or (d, h, w) != self.cfg.shape:
raise ValueError('Unexpected MRI shape')
return x.reshape(b, 1, d//p, p, h//p, p, w//p, p).permute(
0, 2, 4, 6, 1, 3, 5, 7).reshape(b, self.n, p**3)
def volume(self, tokens):
b = tokens.shape[0]
gd, gh, gw = self.grid
p = self.cfg.patch
return tokens.reshape(b, gd, gh, gw, 1, p, p, p).permute(
0, 4, 1, 5, 2, 6, 3, 7).reshape(b, 1, *self.cfg.shape)
def encode(self, x):
return self.encoder(self.input(self.patches(x)) + self.pos)
def features(self, x):
return self.encode(x).mean(1)
def mae_loss(self, x):
target = self.patches(x)
b = x.shape[0]
keep = max(1, min(self.n - 1, int(self.n * (1-self.cfg.mask_ratio))))
order = torch.rand(b, self.n, device=x.device).argsort(1)
ids = order[:, :keep]
all_tokens = self.input(target) + self.pos
visible = all_tokens.gather(1, ids[..., None].expand(-1, -1, self.cfg.embed))
encoded = self.encoder(visible)
decoded_input = self.mask_token.expand(b, self.n, -1).clone()
decoded_input = decoded_input.scatter(1, ids[..., None].expand(
-1, -1, self.cfg.dec_dim), self.bridge(encoded))
pred = self.reconstruct(self.decoder(decoded_input + self.dpos))
mask = torch.ones(b, self.n, device=x.device)
mask.scatter_(1, ids, 0)
return (((pred-target)**2).mean(-1) * mask).sum() / mask.sum()
def roi_outputs(self, x):
tokens = self.encode(x)
seg = self.volume(self.segment(self.decoder(self.bridge(tokens)+self.dpos)))
return self.classify(tokens.mean(1)), seg
def roi_loss(self, x, y, mask):
logits, seg = self.roi_outputs(x)
return F.cross_entropy(logits, y) + self.cfg.roi_alpha * F.binary_cross_entropy_with_logits(seg, mask)
class FactorizedConv(nn.Sequential):
"""Spatial convolution then temporal convolution, with BN and ReLU."""
def __init__(self, cin, cout, stride=1):
mid = max(1, (27 * cin * cout) // (9 * cin + 3 * cout))
super().__init__(
nn.Conv3d(cin, mid, (1,3,3), (1,stride,stride), (0,1,1), bias=False),
nn.BatchNorm3d(mid), nn.ReLU(),
nn.Conv3d(mid, cout, (3,1,1), (stride,1,1), (1,0,0), bias=False),
nn.BatchNorm3d(cout))
class VideoBlock(nn.Module):
def __init__(self, cin, cout, stride):
super().__init__()
self.a = FactorizedConv(cin, cout, stride)
self.b = FactorizedConv(cout, cout)
self.skip = nn.Identity() if cin == cout and stride == 1 else nn.Sequential(
nn.Conv3d(cin, cout, 1, stride=stride, bias=False), nn.BatchNorm3d(cout))
def forward(self, x):
return F.relu(self.b(F.relu(self.a(x))) + self.skip(x))
class VideoModel(nn.Module):
"""R(2+1)D-style 18-layer residual backbone. Custom grayscale stem.
Not checkpoint-compatible with the authors' unspecified exact model.
Load a matching video-pretrained checkpoint before real TVUS training.
"""
def __init__(self, width=64, out=512):
super().__init__()
self.stem = nn.Sequential(FactorizedConv(1, width), nn.ReLU())
layers = []
cin = width
for stage in range(4):
cout = width * (2**stage)
for block in range(2):
stride = 2 if stage > 0 and block == 0 else 1
layers.append(VideoBlock(cin, cout, stride)); cin = cout
self.blocks = nn.Sequential(*layers)
self.project = nn.Linear(cin, out)
self.head = nn.Linear(out, 2)
def features(self, x):
return self.project(self.blocks(self.stem(x)).mean((2,3,4)))
def forward(self, x):
return self.head(self.features(x))
class RNP(nn.Module):
def __init__(self, dim, hidden, out):
super().__init__()
def mlp():
return nn.Sequential(nn.Linear(dim, hidden), nn.ReLU(), nn.Linear(hidden, out))
self.target, self.predictor = mlp(), mlp()
self.target.requires_grad_(False)
def error(self, x):
# Fixed target WEIGHTS; input gradients remain available for fusion CE.
return (self.predictor(x)-self.target(x)).square().sum(-1)
class UnpairedModel(nn.Module):
def __init__(self, mri, tvus, cfg):
super().__init__()
self.mri, self.tvus, self.cfg = mri, tvus, cfg
self.tvus.requires_grad_(False)
self.mproject = nn.Linear(cfg.embed, cfg.fusion_dim)
self.rm = RNP(cfg.fusion_dim, cfg.rnp_hidden, cfg.rnp_out)
self.ru = RNP(cfg.fusion_dim, cfg.rnp_hidden, cfg.rnp_out)
self.head = nn.Linear(2*cfg.fusion_dim, 2)
def train(self, mode=True):
super().train(mode)
self.tvus.eval() # Freezing parameters alone does not freeze BN statistics.
return self
def embeddings(self, mri, tvus):
em = self.mproject(self.mri.features(mri))
with torch.no_grad():
eu = self.tvus.features(tvus)
return em, eu
def forward(self, mri, tvus):
em, eu = self.embeddings(mri, tvus)
errors = torch.stack((self.rm.error(em), self.ru.error(eu)), 1)
total = errors.sum(1, keepdim=True)
unc = torch.where(total > 1e-12, errors / total.clamp_min(1e-12),
torch.full_like(errors, .5))
# Eq. (7): residual amplification, NOT inverse-uncertainty suppression.
fused = torch.cat((em*(1+unc[:,1:2]), eu*(1+unc[:,0:1])), 1)
return self.head(fused), unc
def rnp_loss(self, mri, tvus):
with torch.no_grad():
em, eu = self.embeddings(mri, tvus)
fitting = (self.rm.error(em) + self.ru.error(eu)).mean()
l2 = sum(p.square().sum() for r in (self.rm, self.ru) for p in r.predictor.parameters())
return fitting + self.cfg.rnp_l2*l2
class SameLabelPairs(Dataset):
"""Call only AFTER splitting by patient. Inputs are prepared training tensors."""
def __init__(self, mri, ym, tvus, yu):
self.mri, self.ym, self.tvus = mri, ym.long(), tvus
if not set(ym.tolist()) <= {0,1} or not set(yu.tolist()) <= {0,1}:
raise ValueError('Expected canonical POD labels 0 or 1')
self.pool = {k: (yu == k).nonzero().flatten() for k in (0,1)}
if any(len(self.pool[int(y)]) == 0 for y in ym):
raise ValueError('No same-label TVUS partner')
def __len__(self): return len(self.mri)
def __getitem__(self, i):
y = int(self.ym[i]); pool = self.pool[y]
j = int(pool[torch.randint(len(pool), (1,))].item())
return self.mri[i], self.tvus[j], self.ym[i]
def modality_dropout(mri, tvus, pm, pu):
if min(pm,pu) < 0 or pm+pu > 1:
raise ValueError('Mutually exclusive dropout probabilities required')
r = torch.rand(len(mri), device=mri.device)
mri, tvus = mri.clone(), tvus.clone()
mri[r < pm] = 0
tvus[(r >= pm) & (r < pm+pu)] = 0
return mri, tvus
@torch.no_grad()
def crop_mri(localizer, x, pad):
"""Symmetric padding is a teaching choice, not the paper's anatomical rule.
Empty segmentation raises an error for review rather than hiding failure.
"""
localizer.eval()
_, logits = localizer.roi_outputs(x)
outputs = []
for image, mask in zip(x, logits.sigmoid() > .5):
indices = mask[0].nonzero()
if indices.numel() == 0:
raise ValueError('Empty uterus mask; manual review required')
lo, hi = indices.min(0).values, indices.max(0).values+1
slices = tuple(slice(max(0,int(lo[k])-pad[k]), min(image.shape[k+1],int(hi[k])+pad[k])) for k in range(3))
roi = image[(slice(None),)+slices][None]
outputs.append(F.interpolate(roi, size=localizer.cfg.shape, mode='trilinear', align_corners=False))
return torch.cat(outputs)
def fit_stage(model, loader, optimizer, stage, epochs, device='cpu'):
"""Run MAE, ROI, or TVUS pretraining on already separated training data."""
model.to(device).train()
for _ in range(epochs):
for batch in loader:
batch = [v.to(device) for v in batch]
if stage == 'mae': loss = model.mae_loss(batch[0])
elif stage == 'roi': loss = model.roi_loss(*batch)
elif stage == 'tvus': loss = F.cross_entropy(model(batch[0]), batch[1])
else: raise ValueError(stage)
optimizer.zero_grad(); loss.backward(); optimizer.step()
def fit_fusion(model, loader, epochs=90, device='cpu', rnp_lr=1e-3):
"""RNP LR is a reference choice. RNP fitting uses intact real pairs here.
Paper leaves RNP handling of zero-filled examples insufficiently specified.
CE sees dropout examples; CE also updates predictors, as in Eq. (8).
"""
model.to(device).train()
main = torch.optim.AdamW([p for p in model.parameters() if p.requires_grad], lr=1e-3, weight_decay=.05)
predictors = list(model.rm.predictor.parameters()) + list(model.ru.predictor.parameters())
rnp = torch.optim.SGD(predictors, lr=rnp_lr, momentum=.9)
for _ in range(epochs):
for m, u, y in loader:
m,u,y = m.to(device),u.to(device),y.to(device)
model.zero_grad(set_to_none=True)
loss_r = model.rnp_loss(m,u); loss_r.backward(); rnp.step()
model.zero_grad(set_to_none=True)
md,ud = modality_dropout(m,u,model.cfg.drop_mri,model.cfg.drop_tvus)
logits,_ = model(md,ud)
F.cross_entropy(logits,y).backward(); main.step()
@torch.no_grad()
def evaluate(model, loader, modality, absent_shape, device='cpu'):
"""Return all scores and labels for patient-level ROC/PR analysis.
Accuracy at 0.5 is descriptive only, not a clinical operating threshold.
"""
if modality not in {'mri','tvus'}: raise ValueError(modality)
model.to(device).eval(); scores=[]; labels=[]
for x,y in loader:
x = x.to(device)
absent = torch.zeros(len(x), *absent_shape, device=device, dtype=x.dtype)
logits,_ = model(x,absent) if modality=='mri' else model(absent,x)
scores.append(logits.softmax(1)[:,1].cpu()); labels.append(y.cpu())
if not scores: raise ValueError('Empty evaluation loader')
scores,labels = torch.cat(scores),torch.cat(labels)
pos,neg = scores[labels==1],scores[labels==0]
auc = None if not len(pos) or not len(neg) else float(((pos[:,None]>neg).float()+.5*(pos[:,None]==neg)).mean())
return {'scores':scores,'labels':labels,'auc':auc,
'accuracy_at_half':float(((scores>=.5)==labels.bool()).float().mean())}
def smoke_test():
torch.manual_seed(17); torch.set_num_threads(2)
cfg=Config(shape=(8,8,8),patch=4,embed=24,enc_depth=1,dec_dim=24,
dec_depth=1,heads=4,fusion_dim=16,video_width=2,rnp_hidden=8,rnp_out=4)
x=torch.randn(4,1,8,8,8); y=torch.tensor([0,1,0,1])
masks=(torch.rand_like(x)>.6).float(); u=torch.randn(4,1,8,8,8)
mri=MRIModel(cfg); video=VideoModel(cfg.video_width,cfg.fusion_dim)
assert torch.equal(mri.volume(mri.patches(x)),x)
fit_stage(mri,DataLoader(torch.utils.data.TensorDataset(x),batch_size=2),
torch.optim.AdamW(mri.parameters(),lr=1e-3),'mae',1)
localizer=deepcopy(mri)
fit_stage(localizer,DataLoader(torch.utils.data.TensorDataset(x,y,masks),batch_size=2),
torch.optim.AdamW(localizer.parameters(),lr=1e-4),'roi',1)
fit_stage(video,DataLoader(torch.utils.data.TensorDataset(u,y),batch_size=2),
torch.optim.Adam(video.parameters(),lr=1e-5),'tvus',1)
model=UnpairedModel(mri,video,cfg)
target_before=[p.clone() for p in model.rm.target.parameters()]
frozen_before={k:v.clone() for k,v in video.state_dict().items()}
pairs=SameLabelPairs(x,y,u,y)
fit_fusion(model,DataLoader(pairs,batch_size=2),epochs=1)
assert all(torch.equal(p,q) for p,q in zip(target_before,model.rm.target.parameters()))
assert all(torch.equal(v,video.state_dict()[k]) for k,v in frozen_before.items())
for modality, data in [('mri',x),('tvus',u)]:
result=evaluate(model,DataLoader(torch.utils.data.TensorDataset(data,y),batch_size=2),modality,(1,8,8,8))
assert torch.isfinite(result['scores']).all()
_,unc=model(x[:2],torch.zeros_like(u[:2]))
assert torch.allclose(unc.sum(1),torch.ones(2),atol=1e-6)
md,ud=modality_dropout(x,u,.4,.4)
assert not ((md.flatten(1).abs().sum(1)==0)&(ud.flatten(1).abs().sum(1)==0)).any()
print('Smoke tests passed: all training stages, both test modalities, frozen targets and TVUS, normalized uncertainty. No clinical result reproduced.')
if __name__=='__main__': smoke_test()
Frequently asked questions
Can this AI diagnose every type of endometriosis?
No. The study targets Pouch of Douglas obliteration, a specific sign associated with endometriosis. It does not establish a test that detects or excludes all forms of the disease.
Are MRI and ultrasound required for the same patient?
No. Training uses separate collections with class matched labels. During testing, either MRI or ultrasound is supplied and the missing input is replaced by zeros.
What MRI performance does the paper report?
The detailed main table reports MRI AUC of 0.8023 ± 0.0505, compared with 0.7252 ± 0.0684 for the pretrained MRI baseline. These are cross validation results, not clinical accuracy at a chosen threshold.
Did ultrasound performance remain unchanged?
No numerical equality was shown. TVUS AUC was 0.9238 for the independent model and 0.8921 for the proposed method. The reported difference was not statistically significant, which does not establish equivalence.
Are the study data publicly available?
No. The paper states that the authors do not have permission to share the data. This article does not provide private scans or claim access to an official public dataset.
Does the included code reproduce the clinical results?
No. It is an independent executable reference with documented implementation choices and synthetic smoke tests. Reproducing the study requires authorized data, compatible pretrained weights, and further implementation details.
Academic citation. Zhang, Y., Wang, H., Butler, D., Smart, B., Xie, Y., To, M. S., Knox, S., Condous, G., Leonardi, M., Avery, J. C., Hull, M. L., and Carneiro, G. 2025. Unpaired multimodal training and single modality testing for detecting signs of endometriosis. Computerized Medical Imaging and Graphics, 124, 102575. DOI 10.1016/j.compmedimag.2025.102575.
This analysis is based on the published paper and an independent evaluation of its claims.
Independent evaluation here means critical assessment of the text, tables, and equations. It does not mean independent clinical replication or medical review. The illustration and reference code were created for this explainer. No patient images or original paper figures are reproduced.
Prior work discussed above is drawn from the source bibliography. Maicas and colleagues, Reproduction and Fertility, 2021, volume 2, pages 236 to 243. Butler and colleagues, EMBC, 2023, pages 1 to 5. Zhang and colleagues, ISBI, 2023, pages 1 to 5. He and colleagues, CVPR, 2022, pages 16000 to 16009. Wang and colleagues, ECCV, 2022, pages 200 to 217.

glad to be one of many visitors on this awing site : D.
I know of the fact that today, more and more people are increasingly being attracted to camcorders and the field of taking pictures. However, to be a photographer, you should first devote so much period deciding the exact model of video camera to buy and moving via store to store just so you could buy the least expensive camera of the trademark you have decided to pick. But it will not end now there. You also have to think about whether you can purchase a digital digital camera extended warranty. Thanks a lot for the good guidelines I received from your site.
Your point of view caught my eye and was very interesting. Thanks. I have a question for you. https://www.binance.com/register?ref=IXBIAFVY
I don’t think the title of your article matches the content lol. Just kidding, mainly because I had some doubts after reading the article. https://www.binance.com/ES_la/register?ref=VDVEQ78S
Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me? https://www.binance.com/register?ref=JW3W4Y3A
Your point of view caught my eye and was very interesting. Thanks. I have a question for you.