Skip to Content
InformationInformation
  • Article
  • Open Access

26 August 2026

21 Pages

Contrastive Representation Learning on TabTransformer Latent Features for Imbalanced Post-Stroke mRS Classification

,
,
,
and
1
Data Mining Research Group, University of Salamanca, 37008 Salamanca, Spain
2
Cardiovascular Intensive Care Unit, University Hospital of Salamanca, 37007 Salamanca, Spain
3
Initial Advanced Life Support and Predictive Factors in Critically Ill Patients Research Group, University of Salamanca, 37008 Salamanca, Spain
*
Author to whom correspondence should be addressed.

Abstract

The increasing availability of electronic clinical records has enabled new opportunities for predictive modeling in healthcare. However, clinical data are characterized by heterogeneous patient information, limited sample availability, and highly imbalanced outcome distributions, which may hinder the ability of predictive models to capture complex patterns and generalize across underrepresented groups. This work investigates deep learning-based representation learning strategies for predicting the final post-stroke functional state derived from the modified Rankin Scale (mRS) using clinical tabular data. The proposed methodology learns informative patient representations while addressing class imbalance without altering the original data distribution, avoiding limitations of conventional resampling strategies. Specifically, the proposed framework combines a TabTransformer encoder with Supervised Contrastive Learning and Focal Loss to jointly optimize discriminative representation learning and imbalance-aware classification. By obtaining more separable latent representations and reducing the bias toward majority-class predictions, the approach aims to improve the identification of patients with unfavorable functional outcomes. Experimental results show that the proposed model achieves the highest accuracy (0.92) and macro-averaged F1-score (0.80), with balanced minority-class precision (0.67) and recall (0.64), unlike the other models, which showed a trade-off between these metrics. These results demonstrate improved minority-class identification while maintaining overall predictive performance in clinical outcome prediction.

1. Introduction

Recent advances in healthcare analytics have enabled the widespread use of electronic health records as a foundation for predictive modeling. However, the complexity of these datasets often limits their direct applicability in machine learning, as they combine heterogeneous feature types with high-dimensional representations and highly uneven outcome distributions. These properties can significantly affect model behavior, often leading to overly optimistic global performance while underrepresenting clinically important minority cases. As a result, standard learning approaches may fail to provide reliable decision support in realistic clinical settings.
Stroke is a major cause of long-term disability, and predicting functional outcome after an acute stroke is an important component of patient management and post-stroke care. In patients who have already experienced an ischemic stroke, the clinical objective is to estimate their subsequent degree of disability and functional dependence. The modified Rankin Scale (mRS) is one of the most widely used measures for assessing functional outcome after stroke, ranging from no symptoms or no significant disability to severe disability or death. Accurate prediction of unfavorable functional outcomes at discharge may provide valuable information for clinical decision-making and post-stroke care. To develop such predictive models, clinical data from patients who have experienced an ischemic stroke can be collected and analyzed to identify patterns associated with functional outcomes.
However, these clinical datasets typically exhibit severe class imbalance, with substantially more patients with favorable outcomes than with unfavorable outcomes, making the latter particularly difficult to characterize accurately.
Classical resampling techniques, such as undersampling and oversampling, are widely used to mitigate class imbalance in machine learning [1]. However, they present important limitations, including the potential loss of informative majority-class instances resulting from undersampling, the risk of overfitting due to duplicated minority samples in oversampling, and reduced fidelity to the underlying data distribution due to the introduction of synthetic data points in SMOTE-based oversampling [2]. These drawbacks can compromise model generalization, particularly in complex and heterogeneous domains such as clinical data. In this context, representation learning [3] has emerged as a more flexible alternative, enabling models to learn discriminative feature representations directly from the data while implicitly addressing imbalance-related issues without altering the original dataset structure.
Recent advances in representation learning [4,5] have led to the development of a wide range of methods designed to improve feature extraction from structured data. In particular, deep neural architectures tailored for tabular data aim to capture complex nonlinear relationships among heterogeneous variables through learned embeddings and adaptive feature transformations. Some approaches incorporate attention mechanisms to dynamically weight relevant features, while others rely on structured latent representations that improve robustness to noise and missing information [6]. Compared to traditional feature engineering and data resampling strategies, these methods offer the advantage of learning task-specific representations directly from data, reducing the need for manual preprocessing and improving generalization in high-dimensional and complex datasets.
Beyond data-level strategies, class imbalance can also be addressed at the algorithmic level through cost-sensitive learning, which represents a significant advancement over conventional resampling techniques. Rather than modifying the class distribution, cost-sensitive methods incorporate class-dependent misclassification costs directly into the learning objective, enabling the model to place greater emphasis on correctly identifying minority-class instances during training. This approach allows the learning process to account for the unequal consequences of classification errors without altering the original data distribution, thereby mitigating several limitations associated with data-level resampling while providing greater flexibility for imbalanced classification tasks [7].
In parallel, recent advances in representation learning, particularly Supervised Contrastive Learning (SCL), have demonstrated that learning discriminative latent representations can substantially improve class separability by encouraging samples from the same class to cluster together while pushing samples from different classes farther apart [8]. Combining contrastive representation learning with cost-sensitive optimization represents a promising direction for addressing highly imbalanced classification problems without altering the original data distribution. This potential may become particularly relevant when combined with transformer-based architectures, whose ability to model contextual interactions among heterogeneous tabular features could further enhance the quality of the learned representations.
Building upon these advances, this work proposes a unified framework for post-stroke functional outcome prediction that combines a TabTransformer encoder with Supervised Contrastive Learning and Focal Loss to address the challenges posed by heterogeneous and imbalanced clinical tabular data. Although each of these techniques has demonstrated promising results independently, their joint integration into a unified framework for imbalanced clinical tabular classification has received relatively limited attention, particularly in post-stroke outcome prediction. The proposed framework jointly optimizes a supervised contrastive objective to learn discriminative latent patient representations and a cost-sensitive classification objective based on Focal Loss to mitigate the bias towards the majority class. By simultaneously improving representation quality and minority-class recognition, the proposed approach seeks to achieve a more balanced predictive performance while preserving overall classification accuracy, thereby facilitating the early identification of patients with unfavorable functional outcomes.
In particular, this study makes the following contributions:
  • A unified representation learning framework is proposed for imbalanced clinical tabular classification by integrating transformer-based representation learning, Supervised Contrastive Learning, and cost-sensitive optimization within a single end-to-end architecture. Although these complementary techniques have been individually explored in clinical machine learning, their joint integration remains scarcely explored in this field and, to the best of our knowledge, has not been investigated for post-stroke functional outcome prediction.
  • A learning strategy is introduced to jointly address heterogeneous feature representation and severe class imbalance without relying on data-level resampling techniques. Instead, discriminative representation learning is combined with imbalance-aware optimization to enhance minority-class recognition while preserving the original data distribution.
  • A comprehensive experimental evaluation is conducted using a real-world post-stroke clinical dataset and a representative set of learning approaches integrating different representation learning architectures and class imbalance handling strategies. The experimental study provides a systematic assessment of the contribution of supervised contrastive learning within transformer-based clinical prediction models.
