### Install required packages Source: https://github.com/hooshvare/parsbert/blob/master/notebooks/Taaghche_Sentiment_Analysis.ipynb Installs transformers, hazm, and clean-text[gpl] using pip. The output shows successful installation with progress bars. ```python # Install required packages !pip install -q transformers !pip install -q hazm !pip install -q clean-text[gpl] ``` -------------------------------- ### Run SentimentModel on sample data and get predictions Source: https://github.com/hooshvare/parsbert/blob/master/notebooks/Taaghche_Sentiment_Analysis.ipynb Prepares sample data by moving tensors to the device, runs the model to get logits, and computes predictions using torch.max. The output shows the first five logits and the corresponding predicted labels. ```python # sample data output sample_data_comment = sample_data['comment'] sample_data_input_ids = sample_data['input_ids'] sample_data_attention_mask = sample_data['attention_mask'] sample_data_token_type_ids = sample_data['token_type_ids'] sample_data_targets = sample_data['targets'] # available for using in GPU sample_data_input_ids = sample_data_input_ids.to(device) sample_data_attention_mask = sample_data_attention_mask.to(device) sample_data_token_type_ids = sample_data_token_type_ids.to(device) sample_data_targets = sample_data_targets.to(device) # outputs = F.softmax( # pt_model(sample_data_input_ids, sample_data_attention_mask, sample_data_token_type_ids), # dim=1) outputs = pt_model(sample_data_input_ids, sample_data_attention_mask, sample_data_token_type_ids) _, preds = torch.max(outputs, dim=1) print(outputs[:5, :]) print(preds[:5]) ``` ```text tensor([[-0.0041, 0.3031], [ 0.0351, 0.1129], [-0.3107, 0.2490], [ 0.2128, -0.2075], [ 0.0127, 0.1538]], device='cuda:0', grad_fn=) tensor([1, 1, 1, 0, 1], device='cuda:0') ``` -------------------------------- ### Create TensorFlow dataset from examples with make_examples Source: https://github.com/hooshvare/parsbert/blob/master/notebooks/Taaghche_Sentiment_Analysis.ipynb Defines InputExample and make_examples to convert raw text into TensorFlow datasets or numpy arrays for sequence classification. The function uses glue_convert_examples_to_features and returns a tf.data.Dataset when is_tf_dataset is True, otherwise returns numpy arrays. The second block shows how to call make_examples for train, validation, and test splits, including a non-TF dataset for test. The third block iterates over the first training example and prints its input_ids, attention_mask, token_type_ids, and target. ```python class InputExample: """ A single example for simple sequence classification. """ def __init__(self, guid, text_a, text_b=None, label=None): """ Constructs a InputExample. """ self.guid = guid self.text_a = text_a self.text_b = text_b self.label = label def make_examples(tokenizer, x, y=None, maxlen=128, output_mode="classification", is_tf_dataset=True): examples = [] y = y if isinstance(y, list) or isinstance(y, np.ndarray) else [None] * len(x) for i, (_x, _y) in tqdm(enumerate(zip(x, y)), position=0, total=len(x)): guid = "%s" % i label = int(_y) if isinstance(_x, str): text_a = _x text_b = None else: assert len(_x) == 2 text_a = _x[0] text_b = _x[1] examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)) features = glue_convert_examples_to_features( examples, tokenizer, maxlen, output_mode=output_mode, label_list=list(np.unique(y))) all_input_ids = [] all_attention_masks = [] all_token_type_ids = [] all_labels = [] for f in tqdm(features, position=0, total=len(examples)): if is_tf_dataset: all_input_ids.append(tf.constant(f.input_ids)) all_attention_masks.append(tf.constant(f.attention_mask)) all_token_type_ids.append(tf.constant(f.token_type_ids)) all_labels.append(tf.constant(f.label)) else: all_input_ids.append(f.input_ids) all_attention_masks.append(f.attention_mask) all_token_type_ids.append(f.token_type_ids) all_labels.append(f.label) if is_tf_dataset: dataset = tf.data.Dataset.from_tensor_slices(({ 'input_ids': all_input_ids, 'attention_mask': all_attention_masks, 'token_type_ids': all_token_type_ids }, all_labels)) return dataset, features xdata = [np.array(all_input_ids), np.array(all_attention_masks), np.array(all_token_type_ids)] ydata = all_labels return [xdata, ydata], features ``` ```python train_dataset_base, train_examples = make_examples(tokenizer, x_train, y_train, maxlen=128) valid_dataset_base, valid_examples = make_examples(tokenizer, x_valid, y_valid, maxlen=128) test_dataset_base, test_examples = make_examples(tokenizer, x_test, y_test, maxlen=128) [xtest, ytest], test_examples = make_examples(tokenizer, x_test, y_test, maxlen=128, is_tf_dataset=False) ``` ```python for value in train_dataset_base.take(1): print(f' input_ids: {value[0]["input_ids"]}') print(f'attention_mask: {value[0]["attention_mask"]}') print(f'token_type_ids: {value[0]["token_type_ids"]}') print(f' target: {value[1]}') ``` -------------------------------- ### Select a random sample from the training set Source: https://github.com/hooshvare/parsbert/blob/master/notebooks/Taaghche_Sentiment_Analysis.ipynb Picks a random training example and prints its comment and label for inspection. ```python idx = np.random.randint(0, len(train)) sample_comment = train.iloc[idx]['comment'] sample_label = train.iloc[idx]['label'] print(f'Sample: \n{sample_comment}\n{sample_label}') ``` ```text Output: Sample: من نسخه کاغذی رو خوندم، برای یه زندگینامه سیاسی زیادی سطحی و خاله زنکی. گر چه بعضی از جاها به چهره چند شخصیتی سیاست‌مدارها اشاره میکنه. negative ``` -------------------------------- ### Load ParsBERT model and tokenize Persian text Source: https://github.com/hooshvare/parsbert/blob/master/README.md Use this snippet to load the ParsBERT model and tokenizer from Hugging Face. The example uses the 'HooshvareLab/bert-fa-zwnj-base' model. For TensorFlow, use TFAutoModel instead of AutoModel. The tokenizer output shows the tokenization of a Persian sentence, including the [ZWNJ] token for zero-width non-joiner. ```python from transformers import AutoConfig, AutoTokenizer, AutoModel, TFAutoModel # v3.0 model_name_or_path = "HooshvareLab/bert-fa-zwnj-base" config = AutoConfig.from_pretrained(model_name_or_path) tokenizer = AutoTokenizer.from_pretrained(model_name_or_path) # model = TFAutoModel.from_pretrained(model_name_or_path) For TF model = AutoModel.from_pretrained(model_name_or_path) text = "ما در هوش‌واره معتقدیم با انتقال صحیح دانش و آگاهی، همه افراد میتوانند از ابزارهای هوشمند استفاده کنند. شعار ما هوش مصنوعی برای همه است." tokenizer.tokenize(text) ['ما', 'در', 'هوش', '[ZWNJ]', 'واره', 'معتقدیم', 'با', 'انتقال', 'صحیح', 'دانش', 'و', 'آ', '##گاهی', '،', 'همه', 'افراد', 'میتوانند', 'از', 'ابزارهای', 'هوشمند', 'استفاده', 'کنند', '.', 'شعار', 'ما', 'هوش', 'مصنوعی', 'برای', 'همه', 'است', '.'] ``` -------------------------------- ### Load ParsBERT with TensorFlow 2.0 and tokenize text Source: https://github.com/hooshvare/parsbert/blob/master/model_cards/bert-base-parsbert-uncased.md Uses TFAutoModel to load the ParsBERT model in TensorFlow 2.0. The example also tokenizes a Persian sentence and shows the resulting token list. ```python from transformers import AutoConfig, AutoTokenizer, TFAutoModel config = AutoConfig.from_pretrained("HooshvareLab/bert-base-parsbert-uncased") tokenizer = AutoTokenizer.from_pretrained("HooshvareLab/bert-base-parsbert-uncased") model = TFAutoModel.from_pretrained("HooshvareLab/bert-base-parsbert-uncased") text = "ما در هوشواره معتقدیم با انتقال صحیح دانش و آگاهی، همه افراد می‌توانند از ابزارهای هوشمند استفاده کنند. شعار ما هوش مصنوعی برای همه است." tokenizer.tokenize(text) >>> ['ما', 'در', 'هوش', '##واره', 'معتقدیم', 'با', 'انتقال', 'صحیح', 'دانش', 'و', 'اگاهی', '،', 'همه', 'افراد', 'میتوانند', 'از', 'ابزارهای', 'هوشمند', 'استفاده', 'کنند', '.', 'شعار', 'ما', 'هوش', 'مصنوعی', 'برای', 'همه', 'است', '.'] ``` -------------------------------- ### Set up Kaggle credentials Source: https://github.com/hooshvare/parsbert/blob/master/notebooks/Taaghche_Sentiment_Analysis.ipynb Prompts for Kaggle username and API key, then creates the necessary directories and writes the credentials to kaggle.json. It also sets file permissions and prints a confirmation message. ```python #@title Kaggle Credential { display-mode: "form" } username = 'username' #@param {type: "string"} api_key = 'your api key' #@param {type: "string"} if username and api_key: token = {"username": username, "key": api_key} !mkdir ~/.kaggle !mkdir /content/.kaggle with open('/content/.kaggle/kaggle.json', 'w') as f: json.dump(token, f) !cp /content/.kaggle/kaggle.json ~/.kaggle/kaggle.json !chmod 600 /root/.kaggle/kaggle.json print('Your are ready to use kaggle API!') ``` -------------------------------- ### Set up device and check CUDA availability Source: https://github.com/hooshvare/parsbert/blob/master/notebooks/Taaghche_Sentiment_Analysis.ipynb Sets the device to GPU if available, otherwise CPU. Prints the device and whether CUDA is available for training. ```python device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") print(f'device: {device}') train_on_gpu = torch.cuda.is_available() if not train_on_gpu: print('CUDA is not available. Training on CPU ...') else: print('CUDA is available! Training on GPU ...') ``` ```text Output: device: cuda:0 CUDA is available! Training on GPU ... ``` -------------------------------- ### Get min and max comment length Source: https://github.com/hooshvare/parsbert/blob/master/notebooks/Taaghche_Sentiment_Analysis.ipynb Computes and prints the minimum and maximum word lengths of comments. ```python min_max_len = data["comment_len_by_words"].min(), data["comment_len_by_words"].max() print(f'Min: {min_max_len[0]} \tMax: {min_max_len[1]}') ``` -------------------------------- ### Prepare and batch training/validation datasets Source: https://github.com/hooshvare/parsbert/blob/master/notebooks/Taaghche_Sentiment_Analysis.ipynb Defines dataset preparation functions and then creates training and validation datasets with batching and shuffling. The result shows the number of training and validation steps. ```python def get_training_dataset(dataset, batch_size): dataset = dataset.repeat() dataset = dataset.shuffle(2048) dataset = dataset.batch(batch_size) return dataset def get_validation_dataset(dataset, batch_size): dataset = dataset.batch(batch_size) return dataset ``` ```python train_dataset = get_training_dataset(train_dataset_base, TRAIN_BATCH_SIZE) valid_dataset = get_training_dataset(valid_dataset_base, VALID_BATCH_SIZE) train_steps = len(train_examples) // TRAIN_BATCH_SIZE valid_steps = len(valid_examples) // VALID_BATCH_SIZE train_steps, valid_steps ``` ```text Result: (1859, 206) ``` -------------------------------- ### Instantiate and move SentimentModel to device Source: https://github.com/hooshvare/parsbert/blob/master/notebooks/Taaghche_Sentiment_Analysis.ipynb Instantiates the SentimentModel with the given config, moves it to the device, and prints its type. The output shows that pt_model is an instance of SentimentModel. ```python pt_model = SentimentModel(config=config) pt_model = pt_model.to(device) print('pt_model', type(pt_model)) ``` ```text pt_model ``` -------------------------------- ### Download Taaghche dataset from Kaggle Source: https://github.com/hooshvare/parsbert/blob/master/notebooks/Taaghche_Sentiment_Analysis.ipynb Removes any existing dataset directory, creates a new one, and downloads the Taaghche dataset using the Kaggle API. The output shows the download progress and completion. ```python !rm -rf /content/dataset !mkdir -p /content/dataset !kaggle datasets download saeedtqp/taaghche ``` -------------------------------- ### Load tokenizer and configuration for ParsBERT model Source: https://github.com/hooshvare/parsbert/blob/master/notebooks/Taaghche_Sentiment_Analysis.ipynb Initializes the BERT tokenizer and configuration from the specified model path, passing the label mappings to the config. Prints the configuration as a JSON string. ```python # setup the tokenizer and configuration tokenizer = BertTokenizer.from_pretrained(MODEL_NAME_OR_PATH) config = BertConfig.from_pretrained( MODEL_NAME_OR_PATH, **{ 'label2id': label2id, 'id2label': id2label, }) print(config.to_json_string()) ``` ```text Output: { "architectures": [ "BertForMaskedLM" ], "attention_probs_dropout_prob": 0.1, "gradient_checkpointing": false, "hidden_act": "gelu", "hidden_dropout_prob": 0.1, "hidden_size": 768, "id2label": { "0": "negative", "1": "positive" }, "initializer_range": 0.02, "intermediate_size": 3072, "label2id": { "negative": 0, "positive": 1 }, "layer_norm_eps": 1e-12, "max_position_embeddings": 512, "model_type": "bert", "num_attention_heads": 12, "num_hidden_layers": 12, "pad_token_id": 0, "type_vocab_size": 2, "vocab_size": 100000 } ``` -------------------------------- ### Preview balanced dataset Source: https://github.com/hooshvare/parsbert/blob/master/notebooks/Taaghche_Sentiment_Analysis.ipynb Displays the first few rows of the balanced dataset 'new_data' to inspect the data after balancing. ```python new_data.head() ``` -------------------------------- ### Sample data dictionary keys Source: https://github.com/hooshvare/parsbert/blob/master/notebooks/Taaghche_Sentiment_Analysis.ipynb Shows the keys of the sample data dictionary after tokenization, which are 'comment', 'input_ids', 'attention_mask', and 'token_type_ids'. ```text dict_keys(['comment', 'input_ids', 'attention_mask', 'token_type_ids']) ``` -------------------------------- ### Load tokenizer and config with label mappings Source: https://github.com/hooshvare/parsbert/blob/master/notebooks/Taaghche_Sentiment_Analysis.ipynb Loads the BERT tokenizer and configuration from the specified model path, adding the label mappings to the config. It then prints the config as a JSON string, showing the model architecture and label mappings. ```python tokenizer = BertTokenizer.from_pretrained(MODEL_NAME_OR_PATH) config = BertConfig.from_pretrained( MODEL_NAME_OR_PATH, **{ 'label2id': label2id, 'id2label': id2label, }) print(config.to_json_string()) ``` ```text Output: { "architectures": [ "BertForMaskedLM" ], "attention_probs_dropout_prob": 0.1, "gradient_checkpointing": false, "hidden_act": "gelu", "hidden_dropout_prob": 0.1, "hidden_size": 768, "id2label": { "0": "negative", "1": "positive" }, "initializer_range": 0.02, "intermediate_size": 3072, "label2id": { "negative": 0, "positive": 1 }, "layer_norm_eps": 1e-12, "max_position_embeddings": 512, "model_type": "bert", "num_attention_heads": 12, "num_hidden_layers": 12, "pad_token_id": 0, "type_vocab_size": 2, "vocab_size": 100000 } ``` -------------------------------- ### Create label to ID and ID to label mappings Source: https://github.com/hooshvare/parsbert/blob/master/notebooks/Taaghche_Sentiment_Analysis.ipynb Builds dictionaries mapping labels to integer IDs and vice versa, and prints them for verification. ```python # create a key finder based on label 2 id and id to label label2id = {label: i for i, label in enumerate(labels)} id2label = {v: k for k, v in label2id.items()} print(f'label2id: {label2id}') print(f'id2label: {id2label}') ``` ```text Output: label2id: {'negative': 0, 'positive': 1} id2label: {0: 'negative', 1: 'positive'} ``` -------------------------------- ### Prepare and save data as TSV files Source: https://github.com/hooshvare/parsbert/blob/master/notebooks/Taaghche_Sentiment_Analysis.ipynb Prepares the data by renaming columns to 'text' and 'label' and saves the train, dev, and test sets as TSV files in the /content/taaghche directory. ```python !rm -rf /content/taaghche !mkdir -p /content/taaghche ntrain = train[['comment', 'label']] ntrain.columns = ['text', 'label'] ndev = valid[['comment', 'label']] ndev.columns = ['text', 'label'] ntest = test[['comment', 'label']] ntest.columns = ['text', 'label'] ntrain.to_csv('/content/taaghche/' + 'train.tsv', sep='\t', index=False) ndev.to_csv('/content/taaghche/' + 'dev.tsv', sep='\t', index=False) ntest.to_csv('/content/taaghche/' + 'test.tsv', sep='\t', index=False) ``` -------------------------------- ### Define general configuration for training Source: https://github.com/hooshvare/parsbert/blob/master/notebooks/Taaghche_Sentiment_Analysis.ipynb Sets hyperparameters such as maximum sequence length, batch sizes, number of epochs, learning rate, and gradient clipping. Also specifies the model name and output path for the trained model. ```python # general config MAX_LEN = 128 TRAIN_BATCH_SIZE = 16 VALID_BATCH_SIZE = 16 TEST_BATCH_SIZE = 16 EPOCHS = 3 EEVERY_EPOCH = 1000 LEARNING_RATE = 2e-5 CLIP = 0.0 MODEL_NAME_OR_PATH = 'HooshvareLab/bert-fa-base-uncased' OUTPUT_PATH = '/content/bert-fa-base-uncased-sentiment-taaghceh/pytorch_model.bin' os.makedirs(os.path.dirname(OUTPUT_PATH), exist_ok=True) ``` -------------------------------- ### Create label mappings and print them Source: https://github.com/hooshvare/parsbert/blob/master/notebooks/Taaghche_Sentiment_Analysis.ipynb Creates label-to-id and id-to-label mappings from the labels list and prints them. The output shows that 'negative' maps to 0 and 'positive' maps to 1. ```python label2id = {label: i for i, label in enumerate(labels)} id2label = {v: k for k, v in label2id.items()} print(f'label2id: {label2id}') print(f'id2label: {id2label}') ``` ```text Output: label2id: {'negative': 0, 'positive': 1} id2label: {0: 'negative', 1: 'positive'} ``` -------------------------------- ### Run run_clf_finetuning.py for Taaghche sentiment fine-tuning Source: https://github.com/hooshvare/parsbert/blob/master/notebooks/Taaghche_Sentiment_Analysis.ipynb Cleans previous artifacts and runs the fine-tuning script for the Taaghche sentiment model. The command sets labels to positive/negative, uses the HooshvareLab/bert-fa-base-uncased model, and specifies training, evaluation, and prediction with a max sequence length of 128 and 3 epochs. ```python !rm -rf /content/bert-fa-base-uncased-sentiment-taaghceh-v2/ !mkdir -p /content/bert-fa-base-uncased-sentiment-taaghceh-v2/ !rm -rf /content/scripts/runs !rm /content/taaghche/cached_* !python run_clf_finetuning.py \ --labels positive,negative \ --output_mode classification \ --task_name taaghche \ --model_name_or_path HooshvareLab/bert-fa-base-uncased \ --data_dir /content/taaghche/ \ --output_dir /content/bert-fa-base-uncased-sentiment-taaghceh-v2/ \ --max_seq_length 128 \ --per_device_train_batch_size 16 \ --per_device_eval_batch_size 16 \ --learning_rate 2e-5 \ --num_train_epochs 3.0 \ --logging_steps 500 \ --save_steps 1000 \ --do_train \ --do_eval \ --do_predict \ --overwrite_output_dir \ --logging_first_step ``` -------------------------------- ### Load Taaghche dataset with Pandas Source: https://github.com/hooshvare/parsbert/blob/master/notebooks/Taaghche_Sentiment_Analysis.ipynb Loads the CSV file into a DataFrame, selects the 'comment' and 'rate' columns, and displays the first few rows. ```python data = pd.read_csv('/content/dataset/taghche.csv', encoding='utf-8') data = data[['comment', 'rate']] data.head() ``` -------------------------------- ### Define training and evaluation loops with accuracy and F1 metrics Source: https://github.com/hooshvare/parsbert/blob/master/notebooks/Taaghche_Sentiment_Analysis.ipynb Defines helper functions for accuracy and F1 computation, plus evaluation and training loops for a PyTorch model. The training loop uses gradient clipping, optimizer and scheduler steps, and optionally triggers evaluation callbacks. Requires a global `device`, `optimizer`, `scheduler`, `clip`, `eval`, `eval_data_loader`, `eval_cb`, `eval_loss_min`, and `print_every_step` to be defined in the surrounding scope. ```python def simple_accuracy(y_true, y_pred): return (y_true == y_pred).mean() def acc_and_f1(y_true, y_pred, average='weighted'): acc = simple_accuracy(y_true, y_pred) f1 = f1_score(y_true=y_true, y_pred=y_pred, average=average) return { "acc": acc, "f1": f1, } def y_loss(y_true, y_pred, losses): y_true = torch.stack(y_true).cpu().detach().numpy() y_pred = torch.stack(y_pred).cpu().detach().numpy() y = [y_true, y_pred] loss = np.mean(losses) return y, loss def eval_op(model, data_loader, loss_fn): model.eval() losses = [] y_pred = [] y_true = [] with torch.no_grad(): for dl in tqdm(data_loader, total=len(data_loader), desc="Evaluation... "): input_ids = dl['input_ids'] attention_mask = dl['attention_mask'] token_type_ids = dl['token_type_ids'] targets = dl['targets'] # move tensors to GPU if CUDA is available input_ids = input_ids.to(device) attention_mask = attention_mask.to(device) token_type_ids = token_type_ids.to(device) targets = targets.to(device) # compute predicted outputs by passing inputs to the model outputs = model( input_ids=input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids) # convert output probabilities to predicted class _, preds = torch.max(outputs, dim=1) # calculate the batch loss loss = loss_fn(outputs, targets) # accumulate all the losses losses.append(loss.item()) y_pred.extend(preds) y_true.extend(targets) eval_y, eval_loss = y_loss(y_true, y_pred, losses) return eval_y, eval_loss def train_op(model, data_loader, loss_fn, optimizer, scheduler, step=0, print_every_step=100, eval=False, eval_cb=None, eval_loss_min=np.Inf, eval_data_loader=None, clip=0.0): model.train() losses = [] y_pred = [] y_true = [] for dl in tqdm(data_loader, total=len(data_loader), desc="Training... "): step += 1 input_ids = dl['input_ids'] attention_mask = dl['attention_mask'] token_type_ids = dl['token_type_ids'] targets = dl['targets'] # move tensors to GPU if CUDA is available input_ids = input_ids.to(device) attention_mask = attention_mask.to(device) token_type_ids = token_type_ids.to(device) targets = targets.to(device) # clear the gradients of all optimized variables optimizer.zero_grad() # compute predicted outputs by passing inputs to the model outputs = model( input_ids=input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids) # convert output probabilities to predicted class _, preds = torch.max(outputs, dim=1) # calculate the batch loss loss = loss_fn(outputs, targets) # accumulate all the losses losses.append(loss.item()) # compute gradient of the loss with respect to model parameters loss.backward() # `clip_grad_norm` helps prevent the exploding gradient problem in RNNs / LSTMs. if clip > 0.0: nn.utils.clip_grad_norm_(model.parameters(), max_norm=clip) # perform optimization step optimizer.step() # perform scheduler step scheduler.step() y_pred.extend(preds) y_true.extend(targets) if eval: train_y, train_loss = y_loss(y_true, y_pred, losses) train_score = acc_and_f1(train_y[0], train_y[1], average='weighted') if step % print_every_step == 0: eval_y, eval_loss = eval_op(model, eval_data_loader, loss_fn) eval_score = acc_and_f1(eval_y[0], eval_y[1], average='weighted') if hasattr(eval_cb, '__call__'): eval_loss_min = eval_cb(model, step, train_score, train_loss, eval_score, eval_loss, eval_loss_min) train_y, train_loss = y_loss(y_true, y_pred, losses) return train_y, train_loss, step, eval_loss_min ``` -------------------------------- ### Import required packages Source: https://github.com/hooshvare/parsbert/blob/master/notebooks/Taaghche_Sentiment_Analysis.ipynb Imports all necessary libraries for data processing, model training, and evaluation, including numpy, pandas, sklearn, hazm, cleantext, plotly, and tqdm. ```python # Import required packages import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report from sklearn.metrics import f1_score from sklearn.utils import shuffle import hazm from cleantext import clean import plotly.express as px import plotly.graph_objects as go from tqdm.notebook import tqdm import os import re import json import copy import collections ``` -------------------------------- ### Import HuggingFace transformers and PyTorch libraries Source: https://github.com/hooshvare/parsbert/blob/master/notebooks/Taaghche_Sentiment_Analysis.ipynb Imports necessary libraries for BERT model, tokenizer, optimizer, and learning rate scheduler from HuggingFace transformers, along with PyTorch modules. ```python from transformers import BertConfig, BertTokenizer from transformers import BertModel from transformers import AdamW from transformers import get_linear_schedule_with_warmup import torch import torch.nn as nn import torch.nn.functional as F ``` -------------------------------- ### Training output at step 4000 Source: https://github.com/hooshvare/parsbert/blob/master/notebooks/Taaghche_Sentiment_Analysis.ipynb Output from the training loop at step 4000 of epoch 3/3. Shows training and validation loss/accuracy, but no model saving message because validation loss did not decrease. ```text Output: Epoch: 3/3...Step: 4000...Train Loss: 0.266199...Train Acc: 0.892...Valid Loss: 0.576440...Valid Acc: 0.781... ``` -------------------------------- ### Inspect test data loader batch keys Source: https://github.com/hooshvare/parsbert/blob/master/notebooks/Taaghche_Sentiment_Analysis.ipynb Retrieves the first batch from the test data loader and prints its keys. The output shows the keys 'comment', 'input_ids', 'attention_mask', 'token_type_ids', and 'targets'. ```python sample_test = next(iter(test_data_loader)) print(sample_test.keys()) ``` -------------------------------- ### Training output at step 5000 Source: https://github.com/hooshvare/parsbert/blob/master/notebooks/Taaghche_Sentiment_Analysis.ipynb Output from the training loop at step 5000 of epoch 3/3. Shows training and validation loss/accuracy, but no model saving message because validation loss did not decrease. ```text Output: Epoch: 3/3...Step: 5000...Train Loss: 0.169833...Train Acc: 0.938...Valid Loss: 0.722068...Valid Acc: 0.775... ``` -------------------------------- ### Clone parsbert repo and list scripts Source: https://github.com/hooshvare/parsbert/blob/master/notebooks/Taaghche_Sentiment_Analysis.ipynb Clones the parsbert repository, changes to the scripts directory, removes __pycache__, and lists the files. The output shows the current directory and the available scripts. ```python !git clone https://github.com/hooshvare/parsbert.git parsbert %cd /content/parsbert/scripts/ !rm -rf __pycache__ !ls ``` ```text Output: /content/scripts run_clf_finetuning.py utils.py ``` -------------------------------- ### Unzip the downloaded dataset Source: https://github.com/hooshvare/parsbert/blob/master/notebooks/Taaghche_Sentiment_Analysis.ipynb Extracts the taaghche.zip file into the /content/dataset/ directory. The output shows the extraction of taghche.csv. ```python !unzip /content/taaghche.zip -d /content/dataset/ ``` -------------------------------- ### Tokenize sample comment and show token IDs Source: https://github.com/hooshvare/parsbert/blob/master/notebooks/Taaghche_Sentiment_Analysis.ipynb Tokenizes the sample comment using the BERT tokenizer, converts tokens to IDs, and prints the original comment, the tokenized string, and the token IDs. ```python tokens = tokenizer.tokenize(sample_comment) token_ids = tokenizer.convert_tokens_to_ids(tokens) print(f' Comment: {sample_comment}') print(f' Tokens: {tokenizer.convert_tokens_to_string(tokens)}') print(f'Token IDs: {token_ids}') ``` -------------------------------- ### Check GPU availability with nvidia-smi Source: https://github.com/hooshvare/parsbert/blob/master/notebooks/Taaghche_Sentiment_Analysis.ipynb Verifies that a GPU is available for training. The output shows a Tesla P100 with CUDA 10.1. ```python !nvidia-smi ``` -------------------------------- ### Train ParsBERT with AdamW and linear warmup scheduler Source: https://github.com/hooshvare/parsbert/blob/master/notebooks/Taaghche_Sentiment_Analysis.ipynb Sets up the AdamW optimizer with a linear warmup scheduler, defines a cross-entropy loss, and runs the training loop for a ParsBERT model. The eval_callback prints per-step metrics and saves the model whenever validation loss decreases. The loop uses train_op and eval_op with weighted accuracy/F1 scoring, and records history for later analysis. ```python optimizer = AdamW(pt_model.parameters(), lr=LEARNING_RATE, correct_bias=False) total_steps = len(train_data_loader) * EPOCHS scheduler = get_linear_schedule_with_warmup( optimizer, num_warmup_steps=0, num_training_steps=total_steps ) loss_fn = nn.CrossEntropyLoss() step = 0 eval_loss_min = np.Inf history = collections.defaultdict(list) def eval_callback(epoch, epochs, output_path): def eval_cb(model, step, train_score, train_loss, eval_score, eval_loss, eval_loss_min): statement = '' statement += 'Epoch: {}/{}...'.format(epoch, epochs) statement += 'Step: {}...'.format(step) statement += 'Train Loss: {:.6f}...'.format(train_loss) statement += 'Train Acc: {:.3f}...'.format(train_score['acc']) statement += 'Valid Loss: {:.6f}...'.format(eval_loss) statement += 'Valid Acc: {:.3f}...'.format(eval_score['acc']) print(statement) if eval_loss <= eval_loss_min: print('Validation loss decreased ({:.6f} --> {:.6f}). Saving model ...'.format( eval_loss_min, eval_loss)) torch.save(model.state_dict(), output_path) eval_loss_min = eval_loss return eval_loss_min return eval_cb for epoch in tqdm(range(1, EPOCHS + 1), desc="Epochs... "): train_y, train_loss, step, eval_loss_min = train_op( model=pt_model, data_loader=train_data_loader, loss_fn=loss_fn, optimizer=optimizer, scheduler=scheduler, step=step, print_every_step=EEVERY_EPOCH, eval=True, eval_cb=eval_callback(epoch, EPOCHS, OUTPUT_PATH), eval_loss_min=eval_loss_min, eval_data_loader=valid_data_loader, clip=CLIP) train_score = acc_and_f1(train_y[0], train_y[1], average='weighted') eval_y, eval_loss = eval_op( model=pt_model, data_loader=valid_data_loader, loss_fn=loss_fn) eval_score = acc_and_f1(eval_y[0], eval_y[1], average='weighted') history['train_acc'].append(train_score['acc']) history['train_loss'].append(train_loss) history['val_acc'].append(eval_score['acc']) history['val_loss'].append(eval_loss) ``` -------------------------------- ### Tokenization Output for Sample Comment Source: https://github.com/hooshvare/parsbert/blob/master/notebooks/Taaghche_Sentiment_Analysis.ipynb Shows the tokenization output for a sample Persian comment using the ParsBERT tokenizer. The comment is split into tokens, with the word 'سیاست‌مدارها' replaced by the [UNK] token, and the corresponding token IDs are listed. ```text Output: Comment: من نسخه کاغذی رو خوندم، برای یه زندگینامه سیاسی زیادی سطحی و خاله زنکی. گر چه بعضی از جاها به چهره چند شخصیتی سیاست‌مدارها اشاره میکنه. Tokens: من نسخه کاغذی رو خوندم ، برای یه زندگینامه سیاسی زیادی سطحی و خاله زنکی . گر چه بعضی از جاها به چهره چند شخصیتی [UNK] اشاره میکنه . Token IDs: [2842, 4207, 13304, 2840, 69254, 1348, 2831, 4642, 13504, 3654, 3406, 8196, 1379, 20321, 4100, 3065, 1012, 2911, 3051, 4322, 2791, 21026, 2789, 6802, 3102, 9660, 1, 3364, 12702, 1012] ``` -------------------------------- ### Training output at step 3000 Source: https://github.com/hooshvare/parsbert/blob/master/notebooks/Taaghche_Sentiment_Analysis.ipynb Output from the training loop at step 3000 of epoch 2/3. Shows training and validation loss/accuracy, but no model saving message because validation loss did not decrease. ```text Output: Epoch: 2/3...Step: 3000...Train Loss: 0.359391...Train Acc: 0.847...Valid Loss: 0.482912...Valid Acc: 0.779... ``` -------------------------------- ### Epoch progress bar output Source: https://github.com/hooshvare/parsbert/blob/master/notebooks/Taaghche_Sentiment_Analysis.ipynb Displays a Jupyter progress bar for the epoch loop, showing a FloatProgress widget with max=3.0. This is the output of the training loop's tqdm progress bar. ```text Result: HBox(children=(FloatProgress(value=0.0, description='Epochs... ', max=3.0, style=ProgressStyle(description_wid… ``` -------------------------------- ### Training progress bar output Source: https://github.com/hooshvare/parsbert/blob/master/notebooks/Taaghche_Sentiment_Analysis.ipynb Shows a Jupyter progress bar for the training phase, with max=1859.0 steps. This is the output of the training progress bar. ```text Result: HBox(children=(FloatProgress(value=0.0, description='Training... ', max=1859.0, style=ProgressStyle(descriptio… ``` -------------------------------- ### Training output at step 1000 Source: https://github.com/hooshvare/parsbert/blob/master/notebooks/Taaghche_Sentiment_Analysis.ipynb Output from the training loop at step 1000 of epoch 1/3. Shows training and validation loss/accuracy, and indicates the model was saved because validation loss decreased from inf to 0.479472. ```text Output: Epoch: 1/3...Step: 1000...Train Loss: 0.529089...Train Acc: 0.736...Valid Loss: 0.479472...Valid Acc: 0.778... Validation loss decreased (inf --> 0.479472). Saving model ... ``` -------------------------------- ### Run classification fine-tuning script Source: https://github.com/hooshvare/parsbert/blob/master/notebooks/Taaghche_Sentiment_Analysis.ipynb Runs the classification fine-tuning script. ```python !python run_clf_finetuning.py ``` -------------------------------- ### Define TaaghcheDataset and create_data_loader Source: https://github.com/hooshvare/parsbert/blob/master/notebooks/Taaghche_Sentiment_Analysis.ipynb Defines a PyTorch Dataset class for Taaghche comments and a helper function to create a DataLoader. The dataset tokenizes comments with the provided tokenizer, optionally maps string labels to integers using label_list, and returns flattened tensors for input_ids, attention_mask, and token_type_ids, plus a targets tensor when targets are provided. ```python class TaaghcheDataset(torch.utils.data.Dataset): """ Create a PyTorch dataset for Taaghche. """ def __init__(self, tokenizer, comments, targets=None, label_list=None, max_len=128): self.comments = comments self.targets = targets self.has_target = isinstance(targets, list) or isinstance(targets, np.ndarray) self.tokenizer = tokenizer self.max_len = max_len self.label_map = {label: i for i, label in enumerate(label_list)} if isinstance(label_list, list) else {} def __len__(self): return len(self.comments) def __getitem__(self, item): comment = str(self.comments[item]) if self.has_target: target = self.label_map.get(str(self.targets[item]), str(self.targets[item])) encoding = self.tokenizer.encode_plus( comment, add_special_tokens=True, truncation=True, max_length=self.max_len, return_token_type_ids=True, padding='max_length', return_attention_mask=True, return_tensors='pt') inputs = { 'comment': comment, 'input_ids': encoding['input_ids'].flatten(), 'attention_mask': encoding['attention_mask'].flatten(), 'token_type_ids': encoding['token_type_ids'].flatten(), } if self.has_target: inputs['targets'] = torch.tensor(target, dtype=torch.long) return inputs def create_data_loader(x, y, tokenizer, max_len, batch_size, label_list): dataset = TaaghcheDataset( comments=x, targets=y, tokenizer=tokenizer, max_len=max_len, label_list=label_list) return torch.utils.data.DataLoader(dataset, batch_size=batch_size) ``` -------------------------------- ### Encode Sample Comment with encode_plus Source: https://github.com/hooshvare/parsbert/blob/master/notebooks/Taaghche_Sentiment_Analysis.ipynb Encodes a sample comment using the tokenizer's encode_plus method with a maximum length of 32, truncation, and padding to max_length. Returns PyTorch tensors and prints the keys and values of the encoding dictionary. ```python encoding = tokenizer.encode_plus( sample_comment, max_length=32, truncation=True, add_special_tokens=True, # Add '[CLS]' and '[SEP]' return_token_type_ids=True, return_attention_mask=True, padding='max_length', return_tensors='pt', # Return PyTorch tensors ) print(f'Keys: {encoding.keys()}\n') for k in encoding.keys(): print(f'{k}:\n{encoding[k]}') ``` -------------------------------- ### Build and compile TFBertForSequenceClassification model Source: https://github.com/hooshvare/parsbert/blob/master/notebooks/Taaghche_Sentiment_Analysis.ipynb Builds a TFBertForSequenceClassification model from a pretrained checkpoint, compiles it with Adam optimizer and sparse categorical crossentropy. The output shows the model initialization warnings about unused and newly initialized weights. ```python def build_model(model_name, config, learning_rate=3e-5): model = TFBertForSequenceClassification.from_pretrained(model_name, config=config) optimizer = tf.keras.optimizers.Adam(learning_rate=learning_rate) loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True) metric = tf.keras.metrics.SparseCategoricalAccuracy('accuracy') model.compile(optimizer=optimizer, loss=loss, metrics=[metric]) return model ``` ```python model = build_model(MODEL_NAME_OR_PATH, config, learning_rate=LEARNING_RATE) ``` ```text Result: HBox(children=(FloatProgress(value=0.0, description='Downloading', max=963211760.0, style=ProgressStyle(descri… ``` ```text Output: Some weights of the model checkpoint at HooshvareLab/bert-fa-base-uncased were not used when initializing TFBertForSequenceClassification: ['nsp___cls', 'mlm___cls'] - This IS expected if you are initializing TFBertForSequenceClassification from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForSequenceClassification model from a BertForPretraining model). - This IS NOT expected if you are initializing TFBertForSequenceClassification from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model). Some weights of TFBertForSequenceClassification were not initialized from the model checkpoint at HooshvareLab/bert-fa-base-uncased and are newly initialized: ['dropout_37', 'classifier'] You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference. ``` -------------------------------- ### Inspect a Batch from the Training DataLoader Source: https://github.com/hooshvare/parsbert/blob/master/notebooks/Taaghche_Sentiment_Analysis.ipynb Retrieves a batch from the training DataLoader and prints the keys, shapes, and first elements of the tensors (comment, input_ids, attention_mask, token_type_ids, targets). Useful for inspecting the structure of the dataset. ```python sample_data = next(iter(train_data_loader)) print(sample_data.keys()) print(sample_data['comment']) print(sample_data['input_ids'].shape) print(sample_data['input_ids'][0, :]) print(sample_data['attention_mask'].shape) print(sample_data['attention_mask'][0, :]) print(sample_data['token_type_ids'].shape) print(sample_data['token_type_ids'][0, :]) print(sample_data['targets'].shape) print(sample_data['targets'][0]) ``` -------------------------------- ### Create DataLoaders for Train, Validation, and Test Source: https://github.com/hooshvare/parsbert/blob/master/notebooks/Taaghche_Sentiment_Analysis.ipynb Creates DataLoaders for training, validation, and test sets using the create_data_loader function. The label_list is set to ['negative', 'positive'], and the test loader is created without targets (None). ```python label_list = ['negative', 'positive'] train_data_loader = create_data_loader(train['comment'].to_numpy(), train['label'].to_numpy(), tokenizer, MAX_LEN, TRAIN_BATCH_SIZE, label_list) valid_data_loader = create_data_loader(valid['comment'].to_numpy(), valid['label'].to_numpy(), tokenizer, MAX_LEN, VALID_BATCH_SIZE, label_list) test_data_loader = create_data_loader(test['comment'].to_numpy(), None, tokenizer, MAX_LEN, TEST_BATCH_SIZE, label_list) ``` -------------------------------- ### Balance dataset by random sampling Source: https://github.com/hooshvare/parsbert/blob/master/notebooks/Taaghche_Sentiment_Analysis.ipynb Balances the dataset by randomly sampling the majority class to match the minority class size, then concatenates and shuffles the data. The resulting DataFrame 'new_data' is balanced and its info is printed. ```python negative_data = data[data['label'] == 'negative'] positive_data = data[data['label'] == 'positive'] cutting_point = min(len(negative_data), len(positive_data)) if cutting_point <= len(negative_data): negative_data = negative_data.sample(n=cutting_point).reset_index(drop=True) if cutting_point <= len(positive_data): positive_data = positive_data.sample(n=cutting_point).reset_index(drop=True) new_data = pd.concat([negative_data, positive_data]) new_data = new_data.sample(frac=1).reset_index(drop=True) new_data.info() ``` -------------------------------- ### ParsBERT Training Evaluation Results Source: https://github.com/hooshvare/parsbert/blob/master/model_cards/bert-fa-base-uncased.md Output of the evaluation after 300k training steps, showing the loss and accuracy metrics for masked language modeling and next sentence prediction. ```bash ***** Eval results ***** global_step = 300000 loss = 1.4392426 masked_lm_accuracy = 0.6865794 masked_lm_loss = 1.4469004 next_sentence_accuracy = 1.0 next_sentence_loss = 6.534152e-05 ``` -------------------------------- ### Load ParsBERT with PyTorch Source: https://github.com/hooshvare/parsbert/blob/master/model_cards/bert-fa-base-uncased.md Loads the ParsBERT model for PyTorch using the Hugging Face Transformers library. It initializes the configuration, tokenizer, and model from the 'HooshvareLab/bert-fa-base-uncased' checkpoint. ```python from transformers import AutoConfig, AutoTokenizer, AutoModel config = AutoConfig.from_pretrained("HooshvareLab/bert-fa-base-uncased") tokenizer = AutoTokenizer.from_pretrained("HooshvareLab/bert-fa-base-uncased") model = AutoModel.from_pretrained("HooshvareLab/bert-fa-base-uncased") ``` -------------------------------- ### Save the trained model Source: https://github.com/hooshvare/parsbert/blob/master/notebooks/Taaghche_Sentiment_Analysis.ipynb Saves the trained model to the directory specified by OUTPUT_PATH. ```python # save the model model.save_pretrained(os.path.dirname(OUTPUT_PATH)) ```