import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
import spacy
from datasets import load_dataset
def load_sib200_ru() -> Tuple[Tuple[List[str], List[int]], Tuple[List[str], List[int]], Tuple[List[str], List[int]], List[str]]:
trainset = load_dataset('Davlan/sib200', 'rus_Cyrl', split='train')
X_train = trainset['text']
y_train = trainset['category']
valset = load_dataset('Davlan/sib200', 'rus_Cyrl', split='validation')
X_val = valset['text']
y_val = valset['category']
testset = load_dataset('Davlan/sib200', 'rus_Cyrl', split='test')
X_test = testset['text']
y_test = testset['category']
categories = set(y_train)
unknown_categories = set(y_val) - categories
if len(unknown_categories) > 0:
err_msg = f'The categories {unknown_categories} are represented in the validation set, but they are not represented in the training set.'
raise RuntimeError(err_msg)
unknown_categories = set(y_test) - categories
if len(unknown_categories) > 0:
err_msg = f'The categories {unknown_categories} are represented in the test set, but they are not represented in the training set.'
raise RuntimeError(err_msg)
categories = sorted(list(categories))
y_train = [categories.index(it) for it in y_train]
y_val = [categories.index(it) for it in y_val]
y_test = [categories.index(it) for it in y_test]
return (X_train, y_train), (X_val, y_val), (X_test, y_test), categories
def normalize_text(s: str, nlp_pipeline: spacy.Language) -> str:
doc = nlp_pipeline(s)
lemmas = [('' if token.like_num else token.lemma_.lower()) for token in filter(lambda it1: not it1.is_punct, doc)]
if len(lemmas) == 0:
return ''
return ' '.join(lemmas)
cv.fit([normalize_text(it, nlp) for it in train_data[0]], train_data[1])
print('Best parameters:')
print(cv.best_params_)
print('Best F1-macro:')
print(cv.best_score_)
print(f'Vocabulary size is {len(cv.best_estimator_.named_steps["vectorizer"].vocabulary_)}.')
y_pred = cv.predict([normalize_text(it, nlp) for it in val_data[0]])
print(classification_report(y_true=val_data[1], y_pred=y_pred, target_names=classes_list))
y_pred = cv.predict([normalize_text(it, nlp) for it in test_data[0]])
print(classification_report(y_true=test_data[1], y_pred=y_pred, target_names=classes_list))
Assistant
This code is for a text classification task using the TF-IDF (Term Frequency-Inverse Document Frequency) vectorization method combined with logistic regression (LogReg) as the classifier. It's specifically designed for the Russian language and makes use of the sib200 dataset, which contains labeled text data. Here’s a brief overview of what each part of the code does:
Imports and Setup:
Libraries like numpy, spacy, and datasets are imported.
spacy is used to download a Russian language model, which will help in text normalization (lemmatization and filtering punctuation).
Loading Data:
A function load_sib200_ru() loads the training, validation, and test splits of the sib200 dataset.
It checks for consistency in categories between training, validation, and test datasets to ensure that there are no unknown categories in validation and test splits that are absent from the training data.
The category labels are converted to numerical indices for model training.
Normalization of Text:
The normalize_text() function processes the text using spacy. It lemmatizes the text and converts it to lowercase while replacing numeric tokens with the placeholder <NUM>.
Punctuation is filtered out. This function will be used to preprocess the text data before feeding it into the model.
TF-IDF Vectorization and Model Pipeline:
A pipeline is created that includes TfidfVectorizer for converting text data into TF-IDF feature vectors, and LogisticRegression as the classifier.
A maximum document frequency is calculated to set a threshold (20% of documents) to ignore very common words, which helps in reducing noise in the dataset.
Hyperparameter Tuning:
GridSearchCV is used to find the best hyperparameters for vectorization (like n-gram range) and logistic regression (like regularization strength and penalty type).
It performs 5-fold cross-validation and uses the F1 score as the evaluation metric.
Training the Model:
The pipeline is fitted on the normalized training data.
:
User
What are the differences between code I showed you earlier comparing with:
from typing import List, Tuple
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
import spacy
from datasets import load_dataset
!pip install -U spacy
!python -m spacy download ru_core_news_sm # pre-trained lang model
def load_sib200_ru() -> Tuple[Tuple[List[str], List[int]], Tuple[List[str], List[int]], Tuple[List[str], List[int]], List[str]]:
'''
loads sib200_ru dataset
Returns three tuples (for training, validation and testing) and a list of all categories
'''
code
# Loading data: training set of text and corresponding categories from the dataset
trainset = load_dataset('Davlan/sib200', 'rus_Cyrl', split='train')
X_train = trainset['text']
y_train = trainset['category']
# Loading data: validation set of text and corresponding categories from the dataset
valset = load_dataset('Davlan/sib200', 'rus_Cyrl', split='validation')
X_val = valset['text']
y_val = valset['category']
# Loading data: test set of text and corresponding categories from the dataset
testset = load_dataset('Davlan/sib200', 'rus_Cyrl', split='test')
X_test = testset['text']
y_test = testset['category']
# Checks: if categs from val ant test are in train
categories = set(y_train)
unknown_categories = set(y_val) - categories
if len(unknown_categories) > 0:
raise RuntimeError(f'The categories {unknown_categories} are represented in the validation set, but they are not represented in the training set.')
unknown_categories = set(y_test) - categories
if len(unknown_categories) > 0:
raise RuntimeError(f'The categories {unknown_categories} are represented in the test set, but they are not represented in the training set.')
# categ -> idxs ("sport", "politics", "economy" -> 0, 1, 2)
categories = sorted(list(categories))
y_train = [categories.index(it) for it in y_train]
y_val = [categories.index(it) for it in y_val]
y_test = [categories.index(it) for it in y_test]
return (X_train, y_train), (X_val, y_val), (X_test, y_test), categories
Assistant
The second code snippet you provided is similar to the first one in that both are focused on text classification using TF-IDF and logistic regression, but there are several notable differences. Here’s a breakdown of the key differences:
1. Stop Words Removal:
First Code: The text normalization function does not remove stop words.
Second Code: The normalize_text function includes a filter to remove stop words (not token.is_stop), which can potentially improve the model by not including common but less meaningful words in the features.
2. Docstring Comments:
First Code: The comments are concise and more general, mainly describing the function names and purposes.
Second Code: It includes more detailed docstrings, explaining exactly what each function does and what it returns, improving code readability and understanding.
3. Model Training Iterations:
First Code: The logistic regression model is set to run for a maximum of 100 iterations (max_iter=100).
Second Code: This value is increased to 1000 iterations (max_iter=1000), which may help in converging the model better, especially on larger datasets.
4. Grid Search Parameters:
First Code: The regularization parameter C values provided are [1e-1, 1, 10, 100, 1000].
Second Code: The range has been expanded to include 0.01 alongside those values, allowing for finer tuning of the regularization strength.
Second Code: The sublinear_tf parameter is introduced in the TfidfVectorizer, allowing the option to use sublinear term frequency scaling, which can help in certain contexts by reducing the impact of larger term frequencies.
5. Detailed Comments and Explanations:
Second Code: It includes more comments throughout, explaining each step in detail, such as the purpose of the classifier and hyperparameter optimization. This makes the second version more informative and easier to follow, especially for those who might be less familiar with the concepts being applied.
6. Similar Functional Blocks:
Overall, the basic structure and flow of both codes are similar, such as loading datasets, normalizing text, setting up pipelines, performing hyperparameter tuning, and evaluating the model. The core functionality remains consistent between the two.
Assistant
It seems like your message was cut off or didn't come through. If you have any questions or if there's something specific you'd like to discuss or ask about the code or any other topic, please feel free to let me know!
User
Explain this code (now it uses few-shot prompting):
import random
from typing import Dict, List, Union
from datasets import load_dataset
from fuzzywuzzy import fuzz, process
from sklearn.metrics import classification_report
from tqdm.notebook import tqdm
from transformers import pipeline
def prepare_message_for_llm(text: Union[str, List[str]], categories: Dict[str, str]) -> Dict[str, Union[List[Dict[str, str]], List[List[Dict[str, str]]]]]:
if len(categories) < 2:
raise RuntimeError(f'The category list is too small! Expected 2 or more categories, got {len(categories)} ones.')
categories_ = sorted(list(categories.keys()))
categories_as_string = ', '.join(categories_[:-1]) + ' и ' + categories_[-1]
if isinstance(text, str):
prompt = f'Прочтите, пожалуйста, следующий текст и определите, какая тема из известного '
f'списка тем наиболее представлена в следующем тексте. '
f'В качестве ответа напишите только название темы из списка, больше ничего.\n'
f'Список тем: {categories_as_string}.\n'
for cur in categories_:
prompt += f'Текст: {" ".join(categories[cur].split())}\nВаш ответ: {cur}\n'
prompt += f'Текст: {" ".join(text.split())}\nВаш ответ: '
messages = [
{
'role': 'system',
'content': 'Вы - полезный помощник, умеющий читать тексты на русском языке, глубоко понимать их и анализировать.'
},
{
'role': 'user',
'content': prompt
}
]
else:
messages = []
for it in text:
prompt = f'Прочтите, пожалуйста, следующий текст и определите, какая тема из известного '
f'списка тем наиболее представлена в следующем тексте. '
f'В качестве ответа напишите только название темы из списка, больше ничего.\n'
f'Список тем: {categories_as_string}.\n'
for cur in categories_:
prompt += f'Текст: {" ".join(categories[cur].split())}\nВаш ответ: {cur}\n'
prompt += f'Текст: {" ".join(text.split())}\nВаш ответ: '
messages.append([
{
'role': 'system',
'content': 'Вы - полезный помощник, умеющий читать тексты на русском языке, глубоко понимать их и анализировать.'
},
{
'role': 'user',
'content': prompt
}
])
return {'message_for_llm': messages}
This code is designed for a classification task that employs few-shot prompting techniques with a language model (LLM). The primary goal is to classify text samples from the sib200 dataset based on predefined categories. Here’s a breakdown of what each part of the code does:
1. Library Imports:
Several libraries are imported, including:
datasets: For loading datasets.
transformers: For working with language models.
fuzzywuzzy and python-Levenshtein: For string matching using fuzzy logic.
Others for utilities such as random, typing, and progress tracking (tqdm).
2. Helper Function:
prepare_message_for_llm(text, categories):
This function prepares a prompt for the language model.
It takes in a piece of text (or a list of texts) and a dictionary of categories.
If there are fewer than two categories, it raises an error.
It constructs a prompt string that asks the model to classify a given text based on the provided categories.
For each category, a sample text is included in the prompt to provide context.
The function returns a structured message for the language model.
3. Model Pipeline Initialization:
llm_pipeline: This initializes a pipeline using the specified model (Qwen/Qwen2-7B-Instruct). The model performs the classification task.
4. Data Loading:
The dataset (sib200 in Cyrillic Russian) is loaded into training, validation, and test sets.
The categories for classification are deduced from the union of the categories in all three splits.
5. Example Text Selection:
For each category, a random text from the training set is selected to provide examples that the model can reference during classification.
These examples help the model understand the characteristics of each category (few-shot learning).
6. Message Preparation for Validation and Test Sets:
Two separate datasets are prepared for the validation and test sets using the prepare_message_for_llm function. This modifies each data instance into the prompt format expected by the language model.
User
And what are the differences comparing with this code:
import random
from typing import Dict, List, Union
from datasets import load_dataset
from fuzzywuzzy import fuzz, process
from sklearn.metrics import classification_report
from tqdm.notebook import tqdm
from transformers import pipeline
def prepare_message_for_llm(text: Union[str, List[str]], categories: Dict[str, str]) -> Dict[str, Union[List[Dict[str, str]], List[List[Dict[str, str]]]]]:
if len(categories) < 2:
raise RuntimeError(f'The category list is too small! Expected 2 or more categories, got {len(categories)} ones.')
categories_ = sorted(list(categories.keys()))
categories_as_string = ', '.join(categories_[:-1]) + ' и ' + categories_[-1]
if isinstance(text, str):
prompt = f'Прочтите, пожалуйста, следующий текст и определите, какая тема из известного '
f'списка тем наиболее представлена в следующем тексте. '
f'В качестве ответа напишите только название темы из списка, больше ничего.\n'
f'Список тем: {categories_as_string}.\n'
for cur in categories_:
prompt += f'Текст: {" ".join(categories[cur].split())}\nВаш ответ: {cur}\n'
prompt += f'Текст: {" ".join(text.split())}\nВаш ответ: '
messages = [
{
'role': 'system',
'content': 'Вы - полезный помощник, умеющий читать тексты на русском языке, глубоко понимать их и анализировать.'
},
{
'role': 'user',
'content': prompt
}
]
else:
messages = []
for it in text:
prompt = f'Прочтите, пожалуйста, следующий текст и определите, какая тема из известного '
f'списка тем наиболее представлена в следующем тексте. '
f'В качестве ответа напишите только название темы из списка, больше ничего.\n'
f'Список тем: {categories_as_string}.\n'
for cur in categories_:
prompt += f'Текст: {" ".join(categories[cur].split())}\nВаш ответ: {cur}\n'
prompt += f'Текст: {" ".join(text.split())}\nВаш ответ: '
messages.append([
{
'role': 'system',
'content': 'Вы - полезный помощник, умеющий читать тексты на русском языке, глубоко понимать их и анализировать.'
},
{
'role': 'user',
'content': prompt
}
])
return {'message_for_llm': messages}
New
llm_pipeline = pipeline(
model='Qwen/Qwen2-7B-Instruct',
device_map='auto',
torch_dtype='auto',
temperature=0.7, # decrease random
top_k=50 # use from more probability variants
)
The second code snippet you provided has similarities to the first code, as they both focus on performing classification tasks using few-shot prompting with a language model on the sib200 dataset. However, there are several important differences and enhancements in the second version. Here’s a breakdown of the key differences:
1. Pipeline Configuration:
First Code: The llm_pipeline object is created without specific parameters for sampling methods.
Second Code: The llm_pipeline now includes parameters for temperature (set to 0.7) and top_k (set to 50).
Temperature: A lower temperature tends to produce more deterministic outputs, while a higher value allows for more randomness in predictions.
Top_k: This parameter limits the model's choices to the top k most probable token options, encouraging diversity in potential outputs.
2. Commenting and Documentation:
First Code: The comments are more concise, with minimal explanation included.
Second Code: The comments are updated to explain changes, like "New" next to the changes to indicate modifications. The comments also clarify the purpose of specific parameters, making it easier to understand the intention behind those settings.
3. Predictive Phase:
First Code: Prediction for the validation dataset simply calls llm_pipeline without specifying temperature and top_k.
Second Code: The prediction for the validation dataset now includes these parameters in the pipeline call, making the predictions potentially vary more based on the sampling settings.
4. Fuzzy Matching for Normalization:
Both codes employ fuzzy matching, but the second code retains this functionality without change. However, any updates in how the outputs of predictions are handled, particularly with respect to normalization through fuzzy matching, are more clearly delineated.
5. Introduction of AutoML:
Second Code: It includes a comment at the end mentioning "auto ml: optuna (lib)," suggesting that there may be an intention or plan to integrate the Optuna library for hyperparameter optimization in future iterations of the code.
First Code: There is no mention of integrating any type of automation for model tuning or optimization.
from datasets import load_dataset, Dataset
import evaluate
import numpy as np
from sklearn.metrics import classification_report
import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification
from transformers import DataCollatorWithPadding
from transformers import TrainingArguments, Trainer
from transformers import pipeline
labeled_train_set = tokenized_train_set.add_column(
'label',
[label2id[val] for val in tokenized_train_set['category']]
)
labeled_validation_set = tokenized_validation_set.add_column(
'label',
[label2id[val] for val in tokenized_validation_set['category']]
)
print(labeled_train_set)
classifier = AutoModelForSequenceClassification.from_pretrained(
MODEL_NAME,
num_labels=n_categories, id2label=id2label, label2id=label2id
).cuda()
for param in classifier.parameters(): param.data = param.data.contiguous()
Assistant
This code snippet demonstrates how to perform text classification using a BERT-based model (specifically DeepPavlov/rubert-base-cased) on the sib200 dataset. Instead of employing few-shot prompting with an LLM, this snippet takes a more traditional machine learning approach using a pre-trained transformer model fine-tuned on the task of sequence classification. Here’s a breakdown of the key components of the code:
1. Imports and Initial Setup:
Several libraries are imported:
datasets: To load datasets.
evaluate: For evaluating model performance.
transformers: To access pre-trained models and tokenizers.
sklearn.metrics: For classification metrics.
torch: For handling the model in PyTorch environment.
2. Loading the Dataset:
The sib200 dataset is loaded into separate training, validation, and test sets, specifying the Russian Cyrillic language.
3. Tokenization:
The tokenizer is instantiated from the specified BERT model. The text data from the training and validation sets is tokenized with truncation to ensure that the input fits the model's requirements.
The map function applies the tokenization across batches in a memory-efficient manner.
4. Metrics Definition:
An F1 score metric is loaded using evaluate.load('f1').
A function, compute_metrics(eval_pred), is defined to compute the F1 score based on the predictions and true labels after evaluating the model.
5. Data Preparation:
A data collator (DataCollatorWithPadding) is initialized to ensure that all batch inputs are of the same shape by padding them as needed.
The code constructs mappings from category names to IDs (label2id) and vice versa (id2label) for labels in the dataset.
Labels are added to the tokenized datasets to create the labeled_train_set and labeled_validation_set.
6. Model Initialization:
The classifier model is loaded using AutoModelForSequenceClassification, which is set up to classify texts into categories based on the number of categories present in the dataset.
Assistant
It seems like your message might have been accidentally sent without any content. If you have questions, need clarification, or would like further information on a specific topic, please feel free to let me know! I'm here to help.
from datasets import load_dataset, Dataset
import evaluate
import numpy as np
from sklearn.metrics import classification_report
import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification
from transformers import DataCollatorWithPadding
from transformers import TrainingArguments, Trainer
from transformers import pipeline
NEW
from random import sample
NEW
increase diversity
def random_swap(text):
'''
Swaps two random words
'''
# at least 2 words to swap
words = text.split()
if len(words) > 1:
idx1, idx2 = sample(range(len(words)), 2)
words[idx1], words[idx2] = words[idx2], words[idx1]
return ' '.join(words)
NEW
decrease 'noise'
def random_delete(text, p=0.2):
'''
Randomly deletes words
'''
words = text.split()
if len(words) < 2:
return text
# filtering
remaining = list(filter(lambda _: np.random.rand() > p, words))
def augment_text(dataset, n_samples=1, swap_prob=0.5, delete_prob=0.2):
'''
Generates augmented versions of the text
'''
augmented_texts = []
for text in dataset['text']:
for _ in range(n_samples):
if np.random.rand() < swap_prob:
augmented_texts.append(random_swap(text))
else:
augmented_texts.append(random_delete(text, p=delete_prob))
return augmented_texts
This code snippet demonstrates the use of data augmentation techniques in conjunction with a BERT-based model for text classification. Specifically, it employs two augmentation techniques—random swapping and random deletion—to generate additional training samples from the existing dataset. Here are the main differences and enhancements compared to the previous BERT-based model you provided:
Key Differences and Enhancements:
Data Augmentation:
Random Word Swap: A function (random_swap) is implemented to randomly swap two words in a text, which introduces variability and can help the model become more robust to slight changes in phrasing.
Random Word Deletion: The random_delete function removes words from the text with a specified probability, which helps reduce "noise" in the data and can make the classification task easier for the model.
Augmentation Function: The augment_text function generates augmented versions of the text based on the specified probabilities for swapping and deleting words. This function creates multiple augmented samples for each original text, thereby increasing the size of the training dataset.
Combining Original and Augmented Data:
The original training texts and their corresponding labels are combined with the augmented texts and labels. This yields a new dataset that is larger and more diverse, potentially leading to improved model performance.
A new dataset (augmented_train_set) is created from the combined texts and labels using Dataset.from_dict().
Tokenization of Augmented Data:
The tokenizer is applied to the new augmented dataset in the same way as it was with the original training data. This ensures that all text data is properly processed for BERT.
Increased Training Variety:
By using augmented texts, the model is exposed to variations of the input during training. This can improve generalization to unseen data and help prevent overfitting, given that the model sees more diverse examples.
No Changes to the Model Training Structure:
The remainder of the code, including model initialization, training configuration, and evaluation, remains largely unchanged from the previous BERT implementation. The same training arguments, trainer, and evaluation metrics are utilized.
Summary of Augmentation Benefits:
Not yet included in a published release.
Evaluation
The best hyperparameters and the best F1-macro score are printed.
The size of the vocabulary (number of unique terms) used in the best model is displayed.
Predictions are made on both validation and test datasets, and the classification report (which includes precision, recall, and the F1-score for each category) is printed for evaluation.
Overall, the code follows a typical machine learning pipeline for text classification, covering data loading, preprocessing, model training, hyperparameter tuning, and evaluation.
New: removing stop words
def normalize_text(s: str, nlp_pipeline: spacy.Language) -> str:
'''
normalizes text using nlp_pipeline
'''
code
# Process each token in the document, except punct and w-stops
doc = nlp_pipeline(s)
lemmas = [
('<NUM>' if token.like_num else token.lemma_.lower())
for token in filter(lambda token: not token.is_punct and not token.is_stop, doc)
]
# if empty
if len(lemmas) == 0:
return ''
return ' '.join(lemmas)
class_probability = 1.0 / len(classes_list)
max_df = 1.0 - 0.2 * class_probability
print(f'Maximal document frequency of term is {max_df}.')
Classifier:
#1) Text vectorization using TfidfVectorizer, which converts text data into a numeric format taking into account TF-IDF
#2) Train logistic regression as a classification model
classifier = Pipeline(steps=[
('vectorizer', TfidfVectorizer(token_pattern='\w+', max_df=max_df, min_df=1)),
('cls', LogisticRegression(solver='saga', max_iter=1000, random_state=42)) # New: Increased number of iterations (100 -> 1000)
])
cv.fit([normalize_text(it, nlp) for it in train_data[0]], train_data[1])
print('Best parameters:')
print(cv.best_params_)
print('Best F1-macro:')
print(cv.best_score_)
print(f'Vocabulary size is {len(cv.best_estimator_.named_steps["vectorizer"].vocabulary_)}.')
y_pred = cv.predict([normalize_text(it, nlp) for it in val_data[0]])
print(classification_report(y_true=val_data[1], y_pred=y_pred, target_names=classes_list))
y_pred = cv.predict([normalize_text(it, nlp) for it in test_data[0]])
print(classification_report(y_true=test_data[1], y_pred=y_pred, target_names=classes_list))
Conclusion
These differences indicate that the second code snippet is likely an enhanced version of the first, introducing additional preprocessing (removal of stop words), increased flexibility in hyperparameter tuning, and improved clarity through comments and documentation. These improvements typically contribute to better model performance and maintainability.
The model is called to predict categories for the validation set messages. The predictions are generated using the language model specified in the pipeline.
The true category labels (y_true) are also extracted for comparison.
8. Evaluation:
A classification report is generated initially, comparing the predictions against the true labels. This report provides metrics such as precision, recall, and F1-score.
There’s also a normalization step where fuzzy matching is performed to improve the accuracy of the predictions, comparing predicted categories against the list of known categories.
9. Test Set Predictions:
Similar to the validation set, predictions are made and evaluated for the test set using the same methodology as for the validation set.
Summary
The overall process is aimed at using a few-shot learning approach with an LLM to classify texts based on learned examples from the training data. The targeting of this type of approach is necessary when there is a limited amount of labeled data available for training compared to traditional supervised learning methods. The use of a language model functions as a flexible and powerful way to derive category information from texts without the need to explicitly retrain a model, thus saving time and computational resources.
The variable names and overall structure of the code are consistent, which suggests that if there are specific feature changes in the second code, they were likely implemented in a uniform manner.
Summary
In summary, the second code introduces enhanced parameters for sampling in the llm_pipeline, which can affect the randomness and variability of predictions. It is better documented, making it easier to understand the rationale for changes. Additionally, it hints at future improvements with the inclusion of an AutoML component (Optuna) to improve model performance through automated hyperparameter tuning. Overall, the second version builds on the first by providing a flexible and configurable way to interact with the language model while addressing potential limitations in output variability.
The model is moved to the GPU (if available) using .cuda().
7. Training Configuration:
The training arguments are defined through TrainingArguments, which include settings like learning rate, batch size, number of epochs, and evaluation strategy.
A Trainer object is created, which combines the model and the training arguments, along with the datasets.
8. Model Training:
The model is trained through the trainer.train(), which runs the fine-tuning process on the labeled training set using the specified evaluation criterion.
9. Prediction and Evaluation:
After training, a classification pipeline is created using the trained model and tokenizer which allows for easy inference on texts.
Predictions are made on both the validation and test datasets by passing the texts and extracting the predicted labels.
Finally, classification reports are generated to evaluate the model's performance on both sets, showing metrics like precision, recall, and F1-score.
Key Differences Compared to Previous Code (Few-shot Prompting):
Approach:
This code uses a supervised learning approach with a pre-trained transformer model fine-tuned on labeled data, as opposed to utilizing a generative model with few-shot prompting techniques.
Model Architecture:
The BERT model architecture is fundamentally different from the prompting approach used in the previous codes. Here, a sequence classification model is explicitly fine-tuned rather than asking a language model to interpret and classify the text based on a few examples.
Evaluation Method:
Evaluation in this code is based on performance metrics computed directly from predicted labels against true labels, contrasting with possible variability and fuzziness in classifications made by a generative model.
Complexity and Control:
This code involves more control over model training, hyperparameters, and evaluation strategies compared to the more black-box nature of calling an LLM with prompts.
Token Preparation:
The process of converting text to tokens, preparing for training, and handling padded sequences is more detailed and structured in the BERT code.
Direct Usage of GPU:
The code explicitly moves the model to the GPU for training, which can improve performance significantly for larger datasets or models. In the previous codes, the underlying framework’s automatic device placement might be less explicit.
Conclusion
Overall, the BERT-based code represents a more conventional approach to text classification, relying on the fine-tuning of a pre-trained model alongside a structured supervised learning pipeline, while the previous examples employed few-shot learning with a generative model. Both approaches have their own advantages and disadvantages, depending on the specific requirements of the task at hand and the availability of labeled data.
labeled_train_set = tokenized_train_set.add_column(
'label',
[label2id[val] for val in tokenized_train_set['category']]
)
labeled_validation_set = tokenized_validation_set.add_column(
'label',
[label2id[val] for val in tokenized_validation_set['category']]
)
Robustness: Training on augmented data can help make the model more robust against variations in the input text that it may encounter during inference.
Generalization: By expanding the training dataset with modifications, the model can generalize better to new or unseen examples.
Balance: The augmentation techniques provide the potential to balance datasets if certain categories are underrepresented.
Conclusion:
This code expands on the previous implementation by incorporating data augmentation techniques, enhancing the training dataset's diversity and potentially improving the performance of the BERT model in text classification tasks. The overall structure follows the same principles of using a pre-trained transformer model, but the new augmentation features allow for a more flexible and resilient approach to training.