<?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 Deesya Lovely Susanto on Medium]]></title>
        <description><![CDATA[Stories by Deesya Lovely Susanto on Medium]]></description>
        <link>https://medium.com/@deesya?source=rss-f022522fb40b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*jG9xnGVzV_OQyYc4</url>
            <title>Stories by Deesya Lovely Susanto on Medium</title>
            <link>https://medium.com/@deesya?source=rss-f022522fb40b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 03:11:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@deesya/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[BERT for Multiclass Text Classification using Transformers]]></title>
            <link>https://medium.com/@deesya/bert-for-multiclass-text-classification-using-transformers-fb96a3ca7a52?source=rss-f022522fb40b------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb96a3ca7a52</guid>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[bert]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[multiclass-classification]]></category>
            <dc:creator><![CDATA[Deesya Lovely Susanto]]></dc:creator>
            <pubDate>Wed, 05 Jun 2024 14:51:07 GMT</pubDate>
            <atom:updated>2024-06-06T09:15:51.356Z</atom:updated>
            <content:encoded><![CDATA[<h3>BERT for Multiclass Text Classification using Transformers and PyTorch</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/0*1U1CnpQbIDEwpiMs.png" /><figcaption>Image Source: sesameworkshop.org</figcaption></figure><h3><strong>Introduction</strong></h3><p>This project is focused on fine-tuning the BERT model using a dataset from Local Government-Owned Water Utility (PDAM). The dataset is private and has been collected from their social media and their complaint application. Before being preprocessing, the dataset has 4,668 rows and 2 columns. Our goal is to predict customer complaints into one of eight categories: “air keruh” (cloudy water), “kebocoran” (leakage), “meter” (metering issues), “pemakaian” (usage issues), “TDA” (no water supply), “perubahan kode tarif” (tariff code changes), “layanan” (service), and “apresiasi” (appreciation).</p><p>‎‎</p><h4><strong>1. Import Libraries</strong></h4><pre>import pandas as pd<br>import numpy as np<br>import re<br>import torch<br>from transformers import BertTokenizer<br>from torch.utils.data import TensorDataset<br>from transformers import BertForSequenceClassification<br>from sklearn.model_selection import train_test_split<br>from sklearn.metrics import confusion_matrix<br>from sklearn.metrics import classification_report<br>from collections import defaultdict</pre><ul><li>BertTokenizer : Used for tokenizing data specifically for models based on the BERT (Bidirectional Encoder Representations from Transformers) architecture.</li><li>BertForSequenceClassification: An implementation of a BERT model optimized for sequence classification tasks</li></ul><p>‎</p><h4><strong>2. Load the Data</strong></h4><pre>from google.colab import drive<br>drive.mount(&#39;/content/drive&#39;)<br>df = pd.read_excel(&#39;/content/drive/MyDrive/sentimen-bert-try/train_category.xlsx&#39;)</pre><p>There are 4668 rows of data and the following two columns:</p><ul><li>text : The full text of the customer complaint on their social media or their complaint application</li><li>category : Category of the comment text are “air keruh” (cloudy water), “kebocoran” (leakage), “meter” (metering issues), “pemakaian” (usage issues), “TDA” (no water supply), “perubahan kode tarif” (tariff code changes), “layanan” (service), and “apresiasi” (appreciation)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*6UTpEzkLwRWleJ1ZIYKKqw.png" /></figure><p>You can see from the pie chart below that the most common consumer complaints are about “TDA” (no water supply) and “air keruh” (cloudy water), while the least common are about appreciation comments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*_6hEM-emExcV-9IP-Pe1cQ.png" /></figure><p><strong>Convert the categories labels into numerical</strong></p><p>The code below takes all the categories from the data and assigns a unique number to each one that automatically generated by the enumerate function.</p><pre>num_labels = df.category.unique()<br><br>label_dict = {}<br>for index, num_label in enumerate(num_labels):<br>    label_dict[num_label] = index<br>label_dict</pre><pre>df[&#39;label&#39;] = df.category.replace(label_dict)<br>df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*ip1j9lfoyZW-DyUGF7skiA.png" /></figure><p>‎</p><h4><strong>3. Data Preprocessing</strong></h4><pre># Preprocessing<br><br>character = [&#39;.&#39;,&#39;,&#39;,&#39;;&#39;,&#39;:&#39;,&#39;-,&#39;,&#39;...&#39;,&#39;?&#39;,&#39;!&#39;,&#39;(&#39;,&#39;)&#39;,&#39;[&#39;,&#39;]&#39;,&#39;{&#39;,&#39;}&#39;,&#39;&lt;&#39;,&#39;&gt;&#39;,&#39;&quot;&#39;,&#39;/&#39;,&#39;\&#39;&#39;,&#39;#&#39;,&#39;-&#39;,&#39;@&#39;,<br>             &#39;a&#39;,&#39;b&#39;,&#39;c&#39;,&#39;d&#39;,&#39;e&#39;,&#39;f&#39;,&#39;g&#39;,&#39;h&#39;,&#39;i&#39;,&#39;j&#39;,&#39;k&#39;,&#39;l&#39;,&#39;m&#39;,&#39;n&#39;,&#39;o&#39;,&#39;p&#39;,&#39;q&#39;,&#39;r&#39;,&#39;s&#39;,&#39;t&#39;,&#39;u&#39;,&#39;v&#39;,&#39;w&#39;,&#39;x&#39;,&#39;y&#39;,&#39;z&#39;,<br>             &#39;A&#39;,&#39;B&#39;,&#39;C&#39;,&#39;D&#39;,&#39;E&#39;,&#39;F&#39;,&#39;G&#39;,&#39;H&#39;,&#39;I&#39;,&#39;J&#39;,&#39;K&#39;,&#39;L&#39;,&#39;M&#39;,&#39;N&#39;,&#39;O&#39;,&#39;P&#39;,&#39;Q&#39;,&#39;R&#39;,&#39;S&#39;,&#39;T&#39;,&#39;U&#39;,&#39;V&#39;,&#39;W&#39;,&#39;X&#39;,&#39;Y&#39;,&#39;Z&#39;]<br><br><br># Case Folding, Remove Punctuation<br>def clean_text(text):<br>  text = text.lower() # ubah text menjadi huruf kecil<br>  text = re.sub(r&#39;\n&#39;, &#39; &#39;, text) # ubah enter menjadi spasi<br>  text = emoji.demojize(text) # hapus emoji<br>  text = re.sub(&#39;:[A-Za-z_-]+:&#39;, &#39; &#39;, text) # delete emoji<br>  text = re.sub(r&quot;([xX;:]&#39;?[dDpPvVoO3)(])&quot;, &#39; &#39;, text) # hapus emoticon<br>  text = re.sub(r&quot;(https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z0-9]+\.[^\s]{2,}|www\.[a-zA-Z0-9]+\.[^\s]{2,})&quot;, &quot;&quot;, text) # hapus link<br>  text = re.sub(r&quot;@[^\s]+[\s]?&quot;, &#39; &#39;, text) # hapus usename<br>  text = re.sub(r&#39;#(\S+)&#39;, r&#39;\1&#39;, text) # hapus hashtag<br>  text = re.sub(&#39;[^a-zA-Z,.?!]+&#39;,&#39; &#39;,text) # hapus angka dan beberapa simbol<br>  text = repeatcharClean(text) # hapus karakter berulang<br>  text = re.sub(&#39;[ ]+&#39;,&#39; &#39;,text) # clear spasi<br>  return text<br><br>def preprocess_v1(df):<br>  df_pp = df.copy()<br>  df_pp.text = df_pp.text.map(clean_text)<br><br>  # hapus baris kosong<br>  df_pp.text.replace(&#39;&#39;, np.nan, inplace=True)<br>  df_pp.text.replace(&#39; &#39;, np.nan, inplace=True)<br>  df_pp.dropna(subset=[&#39;text&#39;], inplace=True)<br>  return df_pp<br><br>df_v1 = preprocess_v1(df)</pre><pre># Preprocessing 2<br><br># additional_stopword<br>additional_stop = [] #[&#39;ya&#39;, &#39;deh&#39;, &#39;dia&#39;]<br><br># default stopword<br>default_stop = pd.read_csv(stopword_path, sep=&#39;/n&#39;, names=[&#39;stopwords&#39;])<br>default_stop = default_stop.stopwords.to_list()<br><br># combine all stopword<br>list_stopwords = []<br>list_stopwords = default_stop + additional_stop<br><br>kamus_alay = pd.read_csv(kamus_alay_path)<br><br>normalize_word_dict = {}<br>for index, row in kamus_alay.iterrows():<br>    if row[0] not in normalize_word_dict:<br>        normalize_word_dict[row[0]] = row[1]<br><br>def normalize_text(text):<br>  list_text = word_tokenize(text) # tokenize<br>  list_text = [normalize_word_dict[term] if term in normalize_word_dict else term for term in list_text] # ubah bahasa alay<br>  text = &quot; &quot;.join(list_text) # gabung kembali kalimat<br>  return text<br><br>  def preprocess_v2(df):<br>  df_pp = df.copy()<br>  df_pp.text = df_pp.text.map(normalize_text)<br><br>  # drop missing value<br>  df_pp.text.replace(&#39;&#39;, np.nan, inplace=True)<br>  df_pp.text.replace(&#39; &#39;, np.nan, inplace=True)<br>  df_pp.dropna(subset=[&#39;text&#39;], inplace=True)<br>  return df_pp<br><br>df  = preprocess_v2(df_v1)<br>df</pre><p>‎</p><h4><strong>4. Spliting data into training and validation using SKLearn</strong></h4><pre># Splitting Data<br><br>X_train, X_val, y_train, y_val = train_test_split(df.index.values,<br>                                                  df.labels.values,<br>                                                  test_size=0.15,<br>                                                  random_state=42,<br>                                                  stratify=df.label.values)<br><br>df[&#39;data_type&#39;] = [&#39;not_set&#39;]*df.shape[0]<br><br>df.loc[X_train, &#39;data_type&#39;] = &#39;train&#39;<br>df.loc[X_val, &#39;data_type&#39;] = &#39;val&#39;<br><br>df_grouped = df.groupby([&#39;category&#39;, &#39;label&#39;, &#39;data_type&#39;]).count()<br>df_grouped = df_grouped.rename(columns={&#39;text&#39;: &#39;count&#39;})<br>df_grouped</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*P6q-UmdLva_nedeg4Ae42w.png" /></figure><p>‎</p><h4><strong>5. Tokenizing and Encoding</strong></h4><pre><br>tokenizer = BertTokenizer.from_pretrained(&#39;bert-base-uncased&#39;,<br>                                          do_lower_case=True)<br><br>encoded_data_train = tokenizer.batch_encode_plus(<br>    df[df.data_type==&#39;train&#39;].text.values,<br>    add_special_tokens=True,<br>    return_attention_mask=True,<br>    pad_to_max_length=True,<br>    max_length=256,<br>    return_tensors=&#39;pt&#39;<br>)<br><br>encoded_data_val = tokenizer.batch_encode_plus(<br>    df[df.data_type==&#39;val&#39;].text.values,<br>    add_special_tokens=True,<br>    return_attention_mask=True,<br>    pad_to_max_length=True,<br>    max_length=256,<br>    return_tensors=&#39;pt&#39;<br>)<br><br><br>input_ids_train = encoded_data_train[&#39;input_ids&#39;]<br>attention_masks_train = encoded_data_train[&#39;attention_mask&#39;]<br>labels_train = torch.tensor(df[df.data_type==&#39;train&#39;].label.values)<br><br>input_ids_val = encoded_data_val[&#39;input_ids&#39;]<br>attention_masks_val = encoded_data_val[&#39;attention_mask&#39;]<br>labels_val = torch.tensor(df[df.data_type==&#39;val&#39;].label.values)<br><br>data_train = TensorDataset(input_ids_train, attention_masks_train, labels_train)<br>data_val = TensorDataset(input_ids_val, attention_masks_val, labels_val)</pre><p>We’re using the <a href="https://huggingface.co/docs/transformers/main_classes/tokenizer">BERT Tokenizer</a> from the ‘bert-base-uncased’ model. We set do_lower_case to True to make sure that all text is lowercased before tokenization.</p><p>Then encode the text data in the training and validation sets using batch_encode_plus method. This method tokenizes and encodes a batch of sequences, adding special tokens such as[CLS] and [SEP], padding sequences to the same length, and returning PyTorch tensors.</p><p>For the training set, we extract input IDs, attention masks, and labels. Input IDs represent tokenized text, attention masks indicate which tokens to attend to, and labels represent the categories of the training set.</p><p>Similarly, we extract input IDs, attention masks, and labels for the validation set.</p><p>Finally, we create PyTorch datasets for training and validation using TensorDataset, which combines input IDs, attention masks, and labels into a single dataset.</p><p>‎</p><h4><strong>6. Pre-Trained BERT Model</strong></h4><pre>from torch.utils.data import DataLoader, RandomSampler, SequentialSampler<br><br>model = BertForSequenceClassification.from_pretrained(&quot;bert-base-uncased&quot;,<br>                                                      num_labels=len(label_dict),<br>                                                      output_attentions=False,<br>                                                      output_hidden_states=False)<br><br>batch_size = 3<br><br>dataloader_train = DataLoader(data_train,<br>                              sampler=RandomSampler(data_train),<br>                              batch_size=batch_size)<br><br>dataloader_val = DataLoader(data_val,<br>                                   sampler=SequentialSampler(data_val),<br>                                   batch_size=batch_size)</pre><p>The batch size is usually set between 64 and 256. In the <a href="https://arxiv.org/abs/1609.04836">paper</a>, it suggest between 32–512, but i decided to define the batch size as 3 for both the training and validation dataloaders because tbh it’s kinda weird I get better results with batch size 3.</p><p>‎</p><p><strong>Setting the BERT model parameters</strong></p><pre>from transformers import AdamW, get_linear_schedule_with_warmup<br><br>optimizer = AdamW(model.parameters(),<br>                  lr=1e-5,<br>                  eps=1e-8)<br><br>epochs = 5<br><br>scheduler = get_linear_schedule_with_warmup(optimizer,<br>                                            num_warmup_steps=0,<br>                                            num_training_steps=len(dataloader_train)*epochs)</pre><p>In my experience, BERT tuning usually doesn’t need many epochs (around 5 or more), so feel free to experiment with these parameters (the type of optimizer, number of epochs, and learning rate).</p><p>‎</p><p><strong>Define a function to calculate F1 score &amp; accuracy per class</strong></p><pre>from sklearn.metrics import f1_score<br><br>def f1_score_func(preds, labels):<br>    preds_flat = np.argmax(preds, axis=1).flatten()<br>    labels_flat = labels.flatten()<br>    return f1_score(labels_flat, preds_flat, average=&#39;weighted&#39;)<br><br>def accuracy_per_class(preds, labels):<br>    label_dict_inverse = {v: k for k, v in label_dict.items()}<br><br>    preds_flat = np.argmax(preds, axis=1).flatten()<br>    labels_flat = labels.flatten()<br><br>    for label in np.unique(labels_flat):<br>        y_preds = preds_flat[labels_flat==label]<br>        y_true = labels_flat[labels_flat==label]<br>        print(f&#39;Class: {label_dict_inverse[label]}&#39;)<br>        print(f&#39;Accuracy: {len(y_preds[y_preds==label])}/{len(y_true)}\n&#39;)</pre><p>We have a model that categorizes customer complaints. The F1 Score function tells us how good the model is overall at categorizing all types of customer complaints. The Accuracy per Classfunction tells us how good the model is at correctly identifying each specific type of customer complaints, like “air keruh” (cloudy water), “kebocoran” (leakage), “meter” (metering issues), etc.</p><p>Here’s how the Accuracy per Classfunction might helps us understand its performance:</p><p><strong>Air Keruh:</strong></p><ul><li>Predicted: 50</li><li>Actual: 55</li><li>Correct Predictions: 45</li><li>Accuracy: 45/55=81.8%</li></ul><p>This means the model correctly identifies customer complaints about “air keruh” 81.8% of the time.</p><p>‎</p><h4><strong>7. Evaluate the Model</strong></h4><pre>seed_val = 6<br>random.seed(seed_val)<br>np.random.seed(seed_val)<br>torch.manual_seed(seed_val)<br>torch.cuda.manual_seed_all(seed_val)<br><br>device = torch.device(&#39;cuda&#39; if torch.cuda.is_available() else &#39;cpu&#39;)<br>model.to(device)<br>print(device)<br><br>def evaluate(dataloader_val):<br><br>    model.eval()<br><br>    loss_val_total = 0<br>    predictions, true_vals = [], []<br><br>    for batch in dataloader_val:<br><br>        batch = tuple(b.to(device) for b in batch)<br><br>        inputs = {&#39;input_ids&#39;:       batch[0],<br>                  &#39;attention_mask&#39;:  batch[1],<br>                  &#39;labels&#39;:          batch[2]<br>                 }<br>        with torch.no_grad():<br>            outputs = model(**inputs)<br><br>        loss = outputs[0]<br>        logits = outputs[1]<br>        loss_val_total += loss.item()<br><br>        logits = logits.detach().cpu().numpy()<br>        label_ids = inputs[&#39;labels&#39;].cpu().numpy()<br>        predictions.append(logits)<br>        true_vals.append(label_ids)<br><br>    loss_val_avg = loss_val_total/len(dataloader_val)<br><br>    predictions = np.concatenate(predictions, axis=0)<br>    true_vals = np.concatenate(true_vals, axis=0)<br><br>    return loss_val_avg, predictions, true_vals</pre><p>Set a random seed value of 6, this helps make sure that every time we run the code, we will get the same results. Next, we decide whether to use a GPU or a CPU for running our model.</p><p>Our model is trying to classify different types of customer complaints, so the evaluate function will help us see how well the model is identifying these types by calculating the average loss and comparing the predicted labels to the true labels.</p><pre>for epoch in tqdm(range(1, epochs + 1)):<br><br>    model.train()<br>    loss_train_total = 0<br>    progress_bar = tqdm(dataloader_train,<br>                        desc=&#39;Epoch {:1d}&#39;.format(epoch),<br>                        leave=False,<br>                        disable=False)<br><br>    for batch in progress_bar:<br><br>        model.zero_grad()<br>        batch = tuple(b.to(device) for b in batch)<br><br>        inputs = {<br>            &#39;input_ids&#39;: batch[0],<br>            &#39;attention_mask&#39;: batch[1],<br>            &#39;labels&#39;: batch[2]<br>        }<br><br>        outputs = model(**inputs)  # feed bert our inputs<br><br>        loss = outputs[0]<br>        loss_train_total += loss.item()<br>        loss.backward()  # back propagation step<br><br>        torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)<br><br>        # step optimizer &amp; scheduler<br>        optimizer.step()<br>        scheduler.step()<br><br>        # update progress bar and end batch loop<br>        progress_bar.set_postfix({&#39;training_loss&#39;: &#39;{:.3f}&#39;.format(loss.item() / len(batch))})  # loss of current item / batch length<br><br>    tqdm.write(f&#39;\nEpoch {epoch}&#39;)<br>    loss_train_avg = loss_train_total / len(dataloader_train)<br>    tqdm.write(f&#39;Training loss: {loss_train_avg}&#39;)<br><br>    val_loss, predictions, true_vals = evaluate(dataloader_validation)<br>    val_f1 = f1_score_func(predictions, true_vals)<br>    tqdm.write(f&#39;Validation loss: {val_loss}&#39;)<br>    tqdm.write(f&#39;F1 Score (weighted): {val_f1}&#39;)<br><br># save the model after training completes<br>model.save_pretrained(&#39;Models/class-version-4&#39;)</pre><p>We’re now going to train our model, during each epoch we’ll go through all the training data and adjust the model’s parameters to improve its predictions. After all the epochs are complete, then we save the trained model to a directory called ‘Models/class-version-4’. This way, we can use the model later without retraining it.</p><p>‎</p><p><strong>Evaluation: Load the Model</strong></p><pre># Load the model<br>model = BertForSequenceClassification.from_pretrained(<br>    &#39;/content/drive/MyDrive/sentimen-bert-try/class-version-4&#39;, <br>    num_labels=len(label_dict),<br>    output_attentions=False,<br>    output_hidden_states=False<br>)<br><br>model.to(device)</pre><p>‎</p><p><strong>Accuracy</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/1*8cx34llmTxx0mtw8TtfWUg.png" /></figure><pre>from sklearn.metrics import accuracy_score, precision_recall_fscore_support<br><br># Evaluate the model<br>def evaluate_model(dataloader, model):<br>    model.eval()<br><br>    predictions = []<br>    true_labels = []<br><br>    for batch in dataloader:<br>        batch = tuple(t.to(device) for t in batch)<br>        inputs = {&#39;input_ids&#39;: batch[0],<br>                  &#39;attention_mask&#39;: batch[1],<br>                  &#39;labels&#39;: batch[2]}<br><br>        with torch.no_grad():<br>            outputs = model(**inputs)<br><br>        logits = outputs[1]<br>        logits = logits.detach().cpu().numpy()<br>        label_ids = inputs[&#39;labels&#39;].to(&#39;cpu&#39;).numpy()<br><br>        predictions.extend(np.argmax(logits, axis=1))<br>        true_labels.extend(label_ids)<br><br>    return predictions, true_labels<br><br># Evaluate on validation set<br>predictions, true_labels = evaluate_model(dataloader_validation, model)<br><br># Calculate metrics<br>accuracy = accuracy_score(true_labels, predictions)<br>precision, recall, f1, _ = precision_recall_fscore_support(true_labels, predictions, average=&quot;weighted&quot;)<br><br>print(f&quot;Accuracy: {accuracy:.4f}&quot;)<br>print(f&quot;Precision: {precision:.4f}&quot;)<br>print(f&quot;Recall: {recall:.4f}&quot;)<br>print(f&quot;F1-score: {f1:.4f}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*EgGqVPYefTdbhH9A9q5KRg.png" /></figure><p>Overall, the model shows good accuracy in identifying categories of customer complaints. It performs best with “TDA” and “air keruh” complaints, and even handles positive feedback like “apresiasi” well.</p><p>In this imbalanced dataset, we got 87% for the model accuracy which is good but if you noticed for “layanan” category, it only predicted 17 records correctly out of 25, which means this model’s accuracy is 68% and isn’t able to predict “layanan” category as good as the other categories.</p><p>‎</p><p><strong>Confusion Matrix</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5RRvhfIUDenmoDFvDdk3fQ.jpeg" /></figure><p>We can see that out of 701 validation data records, “air keruh” was correctly predicted 65 times and got 8 wrong predictions. 5 were predicted as “kebocoran”, 1 as “meter”, 1 as “TDA”, and 1 as “perubahan kode tarif”.</p><p>“layanan” had the lowest accuracy. Out of 25 records, it was correctly predicted 17 but got 8 wrong predictions. 7 were predicted as “meter” and 1 as “apresiasi”.</p><p>This happens because the model might find it tricky to tell some categories apart since they can be kinda similar. For example, “air keruh” and “kebocoran” might sound alike or have similar words, so the model mixes them up. Same with “layanan” and “meter” since both can involve customer service stuff. The model’s accuracy also depends on how good and how much training data it had for each category and how different each category’s features are.</p><p>‎</p><h4>8. Making predictions with the new data</h4><pre>from transformers import BertTokenizer, BertForSequenceClassification, pipeline<br><br># Load the tokenizer<br>tokenizer = BertTokenizer.from_pretrained(&#39;bert-base-uncased&#39;, do_lower_case=True)<br><br># Load the pre-trained model with ignore_mismatched_sizes=True<br>model_path = &#39;/content/drive/MyDrive/sentimen-bert-try/class-version-4&#39;<br>model = BertForSequenceClassification.from_pretrained(<br>    model_path,<br>    num_labels=8,  # Specify the correct number of labels<br>    output_attentions=False,<br>    output_hidden_states=False,<br>    ignore_mismatched_sizes=True  # Ignore size mismatches<br>)<br><br># Create the text classification pipeline with the loaded model and tokenizer<br>predict = pipeline(&#39;text-classification&#39;, model=model, tokenizer=tokenizer)</pre><p>For making predictions on your own text, I suggest using the pipeline() function.</p><pre># mapping a label<br>label_map = {&#39;LABEL_0&#39;: &#39;air keruh&#39;, &#39;LABEL_1&#39;: &#39;TDA&#39;, &#39;LABEL_2&#39;: &#39;meter&#39;, &#39;LABEL_3&#39;: &#39;tarif&#39;, &#39;LABEL_4&#39;: &#39;pemakaian/tagihan&#39;, &#39;LABEL_5&#39;: &#39;kebocoran&#39;, &#39;LABEL_6&#39;: &#39;layanan&#39;, &#39;LABEL_7&#39;: &#39;apresiasi&#39;}<br></pre><p>Let’s use our fine-tuned model on a custom text and see if it can classify or predict the text correctly.</p><pre>result = predict(&quot;airnya warna hijau kaya matcha&quot;)<br><br>print(&quot;Predicted label:&quot;, label_map[result[0][&#39;label&#39;]])<br>#print(&quot;Score:&quot;, round(result[0][&#39;score&#39;],3))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*s3I6gM2eJ6TNq8cgsAsQ9Q.png" /><figcaption>Predicted label for “air keruh” category</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*2lJzNncx3cLM8fcEDmKrwg.png" /><figcaption>Predicted label for “layanan” category</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dc5b1Vb_aBB3WTNSPzcn6g.png" /><figcaption>Predicted label for “TDA” category</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MUzdb7jxqQYKFzDXEo_g1A.png" /><figcaption>Predicted label for “tarif” category</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*NJgdHpBd7T0ZA_tU1jBOrg.png" /><figcaption>Predicted label for “pemakaian/tagihan” category</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb96a3ca7a52" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Where vs. Having Clause in SQL: What’s The Differences?]]></title>
            <link>https://medium.com/@deesya/where-vs-having-clause-in-sql-whats-the-differences-f1c45fa46770?source=rss-f022522fb40b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1c45fa46770</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Deesya Lovely Susanto]]></dc:creator>
            <pubDate>Sun, 30 Jul 2023 15:19:43 GMT</pubDate>
            <atom:updated>2023-08-02T02:35:17.948Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*lsxp9I7iJNQrhAzUPzIRXg.png" /></figure><h3>What is the WHERE clause?</h3><p>WHERE clause is used to filter the records into rows before they are grouped, which allows us to focus on only the data relevant to our business questions. It can be used with SELECT, UPDATE, DELETE statements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*yWGup9RPC_rXI4Soj2dbqw.png" /><figcaption>Table Names “films”</figcaption></figure><p>We’ll walk through two questions here to show how to translate them into the correct filter. The first question is “What films were released in the year 1940?”. This question doesn’t indicate any sort of grouping. It asks to see only the titles from a specific year and can therefore be written as SELECT title, FROM films, WHERE release year equals to 1940.</p><pre>SELECT tittle<br>FROM films<br>WHERE release_year = 1940;</pre><p>Output of the above query is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*Fg0YIC0jaxlYUo2CQ-Kmpg.png" /></figure><h3><strong>What is the HAVING clause?</strong></h3><p>In SQL, we can’t filter aggregate functions (such as SUM, COUNT, AVG, MIN, and, MAX) with WHERE clauses. If we want to filter based on the result of an aggregate function, we need another way. Groups have their own special filtering word: HAVING.</p><p>And the second question is, “In what years was the average film duration over 100 minutes?” This query shows films with a duration over 100 minutes grouped by their release year.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*yWGup9RPC_rXI4Soj2dbqw.png" /></figure><pre>SELECT release_year<br>FROM films<br>GROUP BY release_year<br>HAVING AVG(duration) &gt; 100;</pre><p>Output of the above query is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*uLB-DkW8C6Fp_nG4rwcU4A.png" /></figure><h3>Difference Between WHERE clause and HAVING clause</h3><p>In conclusion, the WHERE and HAVING clauses in SQL serve distinct purposes in filtering data from tables. While the WHERE clause filters individual rows based on specific conditions before grouping or aggregation, the HAVING clause filters the grouped results based on aggregate functions. To summarize the differences, let’s take a look at the table below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*lIOvXRy03hb9EBsrUsretA.png" /><figcaption>Difference between WHERE clause and HAVING clause</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1c45fa46770" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>