Научный журнал «Вестник науки»

Режим работы с 09:00 по 23:00

zhurnal@vestnik-nauki.com

Информационное письмо
  1. Главная
  2. Архив
  3. Вестник науки от 27 апреля 2025 г.
  4. Научная статья № 77
Просмотры  205 просмотров

SENTIMENT ANALYSIS OF TEXTS FROM SOCIAL NETWORKS BASED ON MACHINE LEARNING METHODS FOR MONITORING PUBLIC SENTIMENT

Abstract: a sentiment analysis system powered by machine learning was created in this study to improve real-time social network public opinion monitoring. For sophisticated sentiment identification, the suggested approach combines cutting-edge transformer-based architectures (DistilBERT, RoBERTa) with traditional machine learning models (Logistic Regression, SVM, Naive Bayes). The system achieved an accuracy of up to 80–85% using transformer models in real-world scenarios after being tested using both deep learning techniques and standard machine learning processes on annotated social media datasets. According to experimental results, deep learning models perform noticeably better than lexicon-based and conventional rule-based classifiers, lowering misclassification rates and enhancing the ability to recognise nuances like sarcasm. According to feature importance analysis, context tokens, sentiment-bearing keywords, and part-of-speech structure are essential for precise categorisation. The findings confirm that AI-driven sentiment frameworks can provide a more adaptive and efficient approach to modern sentiment challenges. Despite the systems impressive performance, issues with computing overhead, data quality, and domain-specific terminology still exist. In order to monitor opinions on a broad scale, future research will investigate improving computing performance, extending coverage to various languages, and integrating real-time streaming APIs. The results demonstrate that governments, corporations, and social researchers looking for more in-depth understanding of public mood on digital platforms can find a reliable and adaptable answer in AI-powered sentiment analysis.

Keywords: sentiment analysis, social networks, machine learning, public sentiment, natural language processing, real-time monitoring.

INTRODUCTION. Due to their explosive expansion, social media sites like Facebook* (запрещено в РФ), Twitter* (запрещено в РФ), and Reddit have become enormous libraries of public opinion. These platforms are being used by governments, corporations, and researchers more and more to measure sentiment changes in real time. Because language is constantly changing online, conventional text categorisation or keyword-based algorithms sometimes fail to keep up with the variety of linguistic styles, slang, and sarcasm that are common on social networks.

As a result, adaptive, AI-powered techniques that can accurately read and categorise attitudes at scale are required. Sentiment analysis has seen significant promise from machine learning (ML), especially when it comes to handling linguistic ambiguity. Initial studies investigated lexicon-based techniques for sentiment recognition; however, these algorithms frequently fall short in capturing sarcasm, subtle context, or recently developed slang. Better accuracy has been shown using more sophisticated supervised machine learning classifiers (like Support Vector Machines, Logistic Regression, and Naive Bayes) and deep learning models (like LSTM networks, Transformers) that train data-driven representations of language.

However, there are drawbacks to these approaches as well, namely the requirement for substantial computing resources and big annotated datasets.In this paper, we provide a machine learning-based sentiment analysis system for real-time sentiment monitoring and classification of social media data. Building on contemporary machine learning pipelines, such as transformer-based language models and TF-IDF-based feature extraction, the work seeks to improve the precision, versatility, and effectiveness of public sentiment monitoring systems. The approach, which was developed as part of a masters research thesis at Astana IT University, combines literature evaluations with practical experiments to verify the suggested framework in authentic social networking settings.RELATED WORK. Sentiment analysis in Machine Learning.

Sentiment analysis, also known as opinion mining, is the process of examining textual data to ascertain its subjective content, which can be neutral, negative, or positive (Pang & Lee, 2008). Lexicon-based techniques, which map words to lexicons that include sentiment, were the foundation of traditional approaches (Taboada et al., 2011). They usually misclassify complicated verbal patterns, such sarcasm and multiword idiomatic statements, while being straightforward and interpretable (Liu, 2012). Supervised learning algorithms have shown to be more flexible.

