IsmatS commited on
Commit
6ca12ef
1 Parent(s): 1a6d71a

Upload folder using huggingface_hub

Browse files
Files changed (2) hide show
  1. xlm_roberta_large.ipynb +0 -0
  2. xlm_roberta_large.py +263 -0
xlm_roberta_large.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
xlm_roberta_large.py ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """xlm-roberta-large.ipynb
3
+
4
+ Automatically generated by Colab.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/18YiC93vkjig-o550pHFJSB3bCQ7rhb4M
8
+ """
9
+
10
+ !pip install transformers datasets seqeval huggingface_hub
11
+
12
+ # Standard library imports
13
+ import os # Provides functions for interacting with the operating system
14
+ import warnings # Used to handle or suppress warnings
15
+ import numpy as np # Essential for numerical operations and array manipulation
16
+ import torch # PyTorch library for tensor computations and model handling
17
+ import ast # Used for safe evaluation of strings to Python objects (e.g., parsing tokens)
18
+
19
+ # Hugging Face and Transformers imports
20
+ from datasets import load_dataset # Loads datasets for model training and evaluation
21
+ from transformers import (
22
+ AutoTokenizer, # Initializes a tokenizer from a pre-trained model
23
+ DataCollatorForTokenClassification, # Handles padding and formatting of token classification data
24
+ TrainingArguments, # Defines training parameters like batch size and learning rate
25
+ Trainer, # High-level API for managing training and evaluation
26
+ AutoModelForTokenClassification, # Loads a pre-trained model for token classification tasks
27
+ get_linear_schedule_with_warmup, # Learning rate scheduler for gradual warm-up and linear decay
28
+ EarlyStoppingCallback # Callback to stop training if validation performance plateaus
29
+ )
30
+
31
+ # Hugging Face Hub
32
+ from huggingface_hub import login # Allows logging in to Hugging Face Hub to upload models
33
+
34
+ # seqeval metrics for NER evaluation
35
+ from seqeval.metrics import precision_score, recall_score, f1_score, classification_report
36
+ # Provides precision, recall, F1-score, and classification report for evaluating NER model performance
37
+
38
+ # Log in to Hugging Face Hub
39
+ login(token="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")
40
+
41
+ # Disable WandB (Weights & Biases) logging to avoid unwanted log outputs during training
42
+ os.environ["WANDB_DISABLED"] = "true"
43
+
44
+ # Suppress warning messages to keep output clean, especially during training and evaluation
45
+ warnings.filterwarnings("ignore")
46
+
47
+ # Load the Azerbaijani NER dataset from Hugging Face
48
+ dataset = load_dataset("LocalDoc/azerbaijani-ner-dataset")
49
+ print(dataset) # Display dataset structure (e.g., train/validation splits)
50
+
51
+ # Preprocessing function to format tokens and NER tags correctly
52
+ def preprocess_example(example):
53
+ try:
54
+ # Convert string of tokens to a list and parse NER tags to integers
55
+ example["tokens"] = ast.literal_eval(example["tokens"])
56
+ example["ner_tags"] = list(map(int, ast.literal_eval(example["ner_tags"])))
57
+ except (ValueError, SyntaxError) as e:
58
+ # Skip and log malformed examples, ensuring error resilience
59
+ print(f"Skipping malformed example: {example['index']} due to error: {e}")
60
+ example["tokens"] = []
61
+ example["ner_tags"] = []
62
+ return example
63
+
64
+ # Apply preprocessing to each dataset entry, ensuring consistent formatting
65
+ dataset = dataset.map(preprocess_example)
66
+
67
+ # Initialize the tokenizer for multilingual NER using xlm-roberta-large
68
+ tokenizer = AutoTokenizer.from_pretrained("xlm-roberta-large")
69
+
70
+ # Function to tokenize input and align labels with tokenized words
71
+ def tokenize_and_align_labels(example):
72
+ # Tokenize the sentence while preserving word boundaries for correct NER tag alignment
73
+ tokenized_inputs = tokenizer(
74
+ example["tokens"], # List of words (tokens) in the sentence
75
+ truncation=True, # Truncate sentences longer than max_length
76
+ is_split_into_words=True, # Specify that input is a list of words
77
+ padding="max_length", # Pad to maximum sequence length
78
+ max_length=128, # Set the maximum sequence length to 128 tokens
79
+ )
80
+
81
+ labels = [] # List to store aligned NER labels
82
+ word_ids = tokenized_inputs.word_ids() # Get word IDs for each token
83
+ previous_word_idx = None # Initialize previous word index for tracking
84
+
85
+ # Loop through word indices to align NER tags with subword tokens
86
+ for word_idx in word_ids:
87
+ if word_idx is None:
88
+ labels.append(-100) # Set padding token labels to -100 (ignored in loss)
89
+ elif word_idx != previous_word_idx:
90
+ # Assign the label from example's NER tags if word index matches
91
+ labels.append(example["ner_tags"][word_idx] if word_idx < len(example["ner_tags"]) else -100)
92
+ else:
93
+ labels.append(-100) # Label subword tokens with -100 to avoid redundant labels
94
+ previous_word_idx = word_idx # Update previous word index
95
+
96
+ tokenized_inputs["labels"] = labels # Add labels to tokenized inputs
97
+ return tokenized_inputs
98
+
99
+ # Apply tokenization and label alignment function to the dataset
100
+ tokenized_datasets = dataset.map(tokenize_and_align_labels, batched=False)
101
+
102
+ # Create a 90-10 split of the dataset for training and validation
103
+ tokenized_datasets = tokenized_datasets["train"].train_test_split(test_size=0.1)
104
+ print(tokenized_datasets) # Output structure of split datasets
105
+
106
+ # Define a list of entity labels for NER tagging with B- (beginning) and I- (inside) markers
107
+ label_list = [
108
+ "O", # Outside of a named entity
109
+ "B-PERSON", "I-PERSON", # Person name (e.g., "John" in "John Doe")
110
+ "B-LOCATION", "I-LOCATION", # Geographical location (e.g., "Paris")
111
+ "B-ORGANISATION", "I-ORGANISATION", # Organization name (e.g., "UNICEF")
112
+ "B-DATE", "I-DATE", # Date entity (e.g., "2024-11-05")
113
+ "B-TIME", "I-TIME", # Time (e.g., "12:00 PM")
114
+ "B-MONEY", "I-MONEY", # Monetary values (e.g., "$20")
115
+ "B-PERCENTAGE", "I-PERCENTAGE", # Percentage values (e.g., "20%")
116
+ "B-FACILITY", "I-FACILITY", # Physical facilities (e.g., "Airport")
117
+ "B-PRODUCT", "I-PRODUCT", # Product names (e.g., "iPhone")
118
+ "B-EVENT", "I-EVENT", # Named events (e.g., "Olympics")
119
+ "B-ART", "I-ART", # Works of art (e.g., "Mona Lisa")
120
+ "B-LAW", "I-LAW", # Laws and legal documents (e.g., "Article 50")
121
+ "B-LANGUAGE", "I-LANGUAGE", # Languages (e.g., "Azerbaijani")
122
+ "B-GPE", "I-GPE", # Geopolitical entities (e.g., "Europe")
123
+ "B-NORP", "I-NORP", # Nationalities, religious groups, political groups
124
+ "B-ORDINAL", "I-ORDINAL", # Ordinal indicators (e.g., "first", "second")
125
+ "B-CARDINAL", "I-CARDINAL", # Cardinal numbers (e.g., "three")
126
+ "B-DISEASE", "I-DISEASE", # Diseases (e.g., "COVID-19")
127
+ "B-CONTACT", "I-CONTACT", # Contact info (e.g., email or phone number)
128
+ "B-ADAGE", "I-ADAGE", # Common sayings or adages
129
+ "B-QUANTITY", "I-QUANTITY", # Quantities (e.g., "5 km")
130
+ "B-MISCELLANEOUS", "I-MISCELLANEOUS", # Miscellaneous entities not fitting other categories
131
+ "B-POSITION", "I-POSITION", # Job titles or positions (e.g., "CEO")
132
+ "B-PROJECT", "I-PROJECT" # Project names (e.g., "Project Apollo")
133
+ ]
134
+
135
+ # Initialize a data collator to handle padding and formatting for token classification
136
+ data_collator = DataCollatorForTokenClassification(tokenizer)
137
+
138
+ # Load a pre-trained model for token classification, adapted for NER tasks
139
+ model = AutoModelForTokenClassification.from_pretrained(
140
+ "xlm-roberta-large", # Base model (multilingual XLM-RoBERTa) for NER
141
+ num_labels=len(label_list) # Set the number of output labels to match NER categories
142
+ )
143
+
144
+ # Define a function to compute evaluation metrics for the model's predictions
145
+ def compute_metrics(p):
146
+ predictions, labels = p # Unpack predictions and true labels from the input
147
+
148
+ # Convert logits to predicted label indices by taking the argmax along the last axis
149
+ predictions = np.argmax(predictions, axis=2)
150
+
151
+ # Filter out special padding labels (-100) and convert indices to label names
152
+ true_labels = [[label_list[l] for l in label if l != -100] for label in labels]
153
+ true_predictions = [
154
+ [label_list[p] for (p, l) in zip(prediction, label) if l != -100]
155
+ for prediction, label in zip(predictions, labels)
156
+ ]
157
+
158
+ # Print a detailed classification report for each label category
159
+ print(classification_report(true_labels, true_predictions))
160
+
161
+ # Calculate and return key evaluation metrics
162
+ return {
163
+ # Precision measures the accuracy of predicted positive instances
164
+ # Important in NER to ensure entity predictions are correct and reduce false positives.
165
+ "precision": precision_score(true_labels, true_predictions),
166
+
167
+ # Recall measures the model's ability to capture all relevant entities
168
+ # Essential in NER to ensure the model captures all entities, reducing false negatives.
169
+ "recall": recall_score(true_labels, true_predictions),
170
+
171
+ # F1-score is the harmonic mean of precision and recall, balancing both metrics
172
+ # Useful in NER for providing an overall performance measure, especially when precision and recall are both important.
173
+ "f1": f1_score(true_labels, true_predictions),
174
+ }
175
+
176
+ # Set up training arguments for model training, defining essential training configurations
177
+ training_args = TrainingArguments(
178
+ output_dir="./results", # Directory to save model checkpoints and final outputs
179
+ evaluation_strategy="epoch", # Evaluate model on the validation set at the end of each epoch
180
+ save_strategy="epoch", # Save model checkpoints at the end of each epoch
181
+ learning_rate=2e-5, # Set a low learning rate to ensure stable training for fine-tuning
182
+ per_device_train_batch_size=128, # Number of examples per batch during training, balancing speed and memory
183
+ per_device_eval_batch_size=128, # Number of examples per batch during evaluation
184
+ num_train_epochs=12, # Number of full training passes over the dataset
185
+ weight_decay=0.005, # Regularization term to prevent overfitting by penalizing large weights
186
+ fp16=True, # Use 16-bit floating point for faster and memory-efficient training
187
+ logging_dir='./logs', # Directory to store training logs
188
+ save_total_limit=2, # Keep only the 2 latest model checkpoints to save storage space
189
+ load_best_model_at_end=True, # Load the best model based on metrics at the end of training
190
+ metric_for_best_model="f1", # Use F1-score to determine the best model checkpoint
191
+ report_to="none" # Disable reporting to external services (useful in local runs)
192
+ )
193
+
194
+ # Initialize the Trainer class to manage the training loop with all necessary components
195
+ trainer = Trainer(
196
+ model=model, # The pre-trained model to be fine-tuned
197
+ args=training_args, # Training configuration parameters defined in TrainingArguments
198
+ train_dataset=tokenized_datasets["train"], # Tokenized training dataset
199
+ eval_dataset=tokenized_datasets["test"], # Tokenized validation dataset
200
+ tokenizer=tokenizer, # Tokenizer used for processing input text
201
+ data_collator=data_collator, # Data collator for padding and batching during training
202
+ compute_metrics=compute_metrics, # Function to calculate evaluation metrics like precision, recall, F1
203
+ callbacks=[EarlyStoppingCallback(early_stopping_patience=5)] # Stop training early if validation metrics don't improve for 2 epochs
204
+ )
205
+
206
+ # Begin the training process and capture the training metrics
207
+ training_metrics = trainer.train()
208
+
209
+ # Evaluate the model on the validation set after training
210
+ eval_results = trainer.evaluate()
211
+
212
+ # Print evaluation results, including precision, recall, and F1-score
213
+ print(eval_results)
214
+
215
+ # Define the directory where the trained model and tokenizer will be saved
216
+ save_directory = "./xlm-roberta-large"
217
+
218
+ # Save the trained model to the specified directory
219
+ model.save_pretrained(save_directory)
220
+
221
+ # Save the tokenizer to the same directory for compatibility with the model
222
+ tokenizer.save_pretrained(save_directory)
223
+
224
+ from transformers import pipeline
225
+
226
+ # Load tokenizer and model
227
+ tokenizer = AutoTokenizer.from_pretrained(save_directory)
228
+ model = AutoModelForTokenClassification.from_pretrained(save_directory)
229
+
230
+ # Initialize the NER pipeline
231
+ device = 0 if torch.cuda.is_available() else -1
232
+ nlp_ner = pipeline("ner", model=model, tokenizer=tokenizer, aggregation_strategy="simple", device=device)
233
+
234
+ label_mapping = {f"LABEL_{i}": label for i, label in enumerate(label_list) if label != "O"}
235
+
236
+ def evaluate_model(test_texts, true_labels):
237
+ predictions = []
238
+ for i, text in enumerate(test_texts):
239
+ pred_entities = nlp_ner(text)
240
+ pred_labels = [label_mapping.get(entity["entity_group"], "O") for entity in pred_entities if entity["entity_group"] in label_mapping]
241
+ if len(pred_labels) != len(true_labels[i]):
242
+ print(f"Warning: Inconsistent number of entities in sample {i+1}. Adjusting predicted entities.")
243
+ pred_labels = pred_labels[:len(true_labels[i])]
244
+ predictions.append(pred_labels)
245
+ if all(len(true) == len(pred) for true, pred in zip(true_labels, predictions)):
246
+ precision = precision_score(true_labels, predictions)
247
+ recall = recall_score(true_labels, predictions)
248
+ f1 = f1_score(true_labels, predictions)
249
+ print("Precision:", precision)
250
+ print("Recall:", recall)
251
+ print("F1-Score:", f1)
252
+ print(classification_report(true_labels, predictions))
253
+ else:
254
+ print("Error: Could not align all samples correctly for evaluation.")
255
+
256
+ test_texts = ["Shahla Khuduyeva və Pasha Sığorta şirkəti haqqında məlumat."]
257
+ true_labels = [["B-PERSON", "B-ORGANISATION"]]
258
+ evaluate_model(test_texts, true_labels)
259
+
260
+
261
+
262
+
263
+