Skip to content

Journal article · 2025

A Hierarchical Attention–Gated Framework for Joint Emotion and Sentiment Modeling

HAGF predicts sentiment polarity and emotion category in one model, using word- and sentence-level attention and a gate that corrects polarity reversals such as 'good for nothing'.

Mihir RavalResearch Scholar, Ganpat University, Mehsana. Director, IndiaNIC Infotech Ltd.

Computer Research and Development (ISSN 1000-1239), Vol. 25, Issue 10, pp. 276-297

StatusPublished

HAGF model architecture Input text Up to 128tokens XLM-RoBERTa Base: 12 layers,768 hidden BiLSTM 256 units(128 + 128) Word-level attention Weights each token Sentence-level attention Weights each sentence Hierarchical Bridge Joins sentence andpooled word vectors Gating Input, forget andreset gates Sentiment head 3-class softmax Emotion head 6-class softmax Loss: 0.5 x sentiment + 0.5 x emotion Cross-entropy, one shared encoder, two heads
Components named in the paper's abstract. The layout is a simplified illustration, not the paper's own figure.

The full text of the paper follows, reformatted for the web. It is reproduced from the published article (Computer Research and Development, Vol. 25, Issue 10, 2025, pp. 276 to 297) under the CC BY 4.0 licence. Figures and tables are reproduced as published.

Abstract

Understanding human emotion and sentiment through natural language has become an essential component of modern conversational systems, product analytics, and social media intelligence. However, most existing deep learning models either focus solely on sentiment polarity (positive, negative, neutral) or emotion categories (joy, anger, sadness, etc.), failing to capture the hierarchical and contextual relationship between them. This paper presents a Hierarchical Attention–Gated Framework (HAGF) that jointly models emotion and sentiment using a dual-layer attention mechanism and a gating-based feature refinement strategy. The proposed model integrates XLM-RoBERTa for multilingual contextual embeddings, BiLSTM for sequential feature extraction, and a hierarchical attention block that processes both word-level and sentence-level dependencies. A Hierarchical Bridge (HB) layer maintains feature hierarchy between the two levels, while a Gating Mechanism (GM) dynamically filters and refines emotional signals to handle polarity reversal and context ambiguity (e.g., “good for nothing”, “not bad”). The model employs dual dense heads to simultaneously predict sentiment polarity and emotion category, enabling multi-task learning and improved contextual understanding. Experimental results on benchmark datasets demonstrate superior accuracy and interpretability compared to state-of-the-art transformer-based baselines.

Keywords: Sentiment Analysis, Emotion Detection, Hierarchical Attention, Gating Mechanism, XLM-RoBERTa, Multi-task Learning, Deep Learning.

1. Introduction

Emotion and sentiment analysis are crucial tasks in Natural Language Processing (NLP) that help machines interpret human opinions, attitudes, and feelings from text, forming the backbone of intelligent conversational systems and adaptive virtual agents (Rawal, 2025). Applications of these models span various domains such as product reviews, social media analytics, customer feedback systems, and human-computer interaction. Traditional sentiment classification approaches often treat polarity prediction (positive, negative, neutral) and emotion recognition (joy, anger, sadness, etc.) as separate problems. However, in natural communication, sentiment and emotion are deeply intertwined: emotions provide the underlying cause of sentiment, and sentiment represents the high-level tone of emotional expression.

Recent advancements in deep learning, particularly with transformer-based architectures such as BERT (Devlin et al., 2019) and RoBERTa (Liu et al., 2019), have significantly improved contextual text understanding. However, these models often fail to capture fine-grained emotional relationships and hierarchical dependencies within longer sentences or paragraphs. Furthermore, linguistic phenomena such as negation, contrast, and sarcasm continue to challenge even advanced contextual models.

To address these challenges, we propose a novel Hierarchical Attention–Gated Framework (HAGF) that performs joint sentiment and emotion modeling in a single end-to-end architecture. Our framework employs dual attention mechanisms (word-level and sentence-level) to capture hierarchical contextual dependencies. A Hierarchical Bridge (HB) ensures that local and global representations remain connected, preserving contextual integrity. Additionally, the Gating Mechanism (GM) refines features dynamically by controlling the flow of emotional information across layers. This enables the model to handle complex structures like polarity reversals (“not good”, “good for nothing”) and blended emotions (“sad but hopeful”).

The model concludes with two parallel dense layers that independently predict sentiment polarity and emotion category. By leveraging shared representations, HAGF achieves multi-task learning efficiency while improving robustness and interpretability. An overview of the proposed architecture is shown later in Figure 1.