The remainder of this paper is organized as follows. Section 2 reviews the related work. Section 3 presents the proposed methodology. Section 4 describes the experimental setup, including the dataset, the compared approaches, and the evaluation protocol. Section 5 reports and discusses the experimental results, and Section 6 concludes the paper.

3. Methodology

This section presents the proposed methodology for predicting imbalanced post-stroke functional outcomes at discharge based on the modified Rankin Scale (mRS). Figure 1 presents the overall architecture organized into two main components: data preprocessing and the proposed learning framework. The former transforms the raw clinical records into a suitable representation for deep learning, whereas the latter integrates transformer-based representation learning, Supervised Contrastive Learning (SCL), and Focal Loss (FL) to learn discriminative patient representations that support accurate outcome prediction while mitigating the adverse effects of class imbalance. Unlike conventional training strategies that optimize only the classification objective, the proposed framework jointly learns discriminative patient representations through supervised contrastive learning while simultaneously addressing class imbalance using Focal Loss. This dual optimization strategy aims to improve the separability of minority-class samples in the learned representation space, ultimately leading to more robust post-stroke functional outcome prediction.
Figure 1. Overview of the proposed framework.
The following subsections describe each stage in detail.

3.1. Data Preprocessing

The original dataset consists of heterogeneous clinical variables describing demographic characteristics, vascular risk factors, medical history, stroke severity, administered treatments, and laboratory findings. Since these variables include both categorical and numerical attributes, different preprocessing strategies are applied according to their nature.
Categorical variables are first encoded as integer indices using label encoding. Unlike one-hot encoding, this representation enables each category to be mapped to a trainable embedding vector, allowing the model to learn semantic relationships between different categories during training while maintaining a compact input representation.
Numerical variables are normalized using z-score standardization to obtain a zero mean and unit variance. This normalization reduces scale differences among continuous features and facilitates the optimization process during neural network training.
Finally, the clinical outcome is transformed into a binary classification problem according to the modified Rankin Scale (mRS). Patients with mRS scores between 0 and 2 are considered to have a favorable functional outcome, whereas patients with mRS scores between 3 and 6 are assigned to the unfavorable outcome class. This dichotomization follows common clinical practice and results in a markedly imbalanced classification problem.

3.2. Proposed Learning Framework

Following preprocessing, the transformed data are used to train the proposed framework, referred to hereafter as TabTrans-SCL. Instead of processing the complete training partition simultaneously, the model is optimized using shuffled mini-batches, which constitute the fundamental learning units for both the transformer encoder and the supervised contrastive objective.
Each mini-batch consists of a set of heterogeneous clinical records
B = { ( x i , y i ) } i = 1 N ,
where x i denotes the input features of the i -th patient and y i is the corresponding class label.

3.2.1. TabTransformer Encoder

Each mini-batch is provided as input to a modified TabTransformer encoder specifically designed for heterogeneous tabular data. In contrast to the conventional TabTransformer formulation, in which self-attention is primarily applied to embeddings of categorical features, our implementation represents both categorical and numerical information as tokens. Each categorical variable is mapped to a trainable embedding vector of dimension 32, while all standardized numerical variables are jointly projected into the same 32-dimensional latent space through a linear transformation, resulting in a single numerical token. Thus, each patient is represented by a sequence of feature tokens comprising one token for each categorical variable and one token encoding the numerical variables.
The resulting feature representations are then interpreted as tokens and processed by a standard TabTransformer encoder composed of two stacked Transformer encoder layers with four attention heads each. Following the original Transformer architecture represented in Figure 2, each encoder layer integrates a multi-head self-attention mechanism to model interactions among clinical variables, followed by a position-wise feed-forward network that refines the learned representations. Residual skip connections and layer normalization are applied after each sublayer to facilitate gradient propagation and improve optimization stability, while dropout regularization is incorporated to reduce overfitting.
Figure 2. Transformer architecture adopted by the proposed TabTrans-SCL framework.
This architecture enables the encoder to capture complex contextual dependencies among heterogeneous clinical features and to generate informative patient representations. Finally, the contextualized token representations are flattened to produce a single latent representation,
z = F l a t t e n ( H )   ,
where H = f E n c ( T ) denotes the output of the TabTransformer encoder and z represents the latent patient representation shared by both the projection head and the classification head.

3.2.2. Projection Head

The latent representation generated by the TabTransformer encoder is first processed by a projection head implemented as a two-layer multilayer perceptron,
p = g ( z ) ,
where g ( · ) denotes the projection network and p is the projected embedding used exclusively during contrastive learning.
Unlike the classifier, this branch is only required during training to construct a representation space suitable for the supervised contrastive objective. After optimization, the projection head is discarded and is not used during inference.

3.2.3. Supervised Contrastive Learning

The projected embeddings are optimized using the Supervised Contrastive Loss proposed by Khosla et al. [8]. Let P ( i ) denote the set of samples within the mini-batch sharing the same class label as sample i . The contrastive objective is defined as
L S u p C o n = ∑ i ∈ B − 1 ∣ P ( i ) ∣ ∑ p ∈ P ( i ) l o g e x p ( p i · p p / τ ) ∑ a ≠ i e x p ( p i · p a / τ ) ,
where τ is the temperature parameter.
This objective encourages representations of patients belonging to the same functional outcome class to form compact clusters in the embedding space while simultaneously increasing the separation between different outcome classes. Consequently, the encoder learns more discriminative latent representations before the final classification stage.

