Сократи, пожалуйста, комментарий: Define a function to compute performance metrics…
- User
Сократи, пожалуйста, комментарий:
Define a function to compute performance metrics during evaluation
It transforms logits to predicted labels and calculates the F1 score, which is
the harmonic mean of precision and recall providing a balance of both
def compute_metrics(eval_pred): predictions, labels = eval_pred predictions = np.argmax(predictions, axis=1) return cls_metric.compute(predictions=predictions, references=labels, average='macro')
- Assistant
Convert logits to labels and calculate F1 score for performance evaluation
def compute_metrics(eval_pred): predictions, labels = eval_pred predictions = np.argmax(predictions, axis=1) return cls_metric.compute(predictions=predictions, references=labels, average='macro')
- User
Instantiate a data collator that dynamically pads batch elements to the same length
data_collator = DataCollatorWithPadding(tokenizer=tokenizer)
- Assistant
Create a data collator to dynamically pad batch elements to the same length
data_collator = DataCollatorWithPadding(tokenizer=tokenizer)
- User
Gather and sort the possible categories in the dataset for classification labels
This step is essential to map string labels to numerical IDs needed by the model
list_of_categories = sorted(list( set(train_set['category']) | set(validation_set['category']) | set(test_set['category']) )) indices_of_categories = list(range(len(list_of_categories))) n_categories = len(list_of_categories) print(f'Categories for classification are: {list_of_categories}') # Log the categories
Create mappings between labels and numerical IDs used by the classifier
id2label = dict(zip(indices_of_categories, list_of_categories)) label2id = dict(zip(list_of_categories, indices_of_categories))
- Assistant
Sort and map dataset categories to numerical IDs for model classification
list_of_categories = sorted( set(train_set['category']) | set(validation_set['category']) | set(test_set['category']) ) indices_of_categories = range(len(list_of_categories)) n_categories = len(list_of_categories) print(f'Categories for classification are: {list_of_categories}') id2label = dict(zip(indices_of_categories, list_of_categories)) label2id = dict(zip(list_of_categories, indices_of_categories))
- User
Add a numeric label column to train and validation datasets using the created mappings
These labels will be used during the training process
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']] )
- Assistant
Add numeric label column to datasets using mappings for training
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']] )
- User
Load the pre-trained model for sequence classification and configure it for our specific number of categories
classifier = AutoModelForSequenceClassification.from_pretrained( MODEL_NAME, num_labels=n_categories, id2label=id2label, label2id=label2id ) for param in classifier.parameters(): param.data = param.data.contiguous()
- Assistant
Load pre-trained sequence classification model and configure for category count
classifier = AutoModelForSequenceClassification.from_pretrained( MODEL_NAME, num_labels=n_categories, id2label=id2label, label2id=label2id ) for param in classifier.parameters(): param.data = param.data.contiguous()
- User
Там где есть '!' его нужно оставить
Define the training arguments which control the training process's behavior
training_args = TrainingArguments( output_dir='rubert_sib200', # Directory to save the model's output learning_rate=3e-5, # ! Learning rate controls how much to adjust the model's weights during training; experimentation can identify optimal values per_device_train_batch_size=32, # ! Number of training examples processed together in a single update; larger batches may use more effective parallelism per_device_eval_batch_size=32, # Similar batch size for evaluation num_train_epochs=25, # ! Number of times the model will be trained on the entire training set; more epochs can improve or overfit the model weight_decay=0.01, # ! Regularization parameter to prevent overfitting by penalizing large weights eval_strategy='epoch', # Evaluate the model performance at the end of each epoch save_strategy='epoch', # Save the model at the end of each epoch for potential restoration load_best_model_at_end=True # Restore the best performing model at the end of training for final testing )
- Assistant
Set training arguments to control training process behavior
training_args = TrainingArguments( output_dir='rubert_sib200', # Directory for model output learning_rate=3e-5, # ! Learning rate; experimentation can find optimal values per_device_train_batch_size=32, # ! Training examples processed per update; larger batches may improve parallelism per_device_eval_batch_size=32, # Similar batch size for evaluation num_train_epochs=25, # ! Number of times to train on entire set; more epochs can improve or overfit weight_decay=0.01, # ! Regularization to prevent overfitting by penalizing large weights eval_strategy='epoch', # Evaluate performance at end of each epoch save_strategy='epoch', # Save model at end of each epoch load_best_model_at_end=True # Restore best model at training end for testing )
- User
Сделай все комментарии меньше
- Assistant
Configure training arguments
training_args = TrainingArguments( output_dir='rubert_sib200', # Model output directory learning_rate=3e-5, # ! Learning rate per_device_train_batch_size=32, # ! Train batch size per_device_eval_batch_size=32, # Eval batch size num_train_epochs=25, # ! Number of training epochs weight_decay=0.01, # ! Weight regularization eval_strategy='epoch', # Eval after each epoch save_strategy='epoch', # Save model each epoch load_best_model_at_end=True # Restore best model )
- User
Initialize the Trainer which orchestrates the training process using specified datasets, model, and settings
trainer = Trainer( model=classifier, args=training_args, train_dataset=labeled_train_set, eval_dataset=labeled_validation_set, tokenizer=tokenizer, data_collator=data_collator, compute_metrics=compute_metrics, )
- Assistant
Initialize the Trainer to manage training
trainer = Trainer( model=classifier, args=training_args, train_dataset=labeled_train_set, eval_dataset=labeled_validation_set, tokenizer=tokenizer, data_collator=data_collator, compute_metrics=compute_metrics, )
- User
Create a text classification pipeline for predicting categories on new text using the trained model
classifiсation_pipeline = pipeline('text-classification', model=classifier, tokenizer=tokenizer, device=-1)
- Assistant
Create a text classification pipeline for predictions
classification_pipeline = pipeline('text-classification', model=classifier, tokenizer=tokenizer, device=-1)
- User
Predict the categories for the validation set texts and generate a classification report
The report includes precision, recall, F1-score, and support for each class
y_pred = list(map(lambda x: x['label'], classifiсation_pipeline(validation_set['text']))) y_true = validation_set['category'] print(classification_report(y_true=y_true, y_pred=y_pred))
- Assistant
Predict categories and generate classification report
y_pred = [x['label'] for x in classification_pipeline(validation_set['text'])] y_true = validation_set['category'] print(classification_report(y_true=y_true, y_pred=y_pred))