<?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 Rajan Choudhary on Medium]]></title>
        <description><![CDATA[Stories by Rajan Choudhary on Medium]]></description>
        <link>https://medium.com/@codistro?source=rss-af668f0f3788------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*5RTHqx92W0B201V3.</url>
            <title>Stories by Rajan Choudhary on Medium</title>
            <link>https://medium.com/@codistro?source=rss-af668f0f3788------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 18:40:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@codistro/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[Fine-Tuning Bert for Tweets Classification ft. Hugging Face]]></title>
            <link>https://codistro.medium.com/fine-tuning-bert-for-tweets-classification-ft-hugging-face-8afebadd5dbf?source=rss-af668f0f3788------2</link>
            <guid isPermaLink="false">https://medium.com/p/8afebadd5dbf</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[bert]]></category>
            <category><![CDATA[ml-so-good]]></category>
            <category><![CDATA[nlp]]></category>
            <dc:creator><![CDATA[Rajan Choudhary]]></dc:creator>
            <pubDate>Sun, 12 Dec 2021 19:01:26 GMT</pubDate>
            <atom:updated>2021-12-29T20:26:27.362Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kSSld7QWwSggc29EbzX7mQ.png" /></figure><p>Bidirectional Encoder Representations from Transformers (BERT) is a state of the art model based on transformers developed by google. It can be pre-trained and later fine-tuned for a specific task. we will see fine-tuning in action in this post.</p><p>We will fine-tune bert on a classification task. The task is to classify the sentiment of covid related tweets.</p><p>Here we are using the Hugging face library to fine-tune the model. Hugging face makes the whole process easy from text preprocessing to training.</p><h3>Bert</h3><p>Bert was pre-trained on the BooksCorpus dataset and English Wikipedia. It obtained state-of-the-art results on eleven natural language processing tasks.</p><p>Bert was trained on two tasks simultaneously</p><ul><li>Masked language modelling (MLM) — 15% of the tokens were masked and was trained to predict the masked word</li><li>Next Sentence Prediction(NSP) — Given two sentences A and B, predict whether B follows A</li></ul><p>BERT is designed to pre-train deep bidirectional representations from an unlabeled text by jointly conditioning on both left and right context in all layers.</p><p>As a result, the pre-trained BERT model can be finetuned with just one additional output layer to create state-of-the-art models for a wide range of tasks, such as question answering and language inference, without substantial task-specific architecture modifications.</p><h3>Dataset</h3><p>We are using the Coronavirus tweets NLP — Text Classification dataset available on <a href="https://www.kaggle.com/datatattle/covid-19-nlp-text-classification">Kaggle</a>.</p><p>The dataset has two files Corona_NLP_test.csv<strong> </strong>(40k entries) and Corona_NLP_test.csv (4k entries).</p><p>These are the first five entries of training data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*BAQHuxVUdwfbEeYElGXRkA.png" /></figure><p>As you can see we have 5 <strong>features </strong>in our data: UserName, ScreenName Location, TweetAt, OriginalTweet, Sentiment, but we are only interested in 2 i.e <strong>OriginalTweet </strong>contains the actual tweet and <strong>Sentiment </strong>which are labels for our Tweet.</p><p>These tweets are classified into 5 categories — ‘Neutral’, ‘Positive’, ‘Extremely Negative’, ‘Negative’, ‘Extremely Positive’. Hence the number of <strong>labels </strong>is 5.</p><h3>Loading Data and Preprocessing</h3><p>We will be using the Hugging Face library for this project. we need to install the two modules:</p><pre>pip install transformers</pre><pre>pip install datasets</pre><ul><li>transformers: Hugging Face implementation of transformers. We can download a wide range of pre-trained models</li><li>datasets: Loading the dataset and also different datasets can be downloaded that are available of Hugging Face hub</li></ul><pre>from datasets import load_dataset</pre><p>Here we are using load_dataset from datasets library. load_dataset can be used to download datasets from the hugging face hub or we can load our custom dataset.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52ab99088fd32195c4653d54d2360c93/href">https://medium.com/media/52ab99088fd32195c4653d54d2360c93/href</a></iframe><p>We specified the datatype as CSV, passing file names as dictionaries to data_files. we are loading our train and test files into the dataset variable.</p><p>Here is the output if we print the dataset variable:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa1660892ae1ec2b73a2d25ac0bd1e8f/href">https://medium.com/media/aa1660892ae1ec2b73a2d25ac0bd1e8f/href</a></iframe><h3>Preprocessing Data</h3><p>We will keep it simple and only do 2 pre-processing steps i.e tokenization and converting labels into integers.</p><p>Hugging Face AutoTokenizertakes care of the tokenization part. we can download the tokenizer corresponding to our model, which is bert in this case.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2dcf4f95ff984319731ed86dcf80eeb/href">https://medium.com/media/c2dcf4f95ff984319731ed86dcf80eeb/href</a></iframe><p>bert tokenizer automatically convert sentences into tokens, numbers and attention_masks in the form which the bert model expects.</p><p>e.g: here is an example sentence that is passed through a tokenizer</p><pre>&gt;&gt; tokenizer(&quot;Attention is all you need&quot;)</pre><pre>output:<br>{<br>&#39;input_ids&#39;: [101, 1335, 5208, 2116, 1110, 1155, 1128, 1444, 102], &#39;token_type_ids&#39;: [0, 0, 0, 0, 0, 0, 0, 0, 0], <br>&#39;attention_mask&#39;: [1, 1, 1, 1, 1, 1, 1, 1, 1]<br>}</pre><p>Now as part of the preprocessing steps, we will perform two steps:</p><ul><li>Convert Sentiment into an integer</li><li>Tokenize the tweets</li></ul><p>We will be using map function of the dataset which is similar to apply function of the pandas data frame. It takes a function as an argument and applies to the entire dataset.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed4fb82bc26bf61d710a3fedea6a9c0a/href">https://medium.com/media/ed4fb82bc26bf61d710a3fedea6a9c0a/href</a></iframe><p>In the above code, we defined a method to convert labels into integers and tokenized the tweets also dropped the unwanted columns.</p><p>Now we are all set for the training part.</p><h3>Training</h3><p>There are two ways to train the data, either we write our own training loop or we can use trainer from the hugging face library.</p><p>In this case, we will use trainer from the library. To use trainer, first we need to define the training arguments like name, num_epochs, batch_size etc.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c7b1231fbdd73abf9e278e735044d59/href">https://medium.com/media/6c7b1231fbdd73abf9e278e735044d59/href</a></iframe><p>Let’s download the bert model now, which is very simple using the AutoModelForSequenceClassificatio class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3b83f8018168ba4e34d7e882596d1a3/href">https://medium.com/media/f3b83f8018168ba4e34d7e882596d1a3/href</a></iframe><p>The classification model downloaded also expects an argument num_labels which is the number of classes in our data. A linear layer is attached at the end of the bert model to give output equal to the number of classes.</p><pre>(classifier): Linear(in_features=768, out_features=5, bias=True)</pre><p>The above linear layer is automatically added as the last layer. Since the bert output size is 768 and our data has 5 classes so a linear layer with in_features=768 and out_features as 5 is added.</p><p>Before starting the training, we will split our training data into train and evaluation sets. We have 40k in training and 1k in eval set.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b42877b292efe249b15422ac6dd6ff7d/href">https://medium.com/media/b42877b292efe249b15422ac6dd6ff7d/href</a></iframe><p>If we are using a hugging face trainer we need to import the module Trainer and pass model, dataset and training arguments to it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bfb7146ae4130d4505f4dc6cdf8a3297/href">https://medium.com/media/bfb7146ae4130d4505f4dc6cdf8a3297/href</a></iframe><p>That’s it, now we are all set to start the training. We need to call train method on trainer and training will start</p><pre>trainer.train()</pre><p>Training will run for 3 epochs which can be adjusted from the training arguments.</p><p>Once training is done we can run trainer.evalute() to check the accuracy, but before that, we need to import metrics.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64c35f64dca5cac12930fbb778fbf944/href">https://medium.com/media/64c35f64dca5cac12930fbb778fbf944/href</a></iframe><p>datasets library offers a wide range of metrics. We are using accuracy here. On our data, we got an accuracy of 83% by training for only 3 epochs.</p><p>Accuracy can be further increased by training for some more time or doing some more pre-processing of data like removing mentions from tweets and unwanted clutter, but that’s for some other time.</p><p>Thanks for reading.</p><ul><li><a href="https://www.linkedin.com/in/codistro/">My Linkedin</a></li><li><a href="https://github.com/codistro/Articles/blob/main/covid_tweet_classification.ipynb">Colab Notebook</a></li><li><a href="https://huggingface.co/">Hugging Face</a></li></ul><p><a href="https://medium.com/mlearning-ai/mlearning-ai-submission-suggestions-b51e2b130bfb">Mlearning.ai Submission Suggestions</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8afebadd5dbf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>