3.2.4. Classification Head

The latent patient representation z is simultaneously processed by a multilayer perceptron classifier that estimates the posterior probabilities of the two outcome classes,
y ^ = f c l s z .
To explicitly address the severe class imbalance, the classifier is optimized using Focal Loss,
L F L = − α t ( 1 − p t ) γ log p t ,
where p t denotes the predicted probability associated with the true class, α t is the class-specific weighting factor, and γ controls the focusing effect applied to difficult examples. Compared with conventional cross-entropy, Focal Loss reduces the contribution of correctly classified majority-class samples and places greater emphasis on minority-class observations, thereby improving the sensitivity to unfavorable post-stroke outcomes.

3.2.5. Joint Optimization Strategy

Rather than optimizing the representation learning and classification objectives independently, TabTrans-SCL jointly minimizes both losses during each training iteration. The overall objective function is defined as
L = λ L S u p C o n + ( 1 − λ ) L F L ,
where λ ∈ [ 0,1 ] controls the relative contribution of the contrastive and classification objectives.
This joint optimization enables the encoder to learn latent representations that are simultaneously discriminative and robust to class imbalance. During inference, only the TabTransformer encoder and the classification head are retained, whereas the projection head is removed since it is exclusively required to guide representation learning during training.

4. Experimental Setup

This section presents the experimental study conducted to evaluate the effectiveness of the proposed TabTrans-SCL framework. The objective is to assess its effectiveness for post-stroke functional outcome prediction on heterogeneous and imbalanced clinical tabular data and to compare its performance with a representative set of conventional machine learning and state-of-the-art deep learning strategies. The prediction can be performed at any time after hospital admission, once the patient has undergone the initial clinical assessment and early acute treatment has been initiated, using the clinical information available at that stage.
The following subsections present the clinical dataset, the experimental protocol for model training and validation, the compared methods, and other implementation details.

4.1. Clinical Dataset

The dataset was retrospectively collected from medical records of patients with confirmed acute stroke treated at the University Hospital of Salamanca and through the Salamanca 112 emergency service between 2016 and 2019. A total of 2080 medical records were initially considered. The study population was subsequently restricted to patients with ischemic stroke for whom the stroke code had been activated, resulting in 1572 records. These records were then manually reviewed for data quality. Records containing substantial data inconsistencies, such as values incompatible with the predefined variable types or coding schemes, as well as records with extensive missing information, were excluded. After this data-quality screening, the final dataset comprised records from 1531 patients, where each instance corresponds to an individual patient. Every record is described by 16 variables and one outcome variable, providing a comprehensive representation of the patient’s clinical status at hospital admission and subsequent early acute management following the initial assessment.
The predictor variables cover several complementary clinical domains, including demographic information, neurological assessment, medical history, previous pharmacological treatment, diagnostic imaging, and acute therapeutic interventions. Consequently, the dataset exhibits a heterogeneous tabular structure composed of both categorical and numerical variables. Table 1 summarizes the different categories of predictor variables included in the study. Regarding their data types and value ranges, Sex is a binary categorical variable representing biological sex (male or female). Age is a continuous numerical variable ranging from 27 to 101 years, while NIHSS is a continuous numerical variable ranging from 0 to 42. CP comprises several Boolean variables indicating the presence or absence of specific clinical symptoms. Medical History includes 27 types of medical conditions distributed across five variables, while Previous Treatment includes 19 types of treatments distributed across three variables. The variables in Acute Management are Boolean, except for CT Scan, which is a categorical variable with 15 possible values corresponding to the affected artery, with one affected artery recorded per patient.
Table 1. Clinical categories and characteristics of the predictor variables included in the dataset.
Missing values were handled according to the nature and clinical meaning of the corresponding variables. Missing values in medical history variables were coded as ‘N’, indicating no documented condition in the clinical record. The few remaining missing values in other features were handled using standard imputation, with the mean for continuous variables and the mode for categorical variables. Missing NIHSS values were assigned a value of 45, deliberately outside the scale’s maximum score of 42. This coding reflects the clinical circumstances underlying these missing values, as the NIHSS assessment could not be performed in patients whose level of consciousness or clinical condition prevented completion of the scale.
From a statistical perspective, the most challenging characteristic of the dataset is the pronounced imbalance of the clinical outcome. Such imbalance reflects the natural distribution of functional recovery after ischemic stroke and represents a major challenge for conventional classification algorithms, which tend to be biased towards the majority class.
The original outcome variable corresponds to the modified Rankin Scale (mRS) at discharge, an ordinal clinical scale ranging from 0 (no symptoms) to 6 (death) that is widely used to assess post-stroke functional disability. In this study, the original mRS scores are transformed into a binary classification problem by grouping patients into favorable functional outcomes (mRS 0–2) and unfavorable functional outcomes (mRS 3–6). This dichotomization follows common clinical practice and results in a markedly imbalanced class distribution, with 1339 patients (87.45%) belonging to the favorable outcome class and 192 patients (12.54%) to the unfavorable outcome class (Figure 3).
Figure 3. Class distribution of the binary functional outcome variable (mRS_BIN), showing a strong imbalance between favorable (mRS 0–2, 87.5%) and unfavorable (mRS 3–6, 12.5%) outcomes.

4.2. Model Training and Validation

