<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Arkan Alireza on Medium]]></title>
        <description><![CDATA[Stories by Arkan Alireza on Medium]]></description>
        <link>https://medium.com/@arkanalireza?source=rss-cdae932c67b0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Y_v2elJwMtq1cuQW</url>
            <title>Stories by Arkan Alireza on Medium</title>
            <link>https://medium.com/@arkanalireza?source=rss-cdae932c67b0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 18:48:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@arkanalireza/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Sentiment Analysis on Trump’s Shooting]]></title>
            <link>https://medium.com/@arkanalireza/sentiment-analysis-on-trumps-shooting-fc27cd40bada?source=rss-cdae932c67b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc27cd40bada</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[politics]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Arkan Alireza]]></dc:creator>
            <pubDate>Wed, 18 Sep 2024 07:56:26 GMT</pubDate>
            <atom:updated>2024-09-18T07:56:26.742Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SYRxG4IzhSVG72mu.jpg" /><figcaption>From <a href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fwww.cnn.com%2Finteractive%2F2024%2F07%2Fpolitics%2Fphotographers-trump-shooting-cnnphotos%2F&amp;psig=AOvVaw25yOj-F5pTBxgFhrV_KJnw&amp;ust=1726732065399000&amp;source=images&amp;cd=vfe&amp;opi=89978449&amp;ved=0CBQQjRxqFwoTCOD1sq6AzIgDFQAAAAAdAAAAABAE">CNN</a> — Google Images</figcaption></figure><p>On July 13, 2024, in Butler, Pennsylvania, an alarming incident unfolded during a campaign rally for former President Donald Trump, attended by thousands. During Trump’s speech, a man named Thomas Matthew Crooks suddenly opened fire, causing widespread panic among the attendees. Secret Service agents swiftly evacuated Trump from the stage, while a nearby sniper neutralized the shooter within moments. The shocking nature of the event has not only captivated the nation but also sparked widespread discussions regarding the growing threat of political violence and the urgent need for enhanced security measures.</p><p>This article examines the public’s response to the shooting, hypothesizing that the public largely condemns the perceived incompetence of the Secret Service and views the incident as part of an orchestrated conspiracy.</p><h3>Discussion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uuJne5_VHjC-9tXn" /><figcaption>Proportions on Sentiments in Tree map</figcaption></figure><p>In order to comprehend the public’s reaction to the Trump shooting incident, an analysis of comments from six YouTube news videos related to the event was conducted. These comments were categorized based on sentiment using a model from Hugging Face, a leading natural language processing library. The sentiment analysis revealed that the majority of comments were negative, with 42,049 negative comments, followed by 18,058 positive comments, and 15,725 neutral comments. This distribution underscores the predominantly negative sentiment among the public, though some positive and neutral views were also present.</p><h3>Bigram Analysis</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*-YO-u7qOOLTgDJ2Zj543jw.png" /></figure><p>Bigram analysis, which looks at frequently occurring pairs of words, was crucial in identifying the main keywords and themes in this discussion. Phrases like “inside job,” “secret service,” “fake news,” and “assassination attempt” were commonly found across different sentiment categories, highlighting the recurring themes in the public discourse. These bigrams played a pivotal role in shaping the narrative surrounding the Trump shooting incident, encapsulating public concerns about conspiracy theories and institutional competence. Given the prominence of these keywords, a deeper analysis was conducted on both “inside job” and “secret service” to explore the public’s perceptions of conspiracy theories and the performance of the Secret Service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*Yy36AJ89ypH7k3qr2hFxgg.png" /><figcaption><strong>Positive Sentiment from Keyword ‘inside job’</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*J_0w3_2O8--iLkRKC8fWig.png" /><figcaption><strong>Neutral Sentiment from Keyword ‘inside job’</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*MsqM-HANxyUr5K5nIkPIsA.png" /><figcaption><strong>Negative Sentiment from Keyword ‘inside job’</strong></figcaption></figure><p>The term “inside job” frequently appeared in discussions about the Trump shooting, especially among those inclined to believe in conspiracy theories. Many comments reflect a deep-seated suspicion that the shooting was not a random act of violence but rather a planned event orchestrated by certain groups with political motives. Key themes emerged in these discussions:</p><p><strong>Widespread Conspiracy Theories:</strong></p><p>A significant portion of comments suggest that the shooting was part of a larger scheme orchestrated by powerful entities within the government or other influential institutions. This narrative is supported by a pervasive distrust of official accounts, leading to widespread speculation that the event was staged or manipulated.</p><p><strong>Political Accusations and Partisanship:</strong></p><p>The “inside job” narrative is often used to advance partisan agendas, with many commenters blaming specific political groups, particularly those on the left, such as Democrats. This use of conspiracy theories to discredit political opponents reflects the deep political polarization evident in much of the commentary.</p><p><strong>Historical Comparisons:</strong></p><p>References to past political assassinations and conspiracies, such as the JFK assassination, are common in these discussions. By drawing parallels to these historical events, commenters reinforce their belief that the Trump shooting is part of a broader pattern of politically motivated violence and deception.</p><p><strong>Underlying Distrust and Cynicism:</strong></p><p>The overarching sentiment expressed through the “inside job” keyword is one of profound distrust and cynicism. Whether directed at government agencies, political figures, or broader institutions, these discussions reveal a widespread belief that the public is being deceived or manipulated. This reflects a broader societal anxiety about power, control, and the integrity of democratic processes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*EAu3qdCAmHJZNWH_rMdlvw.png" /><figcaption><strong>Positive Sentiment from Keyword ‘secret service’</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*m4Y_eocdD2SaZIbxXRYpwg.png" /><figcaption><strong>Neutral Sentiment from Keyword ‘secret service’</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*N1izNtSHHMxGtP1aZf7O_Q.png" /><figcaption><strong>Negative Sentiment from Keyword ‘secret service’</strong></figcaption></figure><p>The term “secret service” is central to discussions about the Trump shooting incident, generating a range of responses that include harsh criticism as well as recognition of the agency’s critical role. These discussions reflect public expectations, disappointments, and broader concerns about the competence and reliability of government institutions, particularly those tasked with protecting high-profile figures.</p><p><strong>Criticism and Doubt:</strong></p><p>A significant portion of comments express skepticism about the Secret Service’s performance during the incident. Criticism ranges from doubts about their competence to outright accusations of negligence or even complicity. This reflects broader dissatisfaction with government institutions and a lack of confidence in their ability to effectively protect high-profile individuals like Trump.</p><p><strong>Recognition of Critical Role:</strong></p><p>Despite the criticism, there is acknowledgment of the Secret Service’s essential role in high-stakes situations like this. Commenters discuss specific actions taken by agents, such as deploying snipers and executing protective maneuvers, indicating an awareness of the complexity and difficulty of the agency’s responsibilities. This suggests that while there may be disappointment, there is also recognition of the critical nature of their work.</p><p><strong>Attention to Tactical Details:</strong></p><p>Many comments mention the tactical aspects of the Secret Service’s response, such as agent positioning, timing, and strategies employed. This focus on operational details reflects a high level of public interest in understanding how such crises are managed and what could have been done differently. It indicates that the public is concerned not only with the outcomes but also with the processes by which security is maintained.</p><p><strong>Distrust and Accountability:</strong></p><p>Underlying much of the discourse is a theme of distrust toward the Secret Service and other governmental institutions. Commenters frequently question whether the agency fulfilled its duties adequately and whether there were lapses in security or judgment. This skepticism is part of a broader narrative that seeks to hold institutions accountable, especially those tasked with protecting the nation’s most high-profile and vulnerable figures.</p><p><strong>High Expectations and Comparisons:</strong></p><p>There is also an element of comparison in the comments, with some suggesting that the Secret Service should have performed better, possibly drawing on past incidents or expected standards of protection. This reflects the high expectations the public has for the Secret Service, viewing it as a cornerstone of national security and therefore particularly critical when perceived failures occur.</p><h3>Conclusion</h3><p>This analysis reveals that deep distrust and widespread cynicism toward authority and government institutions dominate the public’s response to the Trump shooting incident. The “inside job” keyword underscores how conspiracy theories and narratives of mistrust are shaping public interpretations of the event. Meanwhile, discussions surrounding the “secret service” show that, despite the recognition of their critical role, the agency faces harsh criticism for its perceived failures. These sentiments, rooted in distrust and high expectations, reflect the increasingly polarized political atmosphere and pervasive skepticism in institutions that are expected to protect and serve the public.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc27cd40bada" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comparative Study of Weak Labelling and Manual Labelling on Indonesian Natural Disasters Tweets.]]></title>
            <link>https://medium.com/@arkanalireza/comparative-study-of-weak-labelling-and-manual-labelling-on-indonesian-natural-disasters-tweets-261fd4423692?source=rss-cdae932c67b0------2</link>
            <guid isPermaLink="false">https://medium.com/p/261fd4423692</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Arkan Alireza]]></dc:creator>
            <pubDate>Sun, 12 May 2024 08:02:38 GMT</pubDate>
            <atom:updated>2024-06-04T03:56:18.261Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2nx3U8g-S46o2H8PSEQDhg.jpeg" /><figcaption>Natural disasters by Dall E</figcaption></figure><p>In the ever-evolving landscape of data science, the challenge of effectively labeling vast amounts of data remains a significant hurdle. This research investigates an innovative approach explored in my undergraduate thesis, where weak supervision is utilized to classify Indonesian natural disaster tweets. By leveraging a query-based programmatic function, this research aims to bridge the gap between traditional supervised learning methods and the emerging field of weak supervision, highlighting its potential in time-critical situations.</p><h3>Background: The Need for Efficient Data Labeling</h3><p>Supervised learning has long been the cornerstone of many machine learning applications. However, it comes with a notorious challenge: the need for large, manually labeled datasets. This process is not only time-consuming and laborious but often results in a limited number of labeled data points. This bottleneck is particularly problematic in scenarios requiring rapid response, such as natural disasters, where timely and accurate information is crucial.</p><p>In this context, weak supervision emerges as a promising alternative. Unlike traditional supervised learning, weak supervision leverages various sources of noisy, incomplete, or imprecise labels to generate a larger training dataset. This method has been explored in various domains, but its application in natural disaster tweet classification presents a novel and exciting frontier.</p><h3>Objectives: Bridging the Gap with Weak Supervision</h3><p>The primary goal of this research is to utilize weak supervised learning with a query-based programmatic function to build a robust training dataset. The study also aims to compare the performance of manually labeled datasets with weakly labeled datasets using two classifiers: Support Vector Machine (SVM) and Long Short-Term Memory (LSTM).</p><h4>Problem Statement:</h4><ul><li>Manual labeling in supervised learning is time-consuming and laborious and often results in a limited number of labeled datasets.</li><li>Performance comparison between manually labeled datasets and weakly labeled datasets has not been assessed up to the classification stage.</li><li>To utilize weak supervised learning with a query-based programmatic function for building the training dataset.</li><li>To perform a comparison between manually labeled and weakly labeled datasets using SVM and LSTM as classifiers.</li><li>Weak supervision provides an easier, time-saving, and less laborious method to label datasets for training compared to traditional supervised learning.</li></ul><h3>Methodology</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/0*mSo7mje9BNavzX08" /><figcaption>Flowchart of overall research</figcaption></figure><p>This research aims to compare weak supervision with traditional supervised learning using a dataset from previous research, supplemented with additional Twitter data. The primary tools used in this study include Rubrix for creating and applying labeling models, Snorkel for evaluating labeling models with performance metrics, and classifiers such as Support Vector Machine (SVM) and Long Short-Term Memory (LSTM) for machine learning and deep learning tasks.</p><p>The dataset is split into 70% training data and 30% testing data, with additional data scraped from Twitter using natural disaster keywords. The workflow begins with labeling the scraped Twitter data using Rubrix. The labeling models are then built and evaluated with Snorkel, utilizing performance metrics like Coverage, Conflicts, and Precision.</p><p>Before training the classifiers, the data undergoes preprocessing to ensure consistency and reduce noise. Both the training data and the weakly labeled data are used to train the SVM and LSTM classifiers. The performance of these classifiers is then evaluated using the same test dataset, with metrics such as accuracy, precision, recall, and F1-score.</p><p>By following this streamlined workflow, the research highlights the efficiency of weak supervision compared to traditional supervised learning, providing key insights into their performance and applicability.</p><h4>Data Collection and Data Description</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/0*YonaHwBYz0ZzQ8HV" /><figcaption>Flowchart of Dataset Collection and Preprocessing</figcaption></figure><p>We are utilizing a dataset of tweets gathered using the Twitter API, focusing on various disaster-related keywords such as earthquake, flood, typhoon, drought, landslide, tsunami, and coastal erosion. This approach ensures our disaster model captures a wide range of natural disasters, rather than being limited to a single type.</p><p>The tweets in the dataset are categorized as either “Disaster Tweets” (labeled as 1) if they contain information about natural disasters, or “Non-Disaster Tweets” (labeled as 0) if they do not. This dataset is based on previous research by Dharma and Winarko (2022) and consists of approximately 6,000 tweets, evenly split between disaster-related and non-disaster-related content.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/0*SMpfudNQtPe_ZUzm" /><figcaption>Sample of tweets from original dataset</figcaption></figure><p>In addition to this, we have expanded our dataset by applying similar scraping methods to gather more data. This effort resulted in an additional 30,000 tweets, which will be used to train a separate model, later known as the weak model. The snippets code bellow is example of scraping data using snscrape module.</p><pre>import snscrape.modules.twitter as sntwitter<br>import pandas as pd<br><br>query = &quot;banjir lang:id -filter:links -filter:replies&quot;<br>tweets = []<br>limit = 10000<br><br><br>for tweet in sntwitter.TwitterSearchScraper(query).get_items():<br>    <br>    # print(vars(tweet))<br>    # break<br>    if len(tweets) == limit:<br>        break<br>    else:<br>        tweets.append([tweet.date, tweet.username, tweet.content])<br>        <br>df = pd.DataFrame(tweets, columns=[&#39;Date&#39;, &#39;User&#39;, &#39;Tweet&#39;])<br>print(df)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VzXXW5sEyPMk9YdvC4Yl3g.png" /><figcaption>Samples of scrapped tweet</figcaption></figure><h4>Data Preparation</h4><p>Our dataset of 6,049 tweets will be divided into two parts: 70% for training and 30% for testing. This results in 4,234 tweets in the training set and 1,815 tweets in the test set, which will be used for standard supervised learning. We also have an additional set of scraped data, labeled using a weak supervision method, referred to as the “weakly labeled train dataset.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/0*6f956Lus0U8z-UsA" /><figcaption>Sample of scrapped tweets</figcaption></figure><p>Both the original and scraped datasets may contain various unnecessary characters, such as HTML links, emoticons, and symbols, which can interfere with the learning process. To address this, we will perform a thorough data preprocessing step. This involves:</p><ol><li>Removing symbols.</li><li>Eliminating stop-words.</li><li>Applying case-folding.</li><li>Removing duplicate tweets to reduce noise in the dataset.</li></ol><pre>import re<br>import nltk<br>import pandas as pd<br>from Sastrawi.Stemmer.StemmerFactory import StemmerFactory<br><br># Load the Indonesian stopwords<br>stopwords = nltk.corpus.stopwords.words(&#39;indonesian&#39;)<br><br># Load the Porter stemmer<br>factory = StemmerFactory()<br>stemmer = factory.create_stemmer()<br><br># Define a function to preprocess the text<br>def preprocess_text(text):<br>    # Convert the text to lowercase<br>    text = text.lower()<br>    <br>     # Remove URLs<br>    text = re.sub(r&#39;http\S+&#39;, &#39;&#39;, str(text))<br>    <br>    # Remove usernames<br>    text = re.sub(r&#39;@\w+&#39;, &#39;&#39;, str(text))<br>    <br>    # Remove hashtags<br>    text = re.sub(r&#39;#\w+&#39;, &#39;&#39;, str(text))<br>    <br>    # Remove punctuation and special characters<br>    text = re.sub(r&#39;[^\w\s]&#39;, &#39;&#39;, str(text))<br>    <br>    # Remove emoticons<br>    text = re.sub(r&#39;:\)|;\)|:-\)|\(-:|:\&#39;\(|:\(|:-\(|:O|8\)|:\*|&gt;:O|:\-\/|\^\^|:D|:P|:S|:\|&#39;, &#39;&#39;, str(text))<br>    <br>    #Remove number<br>    text = re.sub(r&#39;\d+&#39;, &#39;&#39;, str(text))<br>    <br>    # Remove extra whitespace<br>    text = re.sub(r&#39;\s+&#39;, &#39; &#39;, str(text)).strip()<br>    <br>    # Remove stopwords<br>    text = [word for word in text.split() if word not in stopwords]<br><br>    # Stem the words<br>    text = [stemmer.stem(word) for word in text]<br>    <br>    # Detokenize the tokens to form text<br>    text = &#39; &#39;.join(text)<br>    <br>    return text</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/0*vjyRjqtSuYuDs_HS" /><figcaption>Sample of preprocessed tweets</figcaption></figure><p>After these cleaning processes, we will have:</p><ul><li>A clean training dataset</li><li>A clean weakly labeled train dataset</li><li>A clean test dataset</li></ul><p>These cleaned datasets will then be used to train our models and build classifiers, ensuring a more accurate and efficient learning process.</p><h4>EDA</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*IT-6lFbqGymSfXUn0qnEmg.png" /><figcaption>Distribution of labels between previous dataset and Word Cloud for each dataset.</figcaption></figure><p>The pie charts illustrate the distribution of labels in both the original dataset (based on previous research) and the weakly labeled dataset. In the original dataset, the distribution is almost balanced, with 50.2% of tweets labeled as disaster-related (1) and 49.8% labeled as non-disaster-related (0). This near-equal split ensures a balanced representation of both classes during training.</p><p>In contrast, the weakly labeled dataset shows a more skewed distribution, with 73.8% of tweets labeled as non-disaster-related (0) and only 26.2% labeled as disaster-related (1). This imbalance highlights the need for careful handling during model training to prevent bias towards the majority class.</p><p>The word clouds visualize the most frequently occurring words in the tweets from both datasets. The left word cloud represents the text data from the original research dataset. Prominent words include “pusat” (center), “gempa” (earthquake), “rasa” (feel), “km” (kilometers), and “kdl” (coordinates), indicating a focus on earthquake-related information.</p><p>The right word cloud represents the text data from the weakly labeled dataset. Key terms include “gempa” (earthquake), “puting” (tornado), “beliung” (whirlwind), “banjir” (flood), and “angin” (wind), showcasing a broader range of natural disasters covered in this dataset.</p><h3>Weak Modelling</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/0*HSoj3aZ5eDhpAsw3" /><figcaption>Flowchart of Weak Modelling</figcaption></figure><h4><strong>Query-based weak modeling</strong></h4><p>We begin the rule-setting process by importing both the scraped tweet dataset and the test dataset. Once imported, these datasets can be viewed in Rubrix’s web UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/0*sFjkeI9dDxI5aaJe" /><figcaption>Example of Rubrix web UI</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/0*LcnO4lG4Any-mgSs" /><figcaption>Labelling using Rubrix Web UI</figcaption></figure><p>There are two methods for writing rules for weak supervision: using the Rubrix UI or programmatically coding the rules in Python. In our research, we utilized the Rubrix UI for writing rules. Although programmatic rules offer more flexibility, the query-based approach using Rubrix UI is easier and allows for real-time evaluation, making it simpler to fine-tune the labels and rulesets. By clicking the tag icon on the right side, we can access the ruleset labeling feature in Rubrix UI.</p><h4><strong>Evaluate label model</strong></h4><p>The flowchart includes a diamond box labeled ‘Is it good?’ which represents the researcher’s satisfaction with the label modeling. If the performance of the label functions is not satisfactory, we can adjust the label function by adding queries or modifying the rules. The level of satisfaction varies between researchers. Since there is no standard benchmark for the performance of label models, we aim to balance maximizing coverage while maintaining accuracy. In our case, we achieved approximately 85% precision for the ‘Is it good?’ metric.</p><p>The rulesets are then fitted into a label model using Snorkel. Snorkel uses a generative model to automatically aggregate these outputs into probabilistic labels, which are then used to train a discriminative model (Ratner et al., 2017). The labels applied to the unlabeled dataset are referred to as the weakly labeled dataset.</p><h3><strong>Classifier training</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/0*XQjlSnfizwnwD_bC" /><figcaption>Flowchart of classifier training</figcaption></figure><p>After completing data preparation and label modeling, we have three distinct datasets: test data, train data, and weakly labeled train data. Each train dataset and weakly labeled train dataset will be trained individually using two learning algorithms: LSTM and SVM.</p><p>For SVM, we will use Count Vectorizer to convert text into numerical features. These features will then be trained using LinearSVC. For LSTM, we will utilize an LSTM layer with 64 units and a sigmoid activation layer. Each dataset will be trained with both algorithms, resulting in four different models:</p><ul><li>LSTM Supervised Model: LSTM trained on the train dataset.</li><li>LSTM Weak Model: LSTM trained on the weakly labeled train dataset.</li><li>SVM Supervised Model: SVM trained on the train dataset.</li><li>SVM Weak Model: SVM trained on the weakly labeled train dataset.</li></ul><p>Additionally, we will combine the datasets and train them using both LSTM and SVM, referred to as the SVM or LSTM Weak Model Combined. Each learning model will be evaluated using classification performance metrics to determine their effectiveness and accuracy.</p><p><strong>Training SVM</strong></p><pre>import pandas as pd<br>from transformers import AutoTokenizer<br>from sklearn.feature_extraction.text import CountVectorizer<br>from sklearn.pipeline import Pipeline<br>from sklearn import svm<br>from sklearn.metrics import accuracy_score, f1_score, recall_score, classification_report, confusion_matrix<br>import matplotlib.pyplot as plt<br>import seaborn as sns<br><br># Load the training data<br>df = pd.read_csv(&quot;preprocessed_train.csv&quot;)<br>train_data = df.text<br>train_labels = df.label<br><br># Instantiate the tokenizer<br>tokenizer = AutoTokenizer.from_pretrained(&quot;MoritzLaurer/mDeBERTa-v3-base-xnli-multilingual-nli-2mil7&quot;)<br><br># Define the classification pipeline<br>classifier = Pipeline([<br>    (&#39;vect&#39;, CountVectorizer(tokenizer=tokenizer.tokenize)),<br>    (&#39;clf&#39;, svm.SVC(kernel=&#39;linear&#39;))<br>])<br><br># Train the classifier<br>classifier.fit(X=train_data, y=train_labels)</pre><p>This code snippet performs building a Support Vector Machine (SVM) model for text classification. We begin by importing essential libraries: `pandas` for data manipulation, `AutoTokenizer` from the `transformers` library for tokenizing text, `CountVectorizer` from `sklearn` for converting text data into numerical features, `Pipeline` from `sklearn` for streamlining the workflow, and `svm` from `sklearn` for implementing the SVM classifier. Additionally, various evaluation metrics and visualization libraries such as `matplotlib.pyplot` and `seaborn` are imported.</p><p>We then load the training data from a CSV file named “<em>preprocessed_train.csv”</em> using `pandas`. The text data is stored in the `train_data` variable, and the corresponding labels are stored in the `train_labels` variable. Next, a tokenizer is instantiated using a pre-trained model from the `transformers` library, specifically “<em>MoritzLaurer/mDeBERTa-v3-base-xnli-multilingual-nli-2mil7</em>”, which is designed for multilingual natural language processing tasks.</p><p>Following this, we defined a pipeline to streamline the process of converting text data into numerical features and then training the SVM classifier. The pipeline consists of two steps: `CountVectorizer`, which uses the instantiated tokenizer to convert the text data into numerical features, and `svm.SVC`, which trains an SVM classifier with a linear kernel on the numerical features. Finally, the classifier is trained on the training data (`train_data`) and the corresponding labels (`train_labels`) using the `fit` method of the pipeline, which processes the text data and trains the SVM classifier.</p><p>This method is also applied to other training datasets. In this example, it represents standard supervised learning since we used the <em>“preprocessed_train.csv”</em> dataset. There is another dataset called <em>“preprocessed_autolabelled_dataset.csv”</em> that represents weakly labeled data for weakly supervised learning, and <em>“preprocessed_combined_dataset.csv”</em> that represents a mixed data version combining the original training data and the weakly labeled data.</p><p><strong>Training LSTM</strong></p><pre>from tensorflow.keras.preprocessing.text import Tokenizer<br>from tensorflow.keras.preprocessing.sequence import pad_sequences<br><br>train_data = pd.read_csv(&#39;preprocessed_autolabelled_dataset.csv&#39;)<br>test_data = pd.read_csv(&#39;preprocessed_test.csv&#39;)<br><br># Split the data into input and target<br>train_text = train_data[&#39;text&#39;].values<br>train_labels = train_data[&#39;label&#39;].values<br>test_text = test_data[&#39;text&#39;].values<br>test_labels = test_data[&#39;label&#39;].values<br><br># Create a tokenizer and fit it on the training data<br>tokenizer = Tokenizer(num_words=5000)<br>tokenizer.fit_on_texts(train_text)<br><br># Convert the training and testing data into sequences of integers<br>train_sequences = tokenizer.texts_to_sequences(train_text)<br>test_sequences = tokenizer.texts_to_sequences(test_text)<br><br># Pad the sequences to a fixed length<br>max_length = 100<br>train_data = pad_sequences(train_sequences, maxlen=max_length)<br>test_data = pad_sequences(test_sequences, maxlen=max_length)<br><br># Define the LSTM model<br>model = tf.keras.Sequential([<br>    tf.keras.layers.Embedding(5000, 64, input_length=max_length),<br>    tf.keras.layers.LSTM(64, dropout=0.2),<br>    tf.keras.layers.Dense(1, activation=&#39;sigmoid&#39;)<br>])<br><br># Compile the model<br>model.compile(loss=&#39;binary_crossentropy&#39;, optimizer=&#39;adam&#39;, metrics=[&#39;accuracy&#39;])<br><br># Train the model on the training data<br>history = model.fit(train_data, train_labels, epochs=15, batch_size=32, validation_split=0.4)</pre><p>In building the LSTM (Long Short-Term Memory) model for text classification, we start by importing necessary modules from the TensorFlow library, specifically for text preprocessing and sequence padding. The training and testing data are loaded from CSV files named <em>“preprocessed_autolabelled_dataset.csv”</em> and <em>“preprocessed_test.csv”</em> using `pandas`. The text and labels from these datasets are extracted into separate variables. The training data text is stored in the `train_text` variable, and the corresponding labels are stored in the `train_labels` variable. Similarly, the test data text is stored in the `test_text` variable, and the corresponding labels are stored in the `test_labels` variable.</p><p>Next, a tokenizer is created and fitted on the training text data. The tokenizer is configured to consider the top 5000 most frequent words in the dataset. This tokenizer is then used to convert both the training and testing text data into sequences of integers, where each integer represents a specific word in the tokenizer’s vocabulary.</p><p>The sequences of integers are then padded to ensure they all have the same length, defined by `max_length`, which is set to 100 in this case. Padding ensures that the input data has a uniform shape, which is required for training the neural network.</p><p>The LSTM model is then defined using the TensorFlow Keras Sequential API. The model consists of an Embedding layer that converts the integer sequences into dense vectors of fixed size, followed by an LSTM layer with 64 units and a dropout rate of 0.2 to prevent overfitting. The final layer is a Dense layer with a sigmoid activation function, which is suitable for binary classification tasks.</p><p>The model is compiled with the binary cross-entropy loss function, the Adam optimizer, and accuracy as a performance metric. It is then trained on the training data for 15 epochs with a batch size of 32. During training, 40% of the training data is used for validation to monitor the model’s performance on unseen data and to adjust the model parameters accordingly.</p><p>Similar to what we did for SVM training, we also use different datasets: <em>“preprocessed_train.csv” </em>to represent standard supervised learning, <em>“preprocessed_autolabelled_dataset.csv”</em> to represent weakly labeled data for weakly supervised learning, and <em>“preprocessed_combined_dataset.csv”</em> to represent a mixed data version combining the original training data and the weakly labeled data.</p><h3>Results and Conclusions</h3><p><strong>SVM Classifiers</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/0*TWhNM08m3O2dyM1Q" /><figcaption>Result table of SVM Classifiers</figcaption></figure><p>This table represents the performance metrics of the SVM classifier evaluated on three different datasets: weakly supervised, supervised learning, and a combination of weakly supervised and standard supervised datasets. The metrics used for evaluation include Accuracy, Precision, Recall, and F1-Score.</p><p>The model trained on the weakly labeled dataset achieved an Accuracy, Precision, Recall, and F1-Score of 80%. This indicates that while the model performs reasonably well, there is room for improvement in all metrics, likely due to the noise and potential inaccuracies in the weakly labeled data. On the other hand, the model trained on the standard supervised dataset showed significantly better performance, with an Accuracy, Precision, Recall, and F1-Score of 93%. These high metrics suggest that the model is highly effective when trained on accurately labeled data, reflecting the importance of high-quality training data for achieving superior model performance.</p><p>Additionally, the model trained on a combined dataset, which includes both weakly labeled and manually labeled data, achieved an Accuracy, Precision, Recall, and F1-Score of 90%. This demonstrates that combining the datasets can enhance the model’s performance compared to using weakly labeled data alone. However, the combined approach still does not reach the performance level of the model trained purely on the supervised dataset.</p><p><strong>LSTM Classifiers</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*wd83DxTdetmzAE92s6gEvw.png" /><figcaption>LSTM learning curves for model accuracy and validation accuracy</figcaption></figure><p>Before discussing the results of the LSTM classifiers, let’s first analyze the model’s behavior. Based on the model accuracy graphs, it is evident that the best-performing model is the one trained using supervised learning, as shown in the accuracy and loss graphs. The supervised learning model displays neither significant overfitting nor underfitting, although there is a slight indication of overfitting, as the validation loss diverges from the training loss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/0*SKIwHhhbBtj3EBCJ" /><figcaption>Table of result for LSTM classifier</figcaption></figure><p>Both the weakly supervised model and the weakly supervised model with the combined dataset exhibit signs of potential overfitting. This is evident from the increasing divergence between the training and validation loss curves as training progresses.</p><p>In terms of performance metrics, the LSTM model trained using supervised learning achieves the highest scores, with an accuracy, precision, recall, and F1-score of 94%. This indicates that the supervised learning approach results in a highly effective model for classifying disaster-related tweets.</p><p>The weakly supervised model, trained solely on the weakly labeled dataset, achieves an accuracy, precision, recall, and F1-score of 82%. While this model performs reasonably well, its performance is lower than that of the supervised learning model, likely due to the noise and inaccuracies inherent in the weakly labeled data.</p><p>The model trained on the combined dataset, which includes both weakly labeled data and accurately labeled data, achieves an accuracy, precision, recall, and F1-score of 83%. This demonstrates an improvement over the purely weakly supervised model but still does not match the performance of the supervised learning model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q5e0rnr86V51YjsPYqo7Sg.png" /><figcaption>Table of results for all models</figcaption></figure><p>For the SVM classifiers, the model trained using standard supervised learning with accurately labeled data performed the best, achieving high metrics across the board: 93% for accuracy, precision, recall, and F1-score. The model trained using weakly supervised data showed lower performance with all metrics at 80%, indicating the challenges posed by noise and inaccuracies in weakly labeled data. The combined dataset approach, which merges weakly labeled data with accurately labeled data, improved the metrics to 90%, demonstrating that while combining datasets can enhance performance, it still does not reach the effectiveness of using purely high-quality labeled data.</p><p>Similarly, the LSTM classifiers showed the highest performance when trained using standard supervised learning. The model achieved 94% for accuracy, precision, recall, and F1-score, outperforming the models trained with weakly labeled data and combined datasets. The weakly supervised LSTM model scored 82% across all metrics, reflecting the difficulties in training with noisy labels. The combined dataset approach for LSTM also showed an improvement over the purely weakly supervised model with 83% for all metrics but still fell short compared to the supervised learning model.</p><h3>Conclusions</h3><p>Weak supervision can be a viable option for labeling large datasets. Our weak supervision method, particularly the combined version, labeled approximately 26,000 texts in a relatively short time and was less labor-intensive compared to manually labeled datasets, which labeled only 6,000 texts. Performance can be further improved with dataset combination and model tuning. SVM with the mDeBERTA tokenizer performed the best overall. The weakly supervised augmented learning approach significantly improved performance, with metrics rising from 80% to 90%. However, the manually labeled dataset still achieved the highest performance at 93%.</p><p>LSTM did not benefit greatly from weakly supervised learning with data augmentation, showing only a slight improvement from 82% to 83%. There was potential overfitting in every dataset, particularly in weakly labeled datasets. Supervised learning still yielded the best results for LSTM, with 94% across all metrics. Despite LSTM with supervised learning achieving the highest performance metrics (94%), we prefer using SVM with the mDeBERTA tokenizer for its ability to improve performance by 10% when using weakly labeled datasets, compared to LSTM’s 1% improvement. This preference is due to LSTM’s overfitting issues, which may be mitigated with larger datasets or fine-tuning the weak model. Combining datasets for weak supervision increases classifier performance by incorporating additional truth datasets.</p><p>For future research on emotion classification incorporating weak supervision, LSTM algorithms require substantial tuning to reduce overfitting and potentially improve performance on different datasets. Advanced weak labeling methods should utilize more complex rules or functions, such as tagging words related to links or considering shorter tweets as spam, using methods like Snorkel labeling and regex functions. If a labeled dataset is unavailable, the zero-shot method should be considered for its usability in weak supervised learning. Additionally, direct comparison studies between manual labeling and weak labeling with similar datasets, along with performance optimization for weak labeling, should be conducted to understand the efficacy of each method.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=261fd4423692" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>