Skip to Content
Future InternetFuture Internet
  • Article
  • Open Access

29 June 2026

22 Pages

Graph-Enhanced Transformer for Cross-Domain Sentiment Analysis: Integrating RoBERTa with Graph Attention Networks

,
,
,
and
1
Department of Information Technology and Computer Science, Dr. C. V. Raman University, Bilaspur 495113, India
2
Faculty of Computing and Informatics, Multimedia University, Cyberjaya 63000, Malaysia
3
Symbiosis Institute of Technology, Nagpur Campus, Symbiosis International (Deemed University), Pune 412115, India
*
Authors to whom correspondence should be addressed.

Abstract

Sentiment analysis has become a critical task in natural language processing for extracting subjective insights from large-scale textual data across domains such as social media, e-commerce, and online reviews. However, existing methods often fail to simultaneously capture contextual semantics and structural relationships, particularly in cross-domain settings. This study proposes a hybrid RoBERTa–graph attention network (GAT) framework that integrates transformer-based contextual embeddings with graph-based relational learning. The methodology involves encoding text using RoBERTa, constructing token-level dependency graphs, and applying multi-head graph attention to model inter-token relationships. The model is evaluated on multiple benchmark datasets, including Twitter, Amazon, and IMDB reviews. The cross-domain results refer only to binary-harmonized positive/negative sentiment transfer and should not be interpreted as full three-class sentiment transfer, including the neutral class. The experimental results show that the proposed approach achieves consistent improvements over the selected baseline models in terms of accuracy, F1-score, MCC, and AUC. Statistical robustness analysis further supports the stability of these improvements across repeated runs. The findings highlight the effectiveness of combining semantic and structural learning, making the proposed framework suitable for robust cross-domain sentiment analysis applications.

1. Introduction

The growth in user-generated text content on the internet requires sentiment analysis, which is essential for completing natural language processing (NLP) tasks that rely on such data [1]. Recent studies show that over 500 million tweets are published on a daily basis, and e-commerce sites such as Amazon and Yelp include millions of reviews, which result in a large opinion-based dataset [2,3]. In the statistical evaluation of sentiment classification models, accuracy, precision, recall and F1-score are used as measures because RoBERTa models, which are based on transformers, achieve accuracy scores between 85% and 92% on benchmark data [4]. The findings demonstrate a 5 to 15% performance decline because cross-domain configurations pose a challenge, which makes it difficult to outperform them [5]. The class imbalance problem, which affects mostly neutral sentiment, leads to F1-scores below 80 percent for this minority group, suggesting that organizations require better modeling approaches, which will help them to spot fine-grained sentiment features across domains and sectors [6].
Sentiment analysis has seen improvements from more traditional machine learning models like Naïve Bayes and Support Vector Machines to deep learning models such as Convolutional Neural Networks (CNNs) and Recurrent Neural Networks (RNNs). But a key challenge for current models is their lack of cross-domain performance [7,8]. Transformer models offer deep contextual embeddings but do not explicitly consider structural relationships such as syntactic structure and token interactions [9,10]. This issue is compounded in a cross-domain scenario, where language usage differs. Moreover, most hybrid models adopt sequential models, which fail to model non-linear interactions between words.
Another major issue with the existing models is their lack of out-of-domain generalization, while the dependency structure of text is mostly understudied. Transformer models provide strong contextual embeddings; however, they do not explicitly encode syntactic topology or dependency-based token relations unless such structural information is incorporated through an additional modeling component. This shortcoming is particularly prominent in cross-domains where social media and product reviews have different sentiment expressions than movie reviews. Furthermore, most of the current hybrid models rely heavily on sequential architectures that are sensitive to order and do not have mechanisms to represent non-linear relations inherent in language. To fill these gaps, this paper proposes a graph-enhanced transformer architecture that integrates RoBERTa and a GAT (graph attention network). The proposed approach first encodes the textual data using RoBERTa to obtain their contextual embeddings and transforms them into graph structures in which tokens are represented as nodes, while relationships among tokens are represented as edges.
It is important to clarify that RoBERTa, graph attention networks, and hybrid transformer–graph architectures are not new by themselves. Recent studies have already explored the integration of transformer-based embeddings with graph learning for text classification and sentiment-related tasks. The novelty of the present study lies in its specific use of dependency-driven token-level graph construction for cross-domain sentiment analysis, where RoBERTa embeddings are combined with graph attention to model syntactic token relations across heterogeneous datasets. Unlike studies that mainly focus on single-domain classification or aspect-level sentiment analysis, this work evaluates the proposed RoBERTa–GAT framework across both noisy social media texts and structured review datasets to examine domain transferability. This study further strengthens reproducibility by explicitly defining the preprocessing pipeline, dependency graph construction process, and alignment between dependency parser tokens and RoBERTa subword representations. In addition, the model is evaluated using accuracy, macro-F1, MCC, AUC, Cohen’s Kappa, log loss, ablation analysis, latency analysis, and statistical validation, thereby providing a broader assessment of both classification performance and practical applicability.
The GAT layer applies attention over the constructed dependency graph, enabling the model to learn weighted contextual and relational dependencies among tokens. This work exploits the unique combination of transformer-based contextual learning and graph-based relational modeling to solve the cross-domain sentiment analysis problem all together while obtaining both high-level semantic information and low-order topological structural information. The contributions of this research to science are described below:
  • This study proposes a RoBERTa–GAT framework for sentiment analysis that integrates transformer-based contextual embeddings with dependency-driven graph attention learning.
  • It develops a token-level dependency graph construction strategy in which syntactic relations among words are represented as graph edges, enabling the model to capture structural interactions that are not explicitly represented in transformer-only classifiers.
  • It clarifies the alignment between dependency parser word tokens and RoBERTa subword embeddings, thereby improving the reproducibility of the graph construction pipeline.
  • It evaluates the proposed framework in both social media- and review-based sentiment domains, with special attention to noisy short texts and cross-domain transferability.
  • It provides a comprehensive empirical assessment using accuracy, macro-precision, macro-recall, macro-F1, MCC, AUC, Cohen’s Kappa, log loss, ablation analysis, latency analysis, and statistical validation.