The proposed framework was evaluated using stratified 5-fold cross-validation to obtain a reliable estimation of the model generalization performance while preserving the class distribution in every fold. For each iteration, one fold was used as the independent test set, whereas the remaining four folds were further divided into 80% training and 20% validation subsets using stratified sampling. The validation subset was employed for hyperparameter selection, model selection, and early stopping, while the test fold was used exclusively for the final performance evaluation.
Model optimization was performed using the Adam optimizer with an initial learning rate of 3 × 10−4. The network was trained using shuffled mini-batches of 64 patients, which constitute the learning units required by the supervised contrastive objective. During each iteration, the model jointly minimized the weighted combination of the Supervised Contrastive Loss and the Focal Loss according to Equation (7), where λ controls the relative contribution of both objectives. The value of λ was selected based on the overall balance of model performance across complementary evaluation criteria. In particular, the selection aimed to achieve a competitive and balanced precision–recall trade-off for the minority class while preserving global performance, including accuracy and F1-score, and avoiding a worsening in the performance of the majority class. Based on this multi-criteria evaluation, λ was set to 0.5, assigning equal importance to representation learning and classification.
The classification branch was optimized using Focal Loss with focusing parameter γ = 2 and class weights α = [ 1.0 ,   2.8 ] , which compensate for the severe imbalance between favorable and unfavorable functional outcomes. The supervised contrastive branch employed a temperature parameter τ = 0.03. The latent patient representation generated by the Transformer was passed through a two-layer projection head consisting of a fully connected layer with 128 hidden units and ReLU activation, followed by a 64-dimensional output layer. Before computing the Supervised Contrastive Loss, the resulting projection vectors were L2-normalized. The projection head was used exclusively during training and was discarded during inference, when the latent patient representation was directly provided to the classification head.
To reduce overfitting, early stopping was applied by monitoring the validation loss with a patience of 50 epochs. The maximum number of training epochs was fixed to 300, although convergence was typically achieved considerably earlier.
Table 2 summarizes the principal hyperparameters used throughout the experimental evaluation.
Table 2. Hyperparameter configuration of the proposed TabTrans-SCL framework.
The hyperparameter values were selected based on preliminary experiments using only the corresponding training and validation subsets and represent a compromise between predictive performance and model complexity. The relatively shallow transformer architecture was intentionally adopted to reduce the risk of overfitting given the limited size of the clinical dataset.

4.3. Compared Approaches

To assess the effectiveness of the proposed framework, it was compared with several representative machine learning and deep learning approaches for clinical tabular classification. The selected methods span different modelling paradigms, ranging from conventional machine learning algorithms to transformer-based architectures and imbalance-aware deep learning models. This comparison allows the individual contribution of transformer-based feature extraction, synthetic data augmentation, and supervised contrastive representation learning to be systematically analysed. The evaluated approaches are summarized below:
  • Random Forest (RF). A traditional ensemble learning algorithm based on multiple decision trees, widely used for clinical prediction tasks due to its robustness and interpretability. To ensure compatibility with this model, categorical variables were encoded using one-hot encoding, while numerical features were standardized through z-score normalization prior to training.
  • XGBoost. A gradient boosting ensemble learning algorithm that sequentially combines decision trees to improve predictive performance, widely used for structured and tabular data due to its effectiveness in capturing complex nonlinear relationships. Categorical and numerical variables were preprocessed using the same strategy as in Random Forest.
  • LightGBM. A gradient boosting framework based on decision trees, designed for efficient and accurate learning on structured and tabular data. Its leaf-wise tree growth strategy enables the modeling of complex nonlinear relationships while maintaining computational efficiency. The same preprocessing procedure described for the previous models was applied.
  • MLP+FL. A multilayer perceptron optimized using Focal Loss to mitigate the effect of class imbalance. This model evaluates the contribution of cost-sensitive optimization without exploiting transformer-based feature representations. The same input representation adopted for Random Forest was used to preprocess the categorical and numerical variables.
  • FT-Trans+MLP+FL. A transformer-based architecture employing a Feature Tokenizer (FT-Transformer) encoder followed by a multilayer perceptron classifier optimized with Focal Loss. This approach evaluates an alternative transformer architecture for heterogeneous tabular data.
  • TabTrans+MLP+FL. A TabTransformer encoder coupled with a multilayer perceptron classification head and optimized using Focal Loss. This model corresponds to the proposed architecture without the supervised contrastive learning component and therefore serves as the most relevant ablation baseline.
  • TabTrans+MLP+FL+CTGAN. The same TabTransformer architecture trained with Focal Loss, where the training data are first balanced using synthetic samples generated by CTGAN. This approach evaluates the effectiveness of combining transformer-based learning with a state-of-the-art data-level imbalance handling strategy.
  • TabTrans-SCL (proposed). The proposed framework integrates a TabTransformer encoder with Supervised Contrastive Learning and Focal Loss through a joint optimization strategy. During training, the supervised contrastive objective encourages patients belonging to the same functional outcome class to form compact clusters in the latent feature space, while Focal Loss improves the robustness of the final classifier under severe class imbalance. During inference, only the TabTransformer encoder and the classification head are retained.
For a fair comparison, all deep learning approaches were trained using the same data partitions, validation protocol, optimization strategy, and evaluation metrics. Furthermore, whenever applicable, common architectural components—including embedding dimensionality, transformer configuration, multilayer perceptron classifier, optimizer settings, and training hyperparameters—were kept identical across methods. Consequently, the observed performance differences can be primarily attributed to the learning strategy adopted by each approach rather than to differences in model capacity or training configuration. In addition, XGBoost and LightGBM were configured with 300 estimators and a learning rate of 0.05, while subsampling and column-sampling ratios were set to 0.8. XGBoost used a maximum tree depth of 6, whereas LightGBM used 31 leaves per tree with no explicit depth constraint.

5. Results and Discussion

