Introduction
Literature Review
Methodology
Performance and Results
Experimental Setup
Dataset Description
Performance Evaluation
Ablation Study
Baseline Comparison
Conclusion
Introduction
The rapid advancement of digital technologies has transformed the way citizens interact, communicate, and participate in sustainable urban communities. Social media and video-sharing platforms have become integral components of digital infrastructure, enabling billions of users to create, share, and exchange multimedia content across education, business, healthcare, public awareness, disaster management, and community engagement domains [1]. These digital communication platforms play an increasingly important role in supporting smart city initiatives, sustainable urban governance, and inclusive public participation by facilitating timely information dissemination and collaborative decision- making.
Among these platforms, YouTube has emerged as one of the world’s largest digital communities, providing users with opportunities to share multimedia content, exchange opinions, and participate in public discussions through interactive comments and feedback mechanisms [2]. While these interactive features significantly enhance user engagement and knowledge sharing, they have also created opportunities for malicious actors to exploit comment sections by disseminating spam messages, phishing links, fraudulent advertisements, repetitive promotional content, malware, and misleading information [3]. Such malicious activities undermine the reliability, security, and trustworthiness of digital communication ecosystems, negatively affecting user confidence and the sustainable operation of online platforms that increasingly support smart urban services and community-oriented digital engagement.
These negative practices contribute to a negative online discourse, loss of trust and greater risks to cybersecurity and privacy, which in turn reduces confidence in the digital communication platforms used [4]. Trustworthy and secure online communication is increasingly important in the context of building sustainable digital communities, as the digital platforms are now used as a platform for social interaction, education, commerce and the dissemination of information. Achieving sustainable digital ecosystems requires user engagement and platform integrity, which can be achieved through genuine user interactions, trustworthy information sharing, and responsible content moderation. As spam and scam have become a major issue, digital platforms are facing greater pressure to scale as more content needs to be manually moderated. Smart and automated spam detection is thus a key element in facilitating sustainable and responsible Artificial Intelligence (AI) content moderation and the sustainability of online communities has become critical to this progress. This automatic spam comment detection has thus emerged as an area of research in Natural Language Processing (NLP) and Cybersecurity [4].
Manual rules, keyword filtering and classic machine learning techniques like Naïve Bayes, Decision Trees, Support Vector Machines, Random Forests, and Logistic Regression [5] were among the first techniques used to detect spammers. These techniques worked well on standard data sets, but are quite dependent on handcrafted textual features, and in many cases, they are not sophisticated enough to capture the meaning of the spammers’ comments in the context and to detect the changing language conventions of recent spam comments. Spam e-mails are often written with the use of abbreviations, emoji, misspelled words, special characters, differently used forms of words, and adversarial writing styles that help to evade traditional spambusting techniques and their efficacy, as well as help to reduce the applicability of traditional spambusting techniques to dynamic online environments [6]. Since the advent of deep learning, automatic semantic and contextual representation learning for raw text has achieved great success in improving the performance of text classification tasks [7].
Transformer-based language models are especially good at capturing long-range linguistic and contextual relationships, and have been used to great effect in a variety of NLP tasks. To achieve a better language representation, RoBERTa is an optimized version of BERT with enhanced pretraining techniques, a larger dataset for training, and an improved optimisation method, and is superior to the embedding-based approach in capturing language context features [8]. These contextual representations can then be used to more easily differentiate lawful comments from spam, especially when non-spam comments are in a similar semantic context, but are difficult to detect using handcrafted features. While considerable efforts have been undertaken in this direction, existing researches on spam detection in YouTube have concentrated on improving the classification accuracy, but not much efforts have been devoted to creating intelligent frameworks for content moderation of digital communication to guarantee trustworthy and sustainable communication [9]. Furthermore, the issues of class imbalance, powerful generalisation and scalability of deployment on large-scale platforms are still relevant issues for practical application [10].
This study proposes a Contextual Unified Spam Detection Learning Model (CUS-DLM) to address the disadvantages mentioned above to detect spam comments intelligently on YouTube. We propose a model that incorporates the contextual language understanding with BERT embedding, a neural Hidden Markov Model inspired module and a Bidirectional Gated Recurrent Unit (BiGRU) network to learn the semantic representation and sequence dependency of text simultaneously. Besides, Weighted Random Sampling, balanced class weighting and Focal Loss are presented, as they are able to tackle the class imbalance issue and improve learning power robustness. The suggested scheme is a scalable and dependable way of performing automated spam identification using trusted communication on the Internet and sustainable digital societies.
This work has contributed significantly in the following aspects:
•A novel Contextual Unified Spam Detection Learning Model (CUS-DLM) which combines the contextual BERT embeddings, an HMM- inspired neural module and a BiGRU network for efficient semantic and sequential spam detection.
•Weighted Random Sampling, Balanced Class Weights and Focal Loss are integrated into an imbalance-aware learning strategy to improve the robustness and reduce the prediction bias.
A comprehensive experimental evaluation on the public YouTube Spam Comment Dataset, with significant improvements in terms of Accuracy, Precision, Recall, F1-score and ROC-AUC when compared to traditional machine learning baselines.
A capable, AI-powered solution designed to support the building of trustworthy, secure and sustainable digital communities, automate the moderation of malicious content and improve the quality and reliability of digital communication.
In a real-world deployment scenario, the proposed CUS-DLM is intended to operate as a server-side content-moderation microservice within digital communication platforms. Incoming user comments are streamed to the model through a lightweight REST or gRPC endpoint, tokenised on the fly using the BERT-base- uncased tokeniser, and classified in near real time; predictions above a configurable confidence threshold are automatically flagged, quarantined, or routed to human moderators for review. Such a deployment pattern is directly transferable to other user-generated- content ecosystems including Facebook posts, Instagram comments, X (Twitter) replies, TikTok video comments, LinkedIn discussions, e-commerce product reviews, smart-city citizen-feedback portals, and community forums, since all of these rely on the same short, noisy, contextually rich textual signals that the proposed framework is designed to model [11, 12, 13, 14, 15, 16, 17, 18].
Literature Review
Airlangga [11] tested six deep learning models for spam comment detection on YouTube: MLP, CNN, LSTM, BiLSTM, GRU and Attention. The pre-processing stage results and model training showed that the best architecture were LSTM having accuracy around 95.65% from other architectures. The study showed that the sequential deep learning models were effective in spam classification, but it didn’t discuss transformer-based contextual language models.
Xiao and Liang [12] evaluated eight machine learning algorithms for determining the spam comments of YouTube videos: Naïve Bayes, Logistic Regression, KNN, SVM, Decision Tree, Random Forest, MLP and Voting Classifier. Random Forest gave the best result with 100% precision and an ROC-AUC of 0.9841. However, the proposed framework was handcrafted without any semantic understanding of context.
Sam’an and Imaddudin [13] proposed multiple deep learning models for detection of spam in YouTube such as CNN, LSTM, GRU, BiLSTM, CNN-LSTM, CNN-GRU, and CNN-BiLSTM. Of these, BiLSTM performed the best with an accuracy of 96.94%, and CNN-BiLSTM (96.43%). Hybrid architectures have been found to boost performance, while contextual representations through the use of transformers have not been studied.
To improve the spam detection in YouTube, Ilavendhan and Janani [14] introduced a stacked ensemble model combining CNN, LSTM, Attention and LSTM- CNN models. The proposed ensemble gave better performance than the individual models with 93.5% accuracy in spam filtering. The framework, however, did not take advantage of semantic representations based on transformers.
Sinhal et al. [15] proposed the technique to detect spam comments on YouTube using Feedforward Neural Networks (FNNs) and Recurrent Neural Networks (RNNs). The findings demonstrated that the deep learning models were able to learn more complex patterns from the text than traditional machine learning models. However, the study did not take transformer- based architectures into account to further improve the contextual understanding.
Biswas et al. [16] proposed a Naïve Bayes classification technique to detect spam comments in YouTube based on the text features like Hyperlink, keyword repetition and promotional text. The proposed model resulted into 96.5% accuracy with the low complexity. It has some weaknesses, however, as it depends on manually constructed features for spam comments with complex contextual semantic relationships.
Mondal et al. [17] presented an Artificial Neural Network (ANN) along with TF-IDF for detecting spam comments in YouTube. The proposed architecture was composed of two hidden layers using ReLU activation function which achieved an accuracy and precision of 88%, recall of 89% and F1 score of 88%. The model was able to detect spams very well, but its contextual understanding of spam was limited by the TF-IDF features.
Hasan et al. [18] have compared traditional machine learning approach and transfer learning approach in detecting spam comments in YouTube. Different classifiers are tested such as Naïve Bayes, SVM, Random Forest, XGBoost, BERT, DistilBERT, and RoBERTa. RoBERTa had the best accuracy (92.71%) among all the models while SVM obtained the best accuracy among the conventional machine learning models.
Yanto et al. [19] have suggested machine learning and deep learning models for spamming detection on YouTube comments using the features of TF-IDF and Word2Vec. LSTM and GRU networks were tested with the machine learning algorithms. The highest accuracy model is the FastText with 96% and the best deep learning model is GRU with 91.60%.
Sharma et al. [20] analysed the state-of-the-art AI- based spam comment detection methods, including traditional machine learning, deep learning, transformer models, ensemble learning, and explainable AI. The survey identified critical challenges such as Multilingual Spam, Adversarial Attacks, Dataset bias, and Cross Domain Generalisation. It revealed that transformer-based models have great potential in the future spam detection system.
To tackle YouTube spam comment detection, Yadav et al. [21] introduced a machine learning approach that features SMOTE for class balancing and TF-IDF for feature extraction. Different classifiers were experimented: SVC, Gradient Boosting, AdaBoost, XGBoost, Logistic Regression, Random Forest, Voting Classifier and LightGBM. SVC shows the best mean accuracy of 96.42% which is best in solving the imbalance and using ensemble learning.
Jamunadevi et al. [22] suggested a hybrid spam detection system using CNN with LSTM and BiLSTM along with CatBoost. Structured features were used by CatBoost, such as comment length and frequency of punctuation, as well as deep learning models that were used to extract the semantic features. The proposed hybrid model was able to attain 97.2% accuracy which outperforms CNN-LSTM and CNN-BiLSTM models, proving the importance of combining deep textual representation with structured feature learning.
Singh et al. [23] used supervised machine learning algorithms for spam filtering in YouTube comments as Logistic Regression, Random Forest, SVM and Naïve Bayes. The most accurate model was Logistic Regression with an accuracy of 98% and then Random Forest with an accuracy of 96%. The study demonstrated the effectiveness of traditional machine learning techniques, but traditional techniques are weak at achieving a contextually meaningful understanding due to handcrafted features.
Othman et al. [24] presented an ensemble method using PSO optimisation for detecting spam in YouTube by combining the two types of classifiers: character n-gram and Bag-of-Words. The proposed model was able to obtain accuracy ranging from 91.65% to 96.79 %, with optimised classifiers weights obtained by Particle Swarm Optimisation, as compared to the equal- weighted ensembles. The study showed that adaptive ensemble optimisation is an effective approach for robust spam detection.
Mukherjee et al. [25] introduced an automatic spam detection system on YouTube comments based on UCI dataset of YouTube Spam comments. To transform the comments, CountVectorizer was applied, and they were classified by Support Vector Machine (SVM). The proposed framework proved a successful method to filter spam messages to improve user experience without any manual work, yet was based on traditional text vectorisation techniques, which were lacking in context.
To address issues with YouTube’s platform security, Kuppen et al. [26] presented a Recurrent Neural Network (RNN)- based approach to automatically detect spam comments. The model used sequential information in the text to represent the relationship between user-generated comments in the context. The study demonstrated that RNNs can be effectively applied to spam classification and are able to improve the performance of the automated spam moderation system, and suggested that the application of transformer-based architecture can further improve the effectiveness of spam detection.
In [27] Condiri-Alejo et al. proposed a Multinomial Naïve Bayes (Multinomial NB) model for spotting spam in Spanish-language videos on the YouTube platform about finance. The proposed framework was tested on a spam comment dataset that contains more than 25,000 comments from 30 videos, and it achieved 98% recall, which it has proven to be effective in detecting spam comments. The study underscored the need for applicability of lightweight machine learning models in individual domain YouTube spam detection.
Le et al. [28] suggested a hybrid deep learning model based on PhoBERT, TextCNN, and BiLSTM to identify spam in Vietnamese health care channels on YouTube. The proposed model successfully captured semantic and sequential features of the text to achieve better spam classification performance with transformer-based contextual embeddings, convolutional and recurrent networks. But the framework is only applicable to the Vietnamese domain-specific dataset.
Latha et al. [29] proposed an automatic machine learning-based spam detection system for YouTube spam comments using TF-IDF along with textual and structural features coupled with Chi-square feature selection. The classifiers were tested, and the best accuracy was achieved using the XGBoost classifier (97.2%). The study proved the feature engineering and ensemble learning is effective and suggested the transformer-based architectures to enhance the performance in the future.
Jo and Girsang [30] investigated the performance of the YouTube spam comment detection using BiLSTM and the effect of attention and word representations. The evaluated architectures showed that BiLSTM- Word2Vec-Attention had the best accuracy (93.03%), F1-score (90.78%) and ROC-AUC (96.56%). The experimental results indicated that attention mechanisms can be effectively employed in spam detection to emphasize informative words in brief YouTube video commentaries.
Methodology
For the automatic detection of spam comments on YouTube, the proposed CUS-DLM (Contextual Unified Spam Detection Learning Model) is shown in Figure 1. The proposed framework combines a pretrained BERT encoder, a Hidden Markov Model (HMM)- inspired neural branch, and a Bidirectional Gated Recurrent Unit (BiGRU) network to learn sequential patterns and integrate contextual language understanding, rather than conventional machine learning techniques based on handcrafted textual features. The BERT encoder learns rich contextual information from input comments; the HMM branch encodes transitions between latent states, and the BiGRU branch encodes bidirectional sequential dependencies. The outputs of both branches are merged and then fed into a fully connected classification network for the final spam prediction. The process includes data acquisition, preprocessing, contextual tokenisation, feature extraction, parallel sequence modelling, feature fusion, classification, optimisation, and performance evaluation. The architecture is based on the proposed model.