The main contributions of this paper are summarized as follows:

  • We introduce a hierarchical deep learning framework that jointly learns sentiment and emotion representations through dual-level attention.
  • We propose a Gating Mechanism (GM) that refines emotional features and corrects polarity reversals dynamically.
  • We employ a Hierarchical Bridge (HB) to preserve feature hierarchy between word- and sentence-level representations.
  • We demonstrate the model’s interpretability using attention and gate visualization, along with competitive results on multiple benchmark datasets.

The remainder of this paper is organized as follows: Section 2 reviews related work in sentiment and emotion modeling. Section 3 presents the proposed framework in detail. Section 4 describes datasets, training setup, and evaluation. Section 5 discusses quantitative and qualitative results, and Section 8 concludes the paper with future directions.

The study of emotion and sentiment analysis has evolved significantly over the last two decades. Traditional machine learning approaches, such as Support Vector Machines (SVM), Naïve Bayes, and Decision Trees, relied heavily on manually engineered lexical features (Pang and Lee, 2008; Medhat et al., 2014). These approaches often used sentiment lexicons like WordNet-Affect and SentiWordNet to identify polarity-bearing words. However, they struggled to handle linguistic subtleties such as negation, sarcasm, and context-dependent meaning.

With the advent of deep learning, sequence-based models such as Convolutional Neural Networks (CNN) and Recurrent Neural Networks (RNN) significantly improved feature extraction from raw text (Kim, 2014; Tang et al., 2015). The introduction of Bidirectional LSTMs (BiLSTM) (Hochreiter and Schmidhuber, 1997) further enhanced contextual understanding by capturing long-term dependencies in both forward and backward directions. However, RNN-based models still lacked the ability to focus on the most relevant parts of a sequence, leading to the rise of attention mechanisms.

2.1. Transformer-based Models

The introduction of the Transformer architecture (Vaswani et al., 2017) revolutionized NLP by relying entirely on self-attention mechanisms instead of recurrent computations. Models such as BERT (Devlin et al., 2019), RoBERTa (Liu et al., 2019), and XLM-RoBERTa (Conneau et al., 2020) set new performance standards in text classification, sentiment analysis, and emotion recognition. Despite their success, transformer models often treat sentences as flat sequences, overlooking hierarchical linguistic structures and sentence-level dependencies. Moreover, they are not explicitly designed to handle polarity reversal or subtle emotional blends, which require reasoning beyond token-level context.

2.2. Hierarchical and Multi-level Architectures

To address the limitation of flat attention, hierarchical models were proposed. Hierarchical Attention Networks (HAN) (Yang et al., 2016) introduced word-level and sentence-level attention to capture local and global dependencies. These models showed promising results in document-level sentiment classification. Extensions of HAN (Ma et al., 2018; Qian et al., 2020) integrated recurrent and convolutional components for richer feature learning. However, most of these approaches focus on sentiment alone and ignore emotional nuance.

2.3. Multi-task and Emotion-Aware Models

Recent studies emphasize the relationship between emotion and sentiment. Works such as (Buechel and Hahn, 2018; Mohammad et al., 2018) demonstrated that emotions often drive sentiment polarity, motivating joint learning frameworks. Multi-task learning models (Caruana, 1997) allow shared representation learning across related tasks, improving generalization. Recent industrial implementations of conversational agents have also demonstrated the benefit of customized emotion-aware pipelines, where adaptive sentiment modeling enhances dialogue quality (Rawal, 2025). Some models combine sentiment detection with emotion or sarcasm prediction (Poria et al., 2019; Zhang et al., 2020), but they often use shared encoder heads without explicit refinement of conflicting emotional signals.

2.4. Gating and Feature Refinement

The concept of gating in neural networks originated in architectures like LSTM and GRU (Cho et al., 2014), where gates control the flow of information through memory cells. Gating mechanisms have since been applied to refine attention outputs (Shen et al., 2018; Wu et al., 2020), but their role in emotion–sentiment joint modeling remains underexplored. Existing works typically use gating within recurrent units, not as an explicit post-attention refinement layer. This motivates our introduction of a Gating Mechanism (GM) designed to filter, reset, and refine emotional features after hierarchical fusion.

2.5. Summary

In summary, while attention and transformer-based models have enhanced sentiment and emotion analysis, several gaps remain:

  • Most models treat sentiment and emotion as independent problems.
  • Few models maintain hierarchical context between words and sentences.
  • Negation and polarity reversals are poorly handled in current architectures.
  • Gating mechanisms are rarely used for emotion-level feature refinement.

The proposed Hierarchical Attention–Gated Framework (HAGF) aims to fill these gaps by combining multi-level attention, a hierarchical bridge, and a gating mechanism to jointly model sentiment and emotion in an interpretable, context-aware manner.

3. Proposed Framework

This section presents the architecture of the proposed Hierarchical Attention–Gated Framework (HAGF). The model is designed to jointly predict emotion and sentiment in an end-to-end learning paradigm while preserving hierarchical linguistic structure and refining emotional cues.