Unlike existing hybrid models that primarily rely on sequential architectures or optimization-based feature integration, the proposed framework introduces explicit graph-based relational modeling to capture token-level dependencies. This allows the model to learn both contextual and structural features, thus enhancing representation learning. This differentiates the proposed framework from capsule-based and sequential hybrid approaches and shows improved generalization over selected baselines in cross-domain sentiment analysis.
The novelty of this study does not lie in proposing RoBERTa or the GAT as independent models but in integrating RoBERTa-based contextual embeddings with dependency-driven token-level graph attention for binary-harmonized cross-domain sentiment transfer. Unlike transformer-only models, the proposed framework explicitly represents syntactic token relations through dependency graphs. Unlike sequential hybrid models such as RoBERTa–BiLSTM or RoBERTa–capsule, it uses graph attention to assign different weights to sentiment-relevant dependency relations. Unlike existing graph-based sentiment studies that mainly focus on single-domain or aspect-level classification, this work evaluates the framework across both noisy social media texts and structured review datasets.

2. Literature Review

In this section, we review the literature on sentiment analysis, which is relevant to the three areas of interest: transformer and hybrid approaches and current structural learning technologies.

2.1. Traditional and Deep Learning Models for Sentiment Analysis

Neural networks in deep learning have replaced traditional machine learning-based methods such as Naïve Bayes, Support Vector Machines, and Maximum Entropy models [11,12]. Early methods involved manual feature engineering, as they relied on bag-of-words models, which tended to ignore contextual and syntactic features. The deep learning era has seen improved performance through the introduction of models such as CNNs and RNNs (LSTM and GRU networks), which have the capacity to learn both sequential and semantic features [13,14]. The models fail to capture hierarchical and long-term relationships that are present in text data.

2.2. Transformer-Based Sentiment Analysis

The development of transformer models BERT and its variants, including RoBERTa, marked a new era in sentiment analysis models [15,16]. These models use a mechanism known as self-attention to consider long-term dependencies in sequences more efficiently. The training optimization strategies in RoBERTa allowed the model to become a strong baseline for solving this particular problem (sentiment classification) [17,18]. Although highly effective, transformer models primarily provide contextual embeddings, which can fall short of being able to explicitly model the structural or relational dependencies that underpin complex sentiment expression.

2.3. Hybrid Transformer Architectures

However, standalone transformer models have their limitations, and recent studies have explored the use of hybrid architectures in combination with sequential models such as BiLSTM and BiGRU [19,20]. Hybrid approaches enhance feature extraction by combining contextual and sequential information from multiple model components [21,22]. Despite their better performance, such models are inherently sequential and typically suffer from extremely high computational complexity and have limited capacity in learning hierarchical pose-invariant relationships within the text [23,24]. Capsule networks (CapsNets) are a new and promising alternative for data with hierarchical relations [25,26]. Capsule networks substitute the scalar neurons of traditional neural networks with vector representation groups organized in capsules, which manage to retain part–whole relationships and accommodate spatial dependencies by virtue of a dynamic routing process [27,28]. Capsule-based models have significantly improved performance (robustness) and accuracy on noisy short-text classification (e.g., sentiment analyses). However, the combination of capsule networks and transformer-based models is still in its infancy and a vast area for research.

2.4. Graph Neural Networks in NLP and Sentiment Analysis

Graph neural networks have increasingly been used in NLP to model text structure beyond simple word sequences. In sentiment analysis, dependency-GCN and dependency-GAT models represent words as nodes and syntactic relations as edges, allowing the model to capture dependency-based interactions among tokens. Graph-based methods are especially useful when sentiment meaning depends on grammatical relations, such as negation, intensification, comparison, or aspect–opinion connections [29]. Transformer–GCN and transformer–GAT models further combine contextual embeddings with graph-based message passing, enabling the model to use both semantic and structural information [30]. However, graph construction in NLP remains challenging, particularly for informal social media texts containing slang, abbreviations, spelling variations, emojis, hashtags, and incomplete grammar. Therefore, a clear explanation of graph construction, parser token alignment, self-loops, and the handling of noisy text is necessary for reproducibility.

2.5. RoBERTa–GAT and Recent Hybrid Graph Models

The work of Gauraha et al. (2026) uses a hybrid model that comprises RoBERTa and capsule networks to overcome the limitations of sequential and transformer-only models in the field of sentiment analysis [31]. RoBERTa is responsible for contextual embedding, followed by capsule layers with dynamic routing to effectively represent hierarchical sentiment features and part–whole relations. The approach achieved an overall accuracy of 91.72% on standard datasets such as Twitter US Airline and Apple sentiment datasets (even with a higher F1-score, Area Under the Curve (AUC), and Cohen’s Kappa scores). This paper makes a significant contribution to the field, especially regarding the neutral class, which is challenging to predict in short messages, as well as the context of neutral text more broadly. But the idea of multimodal interactions as a universal concept is still vague and does not reveal strong relationships in structured models (such as graphs) that may reveal more thorough data interdependencies.
To better position the proposed framework within recent sentiment analysis research, Table 1 presents a comparative summary of representative transformer-based, graph-based, and hybrid sentiment analysis studies. The comparison highlights the dataset/domain, methodology, metrics, strengths, limitations, and the specific research gap addressed by the present RoBERTa–GAT framework.
Table 1. Comparative summary of selected cited sentiment analysis studies.

2.6. Research Gaps and Positioning of Proposed Study

The reviewed literature identifies four significant gaps. First, traditional and sequential deep learning models often struggle to capture both contextual and structural sentiment relationships at the same time. Second, while transformer-only models deliver strong contextual embeddings, they do not explicitly incorporate dependency-based syntactic structures. Third, many hybrid transformer models introduce sequential or hierarchical components but fail to represent token-level dependency relationships as graph structures. Fourth, existing RoBERTa–GAT models primarily concentrate on text classification or aspect-level sentiment classification, whereas the current study emphasizes cross-domain sentiment generalization through dependency-driven, token-level graph construction across diverse social media and review datasets. To address these gaps, this paper proposes a RoBERTa–GAT framework that combines contextual semantic embeddings with dependency-based graph attention learning to enhance sentiment classification across various domains.

3. Dataset Description

