<?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 Furkan Ayık on Medium]]></title>
        <description><![CDATA[Stories by Furkan Ayık on Medium]]></description>
        <link>https://medium.com/@ayikfurkan1?source=rss-329d11003bdf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*F1PLBV13nZD_LB-qCWV8nA@2x.jpeg</url>
            <title>Stories by Furkan Ayık on Medium</title>
            <link>https://medium.com/@ayikfurkan1?source=rss-329d11003bdf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 17:31:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ayikfurkan1/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[Mastering Text Classification with BERT: A Comprehensive Guide]]></title>
            <link>https://medium.com/@ayikfurkan1/mastering-text-classification-with-bert-a-comprehensive-guide-194ddb2aa2e5?source=rss-329d11003bdf------2</link>
            <guid isPermaLink="false">https://medium.com/p/194ddb2aa2e5</guid>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[bert]]></category>
            <category><![CDATA[open-language-models]]></category>
            <category><![CDATA[text-classification]]></category>
            <dc:creator><![CDATA[Furkan Ayık]]></dc:creator>
            <pubDate>Sun, 17 Dec 2023 09:31:01 GMT</pubDate>
            <atom:updated>2023-12-17T09:31:01.453Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/0*PHcJHdY_msyK2n9o.png" /></figure><h3>Introduction</h3><p>Classifying text stands as a ubiquitous task within NLP. Its applications span various fields, from the categorization of text to detecting language used in a customer conversation.</p><p>As an everyday example, consider your email service’s spam filter — it likely employs text classification to shield your inbox from lots of undesired content.</p><p>Another common usage of text classification is sentiment analysis. which is an NLP technique that evaluates and interprets the emotions, opinions, or attitudes expressed within a piece of text. Analyzing the language used determines whether the sentiment conveyed is positive, negative, or neutral, providing insights into the emotional tone or inclination behind the words.</p><p>In this blog post, we will build a text classifier that identifies emotions in tweets. Here is the flow:</p><ol><li><strong><em>Conventional NLP vs Era of Language Models</em></strong></li><li><strong><em>A Little History of Language Models</em></strong></li><li><strong><em>Architecture of BERT</em></strong></li><li><strong><em>Exploring the Dataset</em></strong></li><li><strong><em>Understanding Tokenization in BERT</em></strong></li><li><strong><em>Training BERT with 2 Different Methods</em></strong></li><li><strong><em>Error Analysis</em></strong></li><li><strong><em>Conclusion and Future Directions</em></strong></li></ol><p>This blog post will let you build a text classifier with language models like the BERT family by following fundamentals.</p><blockquote>Before Starting, you can find all the <a href="https://www.kaggle.com/code/aykfrkn/bert-emotion-tweets-classification"><strong>code in the notebook on my Kaggle account</strong></a></blockquote><p><em>Have a cup of coffee, which I would typically suggest to take an espresso for instantly flowing 63.6 mg of caffeine in your vessels with a single shot, and enjoy :)</em></p><h3>Conventional NLP vs Era of Language Models</h3><p>I do only consider using language models for text classification in this post, however in the case of hardware limitations or to create a base model please consider using conventional NLP methods like the below:</p><figure><img alt="Text Classification Steps in Conventional NLP Methods" src="https://cdn-images-1.medium.com/max/633/1*gJ8_6aCx5kc_iUZLWRKs_Q.png" /><figcaption><strong>Text Classification Steps in Conventional NLP Methods</strong></figcaption></figure><p>Text classification stands as a foundational pillar within natural language processing (NLP), serving as the bedrock for various applications that involve understanding and organizing textual data. At its core, text classification involves the automatic categorization of text documents into predefined classes or categories based on their content.</p><p>In Traditional NLP, the classification process relied on handcrafted features and machine learning algorithms, <strong>which often struggle to capture the complexity and nuances of language</strong>, <strong>especially with large and unstructured datasets.</strong></p><p>Language models like BERT leverage transformer-based architectures to grasp the complexities of natural language more comprehensively.</p><p>BERT stands out due to its bidirectional nature, enabling it to consider the full context of a word by analyzing both its preceding and subsequent words in a sequence.</p><p>This bidirectional understanding of context allows BERT to</p><ul><li>Understand subtle details</li><li>Idiomatic expressions</li><li>Contextual meanings within the text and the word</li></ul><p>results in more accurate and context-aware text representations.</p><h3>A Little History of Language Models</h3><p>Language models (LM), model the likelihood of word sequences for predicting the probability of the next word/token.</p><p>The research community of LMs can be divided into 4 stages:</p><ul><li>Statistical Language Models</li><li>Neural Language Models</li><li>Pre-Trained Language Models</li><li>Large Language Models</li></ul><h4>Statistical Language Models</h4><p>Those are models based on statistical learning methods for word prediction based on Markov assumption. The SLMs have a fixed context length which is generally demonstrated with the’n’ letter, and are also called <strong>n-gram models</strong> (<strong>bigram, trigram</strong> etc.).</p><p><strong>Drawback: </strong>Curse of dimensionality! The higher order of the language model means an exponential number of transitions must be estimated accurately. But the research community came up with some ideas like <strong>Good-Turing</strong> <strong>estimation </strong>which is a smoothing strategy and solves sparsity problems up to one point.</p><h4>Neural language models (NLM)</h4><p>In NLMs, transition probabilities are estimated by neural networks like multi-layer perceptrons or recurrent neural networks. One of the famous NLM methods is <strong>word2vec </strong>which builds a shallow neural network to encode word representations.</p><h4>Pre-trained language models (PLM)</h4><p>The predecessor of PLMs is <a href="http://M. E. Peters, M. Neumann, M. Iyyer, M. Gardner, C. Clark, K. Lee, and L. Zettlemoyer, “Deep contextualized word representations,” in Proceedings of the 2018 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, NAACL-HLT 2018, New Orleans, Louisiana, USA, June 1-6, 2018, Volume 1 (Long Papers), M. A. Walker, H. Ji, and A. Stent, Eds. Association"><strong>ELMo</strong></a><strong>. </strong>ELMo captures context-aware word representations since it is pre-trained on a large corpus with a bidirectional LSTM network backbone. This structure enables it to learn word representation without relying on a fixed length.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vDFz5GaWl-x_tw92.png" /><figcaption>Architecture of ELMo</figcaption></figure><p>After a short period of ELMo paper, <a href="http://A. Vaswani, N. Shazeer, N. Parmar, J. Uszkoreit, L. Jones, A. N. Gomez, L. Kaiser, and I. Polosukhin, “Attention is all you need,” in Advances in Neural Information Processing Systems 30: Annual Conference on Neural Information Processing Systems 2017, December 4- 9, 2017, Long Beach, CA, USA, 2017">Transformer </a>and <a href="http://J. Devlin, M. Chang, K. Lee, and K. Toutanova, “BERT: pre-training of deep bidirectional transformers for language understanding,” in Proceedings of the 2019 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, NAACL-HLT 2019, Minneapolis, MN, USA, June 2-7, 2019, Volume 1 (Long and Short Papers), J. Burstein, C. Doran, and T. Solorio, Eds. Association for Computational Linguistics, 2019, pp. 4171–4186">Self-Attention</a> mechanisms are used in a language model: <strong>BERT</strong>.</p><h4>Large Language Models (LLMs)</h4><p>When scaling PLMs, both in data size and model parameters, model capacity improves and able to understand more complex structures in the data. LLMs, can able to accomplish tasks that they are not directly trained on it (<a href="http://J. Wei, Y. Tay, R. Bommasani, C. Raffel, B. Zoph, S. Borgeaud, D. Yogatama, M. Bosma, D. Zhou, D. Metzler, E. H. Chi, T. Hashimoto, O. Vinyals, P. Liang, J. Dean, and W. Fedus, “Emergent abilities of large language models,” CoRR, vol. abs/2206.07682, 2022.">A good paper about the topic</a>). For instance, they are performing well on zero-shot and few-shot predictions. A most well-known example is ChatGPT which has GPT-3 architecture as backbone.</p><h3>Architecture of BERT</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*h9XXGBnUaD2K_nei4pYO1g.png" /><figcaption><a href="https://www.researchgate.net/publication/348214408/figure/fig2/AS:976491001159681@1609825005204/BERT-model-architecture.ppm">BERT Architecture — Detailed</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*azihbo-7a0DxctRg.png" /><figcaption><a href="https://huggingface.co/blog/bert-101">BERT Architecture</a> — Overview</figcaption></figure><p><strong>BERT </strong>was trained on large corpora like Wikipedia (~2.5B words) and Google’s BooksCorpus (~800M words). These large datasets contributed to BERT to observe the context in deep in the text. However, the research community started to see LMs as a “world-model” since they are also able to build abstract relationships.</p><p>BERT’s architecture relies on 12 encoder transformer layers with around 110 Million parameters. To train such a model, the research team employed 64 TPUs which took 4 days!</p><p>BERT’s training process consists 2 steps:</p><h4>Masked Language Model</h4><p>In the masked language model, it’s 15% of the tokenized sentence is hidden to BERT and it needs to predict those tokens accurately. Thus the BERT can understand the underlying structure in the language it is trained for (English, by default).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iAyNlMhMPMjpbsRH.png" /><figcaption><a href="https://towardsdatascience.com/masked-language-modelling-with-bert-7d49793e5d2c">Masked Language Model Logic</a></figcaption></figure><h4>Next Sentence Prediction</h4><p>NSP (Next Sentence Prediction) is used to teach BERT about relationships between sentences. The model needs to predict accurately if a given sentence follows the previous sentence or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/0*PtWObMK_zgXhfoMj" /></figure><h3>Exploring the Dataset</h3><p>For the project we are gonna utilize the ‘emotions’ dataset that consists 6 emotions categories as follows:</p><ul><li>anger</li><li>disgust</li><li>fear</li><li>joy</li><li>sadness</li><li>surprise</li></ul><p>Our goal is to train a classifier model that can classify a tweet into one of those categories accurately.</p><p><strong>Class Distributions in Dataset</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*6Btc4DvqSbGwZixrNe8fsA.png" /><figcaption>Training Set Class Distributions</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*viCe-5Z-9ACi5yy2RL2hcQ.png" /><figcaption>Validation Set Class Distributions</figcaption></figure><h4>Handle Imbalance Class Distributions</h4><p>There is an imbalance distribution in the dataset. Especially samples from the ‘joy’ and ‘sadness’ classes are dominant. To overcome imbalance class distributions, the ‘imbalanced-learn’ library from Python is a way to handle that kind of problem. The library provides many methods to <em>oversample minority class </em>(<a href="https://imbalanced-learn.org/stable/references/generated/imblearn.over_sampling.ADASYN.html#imblearn.over_sampling.ADASYN"><strong>ADASYN</strong></a>, <a href="https://imbalanced-learn.org/stable/references/generated/imblearn.over_sampling.SMOTE.html#imblearn.over_sampling.SMOTE"><strong>SMOTE</strong></a>, <a href="https://imbalanced-learn.org/stable/references/generated/imblearn.over_sampling.RandomOverSampler.html#imblearn.over_sampling.RandomOverSampler"><strong>Random Over Sample</strong>) </a>or <em>undersample majority class</em> (<a href="https://imbalanced-learn.org/stable/references/generated/imblearn.under_sampling.RandomUnderSampler.html#imblearn.under_sampling.RandomUnderSampler"><strong>Random Under Sampler</strong></a>, <a href="https://imbalanced-learn.org/stable/references/generated/imblearn.under_sampling.CondensedNearestNeighbour.html#imblearn.under_sampling.CondensedNearestNeighbour"><strong>Condensed Nearest Neighbour</strong></a>, <a href="https://imbalanced-learn.org/stable/references/generated/imblearn.under_sampling.NeighbourhoodCleaningRule.html#imblearn.under_sampling.NeighbourhoodCleaningRule"><strong>Neighbourhood Cleaning Rule</strong></a><strong>).</strong></p><h3>Understanding Tokenization in BERT</h3><p>Transformer-based models such as DistilBERT necessitate input in the form of tokenized and numerically encoded text rather than raw strings.</p><p>Tokenization involves the segmentation of a string into fundamental units recognized by the model. Various strategies for tokenization exist, with the ideal division of words into subunits typically being acquired from the corpus through learning.</p><p>BERT utilizes the tokenization algorithm <strong>‘WordPiece’ </strong>developed by the Google Research team which is similar to BPE (Byte Pair Encoding) algorithm for the training phase however tokenization is done differently.</p><h4>Text to Tokens</h4><p>Let’s say our input is <strong>“The movie was not good”</strong></p><p>Tokens: [‘[CLS]’, ‘the’, ‘movie’, ‘was’, ‘not’, ‘good’, ‘[SEP]’]</p><p>Input Indices (encoded text) → [101, 1996, 3185, 2001, 2025, 2204, 102]</p><p>BERT or other LMs expect numerical representation of tokens as input like input indices above.</p><p>Note:</p><ul><li>[CLS] Token: Start of the sequence token</li><li>[SEP] Token: End of the sequence token</li></ul><pre>from transformers import AutoTokenizer<br><br># Load Distilbert Tokenizer <br>model_ckpt = &quot;distilbert-base-uncased&quot;<br>tokenizer = AutoTokenizer.from_pretrained(model_ckpt)<br># Encode Our Example Text<br>encoded_text = tokenizer(&quot;The movie was not good&quot;)<br>tokens = tokenizer.convert_ids_to_tokens(encoded_text.input_ids)<br>print(encoded_text,len(encoded_text.input_ids))<br>print(tokens)</pre><pre>{&#39;input_ids&#39;: [101, 1996, 3185, 2001, 2025, 2204, 102], <br>  &#39;attention_mask&#39;: [1, 1, 1, 1, 1, 1, 1]} 7<br>[&#39;[CLS]&#39;, &#39;the&#39;, &#39;movie&#39;, &#39;was&#39;, &#39;not&#39;, &#39;good&#39;, &#39;[SEP]&#39;]</pre><h3>Training BERT</h3><p>Those who made their hands dirty with pre-trained vision models should be familiar with pre-trained models like <strong>ResNet, VGG16, Inception-v3, MobileNet, </strong>and <strong>EfficientNet.</strong></p><p>Those models are commonly used as feature extractors in solving many vision models successfully in two ways:</p><ol><li>Freeze all layers except the classification head, only train the classification head from scratch or start training on the existing head.</li><li>Train all weights.</li></ol><p>BERT and other LMs can also be used in those ways since they already learned high-level features and representations of the language (or languages) they are trained on.</p><h3><strong><em>Training Methodology-1: BERT as Feature Extractor</em></strong></h3><p>In this section I will show, how to train Bert with first methodology: freeze all layers of BERT and use it as a feature extractor. And train a classifier (or a bunch of classifiers) on those features with existing labels.</p><p>This method uses the latest hidden states of BERT to extract features. Once the features are extracted a <em>feature matrix</em> is used to create train, test and validation sets.</p><p>Now let’s get our hands dirty and don’t worry I will share all the code with more details in my Kaggle account which you can find at the end of this post.</p><h4>Load Model and Tokenizer</h4><pre>from transformers import AutoModel<br>from transformers import AutoTokenizer<br><br>model_ckpt = &quot;distilbert-base-uncased&quot;<br>tokenizer = AutoTokenizer.from_pretrained(model_ckpt)<br>device = torch.device(&quot;cuda&quot; if torch.cuda.is_available() else &quot;cpu&quot;)<br>print(&quot;device: &quot;,device)<br>model = AutoModel.from_pretrained(model_ckpt).to(device)</pre><h4>Extract Hidden States</h4><pre># Use whole dataset in Huggingface dataset format<br>batch = df_source<br># Send inputs from CPU to GPU<br>inputs = {k:v.to(device) for k,v in batch.items()<br>          if k in tokenizer.model_input_names}<br># Extract last hidden states<br># Disable gradient calculation on PyTorch Side<br>with torch.no_grad():<br>    last_hidden_state = model(**inputs).last_hidden_state<br># Return latest hidden state as numpy matrix<br>df_hidden = last_hidden_state[:,0].cpu().numpy()</pre><h4>Create Train/Test/Validation Sets</h4><pre>import numpy as np<br><br>X_train = np.array(df_hidden[&quot;train&quot;][&quot;hidden_state&quot;])<br>X_valid = np.array(df_hidden[&quot;valid&quot;][&quot;hidden_state&quot;])<br>X_test = np.array(df_hidden[&quot;test&quot;][&quot;hidden_state&quot;])<br><br>y_train = np.array(df_hidden[&quot;train&quot;][&quot;label&quot;])<br>y_valid = np.array(df_hidden[&quot;valid&quot;][&quot;label&quot;])<br>y_test = np.array(df_hidden[&quot;test&quot;][&quot;label&quot;])<br><br>X_train.shape, y_train.shape</pre><h4>Train a Simple Classifer with Logistic Regression</h4><pre>from sklearn.linear_model import LogisticRegression<br><br>clf_lr = LogisticRegression(max_iter=3000)<br>clf_lr.fit(X_train, y_train)<br>clf_lr.score(X_valid, y_valid)</pre><h4>Model Evaluation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*T75s8XPlPswm3iDDOQ3lPw.png" /></figure><p>The logistic regression classifier would achieve 78<strong>% accuracy</strong> on the test set, which is not a good but average result.</p><p>It is also easy to see, that the model performs poorly on classes with few samples like fear and surprise.</p><blockquote>However, the results can be better with training different classifiers and hyperparameter tuning.</blockquote><h3><strong><em>Training Methodology-2: Fine-Tune BERT</em></strong></h3><p>Fine-tuning BERT is quite easy with HuggingFace Library.</p><h4>Define Training Arguments</h4><p>First, let’s define training arguments:</p><pre># Set Batch Size<br>batch_size = 64<br>logging_steps = len(hf_dataset[&#39;train&#39;]) // batch_size<br>num_train_epochs = 30<br>lr_initial = 2e-5<br>weight_decay = 1e-3<br>output_dir = &quot;&quot;<br>training_args = TrainingArguments(output_dir=output_dir,<br>                                num_train_epochs=num_train_epochs,<br>                                learning_rate=lr_initial,<br>                                per_device_train_batch_size=batch_size,<br>                                per_device_eval_batch_size=batch_size,<br>                                weight_decay=weight_decay,<br>                                evaluation_strategy=&quot;epoch&quot;,<br>                                disable_tqdm=False,<br>                                logging_steps=logging_steps,<br>                                push_to_hub=False,<br>                                log_level=&quot;error&quot;)</pre><p>Note: You can also add parameters for early stop as below:</p><pre>from transformers import EarlyStoppingCallback, IntervalStrategy<br>args = TrainingArguments(<br>   evaluation_strategy = IntervalStrategy.STEPS, # &quot;steps&quot;<br>   eval_steps = 50, # Evaluation and Save happens every 50 steps<br>   save_total_limit = 5, # Only last 5 models are saved. Older ones are deleted.<br>   metric_for_best_model = &#39;f1&#39;, # Metric to pick the best model<br>   load_best_model_at_end=True,<br>...<br>)</pre><p>These training arguments would allow the HuggingFace Trainer function to evaluate the model by validation set after each epoch.</p><p>Most metrics would automatically log into Tensorboard locally.</p><h4>Metrics For Model Evaluation During</h4><pre>from sklearn.metrics import accuracy_score, f1_score<br><br>def compute_metrics(pred):<br>    labels = pred.label_ids<br>    preds = pred.predictions.argmax(-1)<br>    f1 = f1_score(labels, preds, average=&quot;weighted&quot;)<br>    acc = accuracy_score(labels, preds)<br>    return {&quot;accuracy&quot;: acc, &quot;f1&quot;: f1}</pre><h4>Train the Model</h4><pre># Create Model<br>model = (AutoModelForSequenceClassification<br>        .from_pretrained(model_ckpt, num_labels=num_labels)<br>        .to(device))<br>model_name = f&quot;models/{model_ckpt}-finetuned-bert-emotion-tweets&quot;<br>training_args.output_dir = model_name<br>trainer = Trainer(model=model, args=training_args,<br>                compute_metrics=compute_metrics,<br>                train_dataset=df_encoded[&quot;train&quot;],<br>                eval_dataset=df_encoded[&quot;validation&quot;],<br>                tokenizer=tokenizer)<br>trainer.train()</pre><p>After training for 2 epochs, the results will be as follows:</p><pre>{&#39;eval_loss&#39;: 0.31904336810112, &#39;eval_accuracy&#39;: 0.9025, &#39;eval_f1&#39;: 0.9011653468824986, &#39;eval_runtime&#39;: 1.649, &#39;eval_samples_per_second&#39;: 1212.839, &#39;eval_steps_per_second&#39;: 19.405, &#39;epoch&#39;: 1.0}<br>{&#39;loss&#39;: 0.2464, &#39;learning_rate&#39;: 0.0, &#39;epoch&#39;: 2.0}<br><br>{&#39;eval_loss&#39;: 0.2177528589963913, &#39;eval_accuracy&#39;: 0.9215, &#39;eval_f1&#39;: 0.9215056955967161, &#39;eval_runtime&#39;: 1.8332, &#39;eval_samples_per_second&#39;: 1090.98, &#39;eval_steps_per_second&#39;: 17.456, &#39;epoch&#39;: 2.0}<br>{&#39;train_runtime&#39;: 98.2367, &#39;train_samples_per_second&#39;: 325.744, &#39;train_steps_per_second&#39;: 5.09, &#39;train_loss&#39;: 0.5314080963134765, &#39;epoch&#39;: 2.0}</pre><h4>Model Evaluation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*Hh-mOC3z2ZEpQ08pWla_fQ.png" /><figcaption>Confusion Matrix on Validation Set</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*fVAptQJRBgVfEviuo5DoiA.png" /><figcaption>Confusion Matrix on Test Set</figcaption></figure><p>After just 2 epochs, model performance got much better: 92% accuracy on the test set, and much better generalization performance on a few classes.</p><h4>Push Model To HuggingFace Ecosystem</h4><p><em>trainer.push_to_hub(commit_message=”Fine-Tuned BERT For Sentiment Analysis in Tweets!”)</em></p><h3><strong><em>Error Analysis</em></strong></h3><p>Let’s sort some predictions in ascending order to analyze why the model failed to classify them correctly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*4FD00GVmylUGkHYPaYxJTA.png" /></figure><p>Focus on the first one:</p><blockquote>i feel badly about reneging on my commitment to bring donuts to the faithful at holy family catholic church in columbus ohio</blockquote><p>The sentence is labelled as ‘anger’ however the dataset says the true label is ‘joy’.</p><p>The person feels bad about not having the opportunity to achieve his wish and it must be classified as ‘sadness’. So both the model and label are wrong here.</p><p>— — — — — — — — — — — — — — — — — — —</p><p>Focus on the second one:</p><blockquote>i feel that he was being overshadowed by the supporting characters</blockquote><p>Actual Label: Joy</p><p>Predicted Label: Anger</p><p>The text is more related to anger rather than joy. So the label is wrong here. Detecting false labels is crucial in both training/testing datasets for deploying better models.</p><h3><strong><em>Conclusion and Future Directions</em></strong></h3><p>In conclusion, exploring the power of BERT in text classification reveals its transformative impact on natural language processing. BERT’s <strong>contextual understanding</strong> and <strong>pre-trained representations</strong> have elevated the accuracy and depth of text classification tasks across various domains.</p><p>Looking ahead, future blogs could focus on:</p><ol><li><strong>BERT Variants and Transformers</strong>: Examining newer transformer architectures beyond BERT, like GPT (Generative Pre-trained Transformer) models, and their implications in text classification.</li><li><strong>Fairness in Language Models</strong>: Understanding and fixing any unfairness or biases in models like BERT, especially when they’re used to sort text.</li><li><strong>Domain-specific Applications</strong>: Focusing on specialized applications such as medical text classification or legal document analysis using BERT and similar models.</li></ol><p>Stay tuned for more insights into the evolving landscape of NLP and the fascinating developments in the field of text classification!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=194ddb2aa2e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Utilizing Deep Reinforcement Learning in Control: Release the Power of Intelligent Systems]]></title>
            <link>https://medium.com/@ayikfurkan1/utilizing-deep-reinforcement-learning-in-control-unleashing-the-power-of-intelligent-systems-a0e2d690cbd7?source=rss-329d11003bdf------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0e2d690cbd7</guid>
            <category><![CDATA[deepreinforcementlearning]]></category>
            <category><![CDATA[control]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[control-system]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Furkan Ayık]]></dc:creator>
            <pubDate>Sat, 19 Aug 2023 18:34:39 GMT</pubDate>
            <atom:updated>2024-01-18T12:45:17.279Z</atom:updated>
            <content:encoded><![CDATA[<p>Deep Reinforcement Learning (DRL) combines deep learning and reinforcement learning to create intelligent systems.<br>DRL has revolutionized various domains, such as robotics, autonomous vehicles, game-playing, and industrial automation.</p><p>This article explores the critical aspects of DRL in control applications and its potential benefits and talks about a project “Reinforcement Learning in Control” in Github: <a href="https://github.com/frknayk/Reinforcement-Learning-In-Control/tree/master">https://github.com/frknayk/Reinforcement-Learning-In-Control</a>/</p><h3>Understanding the Connection Between Reinforcement Learning and Control Theory</h3><p>Understanding the connection needs a clear understanding of the problem definitions RL and Control theory solves.</p><h4><strong>High-Level Look to Reinforcement Learning</strong></h4><p>If you are a newby to reinforcement learning and machine learning in general this is probably not a good place to start. Please start with Andrew Ng’s machine learning course at Coursera and for the RL side read the Bible of RL: “Reinforcement Learning an Introduction” from Sutton and Burto.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/0*RGGwVH_AjztI8Jn9.png" /><figcaption>Reinforcement Learning Agent Behaviour</figcaption></figure><p><strong>Reinforcement Learning</strong>: In RL, an agent (decision maker) takes the action <strong>Aₜ </strong>in the given state <strong>sₜ </strong>and receives the reward <strong>Rₜ </strong>(we call this feedback in control theory and I will explain it later detailed). After the reward is received, the agent feeds it to the “Policy Function” and the “Value Function” to update their parameters such that the total maximizing discounted expected reward.</p><p>Reinforcement learning employs two fundamental functions: the<em> Policy function </em>and the<em> Value function</em>. (There are some algorithms that only use value functions like Q-learning).</p><p><strong>Policy function</strong> is the function that agent takes decisions in a given state. When the Policy Function is optimal, the agent would take decisions such that the action taken in this state would lead to maximum reward after a sequence of other decisions. (and other decisions are also chosen by the same optimal Policy Function).</p><p><strong>Value Function</strong> on the other hand just stands for the expected value of total collected reward at a given state. Bellman’s optimality equation is used to model the Value Function. Here the “gamma” is a number between (0,1) to weigh future experiences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*QFmi0YOrHOq0BUNUY4sFog.png" /><figcaption>Value Function of a State s under a Policy Pi</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*U5ZgdoTc6iBfeXQh1UU1dw.png" /><figcaption>Action-Value Function for Policy Pi</figcaption></figure><p>Reinforcement learning algorithms are based on the two fundamental equations above (Value Function and Action-Value Function,a.k.a Q Function). All RL algorithms try to find optimal Value Policy Functions that maximize the reward function defined for the problem.</p><h4>High-Level Look to Control Problems</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*6d4-3MjtRa1lPPkh" /><figcaption>General Scheme of Feedback Control System</figcaption></figure><p>Control theory aims to design control systems that regulate and manipulate dynamic systems to achieve desired behaviours.</p><p>Control systems are a fundamental part of engineering and automation, aimed at regulating and manipulating the behavior of dynamic systems. They consist of a combination of hardware and software components that work together to achieve desired objectives. Control systems are operated by continuously measuring system outputs, comparing them to desired setpoints(reference), and using this information to calculate control signals that manipulate system states(altitude of a plane or speed of a vehicle).</p><p>The primary goal of control systems is to maintain stability, improve performance, and ensure system behaviour conforms to desired specifications. They can be found in various applications, such as r<em>obotics, industrial automation, power grids, and transportation systems</em>. Control systems can be designed using different methodologies, including classical control theory, modern control theory, and intelligent control techniques. These systems play a crucial role in enhancing efficiency, safety, and productivity across a wide range of industries and sectors.</p><h4>PID Controller</h4><p>The most famous and widely used control algorithm is the PID (proportional-integral-derivative) controller. In the PID controller, the control engineer must adjust P, I and D coefficients such that system achieve desired set point by satisfying following criteria:</p><ul><li>Rise Time</li><li>Overshoot</li><li>Settling Time</li><li>Steady-State Error</li></ul><p>Actually designing a controller with the least rise time, settling time, overshoot and steady-state error is never possible in real life since each criterion affects the other.</p><p>In this case, there is a branch called ‘Optimal Control’ that defines the control problem as an optimization problem and solves it via optimal control algorithms like <strong>‘MPC’(Model Predictive Controller) </strong>and <strong>‘LQR’(Linear Quadratic Controller).</strong></p><figure><img alt="Proportional-Integral-Derivative (PID) Controller" src="https://cdn-images-1.medium.com/max/400/0*I3cGPo9pHcr9QcQ4.png" /></figure><h3>Connection of RL and Control Theory</h3><p>The connection between RL and control theory lies in their shared goal of optimizing system behaviour through decision-making. RL techniques can be viewed as a modern approach to control theory, offering a framework for learning control policies directly from data. <strong>By incorporating concepts from control theory, such as state estimation, feedback control, and system dynamics modelling, RL can enhance the stability, performance, and adaptability of control systems.</strong></p><p>This synergy between RL and control theory opens up exciting possibilities for creating intelligent and autonomous control systems that can learn and optimize their behaviour in real time.</p><p>So let’s first take a look at how LQR minimizes the difference between the setpoint and reference point:</p><figure><img alt="LQR Objective Function" src="https://cdn-images-1.medium.com/max/403/0*m626mhgaA_BjPNu7" /><figcaption>LQR’s cost function</figcaption></figure><p>LQR control uses dynamical system state-space representation which is X matrix and U vector and two matrices <strong>Q</strong> and <strong>R</strong> to penalize different terms to achieve optimal performance.</p><p>Q matrix penalizes each state’s distance from its reference state in the state-space model. For example, an adaptive cruise control (ACC) system would have stated in longitudinal coordinates like velocity, acceleration and jerk. A perfect ACC system would minimize jerk and tries to achieve the desired velocity with the least amount of acceleration. In this case, our reference state for velocity would be the velocity that maintains a safe distance, and the reference state for acceleration &amp; jerk would be zero vector.</p><h4>Heart of the Connection</h4><p>As you may already realise, designing such a system would need expertise in control engineering and a lot of design parameters with a strong mathematical foundation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SenEjpGAY28IY904.png" /><figcaption>Bellman Equation for Value Function — Revisited</figcaption></figure><blockquote>However a RL is famous by it’s bellman equation which maximizes total reward and then uses different algorithms to optimize the equation. So two equations LQR optimality equation and the Bellman Equations are very similar while the LQR minimizes the cost and the Bellman maximizes the reward!</blockquote><blockquote>Defining a reward function that maximizes difference between reference point and state of dynamical system would enable to use any kind of RL algorithm in control problems</blockquote><h4>Methodology-1: Output Feedback Reinforcement Learning</h4><p>This is the most basic approach to control dynamical systems directly measuring the output and producing control output by minimizing the error. <strong>In the RL setting, once the algorithm maximizes the negative sum of absolute value error and its integral, it will able to control it! Understanding why I used the sum of negative absolute error is very important and gives some time to this concept.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/0*XkcqHaq2DGCd17EN" /><figcaption>State Feedback Reinforcement Learning</figcaption></figure><h4>Methodology-2: State Feedback Reinforcement Learning</h4><p>State feedback reinforcement learning is actually similar to output feedback reinforcement learning, the only difference is using a state-space representation of the system and trying to minimize the difference between state references for each state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/0*xhHeUIgSqnTz8DTS" /><figcaption>State Feedback Reinforcement Learning</figcaption></figure><blockquote><strong>Why Using Integral of Negative Absolute Error ?</strong><br>Reducing state-space error, which is the error once the system achieved a stable point however there is a significant difference between current output (state) and the reference output (state)</blockquote><h4>Why Choosing RL Over Optimal Control Methods?</h4><p>The contrary of conventional control methods based on PID controllers, optimal controllers offer considerable amount of performance increase and reduce deployment time. PID controllers need cascaded schemes in most real-world problems and algorithms to reset integral error (integrator wind-up) while considering derivative error’s sensitivity against sudden changes. All those problems cause lots of hand-crafted solutions based on look-up tables and rule-based reset logic.</p><p><em>I experienced it while developing an adaptive cruise control system, which was exciting to see reducing a large number of Simulink blocks to only a single MPC block.</em></p><h4>Why RL was not ‘so’ Popular in Control Problems?</h4><p>Reinforcement learning (RL) and control theory are two interconnected fields that share fundamental principles and objectives. Reinforcement learning focuses on the interaction between an agent and its environment, where the agent learns to maximize rewards by selecting optimal actions. Control theory uses optimal control methods and frequency domain methods to make the system work at a given reference point. In the real world most of the systems are controlled by a good-old “Proportional-Integral-Derivative” (PID) controller. Control theory has been studied for almost a century and has really strong mathematical foundations which also makes it explainable. <strong>Explainability is the key </strong>factor why control theory is still being used dominantly in the industry instead of intelligent control systems (RL, fuzzy logic, genetic algorithms-based algorithms etc..)</p><h3>Reinforcement Learning in Control Application</h3><p><em>Before proceeding into details of the application, anyone who wants to get hands dirty can try the project online: </em><a href="https://rlcontrol.streamlit.app/"><em>https://rlcontrol.streamlit.app/</em></a></p><p>The project aims to design RL based controller linear and nonlinear dynamical system with distributed training and a large number of RL algorithms thanks to Ray’s <a href="https://docs.ray.io/en/latest/rllib/index.html"><strong>Rllib library</strong></a><strong>.</strong></p><p>The simple user interface written in Streamlit provides users to define dynamical system transfer functions and to determine algorithm hyperparameters.</p><h4>Page Overview</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y19J93z-WigycRqjonUvKw.png" /></figure><p>On the main page, there are 4 tabs on the right to adjust training parameters for:</p><ol><li>Algorithm (Selecting the RL algorithm like DDPG, PPO etc.),</li><li>Transfer Function(dynamical system equation in Laplace domain),</li><li>Agent (RL algorithm’s parameters) and</li><li>Training (number of episodes and log parameters)</li></ol><p>On the left side, the user can choose either of the training/inference/pid design pages. After training is finished and training files are downloaded, the user can use them in inference.</p><p>After design criteria are provided, the controller is trained and all training-related parameters are logged into the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qM691Eh5WQwsquJy" /></figure><h4>Future Work</h4><p>For now, the application only supports the DDPG algorithm and linear systems. The <em>rlcontrol </em>would be able to work with any algorithm that ray/rllib provides. And I would also provide different non-linear systems that are used for benchmarking control systems.</p><h3>Acknowledgements</h3><p>A heartfelt thank you to my advisor, Tufan Kumbasar, for his unwavering guidance during my final year thesis. His expertise and patience were instrumental in shaping this work. His insightful feedback challenged me to excel, and I’m grateful for his mentorship that extended beyond academics.</p><p>I also thank my family, friends, and faculty for their support. This achievement wouldn’t have been possible without Mr Kumbasar and my academic community.</p><p>With gratitude, Furkan Ayik</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0e2d690cbd7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[StarCoder: Empowering Developers with the State-of-the-Art LLM for Code]]></title>
            <link>https://medium.com/@ayikfurkan1/starcoder-empowering-developers-with-the-state-of-the-art-llm-for-code-5051e22e4ed?source=rss-329d11003bdf------2</link>
            <guid isPermaLink="false">https://medium.com/p/5051e22e4ed</guid>
            <category><![CDATA[coding-assistant]]></category>
            <category><![CDATA[starcoder]]></category>
            <dc:creator><![CDATA[Furkan Ayık]]></dc:creator>
            <pubDate>Sat, 19 Aug 2023 15:05:15 GMT</pubDate>
            <atom:updated>2023-08-19T15:05:15.109Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*C2nev2KJAmu6p_MY.png" /></figure><h3>Introduction</h3><p>In the ever-evolving landscape of coding and development, innovation takes centre stage once again with the introduction of StarCoder, a groundbreaking Large Language Model (LLM) designed specifically for code.</p><p>This revolutionary model, along with its counterpart StarCoderBase, has the potential to reshape how developers write, understand, and interact with code across various programming languages.</p><p>Let’s delve into the remarkable features and implications of this <em>State-of-the-Art Code LLM</em>.</p><h3>Unveiling StarCoder: A Leap in Code Understanding</h3><p>StarCoder and StarCoderBase have been meticulously trained on a wealth of data sourced from GitHub. This vast dataset encompasses<strong> over 80 programming languages</strong>, Git commits, GitHub issues, and Jupyter notebooks. With an impressive ~15 billion parameters and training involving 1 trillion tokens, these models are poised to set new standards in code comprehension.</p><p><strong>Enhanced Performance</strong>: Through extensive benchmarking, it’s evident that StarCoderBase not only outperforms existing open Code LLMs but also rivals or even surpasses closed models like code-cushman-001 by OpenAI. This performance superiority is remarkable, considering the model’s relatively smaller size than some of its competitors.</p><p><strong>Expanded Context</strong>: One of the most intriguing aspects of StarCoder is its ability to process input with an unprecedented context length of over 8,000 tokens. This remarkable capacity opens the door to an array of exciting applications, showcasing the model’s potential to revolutionize how developers interact with code.</p><h3>Practical Applications: Empowering Developers</h3><p>StarCoder is more than just an advanced LLM — it’s a tool that empowers developers to excel in their coding endeavours. Some of the applications that have emerged from StarCoder’s capabilities include:</p><ol><li>T<strong>echnical Assistant</strong>: By prompting the model with a series of dialogues, developers can leverage StarCoder as a versatile technical assistant. This marks a significant stride towards enhancing productivity and problem-solving within the coding process.</li><li><strong>Code Autocompletion</strong>: StarCoder’s prowess extends to code autocompletion, making coding faster and more efficient. Developers can receive smart suggestions that align with the context of their work, streamlining the coding journey.</li><li><strong>Code Modification and Explanation</strong>: StarCoder’s innate ability to understand code goes beyond mere completion. It can modify code based on instructions and even explain complex code snippets in natural language, bridging the gap between human understanding and machine-generated code.</li></ol><h3>Safety and Accessibility: A Model for the Future</h3><p>Ensuring safety and privacy is paramount in the development of any advanced AI model. StarCoder incorporates an improved Personally Identifiable Information (PII) redaction pipeline and a novel attribution tracing tool, reaffirming its commitment to data security. The release of StarCoder under an improved version of the OpenRAIL license simplifies integration into various products, fostering accessibility and widespread adoption.</p><h3>Setting a New State-of-the-Art</h3><p>Benchmark evaluations showcase StarCoder’s exceptional capabilities. By crafting clever prompts, the model’s HumanEval score surged from 34% to over 40%, a new state-of-the-art result for open models. This accomplishment solidifies StarCoder’s status as a pioneer in the field of Code LLMs.</p><h3>Embrace the Future: Code Like a Star</h3><p>StarCoder’s debut marks a significant step forward in coding and development. Its unparalleled performance, remarkable context length, and diverse applications herald a new era where developers can harness the power of AI to elevate their craft. With the ability to serve as a technical assistant, enhance code autocompletion, and provide code explanations, StarCoder is not just a tool — it’s a partner in innovation. As we welcome this extraordinary technology, let’s look ahead to a future where coding is not just a task, but a journey of creativity and collaboration with AI.</p><h3>Elevating the Coding Experience with HF Code Autocomplete: A Visual Studio Code Extension</h3><p>No coding journey is complete without the right tools to enhance productivity and streamline the development process. In this context, the integration of StarCoder’s capabilities into Visual Studio Code (VS Code) through the HF Code Autocomplete extension represents a significant leap forward for developers. This extension, available at <a href="https://marketplace.visualstudio.com/items?itemName=HuggingFace.huggingface-vscode">this link</a>, aptly named ‘HF Code Autocomplete,’ brings the power of StarCoder right to your coding environment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5051e22e4ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>