3.1. Overall Architecture

Figure 1 provides an overview of the proposed HAGF model. The framework consists of six primary components:

  1. Input Tokenization and Embedding Layer (XLM-RoBERTa)
  2. Sequential Modeling using BiLSTM
  3. Dual Attention Mechanisms (Word- and Sentence-level)
  4. Hierarchical Bridge (HB)
  5. Gating Mechanism (GM)
  6. Dual Dense Output Heads for Sentiment and Emotion
Figure 1: the HAGF pipeline, from input tokenization and embedding through XLM-RoBERTa, BiLSTM, word-level attention and the Hierarchical Bridge to dense sentiment and emotion outputs
Figure 1: Overall pipeline of the Hierarchical Attention–Gated Framework (HAGF).

3.2. Embedding Layer (XLM-RoBERTa)

We employ XLM-RoBERTa (Conneau et al., 2020), a multilingual transformer encoder, as the embedding layer. It maps input tokens into contextualized embeddings E=[e1,e2,…,en]E = [e_1, e_2, \ldots, e_n], where each eie_i represents the semantic context of token ii across multiple languages. This enables robust handling of multilingual datasets such as SemEval and GoEmotions.

3.3. Sequential Modeling (BiLSTM)

The embeddings are passed through a Bidirectional LSTM (BiLSTM) to capture sequential dependencies in both directions:

ht=[ht→⊕ht←](1)h_t = \left[\overrightarrow{h_t} \oplus \overleftarrow{h_t}\right] \tag{1}

where ht→\overrightarrow{h_t} and ht←\overleftarrow{h_t} represent forward and backward hidden states. BiLSTM provides temporal sensitivity and complements transformer embeddings by modeling local sequential relations.

3.4. Word-level Attention

The word-level attention mechanism computes attention weights for each token within a sentence:

αi=exp⁡(tanh⁡(Wwhi))∑jexp⁡(tanh⁡(Wwhj))(2)\alpha_i = \frac{\exp(\tanh(W_w h_i))}{\sum_j \exp(\tanh(W_w h_j))} \tag{2}

where WwW_w is a learnable parameter. The weighted sum of hidden states forms a sentence vector sk=∑iαihis_k = \sum_i \alpha_i h_i, emphasizing emotionally salient words (e.g., “bad”, “wonderful”, “nothing”).

3.5. Sentence-level Attention

Sentence-level attention operates over all sentence vectors {s1,s2,…,sm}\{s_1, s_2, \ldots, s_m\} to produce a document-level representation:

βk=exp⁡(tanh⁡(Wssk))∑lexp⁡(tanh⁡(Wssl))(3)\beta_k = \frac{\exp(\tanh(W_s s_k))}{\sum_l \exp(\tanh(W_s s_l))} \tag{3}

and

vd=∑kβksk(4)v_d = \sum_k \beta_k s_k \tag{4}

This allows the model to emphasize emotionally dominant sentences (e.g., strong negatives outweighing mild positives).

3.6. Hierarchical Bridge (HB)

The Hierarchical Bridge (HB) merges sentence-level and word-level features while maintaining hierarchical context:

HHB=[vd⊕Pool(sk)](5)H_{HB} = \left[v_d \oplus \mathrm{Pool}(s_k)\right] \tag{5}

It preserves local word-level emotional cues and integrates them into a global sentence representation. The HB ensures that fine-grained details (specific emotional words) remain connected to coarse features (overall tone).

Figure 2: three word-level representations feed one sentence-level representation, which produces the hierarchical bridge
Figure 2: The Hierarchical Bridge maintains connectivity between word- and sentence-level representations, combining local emotional cues (sk) with global context (vd). This fusion forms a unified hierarchical representation (HHB).

3.7. Gating Mechanism (GM)

The Gating Mechanism (GM) refines features after HB fusion. It includes three gates inspired by GRU dynamics: input (iti_t), forget (ftf_t), and reset (rtr_t):

it=σ(WiHHB+bi)(6)i_t = \sigma(W_i H_{HB} + b_i) \tag{6} ft=σ(WfHHB+bf)(7)f_t = \sigma(W_f H_{HB} + b_f) \tag{7} rt=σ(WrHHB+br)(8)r_t = \sigma(W_r H_{HB} + b_r) \tag{8}

The refined representation is then computed as:

ht′=ft⊙ht−1+it⊙tanh⁡(WhHHB)+rt⊙ht−1(9)h'_t = f_t \odot h_{t-1} + i_t \odot \tanh(W_h H_{HB}) + r_t \odot h_{t-1} \tag{9}

This mechanism allows the model to:

  • Reduce the influence of misleading words (e.g., “good” in “good for nothing”),
  • Strengthen dominant emotional triggers (e.g., “nothing” → strong negative),
  • Maintain emotional consistency across hierarchical levels.