The data for testing the proposed RoBERTa–GAT model spanned both social media-based and review-based datasets, ensuring cross-domain diversity. The datasets include short, noisy Twitter texts and longer, structured reviews (Amazon, IMDB, and Yelp), enabling a powerful evaluation over various linguistic contexts. All datasets were preprocessed through standard approaches, including the elimination of URLs, mentions and special characters, after which a tokenization process using the RoBERTa tokenizer was performed. To maintain class distribution, stratified splitting was used (80% training, 10% validation, 10% testing). The model was trained on one domain (e.g., Twitter) and tested on another (e.g., reviews) for cross-domain analysis to evaluate generalization. Table 2 gives a summary of the datasets used for cross-domain sentiment analysis.
Table 2. Dataset characteristics, class distribution, and sentiment label structure.
This dataset setup allows for the proper assessment of contextual and structural learning and enables domain adaptation for sentiment analysis. We used the RoBERTa tokenizer for tokenization. To ensure uniform class distribution, stratified sampling was used for training, validation, and test sets. The datasets used in this paper are pre-annotated benchmark datasets popular in sentiment analysis. Labels are either annotated (e.g., CrowdFlower datasets) or inferred from rating scores (Amazon, Yelp, and IMDB datasets), with rating scores of 4 and above being positive and 2 and below being negative. Neutral ratings are preserved if present. This approach guarantees consistent labeling across different datasets and facilitates cross-domain analysis.

3.1. Class Distribution and Imbalance Handling

The datasets exhibit varying levels of class imbalance. The Twitter Airline and Apple Twitter datasets contain a higher proportion of negative samples, whereas the IMDB dataset is balanced, and the Amazon and Yelp datasets are only mildly imbalanced. To preserve the original class distribution, stratified train–validation–test splitting (80:10:10) was employed. In addition, macro-averaged precision, recall, and F1-score, along with MCC and Cohen’s Kappa, were reported to provide a balanced evaluation under class-imbalanced conditions.

3.2. Text Preprocessing

All datasets were cleaned using a uniform preprocessing pipeline before tokenization. URLs and user mentions were removed, while hashtags were retained after removing the “#” symbol because they may contain sentiment-bearing words. Extra spaces, HTML entities, and non-informative special characters were removed. For social media datasets, repeated characters and informal spellings were normalized where possible to reduce noise before dependency parsing. RoBERTa tokenization was then applied to the cleaned text. Since RoBERTa uses byte-level subword tokenization, casing was preserved, and padding/truncation was performed using a fixed maximum sequence length. Sarcasm and mock expressions were not explicitly modeled and are acknowledged as limitations of the current study.

4. Proposed Methodology

The proposed framework is designed to combine contextual semantic representation with explicit syntactic relational learning for sentiment classification. The overall pipeline consists of five main stages: text preprocessing, RoBERTa-based contextual encoding, alignment between RoBERTa subword tokens and dependency parser word tokens, dependency-driven graph construction, and graph attention-based sentiment classification. Unlike transformer-only models, which directly use pooled contextual embeddings for classification, the proposed model uses RoBERTa token representations as node features in a dependency graph and applies graph attention network layers to learn weighted structural interactions among sentiment-relevant tokens. Our model is composed of multiple steps, including embedding, graph, attention, and classification, as shown in Figure 1.
Figure 1. Proposed RoBERTa–GAT workflow for cross-domain sentiment analysis.
To ensure clarity and consistency in the mathematical formulation, the key notations used in this study are defined as follows:
Let X = { w 1 , w 2 , … , w n } denote the input word sequence, where w i represents the i -th token, and n is the sequence length. Let y denote the sentiment label corresponding to negative, neutral, or positive classes. Let H ∈ R m × 768 represent the contextual embedding matrix generated by RoBERTa-base, where m is the RoBERTa subword token sequence length, and 768 is the hidden dimension. Let G = ( V , E ) denote the constructed dependency graph, where V represents the set of word-level nodes, and E represents dependency-based edges. Let A ∈ R n × n denote the adjacency matrix of the graph.

4.1. Input Representation and Preprocessing

Let an input sentence be represented as X = { w 1 , w 2 , … , w n } , where w i denotes the i -th word token, and n is the sentence length. After preprocessing, the input text is passed through the RoBERTa tokenizer, and the resulting sequence is padded or truncated to a fixed maximum length. The original word token sequence is also retained for dependency parsing so that syntactic relations can be mapped to graph nodes.

4.2. Contextual Embedding Using RoBERTa

The tokenized input sequence is encoded using RoBERTa to obtain contextual token representations:
H = R o B E R T a ( X )
where H ∈ R L × d , L is the RoBERTa token sequence length, and d is the hidden dimension. In this study, RoBERTa-base was used with a hidden dimension of 768. These contextual embeddings were not directly pooled for classification. Instead, they were aligned with dependency parser word tokens and used as initial node features for graph construction.

4.3. Alignment Between Dependency Tokens and RoBERTa Subword Tokens

Dependency parsing was performed at the word token level, whereas RoBERTa uses byte-level subword tokenization. Therefore, a token alignment step was applied before graph construction. Each word token obtained from the dependency parser was mapped to its corresponding RoBERTa subword token or tokens. If a word was split into multiple subword units, the corresponding subword embeddings were averaged to form a single word-level node representation. Thus, each graph node represents one dependency parser word token, while its initial node feature is derived from the aligned RoBERTa subword embedding. Special tokens such as <s> and </s> and padding tokens were excluded from graph nodes, although they were retained during RoBERTa encoding as required by the tokenizer. This alignment ensured consistency between contextual embeddings and dependency-based graph structure.
Token alignment was performed by matching spaCy word tokens with RoBERTa subword tokens using character span overlap. When a word was split into multiple RoBERTa subwords, the corresponding embeddings were averaged to obtain a single word-level node feature. In cases of ambiguous alignment, overlapping subword spans were used. If no reliable alignment was found due to punctuation, normalization, or tokenization mismatch, the token was retained in the graph with a self-loop so that its contextual representation was preserved during graph attention learning.

4.4. Graph Construction

After aligning RoBERTa subword embeddings with dependency parser word tokens, each sentence was represented as a token-level dependency graph. Each word token was treated as a graph node, and its initial feature vector was obtained from the aligned RoBERTa embedding. In the final experiments, graph edges were constructed only from dependency parser head-dependent relations. Co-occurrence-based and semantic similarity-based edges were not used in the reported results. To allow for bidirectional information flow, each dependency relation was converted into an undirected edge by adding both head-to-dependent and dependent-to-head connections. Self-loops were also added to all nodes so that each token could retain its own contextual information during graph attention learning. Special tokens and padding tokens were excluded from graph construction. Dependency labels were not used as separate edge features in the present version of the model.
For noisy social media texts, dependency parsing was applied after basic text normalization; however, self-loops were retained for all nodes so that each token preserved its RoBERTa-based contextual representation even when parser-generated dependency edges were imperfect.

