Instructions to use Eraly-ml/KazBERT-NERD with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Eraly-ml/KazBERT-NERD with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("token-classification", model="Eraly-ml/KazBERT-NERD")# Load model directly from transformers import AutoTokenizer, AutoModelForTokenClassification tokenizer = AutoTokenizer.from_pretrained("Eraly-ml/KazBERT-NERD") model = AutoModelForTokenClassification.from_pretrained("Eraly-ml/KazBERT-NERD", device_map="auto") - Notebooks
- Google Colab
- Kaggle
Create train.py
Browse files
train.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import numpy as np
|
| 3 |
+
import transformers
|
| 4 |
+
from transformers import (
|
| 5 |
+
AutoTokenizer,
|
| 6 |
+
AutoModelForTokenClassification,
|
| 7 |
+
TrainingArguments,
|
| 8 |
+
Trainer,
|
| 9 |
+
DataCollatorForTokenClassification
|
| 10 |
+
)
|
| 11 |
+
from datasets import load_dataset
|
| 12 |
+
import evaluate
|
| 13 |
+
|
| 14 |
+
# 1. Константы и параметры
|
| 15 |
+
MODEL_CHECKPOINT = "Eraly-ml/KazBERT"
|
| 16 |
+
TASK = "ner"
|
| 17 |
+
BATCH_SIZE = 32
|
| 18 |
+
LEARNING_RATE = 5e-5
|
| 19 |
+
EPOCHS = 8
|
| 20 |
+
SAVE_PATH = "./kazbert_ner_finetuned"
|
| 21 |
+
|
| 22 |
+
# 2. Загрузка данных и метрик
|
| 23 |
+
datasets = load_dataset("issai/kaznerd", trust_remote_code=True)
|
| 24 |
+
metric = evaluate.load("seqeval")
|
| 25 |
+
label_list = datasets["train"].features[f"{TASK}_tags"].feature.names
|
| 26 |
+
|
| 27 |
+
# 3. Токенизация с выравниванием меток
|
| 28 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_CHECKPOINT, trust_remote_code=True)
|
| 29 |
+
|
| 30 |
+
def tokenize_and_align_labels(examples):
|
| 31 |
+
tokenized_inputs = tokenizer(examples["tokens"], truncation=True, is_split_into_words=True)
|
| 32 |
+
labels = []
|
| 33 |
+
for i, label in enumerate(examples[f"{TASK}_tags"]):
|
| 34 |
+
word_ids = tokenized_inputs.word_ids(batch_index=i)
|
| 35 |
+
previous_word_idx = None
|
| 36 |
+
label_ids = []
|
| 37 |
+
for word_idx in word_ids:
|
| 38 |
+
if word_idx is None:
|
| 39 |
+
label_ids.append(-100) # Игнорируем спецтокены
|
| 40 |
+
elif word_idx != previous_word_idx:
|
| 41 |
+
label_ids.append(label[word_idx]) # Первая часть слова
|
| 42 |
+
else:
|
| 43 |
+
label_ids.append(-100) # Остальные части слова (игнорируем для оценки)
|
| 44 |
+
previous_word_idx = word_idx
|
| 45 |
+
labels.append(label_ids)
|
| 46 |
+
tokenized_inputs["labels"] = labels
|
| 47 |
+
return tokenized_inputs
|
| 48 |
+
|
| 49 |
+
tokenized_datasets = datasets.map(tokenize_and_align_labels, batched=True)
|
| 50 |
+
|
| 51 |
+
# 4. Модель с маппингом меток
|
| 52 |
+
id2label = {i: label for i, label in enumerate(label_list)}
|
| 53 |
+
label2id = {label: i for i, label in enumerate(label_list)}
|
| 54 |
+
|
| 55 |
+
model = AutoModelForTokenClassification.from_pretrained(
|
| 56 |
+
MODEL_CHECKPOINT,
|
| 57 |
+
num_labels=len(label_list),
|
| 58 |
+
id2label=id2label,
|
| 59 |
+
label2id=label2id,
|
| 60 |
+
trust_remote_code=True
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
# 5. Функция для вычисления метрик (Precision, Recall, F1)
|
| 64 |
+
def compute_metrics(p):
|
| 65 |
+
predictions, labels = p
|
| 66 |
+
predictions = np.argmax(predictions, axis=2)
|
| 67 |
+
true_predictions = [[label_list[p] for (p, l) in zip(prediction, label) if l != -100]
|
| 68 |
+
for prediction, label in zip(predictions, labels)]
|
| 69 |
+
true_labels = [[label_list[l] for (p, l) in zip(prediction, label) if l != -100]
|
| 70 |
+
for prediction, label in zip(predictions, labels)]
|
| 71 |
+
results = metric.compute(predictions=true_predictions, references=true_labels, scheme="IOB2")
|
| 72 |
+
return {
|
| 73 |
+
"precision": results["overall_precision"],
|
| 74 |
+
"recall": results["overall_recall"],
|
| 75 |
+
"f1": results["overall_f1"],
|
| 76 |
+
"accuracy": results["overall_accuracy"],
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
# 6. Настройка и запуск Trainer
|
| 80 |
+
args = TrainingArguments(
|
| 81 |
+
output_dir=SAVE_PATH,
|
| 82 |
+
eval_strategy="epoch",
|
| 83 |
+
learning_rate=LEARNING_RATE,
|
| 84 |
+
per_device_train_batch_size=BATCH_SIZE,
|
| 85 |
+
per_device_eval_batch_size=BATCH_SIZE,
|
| 86 |
+
num_train_epochs=EPOCHS,
|
| 87 |
+
weight_decay=0.01,
|
| 88 |
+
save_strategy="no",
|
| 89 |
+
report_to=[]
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
trainer = Trainer(
|
| 93 |
+
model,
|
| 94 |
+
args,
|
| 95 |
+
train_dataset=tokenized_datasets["train"],
|
| 96 |
+
eval_dataset=tokenized_datasets["validation"],
|
| 97 |
+
data_collator=DataCollatorForTokenClassification(tokenizer),
|
| 98 |
+
tokenizer=tokenizer,
|
| 99 |
+
compute_metrics=compute_metrics
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
trainer.train()
|
| 103 |
+
|
| 104 |
+
# 7. Финальное сохранение
|
| 105 |
+
model.save_pretrained(SAVE_PATH)
|
| 106 |
+
tokenizer.save_pretrained(SAVE_PATH)
|