This section presents and discusses the experimental results obtained by the proposed TabTrans-SCL framework and the compared approaches. The analysis is structured to assess the predictive performance of the different methods from complementary perspectives, including overall classification accuracy, minority-class recognition, and the balance between precision and recall. The results are first analyzed through an overall comparison of the evaluated methods and subsequently examined in greater detail by considering class-specific performance and the effect of the proposed learning strategy on minority outcome prediction.
The results presented in Table 3 and Figure 4 show that the proposed TabTrans-SCL approach achieves the best overall performance among the evaluated methods when considering macro-averaged metrics, which are more appropriate for assessing predictive behavior under severe class imbalance. TabTrans-SCL obtains the highest F1-score (0.80), together with the best Accuracy (0.92), demonstrating its ability to achieve a strong balance between predictive performance and robustness across classes. Moreover, the proposed approach provides a better equilibrium between Precision (0.81) and Recall (0.80), indicating that it can identify minority-class samples without producing an excessive number of false positive predictions.
Table 3. Classification performance of the evaluated approaches, reported using macro-averaged precision, recall, and F1-score to account for class imbalance.
Figure 4. Performance comparison of the evaluated approaches. Precision, recall, and F1-score values correspond to macro-averaged metrics.
Random Forest also achieves a high Accuracy (0.92), comparable to TabTrans-SCL, but its lower macro-averaged Recall (0.74) and higher Precision (0.87) suggest a more conservative prediction behaviour, with a tendency to favour precision at the expense of detecting a larger proportion of positive cases. Gradient-boosting approaches, XGBoost and LightGBM, show a similar overall behavior, with Accuracy values of 0.92 and macro-F1 scores of 0.79. LightGBM achieves a slightly higher Recall (0.77) than XGBoost (0.75), although both remain below the balanced performance of TabTrans-SCL. Conversely, approaches incorporating focal loss generally improve Recall, as observed for FT-Trans+MLP+FL (0.82) and TabTrans+MLP+FL+CTGAN (0.81), but this improvement is accompanied by lower Precision values (0.72 and 0.75, respectively), resulting in lower F1-scores. The standard TabTrans+MLP+FL model provides a more balanced behavior, with Precision and Recall values of 0.77 and 0.80, respectively, although its overall performance remains below that of the proposed approach. Regarding discrimination ability, Random Forest obtains the highest AUC-ROC (0.93), followed by XGBoost and LightGBM (0.91), whereas TabTrans-SCL achieves 0.90, indicating competitive but not superior performance in this metric. Overall, the relatively small standard deviations across the five folds indicate consistent performance, with most values remaining within 0.01–0.04. These results further support the advantage of TabTrans-SCL in achieving a balanced performance across complementary metrics rather than maximizing a single evaluation criterion.
These results suggest that focal loss-based strategies contribute to improving sensitivity in imbalanced scenarios, but they may introduce a trade-off between correctly identifying minority-class samples and maintaining prediction reliability. In contrast, TabTrans-SCL achieves a more favorable compromise between Precision and Recall, leading to the highest macro-averaged F1-score while preserving competitive accuracy. This indicates that the incorporation of supervised contrastive learning enhances the quality of the learned representations, allowing the model to better capture discriminative patterns from both majority and minority classes.
Table 4 and Figure 5 provide a class-wise analysis of the performance achieved by the evaluated approaches, complementing the aggregated metrics reported previously. It reports class-specific performance metrics for each functional outcome interval, allowing a detailed assessment of the models’ ability to identify both majority and minority cases. Given the severe class imbalance, particular attention is paid to the mRS 3–6 interval, which represents the minority class, to evaluate whether the proposed approaches improve minority-class recognition while maintaining balanced performance across both classes.
Table 4. Class-wise performance comparison of the evaluated approaches. The mRS 0–2 and mRS 3–6 intervals represent the majority and minority classes, respectively.
Figure 5. Class-specific precision, recall, and F1-score (mean ± standard deviation) for mRS 0–2 and mRS 3–6 across the evaluated approaches.
The results demonstrate that the proposed TabTrans-SCL approach achieves the most balanced performance among the evaluated methods for mRS-based stroke outcome prediction. Although Random Forest obtains the highest Precision for the minority class (mRS 3–6) (0.82), this value is associated with a substantially lower Recall (0.51), indicating that the model identifies only a limited proportion of patients with unfavorable outcomes. XGBoost and LightGBM models show a similar pattern, with minority-class Precision values of 0.77 and 0.75 and Recall values of 0.52 and 0.56, respectively. Although LightGBM achieves a relatively higher minority-class F1-score (0.64), its Recall is considerably lower. In contrast, TabTrans-SCL provides a better balance between Precision and Recall for the minority class, achieving the second-highest Precision (0.67) together with a competitive Recall (0.64), resulting in the highest F1-score (0.65) among all evaluated approaches. This suggests that the proposed method is better suited to simultaneously detect minority-class patients while maintaining reliable predictions.
Furthermore, TabTrans-SCL preserves a strong performance on the majority class (mRS 0–2), obtaining a Precision of 0.95, Recall of 0.96, and F1-score of 0.95, with minimal degradation compared with the best-performing models. This demonstrates that improving minority-class recognition does not come at the cost of substantially reducing performance on the dominant class. In contrast, the other approaches exhibit a clearer trade-off between Precision and Recall for the minority class. For example, FT-Trans+MLP+FL achieves the highest Recall (0.76), but its low Precision (0.49) leads to a lower F1-score (0.59), while MLP+FL and TabTrans+MLP+FL+CTGAN also improve minority-class Recall at the expense of Precision. Similarly, although CTGAN-based augmentation increases Recall compared with the standard TabTrans+MLP+FL model, it does not translate into a better overall balance, as reflected by the unchanged F1-score. The relatively small standard deviations across the five folds, particularly for the majority class, indicate generally consistent performance, while the larger variability observed for minority-class Precision in Random Forest (±0.10) and LightGBM (±0.12) suggests greater sensitivity to the validation split. Therefore, the results indicate that the proposed TabTrans-SCL approach provides a more effective strategy for handling severe class imbalance by achieving a better compromise between minority-class sensitivity and prediction reliability.
These findings are also consistent with recent efforts to improve stroke-related prediction through more effective representation learning, although most of these approaches rely on imaging or multimodal data. Several studies have increasingly explored representation learning and contrastive learning for stroke-related prediction tasks, although most rely on imaging or multimodal data rather than exclusively on structured clinical variables. Peng et al. proposed a few-shot contrastive learning framework combining brain MRI and clinical records for cross-task stroke prognosis prediction, integrating task-specific and domain-level representations to improve robustness across datasets [31]. Similarly, Dong et al. developed a self-supervised contrastive framework based on 3D brain CTA images and radiological reports, demonstrating improved generalizability across multiple acute stroke management tasks and external data from another institution [32]. Delgrange et al. also investigated self-supervised multimodal learning by jointly integrating brain MRI, clinical variables, and image-derived features for stroke risk prediction, showing the benefits of aligning complementary information from imaging and tabular data [33]. These studies highlight the potential of contrastive and self-supervised representation learning for stroke-related prediction; however, their dependence on imaging or multimodal information limits direct application to the present study, which focuses exclusively on structured clinical data. In this context, Xia et al. demonstrated that contrastive learning can also improve clinical outcome prediction from electronic health records when different data sources are only partially available, supporting the potential of contrastive representation learning for clinical tabular data [34]. Nevertheless, their framework addresses data-source availability rather than severe class imbalance in a single structured clinical dataset. The present work therefore extends this line of research by investigating supervised contrastive learning specifically for imbalanced post-stroke functional outcome prediction using clinical tabular data alone.
To further assess the clinical interpretability of the proposed model, an analysis of the variables contributing to its predictions was performed. Figure 6 presents the global permutation importance of the clinical variables, quantified as the mean decrease in ROC-AUC after permutation across the cross-validation folds, with larger bars indicating a greater contribution to the model’s predictive performance. This analysis provides an overall assessment of the variables on which the model relied most strongly when predicting functional outcome.
Figure 6. Global permutation importance of the top clinical variables in the proposed TabTrans-SCL model.
The permutation importance analysis showed that Age was the most influential individual variable, with a mean decrease in ROC-AUC of 0.0493 ± 0.0168 after permutation, followed by Medical History 1–3 (0.0400 ± 0.0126, 0.0300 ± 0.0155, and 0.0286 ± 0.0126, respectively) and Medical History 4 (0.0184 ± 0.0076). The three previous-treatment variables showed consistent moderate contributions (0.0157–0.0176), whereas acute-management variables had comparatively smaller contributions, with Fibrinolysis showing the highest importance (0.0092 ± 0.0103), followed by Thrombectomy (0.0056 ± 0.0075). Overall, these results suggest that TabTrans-SCL relied primarily on age, pre-existing medical history, and chronic pharmacological treatment before admission when discriminating between favorable (mRS 0–2) and unfavorable (mRS 3–6) outcomes, while acute-management variables played a more limited role.
To complement this global analysis, Table 5 presents representative patient-level explanations for one patient with a favorable outcome (mRS 0–2) and one patient with an unfavorable outcome (mRS 3–6), including their predicted probability of an unfavorable outcome and the variables with the largest individual contributions to each prediction. Together, these analyses provide complementary global and patient-level perspectives on the clinical information underlying the model’s predictions.
Table 5. Representative patient-level explanations of the TabTrans-SCL predictions for favorable and unfavorable functional outcomes.
The representative patient-level analysis further illustrates how TabTrans-SCL integrates multiple clinical variables when generating individual predictions. Representative 1, who had a favorable functional outcome (mRS 0–2), was assigned a low predicted probability of an unfavorable outcome (P(mRS 3–6) = 0.129), with Medical History 1–3, Age, and Previous Treatment 2 contributing most strongly to the prediction. In contrast, Representative 2, who experienced an unfavorable outcome (mRS 3–6), received a substantially higher predicted probability of 0.846, with Previous Treatment 2–3, Medical History 4, Previous Treatment 1, and CT Scan identified as the main contributing variables. These examples show that the model’s predictions are based on combinations of clinical characteristics that differ between individual patients, rather than on a single dominant variable, providing a patient-level perspective that complements the global permutation-importance analysis.