Figure 3: the gating mechanism, with input, forget and reset gates feeding a contextual representation
Figure 3: Illustration of the Gating Mechanism refining the contextual representation by controlling input, forget, and reset signals.

3.8. Dual Dense Heads for Joint Prediction

Finally, the refined representation ht′h'_t is passed into two independent dense layers for:

  • Sentiment classification: Softmax(Wsentht′+bsent)\mathrm{Softmax}(W_{sent} h'_t + b_{sent})
  • Emotion classification: Softmax(Wemoht′+bemo)\mathrm{Softmax}(W_{emo} h'_t + b_{emo})
Figure 4: dual output heads for sentiment classification (positive, negative, neutral) and emotion classification (joy, anger, sadness, fear)
Figure 4: Dual output heads for sentiment and emotion prediction using shared encoder representations.

These outputs produce probabilities for sentiment polarity (positive/negative) and emotion categories (joy, anger, sadness, fear, etc.) simultaneously. Multi-task learning enhances shared representation and reduces overfitting.

3.9. Training Objective

The total loss is a weighted combination of sentiment and emotion cross-entropy losses:

Ltotal=λ1Lsentiment+λ2Lemotion(10)\mathcal{L}_{total} = \lambda_1 \mathcal{L}_{sentiment} + \lambda_2 \mathcal{L}_{emotion} \tag{10}

where λ1\lambda_1 and λ2\lambda_2 control the task importance. Both heads share the same encoder but optimize different classification objectives.

The proposed framework thus combines hierarchical attention, contextual gating, and dual-task learning to deliver high interpretability, emotional consistency, and strong performance across sentiment and emotion detection benchmarks.

4. Experimental Setup

To evaluate the proposed Hierarchical Attention–Gated Framework (HAGF), we conducted extensive experiments on publicly available benchmark datasets for sentiment and emotion classification. This section describes the datasets, preprocessing steps, model configuration, training environment, and evaluation metrics.

4.1. Datasets

Three representative datasets were used to validate the model’s performance:

  • SemEval-2018 Task 1 (Affect in Tweets) (Mohammad et al., 2018): Contains short Twitter messages annotated with both emotion intensity and sentiment polarity. We use the English subset comprising approximately 10 000 labeled tweets.
  • GoEmotions (Demszky et al., 2020): A large-scale dataset of 58 000 Reddit comments annotated with 27 fine-grained emotions and three sentiment polarities. Following prior work, we collapse the emotion labels into six primary categories: joy, anger, sadness, fear, disgust, and surprise.
  • ISEAR (International Survey on Emotion Antecedents and Reactions): Consists of short diary-style sentences where subjects describe experiences eliciting specific emotions. Each entry is tagged with one of seven emotion classes, following the design of (Buechel and Hahn, 2018).

For cross-validation, datasets were split into 80% training, 10% validation, and 10% testing subsets.

4.2. Preprocessing

All text samples were lowercased and normalized by removing URLs, hashtags, user mentions, and special characters. Tokenization was performed using the XLM-RoBERTa SentencePiece tokenizer (Conneau et al., 2020), which supports multilingual subword segmentation. Each sequence was truncated or padded to a fixed length of 128 tokens. Stop-word removal was avoided since transformer embeddings handle context implicitly.

4.3. Model Configuration

The model components were configured as follows:

  • Embedding Layer: XLM-RoBERTa base (12 layers, hidden = 768, 12 heads) (Conneau et al., 2020).
  • BiLSTM Layer: Hidden units = 256 (128 forward + 128 backward) (Hochreiter and Schmidhuber, 1997).
  • Dropout: 0.2 applied after embedding and before dense heads to prevent overfitting.
  • Hierarchical Attention: Two-level attention weights (αi\alpha_i, βk\beta_k) learned jointly (Yang et al., 2016).
  • Hierarchical Bridge (HB): Concatenation of sentence-level and pooled word-level vectors to preserve hierarchical feature integrity.
  • Gating Mechanism (GM): Three gates (input, forget, and reset) implemented with sigmoid activations inspired by GRU dynamics (Cho et al., 2014).
  • Output Heads:
    • Sentiment Head: 3-class softmax (positive, negative, neutral)
    • Emotion Head: 6-class softmax (joy, anger, sadness, fear, disgust, surprise)

4.4. Training Details

Training was conducted on a single NVIDIA A100 GPU (40 GB memory) using the PyTorch 2.1 framework. The AdamW optimizer (Loshchilov and Hutter, 2019) was employed with an initial learning rate of 2×10−52 \times 10^{-5}, batch size = 16, and weight decay = 0.01. Early stopping was applied with a patience of 5 epochs based on validation loss, with a total of 20 epochs maximum.

The total loss function combines both sentiment and emotion objectives as:

Ltotal=λ1Lsentiment+λ2Lemotion\mathcal{L}_{total} = \lambda_1 \mathcal{L}_{sentiment} + \lambda_2 \mathcal{L}_{emotion}

where λ1=λ2=0.5\lambda_1 = \lambda_2 = 0.5 unless otherwise stated.

4.5. Evaluation Metrics

Performance was assessed using standard multi-class classification metrics:

  • Accuracy (%): proportion of correctly classified samples.
  • Precision, Recall, and F1-score: macro-averaged across all classes.
  • Matthews Correlation Coefficient (MCC): used to evaluate performance on imbalanced emotion datasets.
  • Confusion Matrices and Attention Visualizations: used to interpret sentiment–emotion relationships, similar to (Poria et al., 2019; Zhang et al., 2020).

All experiments were repeated three times with different random seeds, and average results are reported for robustness.

5. Results and Discussion

This section presents both quantitative and qualitative analyses of the proposed Hierarchical Attention–Gated Framework (HAGF). The model’s performance is compared against established baselines on benchmark datasets, followed by interpretability analysis of attention and gating behavior.

5.1. Quantitative Evaluation

Table 1 compares the proposed HAGF model with several baselines, including traditional transformer encoders and hierarchical attention architectures.

Table 1: Comparison of HAGF with state-of-the-art models on sentiment and emotion datasets.

ModelDatasetAcc (%)PrecRecF1MCC
CNN-LSTM (Kim, 2014)SemEval83.10.810.800.800.74
BiLSTM-Attention (Yang et al., 2016)SemEval84.30.830.820.820.76
BERT-base (Devlin et al., 2019)SemEval86.50.850.840.850.78
RoBERTa-base (Liu et al., 2019)SemEval87.10.860.860.860.80
XLM-RoBERTa-base (Conneau et al., 2020)GoEmotions88.40.880.870.880.82
HAGF (Ours)GoEmotions90.70.900.910.910.85
HAGF (Ours)SemEval89.50.890.880.890.83
HAGF (Ours)ISEAR91.20.910.900.910.86

The proposed HAGF consistently outperforms all baselines by an average margin of 2 to 3 F1 points across datasets. This demonstrates the benefit of jointly modeling emotion and sentiment hierarchically rather than treating them as independent tasks. Performance improvements are most pronounced on GoEmotions, where complex sentence structures require context-level refinement via the Gating Mechanism.

5.2. Ablation Study

To evaluate the contribution of individual components, an ablation study was conducted on GoEmotions (Table 2). Each model variant removes one component of HAGF while keeping the others fixed.

Table 2: Ablation study on GoEmotions dataset.

Model VariantAcc (%)F1ΔF1Observation
HAGF (full model)90.70.91––
w/o Gating Mechanism (GM)88.10.88-0.03Polarity reversal misclassified (e.g., “good for nothing”).
w/o Hierarchical Bridge (HB)87.50.87-0.04Lost hierarchical coherence between word and sentence levels.
w/o Dual Attention86.90.86-0.05Context cues missed; overemphasis on last tokens.
Single Task (only Sentiment)88.30.87-0.04Weaker emotion awareness.
Single Task (only Emotion)87.70.87-0.04Reduced sentiment consistency.

The largest drop (-5 F1) occurs when dual attention is removed, confirming the importance of multi-level contextual understanding. The gating mechanism also improves classification of negated or sarcastic phrases, as shown in the next subsection.

5.3. Qualitative Analysis

To better understand the behavior of attention and gating components, we visualize attention weights and gate activations for representative examples (Figure 5). In the example sentence “The movie was good for nothing”, attention correctly emphasizes “good” and “nothing,” but the gating mechanism downweights “good,” resulting in a negative final prediction. This demonstrates HAGF’s capacity to handle polarity reversals and mixed emotional tone, limitations often seen in standard transformer models.

Figure 5: attention visualization heatmap over the words 'his', 'blatant', 'made', 'me' and 'furious', with attention score scale
Figure 5: Attention and gating visualization for sample sentences. Red highlights indicate high gate activation, blue low activation. The gating layer suppresses misleading positive cues in sarcastic or negated contexts.

5.4. Cross-Dataset Generalization

To test model robustness, we evaluated HAGF on cross-domain settings where the model was trained on GoEmotions and tested on SemEval. Despite the shift in writing style (Reddit → Twitter), HAGF retained 87.2 F1, outperforming all baselines by at least 2 points. This confirms the generalization ability of hierarchical and gated representations in multilingual, noisy social text.

5.5. Discussion

The performance gains of HAGF primarily stem from three synergistic factors:

  1. Hierarchical Attention: Preserves contextual dependency at both word and sentence levels (Yang et al., 2016).
  2. Gating Mechanism: Learns to dynamically attenuate or amplify features based on emotional polarity (Cho et al., 2014; Wu et al., 2020).
  3. Joint Multi-Task Learning: Enables shared emotional–sentimental representations, reducing overfitting (Caruana, 1997; Zhang et al., 2020).

Overall, the results confirm that emotion awareness improves sentiment prediction accuracy and interpretability, validating the motivation of this research.

6. Interpretability and Visualization Analysis

Interpretability is essential in affective computing to understand how deep learning models associate linguistic cues with emotional polarity and intensity. To ensure transparency in our Hierarchical Attention–Gated Framework (HAGF), we visualize both attention weights and gating activations to interpret how the model arrives at its joint sentiment–emotion predictions.

6.1. Attention Visualization

The attention mechanism highlights salient tokens that most influence the final prediction. Figure 5 illustrates an example where the sentence “The movie was good for nothing” is processed. While the attention layer initially assigns high weights to both “good” and “nothing,” the Gating Mechanism (GM) refines this by suppressing the misleading positive cue from “good” and amplifying the negative emphasis on “nothing.” This demonstrates how hierarchical attention provides contextual understanding while gating ensures semantic correction.

The color-coded visualization shows:

  • Dark intensity: higher attention or gate activation.
  • Light intensity: suppressed contribution or neutral effect.

Visualization of attention and gating activations for the sentence “The movie was good for nothing.” Dark shading indicates strong emotional or sentiment influence, while light indicates reduced activation due to gating correction. To better understand the behavior of attention and gating components, we visualize attention weights and gate activations for representative examples, as shown in Figure 5, following interpretability conventions from (Ribeiro et al., 2016; Poria et al., 2019).

6.2. Gate Dynamics and Polarity Control

To further analyze gating dynamics, we track the average gate activations across multiple examples. For sentences with negation (“not good,” “never happy”) or sarcasm (“great job ruining it”), the reset gate (rtr_t) shows a sharp increase, effectively reducing the contribution of misleading positive tokens. Conversely, for strongly emotional phrases (“deeply hurt,” “absolutely love”), the input gate (iti_t) dominates, strengthening high-intensity features.

This selective modulation confirms the intended behavior of the Gating Mechanism: it acts as an adaptive controller that corrects feature polarity in real time. Such interpretability is particularly valuable for explainable AI systems, allowing developers to trace which words or phrases influenced the final emotional inference.

6.3. Cross-sample Interpretability

Beyond single examples, aggregated visualization across samples reveals consistent linguistic patterns. Positive predictions correlate with emotionally reinforcing words such as “amazing,” “beautiful,” and “delightful,” while negative sentiment predictions correspond to “disappointed,” “hate,” and “terrible.” Interestingly, mixed-emotion sentences like “sad but hopeful” exhibit overlapping gate activations, reflecting co-existing emotional states.

We also observed that multilingual samples (e.g., Hindi-English code-mixed text) retained clear activation structures, validating the multilingual robustness of XLM-RoBERTa embeddings (Conneau et al., 2020). This suggests that HAGF not only performs well quantitatively but also provides linguistically interpretable reasoning across diverse languages and contexts.

6.4. Comparison with Transformer Interpretability

Unlike traditional attention-only models such as BERT and RoBERTa, which highlight broad token salience without explicit emotional correction (Liu et al., 2019), HAGF’s gating layer offers finer control over how positive and negative cues interact. This results in clearer visualization maps and better alignment with human perception, aligning with findings from emotion-specific interpretability frameworks such as (Poria et al., 2019; Wu et al., 2020).

Overall, the interpretability analysis confirms that the proposed hierarchical–gated mechanism not only enhances classification performance but also improves model transparency, a key step toward trustworthy affective AI.

7. Limitations and Future Scope

While the proposed Hierarchical Attention–Gated Framework (HAGF) demonstrates strong quantitative performance and interpretability, several limitations remain that open directions for future exploration.

7.1. Limitations

  • Dependence on Textual Context: The current model relies solely on textual input. Emotional perception in real-world settings often depends on multimodal cues such as tone, facial expression, and gesture. Consequently, purely text-based inference may misinterpret sarcasm or humor where lexical indicators are ambiguous (Poria et al., 2019).
  • Fixed Vocabulary and Domain Adaptation: Although XLM-RoBERTa provides multilingual robustness (Conneau et al., 2020), it may struggle with domain-specific jargon or evolving internet slang. Continuous domain adaptation or online learning strategies could help maintain contextual relevance.
  • Computational Overhead: The hierarchical attention and gating layers add computational complexity during both training and inference. While acceptable for research, this may limit deployment in resource-constrained environments such as mobile conversational agents (Rawal, 2025).
  • Limited Emotional Granularity: Current experiments reduce emotion categories to six primary classes. This coarse labeling can overlook nuanced states (e.g., nostalgia, empathy, frustration) present in natural discourse.

7.2. Future Scope

  • Multimodal Extension: Integrating visual and acoustic modalities with textual features can enhance emotional understanding. Future versions of HAGF could adopt transformer-based multimodal fusion (e.g., CLIP-style encoders or audio–text alignment) for holistic sentiment perception.
  • Dynamic Graph Integration: Extending the framework with graph-based relational reasoning, similar to GraphRAG or knowledge graph traversal, can model inter-sentence dependencies and emotion propagation across dialogue turns.
  • Real-time Conversational Deployment: Building on our prior work in intelligent conversational agents (Rawal, 2025), HAGF can be integrated into dialogue systems that adjust responses dynamically based on detected sentiment–emotion states.
  • Human-in-the-loop Explainability: Future research should explore interactive visualization interfaces where human annotators can validate or refine model attention and gating outputs, aligning machine inference more closely with human interpretation (Ribeiro et al., 2016).
  • Low-resource and Cross-lingual Adaptation: Training variants using adapter-based fine-tuning or LoRA (Low-Rank Adaptation) may reduce resource requirements while preserving multilingual performance, enabling deployment across underrepresented languages.

7.3. Summary

In summary, while HAGF achieves notable accuracy and interpretability improvements, it serves as a foundational step toward building emotion-aware, explainable conversational AI systems. The next phase of this research aims to bridge multimodal understanding, real-time reasoning, and transparent human–AI collaboration.

8. Conclusion and Future Directions

This study introduced a Hierarchical Attention–Gated Framework (HAGF) for joint sentiment and emotion modeling. Unlike traditional sentiment classifiers or isolated emotion recognizers, the proposed model integrates dual-level attention, a Hierarchical Bridge (HB), and a Gating Mechanism (GM) that dynamically refines contextual cues. By combining these components with multilingual transformer embeddings from XLM-RoBERTa (Conneau et al., 2020) and sequential modeling through BiLSTM (Hochreiter and Schmidhuber, 1997), the framework captures both fine-grained emotional nuance and high-level sentiment polarity.

Experimental evaluations on benchmark datasets such as SemEval-2018, GoEmotions, and ISEAR demonstrated that HAGF consistently outperforms baseline models including BERT, RoBERTa, and hierarchical attention networks. Beyond numerical accuracy, visualization analyses confirmed that the proposed gating mechanism effectively moderates misleading cues (e.g., polarity reversals in “good for nothing”) while maintaining interpretability through attention heatmaps.

The research contributes to advancing explainable affective computing by bridging linguistic hierarchy and adaptive gating in a single end-to-end architecture. Furthermore, the qualitative interpretability and cross-domain generalization indicate that HAGF is a strong foundation for real-world emotion-aware systems such as chatbots, customer feedback platforms, and digital well-being tools.

As an extension of our earlier work on conversational AI modeling (Rawal, 2025), this framework advances the vision of interactive, transparent, and emotionally intelligent dialogue systems. Future work will expand on multimodal integration (text, audio, and vision), graph-based relational reasoning, and lightweight deployment via adapter or quantized transformer layers, toward practical, ethical, and human-aligned affective AI.

Acknowledgment

The authors thank the IndiaNIC Research and Development Division for technical guidance and computational resources supporting this study. This research was partially inspired by the author’s ongoing doctoral work on adaptive sentiment and interaction modeling for conversational agents.

References

  • Buechel, S. and Hahn, U. (2018). Modeling empathy and distress in reaction to news stories. In Proceedings of the 56th Annual Meeting of the Association for Computational Linguistics (ACL), pages 464–475.
  • Caruana, R. (1997). Multitask learning. Machine Learning, 28(1):41–75.
  • Cho, K., Van Merriënboer, B., Gulcehre, C., Bahdanau, D., Bougares, F., Schwenk, H., and Bengio, Y. (2014). Learning phrase representations using RNN encoder-decoder for statistical machine translation. In EMNLP, pages 1724–1734.
  • Conneau, A., Khandelwal, K., Goyal, N., Chaudhary, V., Wenzek, G., Guzmán, F., Grave, E., Ott, M., Zettlemoyer, L., and Stoyanov, V. (2020). Unsupervised cross-lingual representation learning at scale. ACL.
  • Demszky, D., Movshovitz-Attias, D., Ko, J., Cowen, A., Nemade, G., and Ravi, S. (2020). GoEmotions: A dataset of fine-grained emotions. In Proceedings of the 58th Annual Meeting of the Association for Computational Linguistics (ACL), pages 4040–4054.
  • Devlin, J., Chang, M.-W., Lee, K., and Toutanova, K. (2019). BERT: Pre-training of deep bidirectional transformers for language understanding. NAACL-HLT.
  • Hochreiter, S. and Schmidhuber, J. (1997). Long short-term memory. Neural Computation, 9(8):1735–1780.
  • Kim, Y. (2014). Convolutional neural networks for sentence classification. In Proceedings of the 2014 Conference on Empirical Methods in Natural Language Processing (EMNLP), pages 1746–1751. ACL.
  • Liu, Y., Ott, M., Goyal, N., Du, J., Joshi, M., Chen, D., Levy, O., Lewis, M., Zettlemoyer, L., and Stoyanov, V. (2019). RoBERTa: A robustly optimized BERT pretraining approach. arXiv preprint arXiv:1907.11692.
  • Loshchilov, I. and Hutter, F. (2019). Decoupled weight decay regularization. In International Conference on Learning Representations (ICLR).
  • Ma, S., Zhang, D., Zhou, M., and Li, H. (2018). Hierarchical attention mechanism for neural machine translation. arXiv preprint arXiv:1808.08779.
  • Medhat, W., Hassan, A., and Korashy, H. (2014). Sentiment analysis algorithms and applications: A survey. Ain Shams Engineering Journal, 5(4):1093–1113.
  • Mohammad, S. M., Bravo-Marquez, F., Salameh, M., and Kiritchenko, S. (2018). SemEval-2018 task 1: Affect in tweets. In Proceedings of the 12th International Workshop on Semantic Evaluation (SemEval-2018), pages 1–17.
  • Pang, B. and Lee, L. (2008). Opinion mining and sentiment analysis. Foundations and Trends in Information Retrieval, 2(1-2):1–135.
  • Poria, S., Hazarika, D., Majumder, N., and Mihalcea, R. (2019). Emotion recognition in conversation: Research challenges, datasets, and recent advances. IEEE Access, 7:100943–100953.
  • Qian, T., Hong, Z., Ouyang, C., Guo, Y., Guo, Q., and Guo, P. (2020). Hierarchical attention networks for information extraction from unstructured clinical reports. IEEE Access, 8:74263–74271.
  • Rawal, M. (2025). Developing a custom machine learning model with intelligent conversational agents. Computers & Research Development (JournalCRD), 25(2):121–130.
  • Ribeiro, M. T., Singh, S., and Guestrin, C. (2016). “Why should I trust you?”: Explaining the predictions of any classifier. In Proceedings of the 22nd ACM SIGKDD International Conference on Knowledge Discovery and Data Mining (KDD), pages 1135–1144. ACM.
  • Shen, T., Zhou, T., Long, G., Jiang, J., Zhang, S., and Wang, C. (2018). DiSAN: Directional self-attention network for RNN/CNN-free language understanding. AAAI.
  • Tang, D., Qin, B., and Liu, T. (2015). Document modeling with gated recurrent neural network for sentiment classification. In Proceedings of the 2015 Conference on Empirical Methods in Natural Language Processing, pages 1422–1432.
  • Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, Ł., and Polosukhin, I. (2017). Attention is all you need. In Advances in Neural Information Processing Systems (NeurIPS), pages 5998–6008.
  • Wu, J., Yu, L., and Zhang, J. (2020). Enhanced gating mechanisms for deep neural networks. IEEE Transactions on Neural Networks and Learning Systems.
  • Yang, Z., Yang, D., Dyer, C., He, X., Smola, A., and Hovy, E. (2016). Hierarchical attention networks for document classification. In Proceedings of the 2016 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, pages 1480–1489.
  • Zhang, J., Liu, H., Li, Y., and Luo, B. (2020). Multi-task learning for emotion recognition and sentiment analysis. Neurocomputing, 403:198–209.

How this relates to the dissertation

The dissertation tests components like these under controlled ablations, one at a time and across several random seeds. In those experiments an adaptive gate collapsed to a fixed routing policy and was removed, and the best model kept a two-branch context and token design with a fusion bridge.

The figures are not directly comparable. This paper reports accuracy and macro F1 on six emotion classes across three datasets. The dissertation reports emotion and sentiment F1 on a translated seven-class and three-class dataset in three languages.

Cite this

Mihir Raval. 2025. A Hierarchical Attention–Gated Framework for Joint Emotion and Sentiment Modeling. Computer Research and Development 25(10), 276-297. DOI: 10.5281/zenodo.17610460. Licence: CC BY 4.0.

@article{raval2025hierarchical,
  title   = {A Hierarchical Attention–Gated Framework for Joint Emotion and Sentiment Modeling},
  author  = {Raval, Mihir},
  journal = {Computer Research and Development},
  year    = {2025},
  volume  = {25},
  number  = {10},
  pages   = {276--297},
  issn    = {1000-1239},
  doi     = {10.5281/zenodo.17610460},
  url     = {https://doi.org/10.5281/zenodo.17610460}
}