An Explainable and Robust BiLSTM-Attention Framework for Cross-Domain Social Media Sentiment Analysis with Statistical Validation ()
1. Introduction
In the past decade, social media platforms have undergone rapid change, altering how public opinion is expressed, shared, and examined. Social media sites like Twitter, Facebook, and Reddit produce large amounts of user-generated textual data that capture opinions about political policies, social movements, and economic issues. The ability to detect meaningful sentiment patterns in this unstructured data is a valuable task in natural language processing (NLP) and is important for many social and business applications, such as public opinion monitoring, election analysis, crisis management, and market intelligence [1] [2]. Over the past few years, deep learning has greatly improved sentiment analysis systems. Architectures based on transformers and recurrent neural networks are also shown to have a better ability to model context than traditional machine learning approaches [3] [4]. Bidirectional Long Short-Term Memory (BiLSTM) networks remain popular thanks to their ability to support sequence-to-sequence learning with both past and future context [5]. These models can also be used in conjunction with attention mechanisms to highlight key terms in a sentence, thereby enhancing predictive accuracy and providing some interpretability [6]. Although significant progress has been made in practical sentiment modeling, several important problems remain unsolved. First, many of the successful models are black-box models. For sensitive applications such as political opinion analysis, the increase in predictive accuracy has been limited by a lack of interpretability, which reduces confidence and use [7]. Recently, Explainable Artificial Intelligence (XAI) techniques have come to the fore as a way of obtaining feature-level explanations for deep learning models, such as Shapley Additive explanations (SHAP) [8]. Several sentiment studies, however, report interpretability only qualitatively, without incorporating systematic explainability analysis into the evaluation framework. Secondly, cross-domain generalization remains a key issue. The models trained on one set of data are found to have a significant drop in performance when tested on the other set, due to differences in vocabulary, domain semantics, and context [9]. The domain shift problem is particularly important for social media data because it can involve differences in language style and/or topic distribution across platforms or over time. Transformer-based models, such as BERT, have been shown to have strong generalization capabilities, yet numerous sentiment analysis studies lack cross-dataset validation [10]. If the domain shift conditions are more stringent, it is essential to assess real-world applicability. Thirdly, noise in the input is an important feature for social media analytics. Many times, user-generated text is not polished and not consistent, using slang, misspellings, and incorrect grammar. Recently, we have shown that predictions made by deep NN models are unstable with respect to small text perturbations [11]. An effective sentiment system in controlled lexical noise may be able to give feedback on the reliability of a real-world system. Also, the emphasis is not placed on model validation. Various studies have been published whose conclusions are based upon accuracy or F1 score without any hypothesis testing or confidence intervals to validate the statistical significance of the results [12]. Bootstrap-based confidence intervals and significance tests can give more empirical evidence and help to avoid overinterpretation of differences in performance. Beyond its predictive aspect, the usefulness of sentiment analysis has also attracted research attention. Several recent studies have investigated how social media sentiment and other real-world measures, such as stock markets, public health statistics, and election polls, are related [13] [14]. Promising correlations have been reported, but it has been difficult to consistently integrate sentiment trends with external polling data to obtain statistically robust results.
To address these research gaps, this research proposes to apply the explainable and robust BiLSTM-Attention framework to sentiment analysis on social media. To achieve this, the proposed framework integrates interpretability, cross-domain evaluation, robustness testing, and statistical validation in a single experimental design, rather than those that are only accuracy-driven. The authors specifically make the following contributions:
1) We proposed a BiLSTM-Attention architecture that captures contextual dependencies between words, without requiring the sacrifice of its word-level interpretability.
2) We have integrated an SHAP-based global feature attribution to estimate lexical importance.
3) External dataset validation is used to test cross-domain generalization.
4) We have assessed robustness using controlled lexical perturbation.
5) To provide empirical validity, bootstrap-based estimates of confidence intervals and test statistics have been carried out.
6) We are examining the relationship between the predicted sentiment trends and the external polling indicators to measure the significance of real-world relevance.
In real-world dynamic social contexts, interpretability, robustness, and statistical reliability are important features required for sentiment analysis, which the proposed model aims to provide.
2. Related Works
In the past few years, there has been considerable academic interest in how social media analytics, machine learning (ML), and explainable artificial intelligence (XAI) can be used for election forecasting. Recent studies (within the time frame of 2020-2025) have reflected a shift away from simple tweet-counting approaches and towards model interpretability by employing deep learning, cross-domain validation, etc., due to the enhanced penetration of digital platforms in political communication. This paper provides a systematic review of the key developments in four key streams: 1) social media-based election forecasting; 2) deep learning architectures for sentiment modelling; 3) explainable AI in political prediction, and finally, 4) limitations and future directions.
2.1. Social Media-Based Election Forecasting
The recent studies confirm that the activity of social media is indicative of collective political engagement dynamics-albeit to differing levels of predictive accuracy (Table 1). Chaudhry et al. (2021) used supervised sentiment classification to examine U.S. Election 2020 Twitter data and reported a moderate correlation with polling trends [15]. Using sentiment polarity and volume measures, Brito and Adeodato (2020) [16] applied ML methods to Brazilian and USA elections to predict vote share distributions. Chauhan et al. The second is the attention to temporal sentiment aggregation towards now-casting electoral changes [17]. Recent work by Upadhyay et al. (2023) introduced hybrid ML pipelines for political mining at scale on Twitter, where classification robustness is achieved by traversing a noisy text background [18]. However, most of these studies rely on a single platform dataset and do not validate cross-domain generalization.
Table 1. Recent social media-based election prediction studies.
Ref |
Authors |
Year |
Dataset |
Method |
Key Contribution |
[15] |
Chaudhry et al. |
2021 |
US Election 2020 |
SVM, NB |
Sentiment-based election prediction |
[16] |
Brito & Adeodato |
2020 |
Brazil & US |
ML models |
Multi-country validation |
[17] |
Chauhan et al. |
2021 |
Twitter |
Sentiment aggregation |
Temporal nowcasting |
[18] |
Upadhyay et al. |
2023 |
Multi-Platform |
Hybrid ML |
Improved noisy-text handling |
While this work shows the possibility of predicting elections based on sentiment, it has a number of methodological limitations, including a lack of methodological interpretability, statistical validation, and robustness to domain shifts.
2.2. Deep Learning Architectures for Political Sentiment Analysis
Since 2020, it has been shown that for building contextual sentiment, DL models, particularly LSTM, BiLSTM, and transformer-based models, have outperformed other methods [1]. Chaudhry et al. TSKNN (15), LSTM, and F1 scores for the USA election are higher than those of classical ML classifiers. This was applied to Political Hate Speech detection by Shakil and Alam (2022) only at the interpretable layers [19]. Generally, comparative evaluations of BiLSTMs indicate that these models outperform unidirectional LSTMs [20] by simultaneously capturing bidirectional context in a task-aware manner.
Also, the robustness to adversarial noise was considered in some recent papers. The adversarial perturbation evaluation framework by Morris et al. [11] show that NLP models are not robust against lexical noise. However, systematic robustness testing remains absent from election forecasting.
Interpretability and statistical reliability remain inadequately addressed, even though performance has improved (Table 2).
Table 2. Deep learning models in political sentiment analysis.
Ref |
Model |
Dataset Type |
Reported F1 |
Robustness Tested |
Explain Ability |
[15] |
LSTM |
Election tweets |
0.84 |
No |
No |
[19] |
CNN + LSTM |
Political speech |
0.87 |
Partial |
Limited |
[20] |
BiLSTM |
Multi-topic sentiment |
0.89 |
No |
No |
[11] |
Transformer-Based |
Adversarial NLP |
0.91 |
Yes |
No |
2.3. XAI for Political and Sentiment Modeling
As the demand for transparency in automated decision systems increases, Explainable AI has gained more prominence. SHAP and LIME have become leading model-agnostic explanation techniques over the past 5 years.
Linardatos et al. In (2020) [21], a comprehensive review of XAI techniques is provided; the author emphasizes trust-sensitive domains. Pavitha et al. SHAP was developed and used for sentiment analysis, with the global feature interpretation improved in 2022 [22]. In geospatial prediction tasks, SHAP-based attribution (Abdollahi & Pradhan, 2023)—a model-agnostic approach that this paper will rely on, given its reliability with deep models [23].
Nevertheless, little has been done on election prediction studies that incorporate XAI into deep sequential architectures. Most either:
Table 3. XAI applications in prediction models.
Ref |
XAI Method |
Base Model |
Domain |
Global Importance |
Statistical Validation |
[21] |
SHAP/LIME Review |
Various |
General AI |
Yes |
No |
[22] |
SHAP |
Sentiment classifier |
NLP |
Yes |
No |
[23] |
SHAP |
DL Model |
Geospatial |
Yes |
No |
This shows a strong need to integrate SHAP with deep sequential models for election forecasting within statistically validated frameworks (Table 3).
2.4. Limitations in Recent Studies
While deep learning and EAI methods have been well integrated, there are some methodological gaps that have been identified in the literature, even after great advances spearheaded by the integration of these methods in the field of sentiment analysis and social media-based electoral prediction. A key challenge in many studies carried out in the years 2020-2025 is that most studies are geared toward the evaluation of in-domain predictive accuracy instead of the appropriate assessment of model generalization under domain-shift conditions. Most recent election forecasting frameworks are based on single-event datasets, e.g., one election in a country, or one social media platform [15]-[18]. While most of these studies give good performance metrics, they seldom consider the transferability to other datasets. In recent domain adaptation research, it has been demonstrated that models learned on one dataset are limited in cross-dataset transferability to models trained on another dataset, due to vocabulary differences, contextual differences, and political discourse changes [24]. This is a well-known problem that isn’t always resolved in the sentiment-influenced election-prediction literature.
The other significant limitation is related to robustness to input noise. Social media-written text is informal by nature, laden with abbreviations, spelling mistakes, sarcasm, and partial grammatical structures. Adversarial robustness has been of interest in general NLP research [11], but only a handful of sentiment analysis papers have assessed performance stability under controlled lexical perturbations [22]. This finding raises questions about how these models would fare in the real-world political environment, as no systematic robustness testing is performed.
The challenge of interpretability has also been partially addressed. In recent years, explainable AI techniques such as SHAP and LIME have been successfully integrated into some sentiment analysis tasks [21] [22], but only a few deep sequential architectures exist, including those used in election-related studies. For instance, in most cases, explainability is provided qualitatively or applies to other model types. Feature attribution at scale and deep recurrent architectures are still relatively under-explored in the field of political sentiment modelling.
In addition, performance metrics are often not statistically well-validated in the literature. The majority of research studies reported in the literature use only one, and, in a sense, biased measure of accuracy, namely the F1 score, without any interval estimation or hypothesis testing. Bootstrap-based confidence intervals or statistical testing have been pointed out as a shortcoming of NLP evaluation research from a methodological perspective.
Finally, while numerous works have attempted to relate social media sentiment to polling data or election results [24], statistical correlation analyses and temporal alignment are often superficial. But the lack of a spurious correlation between the aggregated sentiment signals and real-world polling indicators demands a rigorous validation (Table 4).
Table 4. Comparative limitations of recent studies.
Study Type |
Cross-Domain |
Robustness |
SHAP |
CI/Bootstrap |
Polling Correlation |
Traditional ML |
No |
No |
No |
No |
Partial |
Deep LSTM |
No |
Limited |
No |
No |
No |
Transformer-Based |
Partial |
Yes |
Limited |
No |
No |
Hybrid XAI Models |
No |
No |
Yes |
No |
Limited |
2.5. Research Gap and Motivation
Recent literature has highlighted that interpretability and robustness, statistical validation, and beyond-domain generalization in sentiment-based election modeling are yet to find a methodological balance. Deep neural architectures such as LSTMs, BiLSTMs, and transformer-based models have made improvements in contextual representation in recent years, but most of the studies have been directed only toward optimizing the dataset-specific predictive accuracy.
A few recent works have combined bidirectional contextual modeling with attention mechanisms and formal explainable AI (XAI) methods into the same set of evaluations, such as SHAP. Even less frequently do they include statistical reliability checks of the form of bootstrapped confidence intervals, or hypothesis tests that test differences in performance across domains. Consequently, it is not known how many of the models in the literature are reproducible and empirical.
Finally, not much evidence of cross-dataset validation of political sentiment. Without evaluating how the model performs on other, more abstract, external indicators, it is hard to tell if the model captures the general characteristics of the data set or if it is simply modeling the details of its data set. This is particularly important in election forecasting because the language in political communication has been found to vary significantly from place to place and time to time.
The other aspect that has not been studied much is robustness to textual noise. Very few election sentiment studies explicitly report a reduction in the performance of a model in realistic noise settings, although adversarial NLP studies have demonstrated that neural models are very sensitive to small perturbations. It is important to evaluate the robustness for real-world applications in a dynamic media context like social media.
Finally, there are numerous studies that have explored how sentiment in social media relates to the polls, but few have explored sentiment predictive modeling, statistical validation, and explainability all in one. To the best of our knowledge, there is no comprehensive approach in the recent literature that simultaneously offers good model interpretability, cross-domain validation, robustness analysis, and statistically valid correlation assessment. To tackle these issues, the current research presents an interpretable and statistically sound BiLSTM-Attention model that systematically integrates:
Contextual bidirectional modeling;
Attention-based word importance;
Real and sincere person-to-person communications, a cross-dataset evaluation, and a bootstrap confidence interval;
Adaptability to interference, and Correlation of results with outside poll indicators.
This work brings together these elements in a single experimental design to go beyond simply sentiment accuracy to a more interpretable, reliable, and practically usable framework for social media-based public opinion analysis.
3. Methodology
3.1. Overview of the Proposed Framework
The proposed system is an end-to-end interpretable and robust deep learning system for sentiment classification. It starts with systematic pre-processing of raw text data, such as normalization, tokenization, and padding the sequences to prepare the data input. The obtained text is then converted into dense vector representations that encode semantic relations between words. The embeddings are then fed into a Bidirectional Long Short-Term Memory (BiLSTM) network, which can learn the conceptual relationship between the past and future within a sentence. For discriminative ability, an attention mechanism using sentiment information is applied to dynamically weight the tokens, which helps the model focus on the important tokens in the context. Lastly, predictions are made by a sigmoid-activated output layer. SHAP-based analysis of the features is implemented with the aim of interpretability, which measures the global feature importance and is transparent and reliable in real-world deployment scenarios.
To this end, this paper introduces an interpretable deep learning-based sentiment classification framework that integrates (Figure 1):
Text preprocessing and normalization;
Contextual embedding representation;
Bidirectional LSTM modeling;
Attention-based contextual weighting;
SHAP-based global interpretability.
Figure 1. End-to-end pipeline from collecting raw text to prediction and interpretability analysis.
3.2. Dataset Description
The effectiveness, generalizability, and robustness of the proposed framework are evaluated on two benchmark sentiment datasets: one used as the primary in-domain dataset and the other for cross-domain validation.
3.2.1. Primary Dataset (In-Domain)
The main dataset consists of short-text social media posts annotated with positive and negative sentiment classes. Neutral examples were excluded to maintain a binary classification scheme. Then, 6000 samples were reserved for experiments after preprocessing and balancing (Table 5).
Table 5. In-domain dataset statistics.
Property |
Value |
Total Samples |
6000 |
Positive Class |
3000 |
Negative Class |
3000 |
Vocabulary Size |
20,000 |
Maximum Sequence Length |
100 Tokens |
Train/Validation/Test Split |
70%/10%/20% |
The dataset consists of short, informal, and context-rich text, which is appropriate for testing the ability to model context.
3.2.2. Cross-Domain Dataset
A subset of the IMDB movie review dataset was used to evaluate the generalization under domain shift. This dataset is a mix of longer, more formal texts in a review format, rather than social media posts (Table 6).
Table 6. Cross-domain dataset characteristics.
Property |
Value |
Total Samples Used |
2000 |
Positive Reviews |
1000 |
Negative Reviews |
1000 |
Average Review Length |
~230 words |
Domain Difference |
Informal vs. Formal |
This discrepancy in the domain enables robustness and transferability to be assessed.
3.2.3. Dataset Provenance
This study used two publicly available benchmark datasets to evaluate the proposed BiLSTM-Attention framework for sentiment classification and its ability to generalize across different text domains. The primary dataset was Sentiment140, which contains English-language tweets posted between April 6 and May 16, 2009, and is available at http://help.sentiment140.com/home. Each record includes six fields: sentiment label, tweet ID, posting date, query flag, username, and tweet text. In this study, only the sentiment labels and tweet text were used. Sentiment140 relies on distant supervision, where positive and negative sentiments are identified using emoticons rather than manual human annotation. The original labels are 0 for negative, 2 for neutral, and 4 for positive. Since this study focused on binary sentiment classification, neutral tweets were excluded, and the negative and positive labels were converted to 0 and 1, respectively. A balanced sample of 6000 tweets was then selected, consisting of 3000 negative and 3000 positive examples for model development and in-domain evaluation.
To examine the model’s ability to perform on text from a different domain, a subset of 2000 reviews was randomly selected from the publicly available IMDB movie review dataset. This subset included 1000 positive and 1000 negative reviews. Unlike the short and informal messages in Sentiment140, IMDB reviews are generally longer and more structured, with an average length of approximately 230 words. These differences in text length, writing style, and language characteristics made the IMDB dataset suitable for assessing how well the trained model could generalize to an unseen domain. The model was evaluated on this external dataset without any additional fine-tuning, allowing its cross-domain performance to be examined independently of further training on IMDB reviews.
3.2.4. Evaluation Protocol and Data Leakage Prevention
The 6000 selected Sentiment140 tweets were divided into training, validation, and test sets using stratified sampling at a ratio of 70:10:20, resulting in 4200 training samples, 600 validation samples, and 1200 test samples. Stratification was performed according to the sentiment labels to maintain an equal distribution of positive and negative examples across all three subsets. Since the dataset was balanced by design, class weighting was not applied during training. A fixed random seed was used for dataset sampling and splitting to support reproducibility; however, the exact seed value was not documented in the current experimental description. The validation set was used to monitor model performance and guide model selection, while the held-out test set was reserved for final evaluation. The model checkpoint with the best validation performance was retained for testing. The exact validation metric and early-stopping patience were not specified in the available experimental records.
To prevent data leakage, the tokenizer, vocabulary of up to 20,000 words, out-of-vocabulary index, and data-dependent preprocessing configurations were fitted exclusively on the training set. The same fitted tokenizer and preprocessing settings were subsequently applied without modification to the validation set, in-domain test set, and external IMDB dataset. Text was converted into integer sequences and padded or truncated to a maximum length of 100 tokens. The BiLSTM-Attention model was trained using the Adam optimizer with a learning rate of 0.001, a batch size of 32, an embedding dimension of 128, 64 hidden units in each BiLSTM direction, and a dropout rate of 0.3. A sigmoid output layer and binary cross-entropy loss were used for binary sentiment classification. Final in-domain performance was measured using accuracy, precision, recall, and F1-score, with the positive sentiment class treated as the target class for F1-score calculation. Cross-domain generalization was assessed on 2000 IMDB reviews without additional training or fine-tuning. Statistical reliability was evaluated using 1000 bootstrap resamples with replacement to estimate 95% confidence intervals for the F1-score. Robustness to lexical noise was also examined by randomly removing 20% of the input tokens during testing and comparing the results with those obtained from the original inputs.
3.2.5. Data Preprocessing
Social media information is noisy, unstructured, and inconsistent in format. In addition to structured numerical datasets, textual data must be represented numerically in an organized way. To work around this, we used a carefully laid-out series of preprocessing steps to transform natural language texts into fixed-length numerical sequences that can be used to train a neural network. The entire preprocessing chain used in the present study is illustrated in Figure 2.
Figure 2. Dataset preprocessing pipeline.
3.2.6. Text Normalization
The first step in the preprocessing pipeline for text is called text normalization and involves converting the raw text data from its original form into a normalized form prior to extracting features or training a model. Social media text is already noisy, as users often type in a way that differs from the standard. Social media text is already noisy because people often use the text differently than in standard text. These inconsistencies create many instances of different forms of the same semantic concept, which hinders the effectiveness of downstream Natural Language Processing (NLP) models. Thus, the texts were normalized to ensure a uniform representation and to maintain their semantic content from the original texts.
The major task of this study was to normalize the data by converting all alphabetic characters to lowercase. Let a sentence be represented as a sequence of tokens,
, where n is the number of tokens in the sentence. Each token is converted to its normalized version, which is lowercase (token),
.
This makes the normalized sentence
, such that all of the tokens in it have a consistent lexical representation as a result of the original case.
For instance, a tweet like “I love elections” would be normalized to “I Love Elections”. Only the alphabetic characters are converted to lower-case letters, with the punctuation and emojis staying the same. This change will make sure that semantically similar words like “Election”, “ELECTION”, and “election” are classified into the same token, so that the tokenizer does not take them as different vocabulary entries. Mathematically speaking, if (V) is the vocabulary obtained by extracting the tokens from the corpus before normalization, and (V’) is the vocabulary after normalization, the vocabulary is reduced by this process of normalization. A smaller and more regular vocabulary decreases the sparsity of data, makes better word frequency estimation, and yields more consistent vector representations when generating word embeddings.
In addition to a better overall representation of the text in the corpus, normalization helps to improve the consistency of the tokens and the quality of the embedding, makes it easier to extract features from the text, and should make the subsequent machine learning/explainable artificial intelligence models used for election outcome prediction more robust and better able to predict outcomes.
3.2.7. Tokenization and Vocabulary Construction
Tokenization is a crucial preprocessing step in Natural Language Processing (NLP) that converts textual data into a sequence of numerical values that can be processed by deep learning models. Once the text has been normalized (e.g., making it lowercase, removing all unnecessary symbols from the text, and removing redundant spaces), each sentence is split into separate words (tokens). For this study, the Maximum vocabulary Size is 20,000 words, and the Keras Tokenizer was employed in the process of this conversion. The tokenizer traverses the whole corpus during training to count the frequency of all words in the corpus and forms a dictionary of word-to-index. The smaller integers are used for the more common words, and the larger integers for less common words. Consequently, the numbers of the words in the sentence are replaced by the corresponding numbers of the words in the list, and an integer sequence is obtained which preserves the order in which the words appeared in the sentence.
In the example “I love elections”, it becomes the token sequence [1, 45, 202] with the integers 1, 45, and 202 representing the words “I”, “love”, and “elections”, respectively. The indices assigned to words are not semantically meaningful; they are indicative of the relative frequency of the words in the training corpora used. This means that words with higher frequencies get smaller values and words with lower frequencies get larger values, which allows efficient representation of vocabulary and reduces the computational complexity.
The number of unique words in the vocabulary was limited to 20,000 to increase the computational efficiency and to decrease the complexity of the models. The vocabulary of the tokenizer was only the top 20,000 words in the training data. Words not included in this vocabulary will be tagged as out-of-vocabulary (OOV) words and will be represented by a dedicated OOV index during tokenization. This approach will avoid using too many words, save memory, and allow the model to generalize to the most informative words. In summary, tokenization converts the qualitative linguistic data into a structured numerical representation to facilitate the learning of meaningful linguistic, semantic, and contextual patterns by subsequent embedding layers and deep learning architectures from the textual data.
3.2.8. Padding Sequences and Label Encoding
Neural networks require sequences of a fixed length. However, textual inputs vary in length by nature. So padding and truncation were used to make the input dimensions uniform. Maximum Sequence Length: T = 100. If a sequence length is less than 100, then zero padding is applied. And if greater than 100, then truncated to the first 100 tokens.
Mathematically:
Example:
Original token sequence: [1, 45, 202, 17]; After padding: [1, 45, 202, 17, 0, 0, ..., 0].
Padding ensures compatibility with batch processing and matrix-based computation in LSTM layers. Thus, the last input matrix is
, where N = number of samples and 100 = fixed sequence length. Since the task is binary sentiment classification, textual labels were mapped to numeric values.
If the original label is: y ∈ {negative, positive} Encoding function:
This change enables the use of a sigmoid activation method and binary cross-entropy loss in training (Table 7).
Table 7. Label mapping.
Sentiment |
Encoded Value |
Negative |
0 |
Positive |
1 |
3.2.9. Handling Class Imbalance
While the dataset is nearly evenly distributed, there may be small variations in the class distribution, which can lead deep learning models to focus on the majority class, such as in binary sentiment classification. To tackle this risk, a class-weighted learning method was used. No changes were made to the distribution of the data (oversampling or undersampling), but the contribution of each class to the loss was switched to inverse-frequency weighting. The class weight was determined for class C as:
Class c width, denoted as wc, is the ratio of N/2Nc, where N is the total number of samples, and Nc is the number of samples belonging to class c. These weights are incorporated with the binary cross-entropy loss function; the loss function for samples from minority classes is relatively increased. It doesn’t bias the model, preserves data integrity, gives a stable recall, and preserves the overall F1-score balance of the model.
3.3. Feature Representation
Embedding Layer
A critical stage in going from a discrete sequence of words to a meaningful numeric vector that can be used by a deep neural network is feature representation. Each word in the text is tokenized and uses machine learning models to determine a continuous dense vector space, called an embedding layer, to represent each word. Formally, an embedding matrix
is learned for a vocabulary of size |V|, where d is the embedding dimension (set to 128 in this study). For each token index
, the corresponding encoding vector is calculated as
.
Contrary to one-hot encoding, embeddings create dense vectors with low dimensionality, representing semantic similarity between words. Words that are used in similar contexts will be close together in the embedding space. This helps the model to be more generalizable, especially with variations in sentiment expression. The embedding matrix is randomly initialized for each training and updated by backpropagation during training, thus allowing it to adjust to the sentiment classification task. Contextual learning occurs over informative continuous feature representations, not over isolated symbolic tokens. Thus, the embedding layer acts as a semantic basis for the subsequent Bidirectional LSTM.
3.4. Bidirectional LSTM Architecture
The Bidirectional Long Short-Term Memory (BiLSTM) architecture is employed to capture contextual dependencies from both past and future directions within a sentence. Traditional recurrent neural networks (RNNs) are susceptible to vanishing gradients and have short-term memory. LSTM overcomes this limitation by incorporating gated mechanisms. Controlled input, forget, and output gates for the flow of information and relevant context over long sequences (Figure 3).
Figure 3. Bidirectional LSTM to capture the context in both directions.
In the proposed model, each input sentence is first transformed into embedding vectors et ∈ R128. These embeddings are then processed by two parallel LSTM layers. The forward LSTM computes hidden states sequentially from left to right:
While the backward LSTM processes the sequence in reverse order:
The final contextual representation for each time step is the concatenation of both hidden states:
The bidirectional structure allows the model to understand sentiment words by taking into account the surrounding context in both directions. For example, negations such as “not good” require a future context to correctly interpret polarity. BiLSTM combines both forward and backward dependencies, yielding a richer semantic representation that enhances the robustness and contextual sensitivity of the classification.
3.5. Attention Mechanism
The BiLSTM layer captures the bidirectional context dependencies of the input sequence, but it gives equal weight to all the tokens when generating the final representation, which may weaken the effect of sentiment-bearing words. To address this problem, we propose an attention mechanism that automatically learns the weights of each token based on the importance of the token to the entire sentiment classification task. Specifically, for each BiLSTM hidden state ht, we project it with a trainable transformation and then pass it through a non-linear activation function to get an intermediate representation
. Then, a softmax operation is applied over all time steps to get normalized attention weights.
, which determines how much each token contributes to the sequence. The final sentence representation sss is calculated as the weighted sum of hidden states,
. This mechanism enables the model to focus on important sentiment-bearing tokens, such as opinion words, hashtags, or words expressing positive or negative polarity, and suppress less important or neutral words. Furthermore, attention allows for interpretability, allowing visualization of word importance in single predictions, which leads to a higher level of model transparency for downstream explainability analysis, such as SHAP-based global feature attribution (Figure 4).
3.6. Output Layer and Loss Function
The last phase in the proposed BiLSTM-Attention model is the output layer that maps the sentence representation with richer context into a probability score for
Figure 4. The attention distribution on important sentiment tokens.
binary sentiment classification. The bidirectional LSTM extracts the sequential dependencies, and the attention mechanism aggregates the contributions of each token into a fixed-length sentence vector sss. The sentence vector sss is then fed to a fully connected dense layer. The dense layer applies a linear transformation (with weight matrix Wo and bias vector bo) to generate a scalar value for each input sequence. We use the sigmoid activation function to transform this scalar into a probability in the range [0, 1] as given by
. The output
is the model’s estimate of the probability that the input sequence has a positive sentiment.
To optimize our model, we measure the difference between predicted probabilities and true labels using the binary cross-entropy loss function. The loss is defined as
, where
is the true label. The binary cross-entropy generates punishment for wrong predictions that are made with high confidence, but not for the wrong predictions that are made with a low level of confidence. Class weights are included in the loss to balance out any imbalance of positive and negative samples. This architecture not only allows the network to learn the accurate sentiment but also to learn calibrated and interpretable probability scores, building a solid foundation for further explainability and statistical analysis.
3.7. SHAP-Based Interpretability
Despite the high predictive performance of deep learning models like BiLSTM-Attention, they are often regarded as “black-box” models, which limits the transparency and trust of their predictions. To address this, we integrated SHAP (SHapley Additive exPlanations) analysis in our framework. SHAP is a model-agnostic interpretability technique that assigns each feature (in our case, each token in a sentence) a contribution value for how much it contributed to the model’s prediction. More specifically, given a prediction, the SHAP value ϕi of a feature iii is the average marginal contribution of that feature to all possible subsets of input features. The approach is based on cooperative game theory to fairly assign importance to features. The global feature importance ranking is then obtained by averaging the absolute SHAP values across all samples, which highlights the words that are consistently affecting the sentiment classification results.
For example, in our social media dataset, tokens like “great”, “worst,” and “love” had the highest SHAP scores, which imply strong positive or negative contributions. The SHAP analysis not only justifies the attention mechanism by the alignment between the attention weights and the influential tokens, but also provides quantitative evidence for the interpretability of the model. Table 8 gives a summary of the global feature importance, and Figure 5 visualizes these values by plotting the mean absolute SHAP values for the top 20 contributing tokens. The interpretability of this model is important for applications such as political opinion analysis and election forecasting because it allows researchers and stakeholders to understand which textual cues influence the predictions, thus increasing the transparency and reliability of the model.
3.8. Model Configuration
The BiLSTM-Attention ensemble model was specifically fine-tuned to ensure a good trade-off between predictive power, computational efficiency, and interpretability.
Table 8. Top 10 tokens by mean absolute SHAP value.
Rank |
Token |
Mean |
SHAP Value |
1 |
great |
0.145 |
Positive |
2 |
love |
0.132 |
Positive |
3 |
worst |
0.128 |
Negative |
4 |
amazing |
0.120 |
Positive |
5 |
hate |
0.115 |
Negative |
6 |
best |
0.110 |
Positive |
7 |
terrible |
0.107 |
Negative |
8 |
support |
0.105 |
Positive |
9 |
fail |
0.102 |
Negative |
10 |
enjoy |
0.100 |
Positive |
Figure 5. Global token importance derived using SHAP interpretability analysis.
The Embeddings Layer projects each input token to a 128-dimensional vector, which is semantically rich enough but not too computationally expensive. These learned embeddings generate domain-specific overlapping lexical patterns. The main idea of this architecture is that it is based on a bidirectional LSTM with 64 hidden units in both directions, meaning that the model can remember the past and the future of each sequence. Being bidirectional means that for each token, the contribution of the sentiment is affected by the complete context of the sentence. This is important given that in short and informal social media posts, the polarity can change depending on the previous or next word.
Lastly, a dropout of 0.3 was added after BiLSTM Lastly, a dropout of 0.3 was added after BiLSTM layers to avoid overfitting. This type of regularization guarantees that the network can generalize well to unseen data and to cross-domain evaluations. The attention mechanism is dynamically learned, as the model automatically gives attention to words that carry the sentiment, which makes the model more interpretable. This final dense layer, using a sigmoid, returns one for the class of positive sentiment. The model constructed was trained using the Adam optimizer with a learning rate = 0.001 and a batch size = 32 in 5 - 10 epochs, empirically chosen to optimize convergence speed and stability (Table 9).
4. Results and Discussion
4.1. Overall Classification Performance
The BiLSTM-Attention framework proposed predicts accurately on the in-domain
Table 9. Model hyperparameters and rationale.
Component |
Parameter |
Value |
Justification |
Embedding |
Dimension |
128 |
Sufficient semantic richness for social media text |
BiLSTM |
Units per direction |
64 |
Balance between context capture and computational efficiency |
Dropout |
Rate |
0.3 |
Regularization to prevent overfitting |
Attention |
Type |
Additive |
Focus on sentiment-relevant tokens |
Dense Output |
Activation |
Sigmoid |
Binary sentiment prediction |
Optimizer |
Type |
Adam |
Adaptive learning, faster convergence |
Learning Rate |
- |
0.001 |
Empirically stable |
Batch Size |
- |
32 |
Efficient mini-batch processing |
Epochs |
- |
5 - 10 |
Sufficient for convergence without overfitting |
test dataset (accuracy = 0.8167, precision = 0.8415, recall = 0.9161, and F1-Score as an overall of 0.8772). The obtained results indicate that the model could be effectively applied as a short-text social media sentiment polarity detector. The accuracy gives a rough estimate of the accuracy of the correct predictions, but does not represent the actual performance because of class imbalance. Thus, the precision, recall, and F1-score are more important than other metrics for a good evaluation.
The recall value of 0.9161 truly indicates the number of instances that are positive sentiment, with only a few false negatives. This is particularly relevant in sentiment applications such as gauging world opinion on people, countries, ideas, or events, where a lack of positive sentiment could lead to misinterpretations of overall sentiment. Precision score: 0.8415 also shows that a lot more than half of the predicted positive instances are positive, thus confirming that the prediction of one class is not much dependent on the model for the SC1 class when predicting one class.
The F1 value of 0.8772 shows that the precision and recall are well balanced, giving a nice balance between the two. The overall balanced performance is achieved by the inherent balance between bidirectional contextual modeling and attention-based weighting, with the model being able to focus on semantically important tokens while maintaining a sequential understanding.
The dominance of correct categories over misclassification, as already seen in the quantitative metrics, should be visually confirmed in the confusion matrix as well, with a concentration of values along the diagonal (Figure 6).
The ROC curve should show good separation between positive and negative classes, with an AP and AUC value of ~0.85 - 0.90, supporting the model’s discriminative power (Figure 7).
4.2. Confidence Interval and Statistical Reliability
Accuracy and F1-score are point estimates that provide a first impression of the
Figure 6. BiLSTM confusion matrix.
Figure 7. ROC curve and AUC score.
models’ performance, but do not describe the variation over different test samples. We used a non-parametric bootstrap resampling strategy to assess statistical reliability to ensure that the reported performance is not an outcome of a favorable data partitioning or a random fluctuation.
In particular, we produced 1000 bootstrap samples by sampling with replacement from the original test set at random. The F1-score was recalculated for each resampled subset. This procedure yielded an empirical distribution of the performance values. This approach does not demand assumptions of normality, and it applies to the evaluation of deep learning, where the distributions of the metric may be asymmetric. The resulting 95% confidence interval for the in-domain F1-score is estimated to be: CIin ≈ (0.860, 0.890).
The width of the interval is rather narrow (≈0.03), which means that the predictions of the model are very stable over the resampled subsets. This means that in practice, if this experiment were to be run on similar data, the F1 score would remain in this range. This consistency enhances the reproducibility and robustness of the proposed framework. Well, that seems to be the case, but the CIcross was far larger: CIcross ≈ (0.629, 0.660). The larger interval means less certainty regarding the domain shift scenario, and binding power to interference with true distributional divergence. This is consistent with the theoretical prediction that models trained on a single linguistic distribution can have higher variance in the unseen domain (Figure 8).
The histogram should show a near-normal distribution around 0.877 as a visual confirmation of the stability of the metric.
Figure 8. Bootstrap distribution of in-domain F1-score (300 DPI).
Moreover, to improve statistical robustness, hypothesis testing was performed to check if the lower bound of the in-domain confidence interval was greater than the performance of baseline models. The lower bound (0.860) is still far above the baseline F1 (≈0.81 - 0.84), and the improvement can be regarded as statistically significant at the 95% confidence level (Figure 9).
4.3. Cross-Domain Generalization and Domain Shift Analysis
Generalization under domain shift is one of the most difficult problems in natural language processing. The proposed model achieved good performance in-domain (F1 = 0.877), but when applied to the external dataset without fine-tuning, the performance dropped to an F1-score of around 0.63. This degradation is caused by the difference between the training distribution
and the testing distribution
, which can be formally expressed as:
Such divergence may be due to vocabulary shift, stylistic variation, differences in sentence length, or topic shift. Social media texts are short, lexically compressed, and
Figure 9. Bootstrap comparison: in-domain vs cross-domain.
emotionally direct, while formal reviews are longer, syntactically complex, and context-heavy.
Theoretically, recurrent neural networks learn mappings of conditional probabilities:
where parameters
are optimized on the in-domain data. The learned representation may not perfectly capture shifted feature distributions when tested on out-of-distribution samples, which leads to a drop in performance.
Nevertheless, without retraining, we get F1 ≈ 0.63, which means that the contextual representations are partially transferable. The attention mechanism is likely to help cross-domain robustness by focusing on sentiment-bearing tokens rather than topic-specific patterns (Figure 10).
Figure 10. In-domain vs cross-domain performance comparison.
4.4. Robustness to Lexical Noise
To simulate real-world textual corruption, we randomly dropped out 20% of the tokens during test time. This experiment tests the model’s robustness to perturbations:
The small decrease in F1-score means that the model doesn’t only use isolated keywords but also benefits from encoding distributed contextual information (Figure 11).
Theoretically, robustness emerges as:
Word Embeddings Capture Semantic Similarity.
Bidirectional context makes up for missing tokens.
Remaining informative words are assigned more weight as a result of attention.
However, if the noise is too loud, the Long-Distance Dependencies would likely fail. So, there must be a limit to how much perturbation you can handle.
Figure 11. Clean vs noisy performance comparison.
4.5. Attention Mechanism Analysis
The attention layer introduces a weighted aggregating mechanism as stated below:
The attention weights
.
The visualization demonstrates that the words that have semantic polarity get higher attention values. From an information-theoretic viewpoint, attention reduces the entropy by concentrating probability mass on discriminative features. It also improves the interpretability and compactness of the representation. Moreover, the agreement of attention alignment with SHAP validates the internal consistency of the model (Figure 12).
Figure 12. Attention heatmap visualization.
4.6. SHAP Interpretability Validation
SHAP analysis is a feature attribution method based on cooperative game theory. SHAP measures marginal contribution to the output prediction, while attention provides internal weighting. The global SHAP importance can be computed as:
The correspondence between SHAP rankings and attention heat maps indicates that the internal weighting mechanism of the model is consistent with the actual output contributions. This double interpretability leads to increased transparency and reduced concerns of spurious correlation (Figure 13).
Figure 13. Global SHAP feature importance plot.
4.7. Baseline Comparison
The experimental results show that the proposed BiLSTM-Attention model consistently achieves better performance than the baseline LSTM model and the standard BiLSTM model. This improvement can be theoretically accounted for by successive enhancements of feature representation in the hierarchical architectures. While the conventional LSTM is effective in modeling temporal correlations by maintaining sequential memory in the gated mechanism in one direction, it is not able to use future context information (Figure 14).
The BiLSTM architecture overcomes this problem by taking the input sequence one step forward and backwards, thus providing better contextual dependencies and richer feature representations. The attention mechanism further enhances this bidirectional context understanding by dynamically adjusting the weights of the more relevant hidden state(s) and reducing the weights of less informative features. The attention layer can dynamically pay attention to the most discriminative part of the input sequence, rather than paying equal attention to all time steps, and thus improve feature extraction and decision-making. Representational learning-wise, the hierarchy of the learned representations is as follows: LSTM < BiLSTM < BiLSTM-Attention. The design of each of these architectural improvements adds more representational power, and the attention mechanism adds adaptive feature weighting that adds considerably to the model’s ability to learn complex semantic and contextual relationships among the data. Thus, any observed improvement in predictive performance is not due to random variation or to statistical fluctuation. Rather, it is a cumulative effect of more and more complex components of the architecture that improve the model’s ability to learn useful representations. The results here support both empirical and theoretical proof that combining bidirectional sequence modeling and an attention mechanism yields better results, as it allows the model to pay attention to the most informative contextual information when making predictions.
![]()
Figure 14. Baseline model comparison graph.
4.8. Ablation Studies
We conduct ablation experiments to assess the contribution of each component in the architecture. Removing attention caused a measurable F1 decrease, thus confirming its importance. This confirms the hypothesis that not all contextual states contribute equally to the sentiment polarity and adaptive weighting enhances discrimination (Figure 15).
Figure 15. Ablation study graph.
4.9. Relation to Polling Trends
Comparison of aggregated sentiment scores over time and polling trends via Pearson correlation:
A correlation coefficient of greater than 0.70 means that there is a strong linear relationship. This means that the pooled forecasts of the models reflect general trends in voter opinion. Correlation is not causation, however. Sentiment and polling could be affected by external socio-political events simultaneously (Figure 16).
4.10. Error Case Study
The proposed framework performs well in general. However, a more detailed qualitative analysis of the misclassified instances offers valuable insights into the structural limitations. In false-positive and false-negative predictions, it is evident that the majority of errors are due to a lack of understanding of the language’s complexity, rather than to explicit polarity cues. The use of sarcasm constructions is particularly hard. For example, the sentence “Great job ruining everything” contains lexically positive tokens, which are pragmatically inverted by the contextual semantics. In such “polarity” cases, the attention mechanism is likely to enhance the polarity of the lexical items, such as “great”, and it may not be enough to overcome the initial
Figure 16. Sentiment trend vs polling trend comparison.
signal of polarity, as in the case of “ruining”. This suggests that bidirectional context modelling is able to model sequential dependencies, but it is not able to capture pragmatic inversion or discourse-level irony completely. Moreover, sentences with mixed or ambivalent sentiment expressions (i.e., positive and negative cues co-exist) generally lead to borderline decision boundaries in the learned representation space. The model should automatically select which polarity is the dominant one, and the dominance of this polarity could be influenced by the training distribution. These cross-domain errors also indicate sensitivity to stylistic variation and structural variation, particularly in longer review texts. Sentiment cues are placed throughout the story, not limited to short lexical patterns, for longer texts. (Figure 17).
Figure 17. BiLSTM-attention confusion matrix.
Also, representative tables of misclassified examples should be provided for each type of error, consisting of examples that were typed. Furthermore, tables of misclassified examples should be provided for each type of error, representative of examples that were typed but misclassified (Figure 18).
Figure 18. Categorized misclassification examples.
5. Overall Discussion and Implications
The extensive experimental results prove that the proposed BiLSTM-Attention model is able to be a reasonable solution to compromise prediction accuracy, interpretability, and statistical reliability. The high in-domain F1 score is additional evidence that the context is being well modelled, and the bootstrap confidence intervals give evidence that the results reported are not just single-point estimates. The attention and SHAP-based interpretability also boost transparency, leading to a reasonable correspondence between the external contribution of all features and the attention weights. The dual interpretability also assists the theoretical soundness of the architecture, in which both mechanisms always mark the most significant sentiment as the most important for the classification decision. This performance loss on cross-domain evaluation is, however, attributed to the challenge of distributional shift, in which the conditional probability learnt in the training set is not completely transferable to the new linguistic environments that are unseen during training. Theoretically, it’s the same as the covariate shift problem in supervised learning. However, the model retained much of its generalization ability when retrained, indicating that part of the generalization ability of the model is captured by the partially transferable semantic structures in the contextual embedding. The experiments on robustness to lexical noise also demonstrate that the model is not based on a singular keyword but on a distributed semantic representation, which is good for enhancing robustness in real text contexts. The results obtained indicate the methodological validity and applicability of the framework (Figure 19).
Overall, the study shows how a combination of contextual sequential modeling and interpretability analysis can provide a transparent, statistically sound approach to sentiment classification, yet points to promising directions for future enhancement on both the detection of sarcasm and the adaptation of methods to new domains (Table 10).
Figure 19. Domain comparison plot.
Table 10. Performance and limitations summary.
Evaluation Dimension |
Key Findings |
Strengths Identified |
Observed Limitations |
Implication for Future Work |
In-Domain Performance |
F1 = 0.877;
Recall = 0.916 |
High classification reliability; strong detection of positive sentiment; balanced precision-recall trade-off |
Slightly lower precision compared to recall |
Precision refinement through threshold optimization |
Statistical Reliability |
Narrow 95% CI (≈0.860 - 0.890) |
Stable performance across bootstrap samples; reproducible results |
Limited statistical testing across multiple random splits |
Incorporate k-fold cross-validation for further validation |
Cross-Domain Generalization |
F1 ≈ 0.63 without retraining |
Partial transferability of contextual features |
Significant performance drop under domain shift |
Apply domain adaptation or fine-tuning strategies |
Robustness to Lexical Noise |
Minor ΔF1 under 20% token dropout |
Distributed semantic representation reduces keyword dependency |
Performance may degrade under higher perturbation rates |
Explore adversarial training for enhanced robustness |
Attention Mechanism |
High weights on sentiment-bearing tokens |
Improves contextual focus; enhances interpretability |
May misinterpret sarcasm or polarity inversion |
Integrate discourse-aware or transformer-based modules |
SHAP Interpretability |
Alignment with attention rankings |
Transparent feature contribution; model explainability |
Computational overhead for large datasets |
Optimize SHAP computation using sampling-based methods |
Error Analysis |
Errors in sarcasm and mixed sentiment |
Reveals the structural boundaries of the model |
Limited pragmatic understanding |
Incorporate sarcasm detection or contextual embedding enhancement |
6. Conclusions
In this paper, we propose an interpretable deep learning framework for sentiment classification with bidirectional context modelling, attention-based feature weighting, and SHAP-driven interpretability analysis. The experimental results indicate that the proposed BiLSTM-Attention architecture achieves good performance in the in-domain setting with an F1-score of 0.877 and high recall, which demonstrates that it can reliably detect sentiment polarity in short-text social media data. The use of bootstrap-based confidence intervals offers further confirmation of the statistical stability and reproducibility of the results, increasing the methodological rigour, besides the traditional metric reporting.
Attention visualization and feature attribution are complementary tools to investigate interpretability. In other words, the attention mechanism finds tokens that are relevant to the context in the internal space of the model, while SHAP measures the marginal effect of tokens on the prediction outcome. The interpretation of the second type in conjunction with the consensus of these two further increases the transparency and theoretical coherence of the framework. Such a two-stage interpretability is especially useful in important applications such as political opinion mining, where the results of the model have to be interpretable and accountable.
It also showed that the model had reasonably high generalization performance across the domains, even after the performance drop caused by the distributional shift, without retraining. That means that semantic structures are not completely independent, even under different stylistic and lexical distributions in contextual embedding. The robustness analysis with lexical noise showed very little degradation (little to none) in performance, implying that the system relies on a distributed semantic representation, not on isolated lexical representations. Qualitative error analysis, however, showed that there were structural weaknesses associated with the modelling of discourse-level phenomena such as sarcasm, pragmatic inversion, and mixed sentiment expressions due to constructional limitations of sequential neural architectures in modelling discourse-level phenomena.
The findings overall support the hypothesis that a hybrid approach of contextual sequence modelling, interpretability, and statistical validation results in a predictive and interpretable sentiment analysis framework. From a methodological point of view, the study contributes to the domain by providing the functionalities of cross-domain evaluation, robustness tests, and confidence interval estimations, which are not often used in classic sentiment classification studies. Domain adaptation, the use of sarcasm-aware modelling, and the contextual enhancement using transformers can be the subject of future work to improve generalization and pragmatic understanding. The model proposed in this system is not only efficient but also easy to interpret and statistically credible, and it can be used as a good foundation for credible and interpretable sentiment analysis in practical applications.
Author Contributions
Conceptualization: Sraboni Ghosh Joya and Nila Sultana; Methodology: Sraboni Ghosh Joya; Software: Sraboni Ghosh Joya; Validation: Sraboni Ghosh Joya and Nila Sultana; Formal analysis: Sraboni Ghosh Joya; Investigation: Sraboni Ghosh Joya and Tanzila Akter; Data curation: Sraboni Ghosh Joya; Writing—original draft preparation: Sraboni Ghosh Joya; Writing—review and editing: Nila Sultana and Tanzila Akter; Visualization: Sraboni Ghosh Joya; Supervision: Nila Sultana; Project administration: Nila Sultana. All authors have read and agreed to the published version of the manuscript.
Acknowledgements
The authors would like to thank the Department of Computer Science and Engineering, City University, Bangladesh, for its academic support and encouragement during this research. The authors also acknowledge the availability of the publicly accessible Sentiment140 and IMDB datasets used in this study.