<?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 Abdurhman Fayad on Medium]]></title>
        <description><![CDATA[Stories by Abdurhman Fayad on Medium]]></description>
        <link>https://medium.com/@abdurhmanfayad_73788?source=rss-3db3570e2b2e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*qeKiFI7TWfKaVzx9TZ0u2w.png</url>
            <title>Stories by Abdurhman Fayad on Medium</title>
            <link>https://medium.com/@abdurhmanfayad_73788?source=rss-3db3570e2b2e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 03:30:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abdurhmanfayad_73788/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 a Multi-Label Classification Problem on Colab]]></title>
            <link>https://medium.com/@abdurhmanfayad_73788/fine-tuning-bert-for-a-multi-label-classification-problem-on-colab-5ca5b8759f3f?source=rss-3db3570e2b2e------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ca5b8759f3f</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[pretrained-model]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Abdurhman Fayad]]></dc:creator>
            <pubDate>Sun, 05 Nov 2023 18:16:46 GMT</pubDate>
            <atom:updated>2023-11-05T18:16:46.342Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*GAYwZzu6zjbTcLmZ4nLMfg.jpeg" /></figure><h3>1.Introduction</h3><p>Multi-label classification is a challenging natural language processing task that involves assigning multiple labels or categories to a single piece of text. Unlike single-label classification, where each input is assigned a single category, multi-label classification recognizes that text can belong to several categories simultaneously. This task is crucial in various real-world applications, such as content tagging, sentiment analysis, and topic categorization.</p><p>In this guide, we will explore the ways of applying multi-label classification with BERT, a powerful pre-trained language model. <strong>BERT <em>(</em></strong><em>Bidirectional Encoder Representations from Transformers)</em> has revolutionized natural language processing by understanding the contextual nuances of language. Its pre-trained knowledge can be fine-tuned for specific tasks, making it a formidable choice for multi-label classification.</p><h4>Google Colab</h4><p>For the purposes of this guide, we will utilize Google Colab as our primary environment. Google Colab offers several advantages, making it an ideal choice for both beginners and experienced practitioners. It provides free access to GPU resources (which is all we will need in this example), that is essential for efficiently training deep learning models like BERT.</p><h3>2.Setting up the environment</h3><p>The first step is set the runtime of the notebook and enabling the free GPU by going to <em>Runtime &gt; Change runtime type.</em></p><p>Then we’ll need to install the Transformers Library from Hugging Face and import the following Python libraries</p><pre>!pip install transformers[torch]<br><br>import pandas as pd<br>import numpy as np<br>import torch<br><br>from torch.utils.data.dataset import Dataset<br>from transformers import TrainingArguments, Trainer, AutoTokenizer, AutoModelForSequenceClassification<br>from sklearn.model_selection import train_test_split</pre><h3>3.Dataset</h3><p>In this example, we will be using a dataset of legal documents representing laws in force in the European Union (EU) with respect to the subdirectories to which they belong.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S4ADLndashbePfMxxScGEg.png" /></figure><p>Here we have the columns representing all the chapters and subchapters of the European Law, each law can be labeled with multiple chapters.</p><p>Now we split the dataset into train and test.</p><pre>test_split = 0.1<br>train_df, test_df = train_test_split(<br>    df,<br>    test_size=test_split,<br>)<br>print(f&quot;Number of rows in training set: {len(train_df)}&quot;)<br>print(f&quot;Number of rows in test set: {len(test_df)}&quot;)</pre><p>The next step is create a separate data frame for the labels for both the train and test split, then convert them to lists.</p><pre># Define a list of columns that should not be chosen as label columns<br>not_chosen_columns = [&#39;CELEX_ID&#39;, &#39;Text&#39;,&#39;Citations&#39;]<br><br># Select label columns that are not in the list of not chosen columns<br>label_columns = [col for col in df.columns if col not in not_chosen_columns]<br><br># Create a new DataFrame containing only the selected label columns<br>df_labels_train = train_df[label_columns]<br>df_labels_test = test_df[label_columns]<br><br><br># Convert the label columns to lists for each row<br>labels_list_train = df_labels_train.values.tolist()<br>labels_list_test = df_labels_test.values.tolist()</pre><h3>4.Train</h3><p>We will do the following steps to start training the pretrained model on our data:</p><ul><li>Set the training and evaluation data.</li><li>Import the tokenizer of the choosed model <em>(in our case it is bert-base-uncased)</em></li><li>Apply the tokenizer on the training and evaluation and create the datasets.</li><li>Import the pre-trained model.</li><li>Set the training arguments (these are recommended settings to be used when using the google colab free gpu, more increasing the batch size for example might results in the session crashing).</li><li>Finally, start the training.</li></ul><pre><br>train_texts = train_df[&#39;Text&#39;].tolist()<br>train_labels = labels_list_train<br><br>eval_texts = test_df[&#39;Text&#39;].tolist()<br>eval_labels = labels_list_test<br><br>tokenizer = AutoTokenizer.from_pretrained(&#39;bert-base-uncased&#39;, do_lower_case=True)<br><br>train_encodings = tokenizer(train_texts, padding=&quot;max_length&quot;, truncation=True, max_length=512)<br>eval_encodings = tokenizer(eval_texts, padding=&quot;max_length&quot;, truncation=True, max_length=512)<br><br><br>class TextClassifierDataset(Dataset):<br>    def __init__(self, encodings, labels):<br>        self.encodings = encodings<br>        self.labels = labels<br><br>    def __len__(self):<br>        return len(self.labels)<br><br>    def __getitem__(self, idx):<br>        item = {key: torch.tensor(val[idx]) for key, val in self.encodings.items()}<br>        item[&quot;labels&quot;] = torch.tensor(self.labels[idx])<br>        return item<br><br>train_dataset = TextClassifierDataset(train_encodings, train_labels)<br>eval_dataset = TextClassifierDataset(eval_encodings, eval_labels)<br><br>model = AutoModelForSequenceClassification.from_pretrained(<br>    &quot;bert-base-uncased&quot;,<br>    problem_type=&quot;multi_label_classification&quot;,<br>    num_labels=93<br>)<br><br>training_arguments = TrainingArguments(<br>    output_dir=&quot;.&quot;,<br>    evaluation_strategy=&quot;epoch&quot;,<br>    per_device_train_batch_size=16,<br>    per_device_eval_batch_size=16,<br>    num_train_epochs=8,<br>)<br><br>trainer = Trainer(<br>    model=model,<br>    args=training_arguments,<br>    train_dataset=train_dataset,<br>    eval_dataset=eval_dataset,<br>)<br><br>trainer.train()</pre><h3>5.Using the model</h3><p>After successfully training the model, it can be used on other data following that same steps on the training data, after setting the model in evaluation mode</p><pre>model.eval()<br># Process each text<br>for text in text_list:<br>    inputs = tokenizer(text, padding=True, truncation=True, return_tensors=&quot;pt&quot;)<br>    inputs = inputs.to(device)<br><br>    with torch.no_grad():<br>        outputs = model(**inputs)<br><br>    logits = outputs.logits<br>    probabilities = torch.sigmoid(logits)  # Apply sigmoid to convert logits to probabilities<br><br>    all_probabilities.append(probabilities)</pre><p>The results will be probabilities of each labels for each text, setting the threshold probability on which label is accepted can be tricky, depending on the data you can try and different thresholds and obserb which one work best.</p><pre># Define the new threshold (e.g., 0.4)<br>new_threshold = 0.2<br><br># Create an empty DataFrame with the correct columns<br>df_submission = pd.DataFrame(columns=label_columns)<br><br># Iterate through the rows of all_probabilities_array<br>for row in all_probabilities_array:<br>    # Create a mask for values greater than or equal to the new threshold<br>    mask = row &gt;= new_threshold<br><br>    # Check if any value is above the threshold<br>    if mask.any():<br>        # If there is at least one value above the threshold, use the mask<br>        thresholded_row = mask.astype(int)<br>    else:<br>        # If there are no values above the threshold, take the top 1 value<br>        top_1_index = np.argmax(row)<br>        thresholded_row = np.zeros(len(label_columns), dtype=int)<br>        thresholded_row[top_1_index] = 1<br><br>    # Reshape the thresholded_row to match the length of the index<br>    thresholded_row = thresholded_row.reshape(1, -1)<br><br>    # Append the thresholded row to the DataFrame<br>    df_submission = df_submission.append(pd.DataFrame(thresholded_row, columns=label_columns), ignore_index=True)<br><br># Convert the DataFrame to integer type<br>df_submission = df_submission.astype(int)</pre><h3>6.Conclusion</h3><p>This guide has equipped you with the essential knowledge to fine-tune BERT for multi-label classification using Google Colab. We’ve covered various aspects, from setting up your environment to selecting the right BERT model for your task.</p><p>With this knowledge, you’re well-prepared to start working on your multi-label classification projects.</p><p>The complete code of this project can be found <a href="https://gist.github.com/AFayad0/ca196fc2642cbb01a10b2f3fb2d1e9a4">here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ca5b8759f3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>