4.5. Graph Attention and Sentiment Classification

The constructed dependency graph was processed using a multi-head graph attention network. For each node, the GAT layer computes attention weights over its neighboring nodes and aggregates their features to obtain a structurally informed representation. This allows the model to assign higher importance to sentiment-relevant dependency relations such as negation, modifiers, and opinion-bearing words. The output node representations from the GAT layer were aggregated using global mean pooling to obtain a graph-level sentence representation. This pooled representation was then passed through a fully connected layer and a softmax classifier to predict the sentiment class.
The model was trained using cross-entropy loss and optimized with AdamW. Dropout was applied to reduce overfitting, and the best model was selected based on validation loss.
For example, in the sentence “The flight was not good, although the staff were polite,” RoBERTa can capture the contextual meaning of the sentence, but it does not explicitly represent the syntactic link between the negation word “not” and the opinion word “good.” In the proposed framework, the dependency graph connects these related tokens, and the GAT layer can assign higher attention to such sentiment-relevant relations. This helps the model distinguish the negative sentiment associated with “not good” from the positive expression “staff were polite.” Thus, dependency-based graph attention complements RoBERTa by explicitly modeling structural relations that are important for sentiment interpretation.

4.6. Algorithmic Description of Proposed Frameworks

Algorithm 1 constructs the dependency-based graph representation, while Algorithm 2 performs graph attention learning and sentiment classification. Together, they define the complete RoBERTa–GAT pipeline. Figure 2 shows the proposed two-step algorithm that includes the process of graph generation and attention-based inference for sentiment.
Algorithm 1. Dependency-Based Graph Construction with RoBERTa Token Alignment.
Input: Cleaned sentence X = { w 1 , w 2 , … , w n } , RoBERTa tokenizer T R , dependency parser P D
Output: Graph G = ( V , E ) , adjacency matrix A ~ , node feature matrix X 0
1. Apply dependency parser:
                                                 P D ( X ) → { ( w i , w j ) ∣ w i → w j }
where w i → w j denotes a head–dependent relation.
2. Tokenize the sentence using RoBERTa:
                                                     T R X = s 1 , s 2 , … , s L
where s l is the l -th RoBERTa subword token.
3. Encode the RoBERTa-tokenized sequence:
                                             H = R o B E R T a ( T R ( X ) ) , H ∈ R L × d
where d is the hidden dimension.
4. Align each dependency-parser word token w i with its corresponding RoBERTa subword set:
                                                     M ( w i ) = { s a i , s a i + 1 , … , s b i }
5. If a word is split into multiple subwords, compute its word-level node feature by averaging the aligned subword embeddings:
                                                     x i 0 = 1 ∣ M ( w i ) ∣ ∑ s l ∈ M ( w i ) H l
6. Construct the node set:
                                                 V = { v i ∣ v i ↔ w i ,     i = 1,2 , … , n }
Special tokens such as ⟨ s ⟩ , ⟨ / s ⟩ , and padding tokens are excluded from graph nodes.
7. Construct dependency-based edges:
                                                     E d = { ( v i , v j ) ∣ w i → w j }
8. Add reverse edges for bidirectional information flow:
                                                 E r = { ( v j , v i ) ∣ ( v i , v j ) ∈ E d }
9. Add self-loops:
                                                     E s = { ( v i , v i ) ∣ v i ∈ V }
10. Define the final edge set:
                                                         E = E d ∪ E r ∪ E s
11. Construct the adjacency matrix:
                                                     A ~ i j = 1 , if   ( v i , v j ) ∈ E 0 , otherwise
12. Initialize the node feature matrix:
                                                     X 0 = [ x 1 0 , x 2 0 , … , x n 0 ] T
13. Return:
                                                         G = ( V , E ) , A ~ , X 0
Figure 2. Two-stage algorithmic framework illustrating graph construction and RoBERTa–GAT-based sentiment classification.
Algorithm 2. RoBERTa–GAT Sentiment Classification.
Input: Graph G = ( V , E ) , adjacency matrix A ~ , node features X 0
Output: Predicted sentiment class y ∗
1. Receive G = ( V , E ) , A ~ , and X 0 from Algorithm 1.
2. Initialize node representation:
                                                             h i 0 = x i 0
3. For each GAT layer l , transform node features:
                                                             z i l = W l h i l
where W l is a learnable weight matrix.
4. Compute the attention score between node i and its neighbor j :
                                     e i j l = L e a k y R e L U ( a T [ z i l ∥ z j l ] ) , j ∈ N ( i )
5. Normalize attention scores:
                                                   α i j l = e x p ( e i j l ) ∑ k ∈ N ( i ) e x p ( e i k l )
6. Update node representation:
                                                 h i l 1 = σ ∑ j ∈ N ( i ) α i j l z j l
7. For K -head graph attention, combine the outputs of all heads:
                                           h i l 1 = ∥ k = 1 K σ ∑ j ∈ N ( i ) α i j k W k h j l
8. Apply global mean pooling to obtain graph-level sentence representation:
                                                        h G = 1 ∣ V ∣ ∑ i = 1 ∣ V ∣ h i
9. Compute class logits:
                                                        o = W c h G + b c
10. Compute sentiment-class probabilities:
                                                        p ^ = s o f t m a x ( o )
11. Predict the sentiment label:
                                                        y ^ = a r g   m a x c   p ^ c
12. During training, minimize cross-entropy loss:
                                                  L = − ∑ c = 1 C y c   l o g ( p ^ c )
13. Update model parameters using AdamW and return:
                                                               y ^

4.7. End-to-End Formulation

The overall model can be written compactly as follows:
y ^ = S o f t m a x F C P o o l G A T G R o B E R T a X
This formulation summarizes the flow from RoBERTa-based contextual encoding to dependency graph construction, graph attention learning, pooling, and final sentiment prediction.

5. Experimental Setup

5.1. Implementation Details