In text classification tasks, Support Vector Machines showed a high level of accuracy after being first proposed by Cortes and Vapnik (1995) (Pang et al., 2002). McCallum and Nigam (1998) state that Naive Bayes is still a commonly used baseline, particularly for substantial text analytics. In order to improve accuracy, deep learning methods like CNNs, RNNs, and LSTM networks learn hierarchical text properties (Socher et al., 2013). Recent years have seen the introduction of transformer-based architectures, like as BERT and RoBERTa, to greatly improve state-of-the-art performance in NLP applications, including sentiment analysis.Social Media as a Data Source.

Massive volumes of user-generated text are produced by social networks, opening up possibilities for sentiment monitoring in real time (Bollen et al., 2011). However, traditional NLP pipelines face difficulties due to their dynamic character, which is full of slang, hashtags, and informal spelling. How data is collected and analysed is also heavily influenced by ethical considerations, especially those pertaining to user privacy and data governance (Crawford & Schultz, 2014).Challenges in Real-Time Monitoring. Language change (new slang, memes), processing massive data streams, and recognising context-dependent phenomena like irony and sarcasm are the biggest challenges.

Deep learning solutions usually require strong GPU resources, and large text volumes strain typical machine learning procedures. According to Mehrabi et al. (2021), bias in training data also affects the generalisability and fairness of the model.PROPOSED FRAMEWORK. Inspired by advanced AI approaches in cybersecurity monitoring—where real-time anomaly detection is paramount—this work adapts a similar multi-model strategy for sentiment analysis.

The framework comprises:Data Collection and Preprocessing. APIs and Web Scraping: Harvest tweets or Reddit comments.Cleaning & Normalization: Remove URLs, special characters, convert to lowercase, tokenize text, and filter stopwords.Annotation: Use labeled datasets (positive, negative, neutral) or partially labeled data augmented by annotation tools.Data Collection and Preprocessing. Feature EngineeringTF-IDF Vectors: Compute term frequency–inverse document frequency scores to highlight important words.Subword Tokenization: Transform text into subword tokens (e.g., via DistilBertTokenizerFast) to handle out-of-vocabulary words.Table 1. Example records from the annotated social-media dataset.

Model Selection. Classical ML: Logistic Regression, SVM, Naive Bayes on TF-IDF vectors.Transformer-Based Approaches: DistilBERT, RoBERTa fine-tuned on labeled data for greater contextual understanding.Ethical and Privacy Considerations. Data Anonymization: Strip user-identifiable information in compliance with regulations such as GDPR.Bias Mitigation: Use diverse training data and fairness-aware algorithms where possible (Doshi-Velez & Kim, 2017).Deployment. Real-Time Stream Monitoring: Ingest data from streaming APIs (e.g., Twitter* (запрещено в РФ), API) for near-instantaneous updates.Inference Engine: Batch or real-time classification using either classical or transformer-based ML.User Interface / Dashboards: Graphical or API-based interfaces for visualizing sentiment trends.IMPLEMENTATION AND EXPERIMENTS.

Here, we describe the experimental setup, data preprocessing, hyperparameter tuning, and final results of our sentiment analysis models. We conducted experiments on a carefully curated dataset of social media text (~27k tweets), with 80% training and 20% testing. We experimented with five classifiers: Naive Bayes, Logistic Regression, SVM, DistilBERT, and RoBERTa. We measured each model on Accuracy, Precision, Recall, and F1 Score.