6. Conclusions and Future Work

This paper presented TabTrans-SCL, a deep learning framework for imbalanced post-stroke functional outcome prediction that combines a TabTransformer encoder with Supervised Contrastive Learning and Focal Loss. Unlike conventional approaches that address class imbalance either through data resampling or cost-sensitive optimization alone, the proposed framework jointly learns discriminative latent representations and an imbalance-aware classifier within a unified optimization process.
The experimental evaluation on a real-world clinical dataset demonstrated that the proposed approach achieves competitive predictive accuracy while providing a more balanced performance across outcome classes. Compared with the evaluated baseline methods, TabTrans-SCL obtained the highest macro-averaged F1-score and improved the trade-off between precision and recall, indicating that the integration of supervised contrastive learning contributes to learning more discriminative patient representations without compromising performance on the majority class.
These findings suggest that combining transformer-based representation learning with contrastive and cost-sensitive optimization constitutes a promising strategy for clinical tabular classification problems characterized by heterogeneous variables and severe class imbalance. Nevertheless, the results should be interpreted in light of the study’s limitations, particularly the retrospective single-center design and the limited sample size, which may affect the generalizability of the findings to other clinical settings and patient populations. The availability of suitable datasets remains an additional challenge, as publicly accessible stroke datasets do not generally provide the same combination of clinical variables and functional outcome definition required for a directly comparable evaluation.
Future research will focus on assessing the generalizability of TabTrans-SCL across additional clinical cohorts as suitable datasets become available, as well as investigating alternative contrastive objectives and transformer architectures. Further work will also explore model robustness under dataset shift, multi-class functional outcome prediction, and applications to other clinical prognosis tasks. These research directions may provide further evidence of the robustness and broader clinical applicability of the proposed framework.

Author Contributions

Conceptualization, M.N.M.-G., A.R.V. and F.S.-H.; methodology, M.N.M.-G., V.F.L.B., M.D.M.V. and F.S.-H.; software, M.N.M.-G., V.F.L.B. and M.D.M.V.; validation, M.N.M.-G., A.R.V. and F.S.-H.; formal analysis, F.S.-H. and M.N.M.-G.; investigation, M.N.M.-G., A.R.V., V.F.L.B., M.D.M.V. and F.S.-H.; data curation, A.R.V. and F.S.-H.; writing—review and editing, M.N.M.-G.; supervision, M.N.M.-G. and F.S.-H.; project administration, M.N.M.-G.; funding acquisition, M.N.M.-G. All authors have read and agreed to the published version of the manuscript.

Funding

This research was funded by the Regional Ministry of Education of the Junta de Castilla y León (Spain). Project SA061G24, under ORDEN EDU/740/2024 19 July 2024.

Institutional Review Board Statement

Ethical review and approval were waived for this study due to the use of data derived from a retrospective review of anonymized clinical records, which had also been used in other previously published studies.

Data Availability Statement

The data used in this study are subject to access restrictions. The original contributions presented in this study are included in the article. Further inquiries regarding the data can be directed to the corresponding author.

Conflicts of Interest

The authors declare no conflicts of interest.

