Study design and HeartFusion framework
HeartFusion was implemented as a multimodal framework for CVD diagnosis and severity classification by integrating ECG and cardiac MRI representations. As shown in Figure 2, the workflow used Cardioformer for ECG encoding, TransUNet for MRI encoding, cosine-similarity-based cross-modal fusion, and transformer-based diagnostic and ordinal prediction heads. Wavelet-derived time-frequency information and a manifold-alignment loss were incorporated to improve robustness and preserve geometric structure. The datasets, software, and computational resources specified for reproducible implementation are listed in the Table of Materials.
Ethics and compliance
The study consisted exclusively of secondary computational analysis of de-identified data obtained from established public or controlled-access repositories. No new participants were recruited, no intervention was performed, and no directly identifiable information was collected for this study. Source datasets were accessed and used under the respective repository licenses, data-use agreements, and credentialing requirements. On this basis, the work did not involve new prospective human-subject enrollment or consent procedures; the exact institutional determination should remain consistent with the authors’ local research-governance requirements.
Data collection
To support multimodal CVD assessment, ECG data were used to represent cardiac electrical activity, and cardiac MRI data were used to represent anatomical and functional structure. Because the selected public repositories did not provide both modalities for the same patients, a multi-source alignment strategy was applied. ECG and MRI observations were matched using harmonized diagnostic categories and, for severity experiments, ordered stage information together with demographic compatibility variables. Each dataset pair was then evaluated independently as a controlled pseudo-paired multimodal cohort. Table 2 summarizes the source datasets and cohort composition. CVD-I combined PTB-XL ECG observations with ACDC cardiac MRI examinations. CVD-II combined MIMIC-IV-ECG observations with CMRxRecon MRI examinations. CVD-III combined ECG observations from PTB-XL and MIMIC-IV-ECG with MRI observations from OCMR and the Cardiac Atlas Project. These source repositories were selected because well-characterized cardiovascular signals or imaging data suitable for benchmark construction were available.
Dataset construction, label harmonization, and data partitioning
Three algorithmically constructed pseudo-paired cohorts were created because the source repositories did not contain synchronized ECG and cardiac MRI examinations from the same individuals. Diagnostic harmonization, severity assignment, demographic matching, and cross-modal pairing were performed according to a predefined protocol. CVD-I, CVD-II, and CVD-III, therefore, represented controlled phenotype-matched benchmark cohorts rather than patient-matched ECG-MRI acquisitions. Each cohort was constructed independently, and no source observation or generated pseudo-pair was shared across cohorts.
ECG records were included when a complete 12-lead configuration, at least 10 s of signal, a sampling frequency of at least 100 Hz, an interpretable diagnostic annotation, and a signal-quality index of at least 0.80 were available. Records with more than 20% corrupted signal, missing essential leads, severe baseline drift, or unmappable diagnostic labels were excluded. MRI examinations were included when a complete short-axis cine sequence, at least 20 temporal frames, at least six interpretable ventricular slices, and adequate ventricular structural information were available. Examinations with severe motion artifacts, incomplete ventricular coverage, corrupted files, missing annotations, or major reconstruction failure were excluded. After filtering, CVD-I contained 3,200 ECG observations and 800 MRI examinations; CVD-II contained 3,600 ECG observations and 900 MRI examinations; and CVD-III contained 3,400 ECG observations and 850 MRI examinations.
Diagnostic-label harmonization was performed by mapping source annotations into four cardiovascular phenotype categories: normal, ischemic myocardial injury, hypertrophic remodeling, and ventricular dysfunction. The normal category included ECG records without clinically significant electrical abnormalities and MRI examinations without important structural or functional impairment. Ischemic myocardial injury included myocardial infarction, ischemic ST-T abnormalities, and infarct-related ventricular impairment. Hypertrophic remodeling included electrocardiographic evidence of ventricular hypertrophy and MRI evidence of increased myocardial wall thickness. Ventricular dysfunction included conduction abnormalities, dilated ventricular morphology, reduced ventricular contraction, and abnormal right-ventricular structure. Ambiguous or unsupported labels were excluded, and the dominant phenotype was selected using the predefined hierarchy when multiple abnormalities were present.
Ischemic myocardial injury > Ventricular dysfunction > Hypertrophic remodeling > Normal
The same mapping procedure was applied to all three cohorts before partitioning and model training. Disease severity was represented using four ordered stages as defined in Equation (1).
(1)
In Equation (1), s denotes the ordinal severity label, with 0 representing normal cardiac status, 1 mild disease, 2 moderate disease, and 3 severe disease. For each observation, an ECG abnormality score E, an MRI structural-abnormality score M, and a cardiac functional-impairment score F were calculated on normalized 0-3 scales. E incorporated QRS prolongation, ST-T deviation, rhythm disturbance, and waveform distortion; M incorporated ventricular-wall thickness, chamber enlargement, regional wall-motion impairment, and myocardial injury; and F was derived from left-ventricular ejection fraction and ventricular-volume abnormalities. A continuous severity index was calculated according to Equation (2).
(2)
In Equation (2), R denotes the continuous severity index, and E, M, and F denote the normalized ECG, MRI structural, and functional-impairment scores, respectively; the coefficients are the predefined weighting factors. Stage 0 corresponded to ejection fraction at least 55% without important structural or electrical abnormality; stage 1 to ejection fraction 45–54% or mild remodeling/low-risk electrical abnormality; stage 2 to ejection fraction 30–44% or moderate structural/electrical abnormality; and stage 3 to ejection fraction below 30% or extensive myocardial injury, marked remodeling, or combined high-risk abnormalities.
Age and sex were used only as demographic matching variables and were not treated as diagnostic labels. Ages were restricted to 18–90 years. Category-level mean ages were set to 48 years for Normal, 62 years for Ischemic myocardial injury, 56 years for Hypertrophic remodeling, and 65 years for Ventricular dysfunction, with a standard deviation of 11 years. The overall male proportion was maintained at approximately 54%. A fixed cohort-construction seed of 2026 was used so that demographic assignments and cross-modal candidate selection could be reproduced. Cross-modal pseudo-pairs were created only between ECG and MRI observations belonging to the same harmonized diagnostic category. For severity-stage experiments, observations were additionally required to share the same ordered severity stage. The ECG-MRI compatibility score was calculated using Equation (3).
(3)
In Equation (3), y represented the diagnostic category, s represented the severity stage, a represented the age, g represented the sex, I(·) was the indicator function, and Pij was the compatibility score for ECG observation i and MRI observation j. Eligible MRI candidates were ranked by Pij; the five highest-scoring observations formed the candidate pool, and two candidates were selected without replacement for each ECG observation. This process generated 6,400 pseudo-pairs for CVD-I, 7,200 for CVD-II, and 6,800 for CVD-III. During training, one eligible MRI candidate was sampled at each epoch; validation and test pairings were generated once and remained fixed. Training, validation, and test partitioning were performed before pseudo-pair construction. The original ECG and MRI observations were split using a stratified 70:15:15 ratio, with stratification jointly preserving diagnostic category and severity stage. All segments from the same ECG record were assigned to one partition, and all slices and temporal frames from the same MRI examination were retained within one partition. Cross-modal pairing was restricted to source observations within the same partition, as specified in Equations (4)–(6).
(4)
(5)
(6)
In Equations (4)–(6), Ptrain, Pvalidation, and Ptest denoted the pseudo-pair sets; Etrain, Evalidation, and Etest denoted partition-specific ECG sets; and Mtrain, Mvalidation, and Mtest denoted partition-specific MRI sets. This constraint prevented source ECG records, MRI examinations, waveform segments, image slices, and pseudo-pairs from appearing in more than one partition. Normalization parameters, class weights, augmentation settings, and other data-dependent parameters were estimated only from the training partition and then applied to validation and test data. Five experimental runs used random seeds 11, 23, 37, 51, and 79. The same partitions and seeds were used for HeartFusion and all baselines. Model selection and early stopping were based only on validation performance, and the test partition was evaluated only after the final model configuration had been selected without using test results for model tuning.
Data preprocessing
ECG and cardiac MRI inputs were preprocessed to produce standardized, diagnostically meaningful representations. ECG preprocessing addressed baseline drift, motion artifacts, high-frequency noise, and scale variation, whereas MRI preprocessing standardized spatial resolution, intensity range, and slice selection.
ECG preprocessing began with denoising. A frequency-domain bandpass filter was applied according to Equation (7).
(7)
In Equation (7), xfilter(t) denotes the filtered ECG signal, F and F^-1 denote the Fourier and inverse Fourier transforms, H(f) denotes the passband filter, and x(t) denotes the original signal. The filtered signal was then standardized using Equation (8).
(8)
In Equation (8), xnorm(t) denotes the standardized ECG signal, µx denotes the signal mean, and σx denotes the signal standard deviation. R-peaks were detected with a modified Pan-Tompkins procedure, and beat-level segments were extracted. A continuous wavelet transform using a Morlet basis was then calculated according to Equation (9).
(9)
In Equation (9), W(a,b) denotes the wavelet coefficient at scale a and temporal translation b, x(t) denotes the ECG segment, ψ denotes the complex Morlet mother wavelet, and the integral represents the continuous projection of the signal onto scaled and translated wavelets. The resulting scalogram was used as the two-dimensional Cardioformer input. Cardiac MRI scans were resampled to 256 × 256 pixels using bicubic interpolation and center-cropped around the cardiac region. Intensity normalization was performed according to Equation (10).
(10)
In Equation (10), Inorm(x,y) denotes the normalized pixel intensity, I(x,y) the original pixel intensity, and Imin and Imax the minimum and maximum intensities in the image. A fixed number of mid-ventricular slices was selected from each examination. When segmentation masks were available, left-ventricular, right-ventricular, and myocardial structures were retained for auxiliary supervision or the derivation of functional biomarkers.
Feature Extraction
Feature extraction transformed the preprocessed ECG scalograms and MRI slices into fixed-dimensional modality-specific representations. Detailed pseudocode for the feature-extraction procedure is provided. As illustrated in Figure 3, separate encoders were used for the time-frequency ECG representation and the spatial MRI representation before the resulting embeddings were projected into a common latent space.
For ECG feature extraction, wavelet-derived scalograms were processed by Cardioformer.20 Convolutional layers captured local waveform structures such as QRS and T-wave morphology, and Transformer layers modeled long-range dependencies across the time-frequency representation. A convolutional feature map was calculated according to Equation (11).
(11)
In Equation (11), F(l) denotes the feature map at layer l, W(l) denotes the convolution kernel, b(l) denotes the bias term, and σ denotes the SiLU activation. The resulting maps were flattened and processed with self-attention according to Equation (12).
(12)
In Equation (12), Q, K, and V denote query, key, and value matrices derived from the same ECG feature set, and dk denotes the key-feature dimension. The attention operation assigned data-dependent weights to time-frequency regions, thereby enabling the representation of long-range ECG dependencies. For MRI feature extraction, TransUNet was used as a transformer-enhanced image encoder21. Downsampling convolutional layers first extracted hierarchical spatial features, and the recursive encoder mapping was defined by Equation (13).
(13)
In Equation (13), Fl denotes the MRI feature map at encoder level l, Conv(·) denotes the convolutional transformation, bl denotes the level-specific bias, σ denotes the activation function, and L denotes the number of encoder levels. The encoder output was reshaped into image-patch tokens and passed through a Vision Transformer block to model spatial dependencies across ventricular regions. The ECG and MRI encoders produced fixed-dimensional embeddings that retained modality-specific diagnostic information and were subsequently aligned by the cross-modal fusion module.
Multimodal feature alignment and fusion
Multimodal fusion was performed after modality-specific feature extraction to integrate electrical and anatomical information without directly concatenating raw inputs or averaging final predictions. Cross-modal attention was used because it allowed one modality to modulate the interpretation of the other while preserving the structure of each representation. ECG and MRI embeddings were projected into a common latent space using Equation (14), after which pairwise cosine similarity was calculated to preserve directional agreement without constraining the alignment weights to be strictly positive.
(14)
In Equation (14), xECG and xMRI denote modality-specific encoder outputs, WECG and WMRI denote learned linear projection matrices, and zECG and zMRI denote the corresponding projected tokens. For ECG token i and MRI token j, cosine similarity was then calculated according to Equation (15).
(15)
In Equation (15), simij denoted the directional similarity between projected ECG token zECG,i, and MRI token zMRI,j; the numerator was the vector inner product, and the denominator was the product of the two Euclidean norms. The similarity matrix was then used to construct a fused representation according to Equation (16).
(16)
In Equation (16), zfused(i) denotes the cross-modal representation associated with ECG token i, Sij denotes the ECG-MRI alignment weight, zMRI(j) denotes MRI token j, and TMRI denotes the number of MRI tokens. This procedure preserved positive, negative, and near-zero correspondence and enabled token-level cross-modal reasoning before pooling.
Disease diagnosis and severity classification
The fused multimodal representation was used to predict both diagnostic category and ordered severity stage. A Transformer prediction module was applied because self-attention could model global interactions among fused ECG-MRI tokens, while an ordinal head represented the ordered progression of disease severity. Given the fused token sequence Z, query, key, and value matrices were calculated using learned projections: 
(17)
In Equation (17), Z denotes the fused token matrix, and WQ, WK, and WV denote learned projection matrices for queries, keys, and values. Cosine-similarity self-attention was then calculated as:
(18)
In Equation (18), Attention(Q, K, V) denotes the self-attention output, cos(Q, K) denotes pairwise cosine-similarity weights, and V denotes the value matrix. Each pairwise similarity score was calculated as:
(19)
In Equation (19), qi and kj denote the i-th query and j-th key vectors; the numerator was the vector dot product, and the denominator normalized the score by the product of the vector norms. The attention output was processed by the position-wise feed-forward network:
(20)
In Equation (20), x denoted the attention-layer input, W1 and W2 denoted learned weight matrices, b1 and b2 denoted bias vectors, ReLU denoted the rectified linear unit, and FFN(x) denoted the nonlinear transformation. After the Transformer stack, global pooling produced a single latent vector. Diagnostic probabilities were calculated using a fully connected layer followed by element-wise sigmoid activation: 
(21)
In Equation (21), y_disease denotes the vector of diagnostic probabilities, Wc and bc denote classifier weights and bias, z denotes the pooled fused representation, and σ denotes the sigmoid function. A margin-based binary cross-entropy loss was used for diagnostic learning: 
(22)
In Equation (22), Ldiagnosis denotes diagnostic loss, yc denotes the target indicator for class c, zc denotes the corresponding class logit, m denotes the margin hyperparameter, σ denotes the sigmoid function, and C denotes the number of diagnostic categories. Severity staging was modeled with ordered threshold regressors using learnable cutoffs: 
(23)
In Equation (23), P(y>k) denotes the probability that severity exceeded threshold k, wk denotes the threshold-specific weight vector, z denotes the pooled representation, θk denotes the learnable cutoff, and K denotes the number of ordered severity stages. The cumulative ordinal loss was calculated as:
(24)
In Equation (24), Lordinal denotes ordinal staging loss, yk denotes the binary target indicating whether the true stage exceeded threshold k, P(y>k) denotes the corresponding cumulative probability, and K-1 denotes the number of ordered thresholds. This formulation preserved the ordering among normal, mild, moderate, and severe stages. This formulation respects the ordinal nature of severity (e.g., mild < moderate < severe), unlike Softmax which treats all classes as flat and unordered.
Model training and testing
HeartFusion was trained and evaluated independently on the three pseudo-paired cohorts using the configuration summarized in Table 3. Source ECG and MRI observations were split before pairing, dynamic MRI-candidate selection was used only during training, and validation/test pairings remained fixed. No source observation, derived segment, image slice, or pseudo-pair was shared across partitions, and identical partitions were used for the comparison methods. The ECG and MRI encoders were initialized with He-normal weights and optimized jointly using a weighted sum of losses: margin-based binary cross-entropy for diagnosis and ordinal cumulative loss for severity staging. The total loss function is given by:
(25)
In Equation (25), Ltotal denotes the total optimization objective; λ1, λ2, and λ3 denote task-balancing weights; Ldiagnosis denotes the margin-based diagnostic loss; Ordinal denotes the cumulative ordinal loss; and Lfusion denotes the optional manifold-alignment loss. Optimization used Adam with cosine annealing and validation-based early stopping. The batch size was 16, training was capped at 100 epochs, dropout was 0.30, and weight decay was applied consistently across the three cohorts and baseline experiments.
Evaluation
Performance was evaluated for diagnostic classification and severity staging. Diagnostic performance was summarized using accuracy, F1-score, and area under the receiver operating characteristic curve (AUC). Severity performance was summarized using ordinal accuracy, Cohen's kappa, and mean absolute error (MAE). Results were calculated over five matched runs using random seeds 11, 23, 37, 51, and 79. Statistical comparisons used paired Wilcoxon signed-rank tests on matched partitions and seeds, followed by Holm-Bonferroni correction; adjusted p-values below 0.05 were treated as statistically significant.
Baseline models
HeartFusion was compared with recent task-specific methods spanning unimodal ECG classification, multimodal ECG-MRI representation learning, temporal-frequency ECG fusion, and ECG-clinical metadata fusion. A recent ECG foundation-model benchmark was also discussed as a literature reference rather than a direct numerical baseline because its datasets, labels, and evaluation protocol differed from those used in this study. Cardioformer was used as a unimodal ECG reference because it combined convolutional feature extraction, multi-granularity tokenization, and hierarchical Transformer attention, but it did not incorporate cardiac imaging or explicit ordered severity modeling22. Girlanda et al. developed a self-supervised multimodal framework that jointly pretrained ECG and cardiac MRI encoders using masked reconstruction and contrastive alignment. The method was the closest multimodal reference to HeartFusion, although its primary objective was representation learning rather than explicit ordinal severity staging23.
Liu introduced a Transformer architecture that integrated spatial-temporal and frequency-domain ECG representations within a shared attention mechanism. Both inputs originated from ECG, so the approach did not perform physiological-imaging cross-modality integration24. Qiu et al. combined ECG signals with clinical metadata using a noise-tolerant Transformer for atrial-fibrillation recurrence prediction. The method supported multimodal clinical input but addressed a binary task and did not incorporate cardiac MRI or ordered CVD severity assessment25. Al-Masud et al. benchmarked eight ECG foundation models across multiple clinical tasks and public datasets. The benchmark showed that strong ECG representations remained task-dependent and had persistent limitations for structural assessment and outcome characterization. Because the benchmark was ECG-only and used different tasks and protocols, it was treated as a literature-based reference rather than a directly comparable baseline26. Together, the comparison methods provided context for evaluating modality complementarity, cross-modal representation learning, and ordered staging within HeartFusion.