The proposed RoBERTa–GAT model is implemented using Python 3.10 with the PyTorch 2.0 deep learning framework and the HuggingFace Transformers library. Dependency parsing for graph construction is performed using the SpaCy parser. The experiments were conducted on a system configured with an NVIDIA RTX 3080 GPU (10 GB), 32 GB RAM, and an Intel i7 processor.
The key hyperparameters used in the model are as follows: learning rate = 2 × 10−5, batch size = 16, number of epochs = 10–15, dropout rate = 0.3, GAT hidden dimension = 128, and number of attention heads = 4. To ensure reproducibility and robustness, all experiments are repeated three times with different random seeds, and the average performance is reported. All reported performance values are presented as the mean ± standard deviation across three independent runs.
To support reproducibility, additional implementation details were specified. The model was implemented in Python 3.10 using PyTorch, HuggingFace Transformers, spaCy, and PyTorch Geometric. Dependency parsing was performed using the spaCy en_core_web_sm model. The RoBERTa-base encoder was used with a maximum sequence length of 128. The GAT module used two graph attention layers, a hidden dimension of 128, four attention heads, and a dropout of 0.3. Experiments were repeated using three random seeds: 42, 123, and 2024. Sentence-level dependency graphs were batched using PyTorch Geometric’s graph batching utility, and graph-level representations were obtained through global mean pooling. For token alignment, RoBERTa subword embeddings corresponding to the same spaCy word token were averaged. In ambiguous alignment cases, overlapping subword spans were used; when no reliable alignment was possible, the token was retained through a self-loop to preserve its contextual representation.

5.2. Experimental Details

The RoBERTa–GAT framework was evaluated both in-domain and cross-domain to study generalizability. All datasets were first preprocessed using standard cleaning and RoBERTa tokenization before they were split into stratified sets (80%:10%:10%) for training, validation, and testing respectively. For the used Amazon and Yelp datasets, sentiment labels were assigned based on their associated ratings (≥4 positive, ≤2 negative). Stratified sampling was used to maintain class proportions across training, validation, and testing subsets. In-domain experiments were performed using the original label structure of each dataset, whereas cross-domain experiments used binary label harmonization to maintain a consistent positive–negative sentiment space across source and target domains.
For cross-domain evaluation, the sentiment label space was harmonized across datasets to avoid incompatibility between binary and three-class classification settings. Since some datasets contain positive, neutral, and negative labels, while others contain only positive and negative labels, cross-domain experiments were conducted in a binary setting. Neutral instances from the three-class social media datasets were excluded only for cross-domain evaluation, while positive and negative samples were retained. This ensured that all train–test domain pairs used a consistent positive–negative label structure.
The model uses RoBERTa embeddings and a GAT to generate graphs at the token level using dependency relations. AdamW optimizer is used for training and various metrics such as accuracy, precision, recall, F1-score, Matthews Correlation Coefficient (MCC), AUC and Cohen’s Kappa for evaluation. The experiments are conducted with varied random seeds, and the average is taken. The setup and model configuration used for train and eval is outlined in Table 3.
Table 3. Experimental setup and model configuration.

6. Results and Discussion

We compare the results of the proposed RoBERTa-GAT framework on multiple datasets in both in-domain and cross-domain settings. This demonstrates the benefits of using contextualized transformer embeddings and learning the graph structure. We use macro-averaging for all the metrics to mitigate the impact of class imbalance.
Along with traditional metrics (accuracy, precision, recall, and F1-score), this research uses more sophisticated performance metrics such as the Matthews Correlation Coefficient (MCC), Area Under the Curve (AUC), Cohen’s Kappa, and log loss to assess and understand the overall performance of the models. These measures allow for better evaluation in the presence of class imbalance and domain shift. An exploratory paired comparison and effect size analysis were conducted to provide supportive evidence regarding the consistency of performance differences. Because the number of dataset-level comparisons is small, these statistical results are interpreted cautiously and are not treated as definitive confirmation of significance.

6.1. In-Domain Performance Analysis

Together, Table 4a,b show that the proposed RoBERTa–GAT model consistently outperforms the selected baselines across classification, robustness, and calibration metrics. This indicates that augmenting sentiment classification with graph-based structural information results in improved accuracy (≈2–4%) and F1-score (≈2–3%). This improvement is also reflected in the MCC and Cohen’s Kappa, suggesting stronger classification robustness and agreement. The drop in log loss also indicates more confidence and calibration in predictions. Figure 3 highlights the comparative performance of the proposed and baseline models on different datasets and evaluation metrics.
Table 4. (a). In-domain classification performance of baseline and proposed models across benchmark datasets. (b). In-domain robustness and calibration performance of baseline and proposed models across benchmark datasets.
Figure 3. Comparative performance of proposed and baseline models across datasets: (a) accuracy, precision, recall, and F1-score; (b) MCC and AUC.

6.2. Binary-Harmonized Cross-Domain Evaluation

The proposed model shows consistent improvement over the selected baseline models in the binary-harmonized cross-domain setting. These results suggest that dependency-based graph attention can improve cross-domain generalization by adding structural token-level information to RoBERTa embeddings. In Table 5, we show the cross-domain generalization performance (accuracy).
Table 5. Binary-harmonized cross-domain generalization performance using positive and negative sentiment classes only.
Neutral samples from three-class datasets were removed only for cross-domain experiments to maintain a consistent binary label space across all source and target domains.

6.3. Ablation Study

To assess the impact of its individual components in the RoBERTa–GAT framework, we performed an ablation study by gradually adding graph construction and attention mechanisms. The results illustrate a distinct performance increase at each model refinement stage. The baseline RoBERTa model produces strong contextual representations but lacks explicit structural information. Adding more high-level relationships through graph-based representation gives a consistent performance gain, a signature of the missed token-wise interactions. Incorporating graph attention networks further enhances this performance by enabling the model to learn weighted dependencies among tokens. The contributions of different modules in the proposed model are shown in Table 6. Where, “✓” indicates the inclusion of the corresponding component in the model configuration, whereas “✗” indicates its absence. Various components, including graph construction and multi-head attention, with their impact on model performance, are shown in Figure 4.
Table 6. Component-wise contribution analysis.
Figure 4. Ablation study showing impact of graph structure and multi-head attention on model performance in terms of accuracy, F1-score, and MCC.
Additionally, multi-head attention provides a measurable performance improvement because it allows the model to learn different relational patterns simultaneously. The model with higher attention heads achieves the best results of all configurations, further demonstrating that parallel attention mechanisms work better when it comes to this kind of task. In general, the ablation results demonstrate that both the graph structure and attention mechanisms are important for achieving superior performance in sentiment classification, but their joint integration is important for improving classification performance.