References

  1. He, H.; García, E.A. Learning from imbalanced data. IEEE Trans. Knowl. Data Eng. 2009, 21, 1263–1284. [Google Scholar] [CrossRef] [Scilit]
  2. Chawla, N.V.; Bowyer, K.W.; Hall, L.O.; Kebelmeyer, W.P. SMOTE: Synthetic minority over sampling technique. J. Artif. Intell. Res. 2002, 16, 321–357. [Google Scholar] [CrossRef] [Scilit]
  3. Bengio, Y.; Courville, A.; Vincent, P. Representation Learning: A Review and New Perspectives. IEEE Trans. Pattern Anal. Mach. Intell. 2013, 35, 1798–1828. [Google Scholar] [CrossRef] [Scilit]
  4. Bardes, A.; Ponce, J.; LeCun, Y. VICReg: Variance-Invariance-Covariance Regularization for Self-Supervised Learning. arXiv 2022, arXiv:2105.04906v3. [Google Scholar]
  5. Alshammari, S.; Hershey, J.; Feldmann, A.; Freeman, W.T.; Hamilton, M. I-Con: A Unifying Framework for Representation Learning. arXiv 2025, arXiv:2504.16929. [Google Scholar]
  6. Borisov, V.; Leemann, T.; Seßler, K.; Haug, J.; Pawelczyk, M.; Kasneci, G. Deep Neural Networks and Tabular Data: A Survey. IEEE Trans. Neural Netw. Learn. Syst. 2024, 35, 7499–7519. [Google Scholar] [CrossRef] [Scilit] [PubMed]
  7. Elkan, C. The Foundations of Cost-Sensitive Learning. In Proceedings of the 17th International Joint Conference on Artificial Intelligence (IJCAI); Morgan Kaufmann: San Francisco, CA, USA, 2001; pp. 973–978. [Google Scholar]
  8. Khosla, P.; Teterwak, P.; Wang, C.; Sarna, A.; Tian, Y.; Isola, P.; Maschinot, A.; Liu, C.; Krishnan, D. Supervised Contrastive Learning. Adv. Neural Inf. Process. Syst. 2020, 33, 18661–18673. [Google Scholar] [CrossRef] [Scilit] [PubMed]
  9. Eini, P.; Rezayee, M.; Kassulke, M.; Tremblay, J. Efficacy and Comparative Performance of Machine Learning Models for Stroke Risk Prediction in Hypertensive Patients: A Systematic Review and Meta-Analysis. Int. J. Cardiol. Cardiovasc. Risk Prev. 2026, 28, 200564. [Google Scholar] [CrossRef] [Scilit]
  10. Li, Y.; Wang, Z.; Wu, T.; Zhou, T. Comparison of Six Machine Learning Algorithms for Stroke Risk Estimation. Appl. Comput. Eng. 2023, 8, 556–561. [Google Scholar] [CrossRef] [Scilit]
  11. Landi, I.; Glicksberg, B.S.; Lee, H.C.; Cherng, S.; Landi, G.; Danieletto, M.; Dudley, J.T.; Furlanello, C.; Miotto, R. Deep Representation Learning of Electronic Health Records to Unlock Patient Stratification at Scale. npj Digit. Med. 2020, 3, 96. [Google Scholar] [CrossRef] [Scilit]
  12. González, J.; Martín, F.; Sánchez, M.; Sánchez, F.; Moreno, M.N. Multiclassifier Systems for Predicting Neurological Outcome of Patients with Severe Trauma and Polytrauma in Intensive Care Units. J. Med. Syst. 2017, 41, 136. [Google Scholar] [CrossRef] [Scilit]
  13. Sánchez-Hernández, F.; Ballesteros-Herráez, J.C.; Kraiem, M.S.; Sánchez-Barba, M.; Moreno García, M.N. Predictive Modeling of ICU Healthcare-Associated Infections from Imbalanced Data Using Ensembles and a Clustering-Based Undersampling Approach. Appl. Sci. 2019, 9, 5287. [Google Scholar] [CrossRef] [Scilit]
  14. Sitompul, L.R.; Nababan, A.A.; Manihuruk, M.L.; Ponsen, W.A.; Supriyandi, S. Comparison of XGBoost, Random Forest and Logistic Regression Algorithms in Stroke Disease Classification. SinkrOn 2025, 9, 957–968. [Google Scholar] [CrossRef] [Scilit]
  15. Akinwumi, P.O.; Ojo, S.; Nathaniel, T.I.; Wanliss, J.; Karunwi, O.; Sulaiman, M. Evaluating Machine Learning Models for Stroke Prediction Based on Clinical Variables. Front. Neurol. 2025, 16, 1668420. [Google Scholar] [CrossRef] [Scilit]
  16. Salmi, M.; Atif, D.; Oliva, D.; Abraham, A.; Ventura, S. Handling Imbalanced Medical Datasets: Review of a Decade of Research. Artif. Intell. Rev. 2024, 57, 273. [Google Scholar] [CrossRef] [Scilit]
  17. Dablain, D.; Krawczyk, B.; Chawla, N.V. DeepSMOTE: Fusing Deep Learning and SMOTE for Imbalanced Data. IEEE Trans. Neural Netw. Learn. Syst. 2022, 33, 3420–3434. [Google Scholar] [CrossRef] [Scilit]
  18. Baowaly, M.K.; Lin, C.C.; Liu, C.L.; Chen, K.T. Synthesizing Electronic Health Records Using Improved Generative Adversarial Networks. J. Am. Med. Inform. Assoc. 2019, 26, 228–241. [Google Scholar] [CrossRef] [Scilit]
  19. Douzas, G.; Bação, F. Effective Data Generation for Imbalanced Learning Using Conditional Generative Adversarial Networks. Expert Syst. Appl. 2018, 91, 464–471. [Google Scholar] [CrossRef] [Scilit]
  20. Umesh, C.; Mahendra, M.; Bej, S.; Wolkenhauer, O.; Wolfien, M. Challenges and Applications in Generative AI for Clinical Tabular Data in Physiology. Pflug. Arch. Eur. J. Physiol. 2025, 477, 531–542. [Google Scholar] [CrossRef] [Scilit]
  21. Goodfellow, I.; Pouget-Abadie, J.; Mirza, M.; Xu, B.; Warde-Farley, D.; Ozair, S.; Courville, A.; Bengio, Y. Generative Adversarial Nets. In Proceedings of the 27th International Conference on Neural Information Processing Systems (NeurIPS 2014), Montreal, QC, Canada, 8–13 December 2014; Ghahramani, Z., Welling, M., Cortes, C., Lawrence, N.D., Weinberger, K.Q., Eds.; Curran Associates, Inc.: Red Hook, NY, USA, 2014; pp. 2672–2680. [Google Scholar] [CrossRef] [Scilit]
  22. Xu, L.; Skoularidou, M.; Cuesta-Infante, A.; Veeramachaneni, K. Modeling Tabular Data Using Conditional GAN. arXiv 2019, arXiv:1907.00503. [Google Scholar] [CrossRef] [Scilit]
  23. Alqulaity, M.; Yang, P. Enhanced Conditional GAN for High-Quality Synthetic Tabular Data Generation in Mobile-Based Cardiovascular Healthcare. Sensors 2024, 24, 7673. [Google Scholar] [CrossRef] [Scilit]
  24. Zheng, H.; Sherazi, S.W.A.; Lee, J.Y. A Cost-Sensitive Deep Neural Network-Based Prediction Model for the Mortality in Acute Myocardial Infarction Patients with Hypertension on Imbalanced Data. Front. Cardiovasc. Med. 2024, 11, 1459994. [Google Scholar] [CrossRef] [Scilit]
  25. Lin, T.Y.; Goyal, P.; Girshick, R.; He, K.; Dollár, P. Focal Loss for Dense Object Detection. In Proceedings of the IEEE International Conference on Computer Vision (ICCV), Venice, Italy, 22–29 October 2017; pp. 2999–3007. [Google Scholar] [CrossRef] [Scilit]
  26. Cui, Y.; Jia, M.; Lin, T.-Y.; Song, Y.; Belongie, S. Class-Balanced Loss Based on Effective Number of Samples. In Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR), Long Beach, CA, USA, 15–20 June 2019; pp. 9268–9277. [Google Scholar] [CrossRef] [Scilit]
  27. Ridnik, T.; Ben-Baruch, E.; Zamir, N.; Noy, A.; Friedman, I.; Protter, M.; Zelnik-Manor, L. Asymmetric Loss for Multi-Label Classification. In Proceedings of the IEEE/CVF International Conference on Computer Vision (ICCV), Montreal, QC, Canada, 11–17 October 2021; pp. 82–91. [Google Scholar] [CrossRef] [Scilit]
  28. Yeung, M.; Sala, E.; Schönlieb, C.B.; Rundo, L. Unified Focal Loss: Generalising Dice and Cross Entropy-Based Losses to Handle Class Imbalanced Medical Image Segmentation. Comput. Med. Imaging Graph. 2022, 95, 102026. [Google Scholar] [CrossRef] [Scilit]
  29. Li, C.; Liu, K.; Liu, S. A Survey of Loss Functions in Deep Learning. Mathematics 2025, 13, 2417. [Google Scholar] [CrossRef] [Scilit]
  30. Terven, J.; Cordova-Esparza, D.-M.; Romero-González, J.-A.; Ramírez-Pedraza, A.; Chavez-Urbiola, E.A. A Comprehensive Survey of Loss Functions and Metrics in Deep Learning. Artif. Intell. Rev. 2025, 58, 195. [Google Scholar] [CrossRef] [Scilit]
  31. Peng, H.; Dai, Y.; Zheng, R.; Wang, M.; Wang, C.; Luo, Y.; Wang, H. Few-Shot Contrastive Learning for Cross-Task Stroke Prognosis Prediction with Multimodal Data. IEEE Trans. Med. Imaging 2026, 45, 2780–2794. [Google Scholar] [CrossRef] [Scilit]
  32. Dong, Y.; Pachade, S.; Roberts, K.; Jiang, X.; Sheth, S.A.; Giancardo, L. Generalizable Self-Supervised Learning for Brain CTA in Acute Stroke. Comput. Biol. Med. 2024, 184, 109337. [Google Scholar] [CrossRef] [Scilit]
  33. Delgrange, C.; Demler, O.V.; Mora, S.; Menze, B.; de la Rosa, E.; Davoudi, N. A Self-Supervised Model for Multi-modal Stroke Risk Prediction. arXiv 2024, arXiv:2411.09822. [Google Scholar]
  34. Xia, M.; Wilson, J.; Goldstein, B.; Henao, R. Contrastive Learning for Clinical Outcome Prediction with Partial Data Sources. In Proceedings of the 41st International Conference on Machine Learning (ICML 2024); Proceedings of Machine Learning Research; PMLR: Vienna, Austria, 2024; Volume 235, pp. 54156–54177. [Google Scholar]
  35. Huang, X.; Khetan, A.; Cvitkovic, M.; Karnin, Z. TabTransformer: Tabular Data Modeling Using Contextual Embeddings. arXiv 2020, arXiv:2012.06678. [Google Scholar]
  36. Gorishniy, Y.; Rubachev, I.; Khrulkov, V.; Babenko, A. Revisiting Deep Learning Models for Tabular Data. In Proceedings of the 35th Conference on Neural Information Processing Systems (NeurIPS 2021), Virtual Event, 6–14 December 2021; pp. 18932–18943. [Google Scholar]
  37. Nishad, K.A. Enhanced TabTransformer Architecture with Gated Multi-Layer Perceptron for Improved Tabular Data Modeling. In Proceedings of the 2025 IEEE 6th India Council International Subsections Conference (INDISCON 2025), Rourkela, India, 24–26 July 2025; pp. 1–7. [Google Scholar] [CrossRef] [Scilit]
  38. Ruan, Y.; Lan, X.; Tan, D.J.; Abdullah, H.R.; Feng, M. P-Transformer: A Prompt-Based Multimodal Transformer Architecture for Medical Tabular Data. In Artificial Intelligence in Medicine; Leonidas, K., Ed.; Lecture Notes in Computer Science; Springer: Cham, Switzerland, 2025; Volume 15734, pp. 375–385. [Google Scholar] [CrossRef] [Scilit]
  39. Ather, M.A.; Abdullah; Fatima, Z.; Rodríguez, J.L.O.; Sidorov, G. An Interpretable Multi-Dataset Learning Framework for Breast Cancer Prediction Using Clinical and Biomedical Tabular Data. Computers 2026, 15, 97. [Google Scholar] [CrossRef] [Scilit]
Disclaimer/Publisher’s Note: The statements, opinions and data contained in all publications are solely those of the individual author(s) and contributor(s) and not of MDPI and/or the editor(s). MDPI and/or the editor(s) disclaim responsibility for any injury to people or property resulting from any ideas, methods, instructions or products referred to in the content.

Article Metrics

Citations

Article Access Statistics

Multiple requests from the same IP address are counted as one view.