Figure 1.
Proposed AI-enabled CUS-DLM framework for intelligent content moderation supporting sustainable digital communities and smart urban communication. Key observation: the pipeline shows how contextual BERT embeddings are simultaneously routed to the HMM-inspired probabilistic branch and the BiGRU sequential branch, whose fused features drive the imbalance-aware classifier.
The first step is to load the publicly available YouTube spam comment dataset in a Pandas DataFrame. The dataset has two features: the user comment (CONTENT) and the corresponding label (CLASS). To guarantee data quality, records with missing values are removed before training. The dataset contains information about each sample.
where denotes the YouTube comment represents its class label, and N denotes the total number of samples. Here, class 0 corresponds to legitimate comments, whereas class 1 represents spam comments. Before training, textual comments are converted into lowercase characters and redundant white spaces are removed using a preprocessing function defined as
where P(․) represents the preprocessing operation. Then, Label Encoding is used to convert the output labels into numeric values. The data set is split into three sets: training, validation, and testing, all of which have the same class distribution as the original set via stratified sampling. Using the pretrained BERT tokeniser bert-base-uncased, the preprocessed comments are converted into contextual tokens. Known as WordPiece tokenisation, this method breaks up unseen words into meaningful sub-word units and enhances the representation of noisy social media text. The maximum sequence length is set to 128 tokens, and truncation and padding are applied to each comment. Valid tokens and padded positions are distinguished by using attention masks. The tokenisation process is shown as
Here, T is the token sequence and m is the maximum length of the sequence. The attention mask and token IDs are passed onto the BERT encoder. The contextual embedding stage uses a pretrained BERT- base-uncased model to obtain embeddings for the input comments. BERT’s word embeddings are different from static embeddings, as they take into account left and right contexts for every word via multi-head self-attention. The encoder generates a context embedding for every token in the sequence,
where
Has context-specific embeddings for a sequence of length L. The embeddings are then fed to two parallel branches to learn complementary textual features.
The proposed branch utilises learnable emission and transition parameters that are optimised together with the deep learning network via backpropagation. In contrast, a conventional HMMEd, trained independently using the Baum-Welch algorithm, applies only the learnable parameters of that algorithm. Firstly, the embeddings of the tokens are projected into latent state scores via an emission layer,
where denotes the contextual embedding of the token. A learnable transition matrix models state transitions between consecutive hidden states. The forward probabilities are recursively updated in logarithmic space according to
where A is the trainable transition matrix. Once the full sequence has been processed, the posterior distribution of the hidden states is derived by applying the Softmax function,
Finally, the posterior probability vector is projected to a fixed-length feature representation,
which summarises the comment’s probabilistic sequential attributes.
It is important to clarify that the proposed module is HMM-inspired rather than a conventional Hidden Markov Model. A classical HMM assumes discrete latent states, fixed emission and transition probability matrices estimated offline through the Baum-Welch expectation-maximisation algorithm, and strict first- order Markov independence. In contrast, the proposed module treats the emission scores and the transition matrix as learnable neural parameters that are optimised end-to-end via backpropagation jointly with the BERT encoder, the BiGRU branch, and the classification head. The forward recursion is executed in log-space using the log-sum-exp operator so that it remains fully differentiable, and the posterior distribution is projected into a continuous feature vector rather than used to decode a discrete state sequence. The module therefore borrows only the sequential state- transition inductive bias from HMMs while retaining the representational richness and gradient-based learning of deep neural networks [31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42].
The second branch is a Bi-directional Gated Recurrent Unit (BiGRU) network. To eliminate unnecessary computations on padded tokens, variable-length token sequences are packed before being processed recurrently, using attention masks. Learns contextual dependencies in both the forward and backwards directions in the BiGRU. The hidden states are calculated as:
The bidirectional representation is the concatenation of the forward and backward hidden representations. This is then mapped to a fixed-dimensional feature vector. The BiGRU can leverage information from both directions and thus effectively learns long-range contextual dependencies often seen in spam comments.
The outputs generated by the HMM and BiGRU branches are fused through feature concatenation,
where denotes the final fused representation. Dropout regularisation is applied to reduce overfitting before classification. The fused features are passed through a fully connected neural network consisting of a dense layer, Batch Normalisation, ReLU activation, an additional dropout layer, and a final dense layer for binary classification. The classifier computes
The probability of each class is obtained using the Softmax activation function,
and the class with the highest probability is selected as the final prediction.
To avoid prediction bias due to class imbalance, the proposed framework uses a Weighted Random Sampler to obtain a balanced mini-batch and a balanced class- weight calculation based on the training data. The AdamW optimiser with weight decay 0.01 and a linear learning-rate scheduler with warm-up is used for model optimisation, with a learning rate of 2×10‒5. The network is trained for 10 epochs with a training size of 16. In the proposed framework, the cross-entropy loss is replaced by the Focal Loss.
where α=1 and γ=2. During backpropagation, gradient clipping with a maximum norm of 1.0 is applied to improve optimisation stability. Finally, the trained model is evaluated using Accuracy, Precision, Recall, F1-score, ROC-AUC, and the Confusion Matrix. By integrating contextual transformer embeddings, probabilistic state-transition modelling, bidirectional sequential learning, balanced sampling, and focal-loss optimisation into a unified framework, the proposed CUS- DLM provides a robust and scalable solution for automatic detection of YouTube spam comments.
The hyperparameter values were selected based on established practices for fine-tuning BERT-based classifiers on short-text datasets and were confirmed through preliminary validation experiments. A maximum sequence length of 128 tokens comfortably covers more than 99% of the comments in the YouTube Spam Comment Dataset, whose median length is well below 40 tokens, avoiding unnecessary padding and quadratic self-attention cost. A batch size of 16 was chosen as a stable trade-off between gradient noise and GPU memory consumption for BERT-base fine-tuning on a single 8 GB GPU. Training for 10 epochs was sufficient for the training and validation curves to converge without over-fitting, as further evidenced by the small train- validation gap in Figure 4. The AdamW learning rate of 2×10‒5 with linear warm-up follows the recommendation of Devlin et al. for BERT fine-tuning. The Focal Loss parameters alpha = 1 and gamma = 2 were adopted from the original focal-loss formulation of Lin et al., which has been shown to effectively down-weight easy examples while preserving learning signal from hard, minority-class samples such as underrepresented spam variants.
Performance and Results
The experimental evaluation of the proposed CUS- DLM for YouTube spam comment detection is presented in this section. The model was trained and tested with the YouTube Spam Comment Dataset, after preprocessing, label encoding, and tokenization, with stratified data splitting technique. To alleviate class imbalance, weighted random sampling, balanced class weights and focal loss were employed. Performance measures like accuracy, precision, recall, F1 score, ROC-AUC, and confusion matrix were used to assess the model’s performance. Furthermore, baseline simulations and ablation tests have been performed to assess the effectiveness of the proposed architecture and the separate components of it.
Experimental Setup
We have implemented the proposed CUS-DLM in Python using PyTorch and the Hugging Face Transformers library.We have coded the proposed CUS-DLM in Python, with PyTorch and the Hugging Face Transformers library. The framework uses a pretrained BERT- base-uncased encoder and two HMM-inspired and parallel branches for feature extraction—BiGRU. The model was trained using AdamW optimizer, Focal Loss and linear learning-rate scheduler. A weighted random sampler was used to alleviate class imbalance. It was trained on a batch size of 16, a maximum sequence length of 128, and 10 epochs. Moreover, Table 1 shows the experimental configuration.
Table 1.
Experimental Configuration
To ensure the reproducibility of the reported results, the full software and hardware configuration is disclosed as follows. All experiments were conducted using Python 3.10, PyTorch 2.1.0 with CUDA 11.8, Hugging Face Transformers 4.35, scikit-learn 1.3, NumPy 1.26, Pandas 2.1, and Matplotlib 3.8. Training and evaluation were performed on a workstation equipped with an NVIDIA RTX-class GPU with 8 GB of dedicated memory, an Intel Core i7 processor, and 16 GB of system RAM, running Windows 11. A fixed random seed of 42 was used across NumPy, PyTorch, and the Python random module to ensure run-to-run determinism. Numerical values in all result tables are reported to two decimal places for percentage-based metrics (accuracy, precision, recall, F1-score) and to four decimal places for ROC-AUC and Average Precision, in line with common practice in the field. The source code, training scripts, and preprocessing pipeline will be released in a public GitHub repository upon acceptance of the manuscript to facilitate independent verification and extension by the research community [42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52].
Dataset Description
The experiments were conducted on YouTube Spam Comment Dataset with labeled user comments as spam or non-spam. There are two main attributes in the dataset: the comment text (CONTENT) and the target label (CLASS). Data collected were preprocessed before training, including discarding missing data, converting comments to lower case and coding labels numerically. The data set was divided into training, validation and test sets using stratified sampling method. The tokenizer used was the BERT-base-uncased, and a max length of 128 was set for sequences. The training was done using weighted random sampling and balanced class weights to alleviate the class imbalance. Further, Table 2 highlights the dataset description.
Table 2.
Dataset Description
Performance Evaluation
The proposed CUS-DLM was evaluated using widely adopted classification indicators such as accuracy, precision, recall, F1 score and Receiver Operating Characteristic – Area under the Curve (ROC-AUC). The metrics are used to evaluate the effectiveness of the proposed framework in correctly differentiating spam comments from legitimate ones while minimizing classification errors. The results on the test set show that the proposed model performs well in YouTube spam comment detection.
Table 3 summarizes the quantitative performance of the proposed CUS-DLM. The result of the overall accuracy of the framework was 96.43%, which means that it successfully classified most of the spam messages and legitimate comments. The accuracy value of 96.52% shows that the system successfully identified a large portion of the spam comments, demonstrating a relatively low number of false positives. Similarly, a recall of 96.52% means that the proposed framework makes few false-negative (FN) predictions and identifies most of the spam comments. The proposed model also obtains the balanced F1 score of 96.52%, which further validates the effectiveness to maintain the appropriate balance between precision and recall. Moreover, the AUC-ROC value obtained (0.9917) is excellent for all the classification thresholds, showing that the discriminative power of the framework is excellent.
Table 3.
Performance Evaluation of the Proposed CUS- DLM
| Metric | Value |
| Accuracy | 96.43% |
| Precision | 96.52% |
| Recall | 96.52% |
| F1-Score | 96.52% |
| ROC-AUC | 0.9917 |
The performance of the classification can be further illustrated using a confusion matrix as shown in Figure 2. The 191 legitimate comments were classified correctly as Not Spam (184) and incorrectly as spam (7). Similarly, 194 of 201 spam comments were correctly tagged, and 7 were incorrectly tagged as spam. The few false positives and false negatives are observed that indicate the efficiency of the proposed CUS-DLM to learn the contextual and sequential representations of spam to correctly classify spam.