6.4. Comparison with a Graph-Based Non-Attention Baseline

To further clarify the contribution of graph-based modeling, a graph-based non-attention baseline was included under the same experimental protocol. In this baseline, the same dependency-based token graph and RoBERTa word-level node features were used, but graph attention was not applied. This comparison helps examine whether the performance gain comes only from dependency graph construction or from the additional attention-based graph learning mechanism. To further validate the contribution of the proposed attention-based graph learning component, Table 7 compares the proposed model with a graph-based non-attention baseline under the same experimental protocol.
Table 7. Comparison with graph-based non-attention baseline under same experimental protocol.
The results show that adding a dependency-based graph structure improves the transformer-only RoBERTa baseline. The RoBERTa + dependency graph non-attention baseline performs better than RoBERTa alone, indicating that syntactic graph structure contributes useful information. The dependency-GAT variants further improve the results, suggesting that attention-based neighbor weighting adds value beyond graph construction alone. The four-head RoBERTa + dependency-GAT configuration achieves the best performance among the compared configurations.

6.5. Computational Efficiency and Latency Analysis

We performed a detailed analysis in terms of training efficiency and inference latency to evaluate the practicality of the RoBERTa–GAT framework (based on Figure 5 and Figure 6).
Figure 5. Training time decomposition and latency distribution comparison between the base RoBERTa model and the proposed RoBERTa–GAT framework across datasets.
Figure 6. Comparative analysis of training time and inference latency across models and datasets.
The time comparison on the training of each dataset depicted in Figure 5 demonstrates that the proposed model incurs a moderate increase in computation cost compared to the baseline RoBERTa model since it involves graph construction as well as attention. Although the proposed model introduces additional computational overhead, it remains more efficient than other hybrid architectures such as RoBERTa + BiLSTM and RoBERTa + capsule. This demonstrates that the proposed methodology achieves a favorable trade-off between higher representational power and computational complexity.
The analysis of inference latency also backs up the results. Figure 6 shows that the proposed model has competitive latency performance across all datasets, with only a small amount of overhead over the baseline. Even though the proposed model adds complexity to the design in an asynchronous setting, it still achieves low latency with lower inference overhead than many sequential hybrid models that exhibit efficient inference behavior.
Additionally, Figure 5 demonstrates a comprehensive breakdown regarding the components of training time and latency distribution. As shown in the stacked bar charts, the training time is mainly dominated by graph learning computation operations, with data loading and auxiliary overhead remaining steady. The latency distribution curves show that the proposed model achieves a steady and controlled inference pattern, having at most 5% higher mean and 95th percentile latency than the baseline without major variance. In summary, the results demonstrate that the proposed RoBERTa–GAT model yields significant performance benefits and is computationally affordable while being applicable for practical usage in cross-domain sentiment analysis problems.

6.6. Hyperparameter Sensitivity

In this section, we analyze the sensitivity of the proposed RoBERTa–GAT model to critical hyperparameters such as the number of attention heads, learning rate and hidden dimensions. Understanding the impact of hyperparameters is essential for optimizing model performance. As we increase the number of attention heads, performance improves before marginal gains are saturated. This means that moderate attention complexity is the best. As shown in Table 8, different attention head options change the performance of our proposed model.
Table 8. Impact of multi-head attention on model performance averaged over three independent runs (mean ± SD).

6.7. Statistical Robustness Analysis

To examine the stability of the reported improvements, experiments were repeated using three independent random seeds. For each dataset, the mean and standard deviation of the evaluation metrics were reported. A paired t-test was used to compare the proposed RoBERTa–GAT model with the RoBERTa baseline using run-wise performance scores. However, because the number of independent runs was limited, the statistical results are interpreted cautiously. Therefore, the analysis focuses not only on p-values but also on the consistency of improvement across datasets and the magnitude of performance gain. The results indicate that RoBERTa–GAT consistently has improved accuracy, macro-F1, and MCC over the selected RoBERTa baseline, suggesting that dependency-based graph attention contributes positively to sentiment classification performance. Table 9 shows the statistical robustness analysis results.
Table 9. Statistical robustness comparison between RoBERTa and RoBERTa–GAT.
Because the paired t-test is based on a small number of dataset-level comparisons, the statistical results should be interpreted as exploratory and supportive rather than confirmatory. The main evidence for model improvement is therefore based on consistent mean performance gains across datasets and repeated runs. Gains represent the improvement in RoBERTa–GAT over the RoBERTa baseline. For accuracy and Macro-F1, gains are reported in percentage points. For the MCC, AUC, Kappa, and log loss, gains are reported in absolute metric units. The paired t-test was conducted across the three in-domain datasets; therefore, the results should be interpreted cautiously due to the small number of paired comparisons. The effect size is reported as Cohen’s d z .

6.8. Error Analysis

The proposed model reduces both false positives and false negatives, with the largest reduction observed in neutral misclassification, reinforcing its ability to handle ambiguous sentiment. The distribution of classification errors across different classes and models is presented in Table 10.
Table 10. Error distribution across classes and models.

7. Limitations and Future Work

7.1. Limitations

Although the proposed RoBERTa–GAT framework achieved improved performance over the selected baselines, this study has some limitations. First, the model introduces additional computational cost because dependency graphs must be constructed and processed through graph attention layers. Second, the quality of the dependency graph depends on the parser, and parsing errors may occur in noisy social media texts containing slang, abbreviations, spelling variations, hashtags, emojis, sarcasm, or incomplete sentence structures. Although preprocessing and self-loops were used to reduce this issue, parser noise may still affect downstream classification. Third, sarcasm, mock expressions, and deeper pragmatic meanings were not explicitly modeled. Fourth, this study used English-language datasets only; therefore, the generalizability of the framework to multilingual and low-resource settings remains untested. Fifth, cross-domain experiments required binary label harmonization by excluding neutral samples from three-class datasets, which may limit the interpretation of neutral sentiment transfer. Finally, the present work focuses on sentence-level sentiment classification and does not examine aspect-level or document-level sentiment tasks. Although full graph neural baselines such as dependency-GCN and transformer–GCN are closely related to the proposed approach, they were not fully reimplemented in the present study. This limitation is acknowledged, and future work will extend the comparison to additional graph neural architectures under identical experimental settings.