As an extra perspective, we also present confusion matrices for the four principal models used in this project.Data Preprocessing and Exploratory Analysis. Data Cleaning. Removal of URLs and Mentions: We used a regex-based approach to strip out URLs (e.g., http://...) and user mentions (e.g., @username) to reduce noise.Lowercasing: All text was transformed to lowercase for consistency.Stopword Filtering: Common English stopwords (e.g., the, a, an) were removed to emphasize more semantically important words.Tokenization: We split text into individual tokens (words or subwords), allowing for more precise feature extraction or embedding generation.Annotation review. The dataset contained three sentiment classes—negative (neg), neutral (neu), and positive (pos).We randomly sampled 300 instances to cross-check sentiment annotations; consistency was above 95%, indicating that labels were generally reliable.Feature Extraction.

TF-IDF: Traditional classifiers (Naive Bayes, Logistic Regression, SVM) were trained on TF-IDF vectors. A maximum vocabulary size of 10,000 features was chosen to balance information content and computational efficiency.Transformer Tokenization: For DistilBERT and RoBERTa, we used subword tokenization (e.g., WordPiece or Byte-Pair Encoding) via the Hugging Face TokenizerFast classes. We set a max_length of 64 tokens, padding shorter sequences and truncating longer ones.Model Training And hyperparameters. Link to the code base: https://colab.research.google.com/drive/1UVjiu8P-pu2Us45bsSTNirY_UNvLJB_v?usp=sharing Naive Bayes was implemented using MultinomialNB from scikit-learn.

The smoothing parameter (α) was set to 1.0 (default), as this often provides decent performance in text classification tasks. Logistic Regression was implemented with scikit-learn’s model using an L2 penalty. C (inverse of regularization strength) was tuned over the set {0.1,1.0,10.0}, with 1.0 performing best in cross-validation. SVM was Implemented using SVC(kernel=linear) in scikit-learn. Similar to Logistic Regression, C was grid-searched over {0.1,1.0,10.0}. A value of 1.0 gave balanced results in terms of accuracy and generalization. As model we used distilbert-base-uncased from Hugging Face. 2–3 epochs were set, to prevent overfitting on a relatively small dataset (27k is moderate, but not huge for language models).

Batch size was chosen between16–32, depending on GPU memory availability. Learning rate is 5×10−5 with a linear warmup over 10% of the steps. Model is roberta-base from Hugging Face. Epochs were similar as DistilBERT. Batchs size was chosen between 16–32 as well.

Learning rate is typically: 3×10−5 or : 5×10−5. A small grid search indicated 3e-5 performed slightly better on the validation split.Model Performance. A condensed performance summary is shown in Table 1 below. All models were evaluated on the same 20% test set (approximately 5,400 posts):Table 2.

Key hyper-parameters selected for each classifier. Figure 1. F1-score of classical versus transformer-based models. Key Observations:RoBERTa outperforms the other models, especially on posts containing slang or mild sarcasm, reflecting the strength of contextual embeddings.Classical ML approaches (Logistic Regression, SVM) remain more resource-efficient, though they underperform by about 10% on F1 compared to transformers.Naive Bayes lags in part because it often struggles with short, slang-filled social media text that does not match typical independence assumptions.Confusion Matrix Analysis.Below are the confusion matrices for four of our key models, visualizing how each classifier deals with negative (neg), neutral (neu), and positive (pos) classes.Figure 2.

Confusion matrix for the Logistic-Regression classifier.Interpretation.The classifier correctly identified a large majority of negative posts (938) but misclassified about 538 of them as neutral.It also demonstrated moderate confusion between neutral and positive classes (254 neu → pos, 482 pos → neu).Overall, Logistic Regression excels in distinguishing strongly negative language but struggles when the post is subtly positive or emotionally ambiguous.Figure 3. Confusion matrix for the SVM classifier.Interpretation. The SVM shows slightly better discrimination in all three classes than Logistic Regression, reducing misclassifications of negative → neutral from 538 to 523.A notable improvement is seen in the neutral → negative confusion (294 vs. 308 for LR).The neutral → positive confusion remains an issue (256), though slightly lower than in LR (254). Overall, SVM’s margin-based approach yields a small edge.Figure 4.

Confusion matrix for the Naïve-Bayes classifier.Interpretation. High confusion between negative and neutral classes: 830 neg → neu. Naive Bayes often over-relies on words that appear frequently in “neutral” contexts, diluting the “negative” signal.The model also confuses positive with neutral quite often (719 pos → neu), indicating it struggles with subtle positivity, especially if emotive keywords are missing.Despite these gaps, Naive Bayes remains fast to train and runs efficiently on CPU, making it attractive for quick prototyping or low-resource environments.Figure 5. Confusion matrix for the RoBERTa classifier.Interpretation.

The largest gains are evident in the negative class: 1274 correct neg predictions, which is substantially higher than any classical model.It still confuses some neutral posts as negative (294) and some positive ones as neutral (249), though these numbers are lower than in any of the classical approaches.High true positives in the positive class (1433) demonstrate the model’s effectiveness in capturing context-laden or emotive language that signals positivity.Overall, RoBERTa’s rich language representation results in fewer cross-class confusions, boosting the final F1 score to 0.80.DISCUSSION. Our findings validate state-of-the-art machine learning approaches especially transformer-based architectures in sentiment analysis tasks. The contextualized embeddings capture nuances which are missed by simplistic lexicon-based methods. However, large transformer models are computationally expensive to be used in real-time inference and may require optimizations or condensed model (DistilBert) for their practical usage.

Ethics and consideration still has the utmost importance. Social media data often includes personally identifying information and sensitive data. Systems that scrape this sort of data constantly should have strict anonymization protocols and comply with data privacy laws. There are risks of bias as well; if training data are biased toward particular demographic or linguistic cohorts, model outputs can systematically misrepresent other communities.Conclusion and Future Work.

The suggested solution shows how well deep learning and sophisticated machine learning techniques may be used to analyse sentiment in real time on social networks. Higher accuracy and flexibility in public sentiment classification may be attained by combining potent transformer-based models (DistilBERT, RoBERTa) with traditional machine learning pipelines (TF-IDF + SVM/Logistic Regression).Key Findings. Transformer-based models outclass standard machine learning models by 10–11% in terms of F1 scores, considering their superior ability to capture context nuances in the task of sentiment analysis. In spite of its feasibility in monitoring sentiment in real time using the advanced models, it needs proficient data pipelines coupled with significant GPUs to address computing requirements.

Furthermore, ethical and privacy concerns are also paramount when applying mass-scale sentiment monitoring systems, especially in business or governmental use, where the data of users has to be managed ethically in order to remain compliant with privacy laws and uphold public trust.Limitations. Although their performance is great, transformer models suffer from a couple of important weaknesses. They are immensely resource hungry and may be immensely resource-demanding to fine-tune and run in real-time, usually requiring high-performance GPUs to manage the load properly. The second weakness is biased training data risk, which will lead to biased or skewed sentiment prediction, which can mislead certain groups or opinions.

One of the most difficult to overcome is perhaps detecting sarcasm—something that even humans also get wrong. Transformers have the tendency to disregard the finer details and context needed to detect sarcasm, pushing the need for more sophisticated models to handle such subtlety.Future Research. Scalability: Deploying the system on cloud-based or distributed architectures for large-scale streaming data.Multilingual Support: Extending the framework to handle multiple languages and cross-cultural slang.Explainability: Integrating interpretability tools (e.g., LIME, SHAP) to improve trust in sentiment predictions.Continuous Learning: Adapting the system to evolving language trends by retraining on newly collected text samples.Finally, AI-powered sentiment analysis tools offer a sophisticated, adaptive way of capturing the evolution of public opinion as it shifts on social media. These sites, improving computational power, lowering bias, and facilitating real-time analytics, can transform fields such as market research, brand reputation management, and policy-making by offering policymakers timely, evidence-based insights into online community sentiment.


Полная версия статьи PDF

Номер журнала «Вестник науки» № 4 (85) том 4


Ссылка для цитирования:

Tolebay A.N. SENTIMENT ANALYSIS OF TEXTS FROM SOCIAL NETWORKS BASED ON MACHINE LEARNING METHODS FOR MONITORING PUBLIC SENTIMENT // Журнал «Вестник науки» от 27 апреля 2025 г. № 4 (85) том 4. С. 610 - 623. 2025 г. ISSN 2712-8849 // Электронный ресурс: https://www.вестник-науки.рф/article/22577 (дата обращения: 29.11.2026 г.)


Альтернативная ссылка латинскими символами: vestnik-nauki.com/article/22577



Нашли грубую ошибку (плагиат, фальсифицированные данные или иные нарушения научно-издательской этики) ?
- напишите письмо в редакцию журнала: zhurnal@vestnik-nauki.com


Вестник науки © 2025.    16+




* В выпусках журнала могут упоминаться организации (Meta, Facebook, Instagram) в отношении которых судом принято вступившее в законную силу решение о ликвидации или запрете деятельности по основаниям, предусмотренным Федеральным законом от 25 июля 2002 года № 114-ФЗ «О противодействии экстремистской деятельности» (далее - Федеральный закон «О противодействии экстремистской деятельности»), или об организации, включенной в опубликованный единый федеральный список организаций, в том числе иностранных и международных организаций, признанных в соответствии с законодательством Российской Федерации террористическими, без указания на то, что соответствующее общественное объединение или иная организация ликвидированы или их деятельность запрещена.