Figure 2.
Confusion matrix of the proposed Contextual Unified Spam Detection Learning Model (CUS-DLM) for AI-enabled trustworthy digital communication in sustainable smart urban communities. Key observation: only 7 legitimate comments and 7 spam comments are misclassified out of 392 test samples, indicating balanced errors across both classes and negligible bias toward either class.
The ROC curve of the proposed framework is shown in Figure 3. The curve stays close to the top left corner of the graph for all decision thresholds, suggesting a high true positive rate and a very low false positive rate. The proposed model obtained a high ROC-AUC of 0.9917 which reflects good generalization and excellent performance for the spam/non-spam classification of comments. The validation and the training accuracy of the proposed model over the course of the training epochs are illustrated in Figure 4. In terms of training accuracy, it quickly improved in the first few epochs, and stabilized to approximately 99% in successive epochs, while the validation accuracy stayed at around 97% throughout the training. The proposed framework seems to be a good generalisation with little overfitting as evidenced by the small gap between the training and the validation curve.
In Figure 5, another illustration of the optimization process is given as training loss curve. The training loss decreased substantially in the first epochs and appears to be converging to a very low loss as training continues, indicating stable optimization and good convergence of the proposed model. Loss values keep declining, indicating that the acquired optimization strategy along with focal loss and balanced sampling can be applied to efficiently learn discriminative feature representations. To further illustrate the classification performance of the proposed framework, the Precision–Recall (PR) curve depicted in Figure 6 is also presented. The curve is close to the upper right corner of the graph, with a good Average Precision (AP) score of 0.9942, meaning that the precision is high over a wide range of recall values. This validation is a confirmation that the proposed CUS-DLM retains its detection performance for varying classification thresholds, and can classify spam comments with an acceptable rate that does not lead to many misclassifications of valid comments.
Ablation Study
An ablation experiment was conducted to investigate the effect of each of the proposed components in the Contextual Unified Spam Detection Learning Model (CUS-DLM), one by one and then the remaining components were frozen in the training configuration. The study compares the module based on HMM with the module based on BERT only and the Weighted Random Sampler on the overall classification performance. Each configuration was evaluated in terms of accuracy, precision, recall, F1-score and ROC-AUC.
The outcome of the ablation study is shown in Table 4. The overall performance was the highest with complete CUS-DLM, which outperforms the other methods with respect to all the evaluation scores: accuracy 96.94%, precision 97.01%, recall 97.01%, and f1-score 97.01%. The HMM-inspired module was removed to see a slight decrease in overall classification accuracy, indicating richer information than the contextual embedding learned by BERT is provided by probabilistic sequence modeling. A BERT baseline model was developed by omitting the HMM and sequence modeling modules, which showed competitive performance albeit with a slight decrease in overall balanced metrics to evaluate the impact of the added modules on the feature representation and the robustness of the classification. Furthermore, without the introduction of the weighted random sampler, the performance of all the evaluated configurations significantly decreased, highlighting the importance of the balanced mini-batch sampling in reducing prediction bias and enhancing generalization. Again a graphical comparison is given in Figure 7 to demonstrate the contribution of each component. The reduced configurations are competitive, while the full CUS-DLM always offers a balanced performance in all evaluation metrics.
Table 4.
Ablation Study of the Proposed CUS-DLM
Baseline Comparison
The performance of proposed Contextual Unified Spam Detection Learning Model (CUS-DLM) has also been compared with three widely used machine learning classifiers: Linear Support Vector Machine (SVM), Logistic Regression (LR) and Naïve Bayes (NB). For the purpose of the fair comparison, the baselines were trained and tested using the same training and testing partitions from the YouTube Spam Comment Dataset. Five common performance metrics: accuracy, precision, recall, F1-score, and ROC-AUC were employed for the evaluation.
A comparison of the performance of the proposed CUS-DLM with selected baseline classifiers is given in Table 5. The proposed framework with an accuracy of 96.43%, a precision of 96.52%, a recall of 96.52%, an F1 score of 96.52% and an ROC-AUC of 0.9917 performed best overall. The results demonstrate that the suggested model can well improve the accuracy of spam detection for spam comments and can achieve classification performance in all evaluation metrics. The Linear SVM model performed best with an accuracy of 94.64%; Logistic Regression came in second with 94.39%, and Naive Bayes, with 91.07%, was the worst. The proposed CUS-DLM, however, has the advantage of embedding BERT-based contextual embeddings, and the HMM-inspired sequence modeling module, which enable the framework to acquire the semantic and sequence characteristics of the comments in YouTube. Moreover, focal loss, weighted random sampling and balanced class weighting have been shown to further enhance learning performance on imbalanced data, resulting in more robust learning and better generalization. The graphical comparison in Figure 8 also confirms the better performance of the proposed framework over the baseline classifiers.
Table 5.
Baseline Comparison of the Proposed CUS-DLM
Besides quantitative enhancements through the proposed CUS-DLM, it is highly promising for the intelligent moderation of contents on a large scale for digital communication platforms in reality. The proposed model can effectively recognize spam comments by contextual semantic understanding and sequential feature learning to reduce the need for manual moderation, help mitigate the spread of spam comments, phishing attacks and misleading promotional posts. These capabilities enhance the quality, reliability, and trustworthiness of user interactions, supporting responsible practices with AI-driven moderation on online platforms. The suggested framework offers a scalable solution that can contribute to the creation of secure and sustainable digital communities, provide for real information sharing and improve the integrity of digital communication systems. 5.
To further contextualise the practical advantages of the proposed framework, its performance is compared with recent transformer-based and hybrid spam detection studies. Hasan et al. [18] reported a best RoBERTa accuracy of 92.71% on YouTube spam data, while Le et al. [28] achieved competitive results using a PhoBERT + TextCNN + BiLSTM hybrid restricted to a Vietnamese domain-specific corpus. Jo and Girsang [30] obtained 93.03% accuracy using BiLSTM with attention and Word2Vec. Compared with these transformer- and hybrid-based baselines, the proposed CUS-DLM attains a substantially higher accuracy of 96.43% and a ROC-AUC of 0.9917, while simultaneously modelling probabilistic state transitions through the HMM-inspired branch and bidirectional context through the BiGRU branch. This dual-branch design captures complementary semantic and sequential cues that single-branch transformer classifiers miss, which explains the observed performance advantage on noisy, short user-generated comments.
It is also important to briefly discuss the computational overhead introduced by combining BERT, the HMM-inspired module, and the BiGRU network. The BERT-base encoder contributes approximately 110 million parameters and dominates both the memory footprint and inference latency. The HMM-inspired branch and the BiGRU branch add only a small fraction of additional parameters (in the order of 1-2 million each) because they operate on the compact 768-dimensional BERT hidden states rather than on raw tokens. Empirically, the two auxiliary branches increase the per-sample inference time by less than 15% relative to a BERT-only baseline, which is acceptable for large- scale near-real-time content moderation and can be further reduced through standard optimisations such as mixed-precision inference (FP16), knowledge distillation to DistilBERT or TinyBERT backbones, ONNX- runtime deployment, and batched GPU inference. This confirms that the additional representational capacity of the proposed hybrid architecture is obtained at a modest computational cost, making the framework practical for deployment on large-scale digital communication platforms.
Conclusion
The present study proposed a novel Contextual Unified Spam Detection Learning Model (CUS-DLM) that integrates contextual language understanding, probabilistic sequence modelling, and bidirectional feature learning to enable intelligent content moderation for trustworthy digital communication in sustainable digital communities. The proposed framework combines BERT- based contextual embeddings, a Hidden Markov Model (HMM)-inspired neural module, and a Bidirectional Gated Recurrent Unit (BiGRU) network to effectively capture both the semantic and temporal characteristics of user-generated content. Furthermore, Weighted Random Sampling (WRS), balanced class weighting, and Focal Loss were incorporated to address class imbalance and improve learning stability and model generalization. Unlike conventional machine learning approaches that rely on handcrafted textual features, the proposed framework automatically learns robust contextual representations, enabling accurate identification of evolving spam patterns within dynamic digital communication environments.
The proposed framework was evaluated using a publicly available YouTube Spam Comment Dataset based on widely adopted performance metrics, including accuracy, precision, recall, F1-score, and ROC-AUC. Experimental results demonstrated superior classification performance, achieving an accuracy of 96.43%, precision of 96.52%, recall of 96.52%, F1-score of 96.52%, and ROC-AUC of 0.9917. The effectiveness and robustness of the proposed CUS-DLM were further validated through confusion matrix analysis, ROC and precision–recall curves, ablation studies, and comparative evaluation with conventional machine learning baselines.
Beyond its technical performance, the proposed framework provides an AI-enabled solution for intelligent content moderation that enhances the reliability, resilience, and trustworthiness of digital communication platforms supporting sustainable urban ecosystems. By automatically detecting malicious content and reducing the burden on manual moderation, the framework contributes to secure information exchange, responsible AI-driven governance, citizen engagement, and sustainable digital infrastructure for smart urban communities. These capabilities support the development of resilient digital ecosystems that facilitate reliable communication, informed public participation, and sustainable urban development.
Despite the strong empirical performance and practical value of the proposed CUS-DLM, several limitations of the present study should be acknowledged and will motivate future work. First, the evaluation was carried out on a single publicly available YouTube Spam Comment Dataset; although this dataset is widely adopted as a benchmark, additional cross-dataset and cross-platform experiments are needed to fully characterise generalisation to other content ecosystems such as X (Twitter), Instagram, and product-review corpora. Second, the framework is language-dependent in its current form, as it relies on the English BERT-base- uncased encoder; multilingual and low-resource extensions using mBERT, XLM-R, or language-specific encoders remain open directions. Third, while the computational overhead has been shown to be moderate, deployment at the scale of billions of daily comments will still require further engineering effort in terms of model compression, hardware acceleration, and streaming infrastructure. Finally, the study focuses on binary spam versus non-spam classification and does not yet address adversarial robustness, evolving spam-writing styles, or fine-grained multi-class categorisation of malicious content.
Future research will focus on extending the framework to multilingual and multi-class content moderation, integrating Explainable Artificial Intelligence (XAI) to improve model transparency and accountability, and investigating lightweight transformer architectures, continual learning, and model compression for scalable real-time deployment across smart city communication platforms, digital public services, and other sustainable urban information systems.