7.2. Future Work

Future work can address these limitations in several directions. First, lightweight graph attention mechanisms, sparse attention, pruning, or model compression can be explored to reduce computational cost. Second, more robust graph construction strategies, such as semantic similarity graphs, dynamically learned graphs, or parser-independent graph structures, may improve performance on noisy social media text. Third, sarcasm-aware and slang-aware preprocessing modules can be incorporated to improve the interpretation of informal online expressions. Fourth, the framework can be extended to multilingual and cross-lingual sentiment analysis using models such as XLM-R or mBERT. Fifth, future studies may evaluate the method on aspect-based and document-level sentiment tasks. Finally, broader comparison with recent transformer–graph models and testing on larger real-time datasets can further validate the scalability and practical applicability of the proposed approach.

8. Conclusions

This study proposed a RoBERTa–GAT framework for cross-domain sentiment analysis by combining transformer-based contextual embeddings with dependency-driven graph attention. The model uses RoBERTa to capture semantic context and a GAT to learn weighted syntactic token relations from dependency graphs. Experiments across social media- and review-based datasets showed consistent improvements over selected baselines in classification and robustness metrics. The findings suggest that incorporating dependency-based structural information can improve cross-domain sentiment representation, particularly when sentiment cues depend on relations such as negation, modifiers, and opinion-bearing words. However, this study is limited to English datasets and binary-harmonized cross-domain transfer, and future work should evaluate broader graph-neural baselines, multilingual datasets, and aspect-level sentiment tasks.

Author Contributions

Conceptualization, P.D. and R.K.R.; methodology, M.P., A.S., and P.D.; software, M.P. and P.K.M.; validation, M.P. and A.S.; formal analysis, R.K.R.; investigation, M.P. and P.K.M.; resources, R.K.R.; data curation, M.P., A.S., and P.K.M.; writing—original draft preparation M.P.; writing—review and editing, P.D. and R.K.R.; visualization, M.P. and A.S.; supervision, P.D. and R.K.R.; project administration, R.K.R.; funding acquisition, R.K.R. All authors have read and agreed to the published version of the manuscript.

Funding

The APC will be paid by Multimedia University.

Data Availability Statement

The authors confirm that all relevant data were included in this article.

Conflicts of Interest

The authors declare no conflicts of interest.

Abbreviations

The following abbreviations are used in this manuscript:
RoBERTaRobustly Optimized Bidirectional Encoder Representations from Transformers
GATGraph Attention Network
MCCMatthews Correlation Coefficient
AUCArea Under the Curve
NLPNatural Language Processing

References

  1. Tembhurne, J.V.; Lakhotia, K.; Agrawal, A. Twitter sentiment analysis using ensemble of multi-channel model based on machine learning and deep learning techniques. Knowl. Inf. Syst. 2024, 67, 1045–1071. [Google Scholar] [CrossRef] [Scilit]
  2. Parmar, H.; Sikawar, S.S. Enhancing sentiment analysis in natural language processing: A hybrid approach of machine learning and deep learning model for emotion classification. In Lecture Notes in Networks and Systems; Springer: Singapore, 2025; pp. 777–798. [Google Scholar] [CrossRef] [Scilit]
  3. Pande, S.D.; Altahan, B.R.; Ahammad, S.H.; Mane, A.S.; Inthiyaz, S.; Smirani, L.K.; Hossain, M.A.; Rashed, A.N.Z. Assessment and recommendation of neural networks and precise techniques for sentiment systems analysis. J. Ambient Intell. Humaniz. Comput. 2023, 14, 11285–11299. [Google Scholar] [CrossRef] [Scilit]
  4. Ahmad, H.O.; Umar, S.U. Sentiment Analysis of Financial Textual data Using Machine Learning and Deep Learning Models. Informatica 2023, 47, 153–158. [Google Scholar] [CrossRef] [Scilit]
  5. Choyal, B.; Sharma, S. Leveraging Machine learning and Artificial intelligence for sentiment analysis in Financial Markets: A Comprehensive Systematic review. In Smart Innovation, Systems and Technologies; Springer: Singapore, 2025; pp. 375–387. [Google Scholar] [CrossRef] [Scilit]
  6. Das, A.; Malaviya, S. Artificial Intelligence and Sentiment Analysis in Political Campaigns. In Cyber-Physical Systems for Innovating and Transforming Society 5.0; Wiley: Hoboken, NJ, USA, 2025; pp. 193–209. [Google Scholar] [CrossRef] [Scilit]
  7. Singh, N.; Jaiswal, U.C. A detailed sentiment analysis survey based on machine learning techniques. Adcaij Adv. Distrib. Comput. Artif. Intell. J. 2023, 12, e29105. [Google Scholar] [CrossRef] [Scilit]
  8. Silviya, S.H.A.; Faith, S.J.; Seetha, R.; Hemalatha, M. Performance evaluation of natural language processing algorithms for sentiment Analysis. SN Comput. Sci. 2024, 5, 724. [Google Scholar] [CrossRef] [Scilit]
  9. Selvakumar, P.; Poorani, S.; Sahith, R.; Pathak, G.P.; Anute, N.; Manjunath, T.C. Implementing Sentiment Analysis for Evaluating Stakeholder Perception and Social Impact. In Data-Driven ESG Strategy Implementation Through Business Intelligence; IGI Global: Hershey, PA, USA, 2025; pp. 227–254. [Google Scholar] [CrossRef] [Scilit]
  10. Bodhankar, A. Exploring the Potential of Sentiment Analysis for Insight Generation; IEEE: Piscataway, NJ, USA, 2023; Volume 2, pp. 1570–1575. [Google Scholar] [CrossRef] [Scilit]
  11. Singh, B.; Kaur, K.; Kaur, G. Optimizing Emotion Detection: An NLP-Driven Deep Learning Approach to Sentiment Encoding; IEEE: Piscataway, NJ, USA, 2025; pp. 1–6. [Google Scholar] [CrossRef] [Scilit]
  12. Pandey, A.C.; Rajpoot, D.S. Improving Sentiment Analysis using Hybrid Deep Learning Model. Recent Adv. Comput. Sci. Commun. 2019, 13, 627–640. [Google Scholar] [CrossRef] [Scilit]
  13. Kapočiūtė-Dzikienė, J.; Damaševičius, R.; Woźniak, M. Sentiment analysis of Lithuanian texts using traditional and deep learning approaches. Computers 2019, 8, 4. [Google Scholar] [CrossRef] [Scilit]
  14. Shad, R.; Potter, K.; Gracias, A. Natural Language Processing (NLP) for Sentiment analysis: A Comparative study of Machine learning algorithms. Int. J. Artif. Intell. Mach. Learn. 2025, 5, 58–69. [Google Scholar] [CrossRef] [Scilit]
  15. Kaur, I.; Kumar, S.; Singhal, K. Multilingual sentiment analysis using transfer learning and transformer architecture: A survey. In Recent Trends in Intelligent Computing and Communication: Volume 1; CRC Press: Boca Raton, FL, USA, 2025; pp. 292–298. [Google Scholar] [CrossRef] [Scilit]
  16. Zou, H.; Wang, Y.; Huang, A. A novel span and syntax enhanced large language model based framework for fine-grained sentiment analysis. Neural Netw. 2025, 193, 108012. [Google Scholar] [CrossRef] [Scilit] [PubMed]
  17. Kale, T.V.; Mendhe, S. A Review on Advances in Sentiment Analysis: A Deep Learning Approach Using Transformer Based Models; IEEE: Piscataway, NJ, USA, 2025; pp. 235–239. [Google Scholar] [CrossRef] [Scilit]
  18. Mathew, L.; R, B.V. Efficient transformer-based sentiment classification models. Informatica 2022, 46, 175–184. [Google Scholar] [CrossRef] [Scilit]
  19. Srianan, S.; Nanthaamornphong, A.; Phucharoen, C. Advancing tourism sentiment analysis: A comparative evaluation of traditional machine learning, deep learning, and transformer models on imbalanced datasets. Inf. Technol. Tour. 2025, 27, 1011–1045. [Google Scholar] [CrossRef] [Scilit]
  20. Almalki, S.S. Sentiment analysis and emotion detection using transformer models in multilingual social media data. Int. J. Adv. Comput. Sci. Appl. 2025, 16, 324. [Google Scholar] [CrossRef] [Scilit]
  21. Raychawdhary, N.; Bhattacharya, S.; Seals, C.; Dozier, G.V. Empowering sentiment analysis in African Low-Resource languages through transformer models and strategic language selection. IEEE Access 2025, 13, 147859–147873. [Google Scholar] [CrossRef] [Scilit]
  22. Murfi, H.; Syamsyuriani; Gowandi, T.; Ardaneswari, G.; Nurrohmah, S. BERT-based combination of convolutional and recurrent neural network for indonesian sentiment analysis. Appl. Soft Comput. 2023, 151, 111112. [Google Scholar] [CrossRef] [Scilit]
  23. Gaur, N.; Chintala, S. Enhancing Sentiment Analysis with Hybrid Transformer-ML Models: A Deep Learning and Explainable AI Approach. In Lecture Notes in Networks and Systems; Springer: Singapore, 2026; pp. 295–304. [Google Scholar] [CrossRef] [Scilit]
  24. Tambunan, N.R.A.; Saputro, D.R.S.; Widyaningsih, P. Hybrid Integration of Bert and Bilstm Models for Sentiment Analysis. Barekeng J. Ilmu Mat. Dan Terap. 2026, 20, 1719–1730. [Google Scholar] [CrossRef] [Scilit]
  25. Dong, Y.; Fu, Y.; Wang, L.; Chen, Y.; Dong, Y.; Li, J. A sentiment analysis method of capsule network based on BILSTM. IEEE Access 2020, 8, 37014–37020. [Google Scholar] [CrossRef] [Scilit]
  26. Sagili, S.R.; B, S.; RVS, P.; P, A. Sentiment Classification for Depression Detection: Integrating Capsule Networks with CNNs on Review Data; IEEE: Piscataway, NJ, USA, 2025; pp. 1–7. [Google Scholar] [CrossRef] [Scilit]
  27. Singh, M.; Panwar, S.; Choudhary, S. BiERU-CapsNet: Bidirectional Emotional Recurrent Unit with Capsule Network, a Novel Approach for Textual Sentiment Analysis. SN Comput. Sci. 2026, 7, 183. [Google Scholar] [CrossRef] [Scilit]
  28. Zhang, B.; Xu, X.; Yang, M.; Chen, X.; Ye, Y. Cross-Domain sentiment classification by capsule network with semantic rules. IEEE Access 2018, 6, 58284–58294. [Google Scholar] [CrossRef] [Scilit]
  29. Lv, S.; Dong, J.; Wang, C.; Wang, X.; Bao, Z. RB-GAT: A Text Classification Model Based on RoBERTa-BiGRU with Graph ATtention Network. Sensors 2024, 24, 3365. [Google Scholar] [CrossRef] [Scilit] [PubMed]
  30. Fan, M.; Kong, M.; Wang, X.; Hao, F.; Zhang, C. FITE-GAT: Enhancing aspect-level sentiment classification with FT-RoBERTa induced trees and graph attention network. Expert Syst. Appl. 2025, 264, 125890. [Google Scholar] [CrossRef] [Scilit]
  31. Gauraha, R.; Agrawal, A.K.; Dubey, P. Capsule-enhanced RoBERTa for hierarchical sentiment analysis on social media texts. Discov. Artif. Intell. 2026, 6, 147. [Google Scholar] [CrossRef] [Scilit]
  32. Apple Twitter Sentiment (CrowdFlower). Available online: https://www.kaggle.com/datasets/slythe/apple-twitter-sentiment-crowdflower (accessed on 25 January 2026).
  33. Apple_Twitter_Sentiment_Texts. Available online: https://www.kaggle.com/datasets/seriousran/appletwittersentimenttexts (accessed on 25 January 2026).
  34. Amazon Reviews. Available online: https://www.kaggle.com/datasets/kritanjalijain/amazon-reviews (accessed on 25 January 2026).
  35. IMDB Dataset of 50K Movie Reviews. Available online: https://www.kaggle.com/datasets/lakshmi25npathi/imdb-dataset-of-50k-movie-reviews (accessed on 25 January 2026).
  36. Yelp Reviews Dataset. Available online: https://www.kaggle.com/datasets/omkarsabnis/yelp-reviews-dataset (accessed on 25 January 2026).
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.