Instructions to use NoNeet/TestSLM with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use NoNeet/TestSLM with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-classification", model="NoNeet/TestSLM")# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModelForSequenceClassification tokenizer = AutoTokenizer.from_pretrained("NoNeet/TestSLM") model = AutoModelForSequenceClassification.from_pretrained("NoNeet/TestSLM", device_map="auto") - Notebooks
- Google Colab
- Kaggle
File size: 10,565 Bytes
5f268d3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 | import numpy as np
from datasets import load_dataset
from transformers import (
AutoTokenizer,
AutoModelForSequenceClassification,
TrainingArguments,
Trainer,
pipeline,
PushToHubCallback
)
import evaluate
import torch
from torch.nn import CrossEntropyLoss
from sklearn.utils import compute_class_weight
import os
import shutil
print("Загрузка и разделение датасета 'blinoff/kinopoisk'...")
raw_dataset = load_dataset("blinoff/kinopoisk", split='train')
dataset_splits = raw_dataset.train_test_split(test_size=0.2, seed=42)
print("\nФильтрация датасета для бинарной классификации и преобразование меток...")
dataset_splits_filtered = dataset_splits.filter(lambda example: example['grade3'] != 'Neutral')
def map_labels(example):
if example['grade3'] == 'Good':
example['grade3'] = 1
elif example['grade3'] == 'Bad':
example['grade3'] = 0
return example
dataset_splits_mapped = dataset_splits_filtered.map(map_labels)
print("Выбор небольших подвыборок для демонстрации...")
train_dataset = dataset_splits_mapped["train"].shuffle(seed=42).select(range(4000))
eval_dataset = dataset_splits_mapped["test"].shuffle(seed=42).select(range(1000))
print("Данные отфильтрованы и преобразованы. Оставшиеся метки в train_dataset:", set(train_dataset['grade3']))
print("Данные отфильтрованы и преобразованы. Оставшиеся метки в eval_dataset:", set(eval_dataset['grade3']))
model_name = "sberbank-ai/rubert-base"
print(f"\nЗагрузка русской модели {model_name}...")
tokenizer = AutoTokenizer.from_pretrained(model_name)
id2label = {0: "НЕГАТИВНЫЙ", 1: "ПОЗИТИВНЫЙ"}
label2id = {"НЕГАТИВНЫЙ": 0, "ПОЗИТИВНЫЙ": 1}
model = AutoModelForSequenceClassification.from_pretrained(
model_name,
num_labels=2,
id2label=id2label,
label2id=label2id
)
def tokenize_function(examples):
return tokenizer(examples["content"], padding="max_length", truncation=True, max_length=512)
print("\nПрименение токенизатора к данным...")
tokenized_train_dataset = train_dataset.map(
tokenize_function,
batched=True,
)
tokenized_eval_dataset = eval_dataset.map(
tokenize_function,
batched=True,
)
tokenized_train_dataset = tokenized_train_dataset.rename_column("grade3", "labels")
tokenized_eval_dataset = tokenized_eval_dataset.rename_column("grade3", "labels")
required_columns = ['input_ids', 'attention_mask', 'labels']
if 'token_type_ids' in tokenized_train_dataset.column_names:
required_columns.append('token_type_ids')
else:
if tokenized_train_dataset and 'token_type_ids' in tokenized_train_dataset[0]:
required_columns.append('token_type_ids')
else:
print("Внимание: 'token_type_ids' не найдены в токенизированных данных.")
def cast_labels_to_long(examples):
return {"labels": torch.tensor(examples["labels"], dtype=torch.long)}
tokenized_train_dataset = tokenized_train_dataset.map(cast_labels_to_long, batched=True)
tokenized_eval_dataset = tokenized_eval_dataset.map(cast_labels_to_long, batched=True)
tokenized_train_dataset.set_format(type="torch", columns=required_columns)
tokenized_eval_dataset.set_format(type="torch", columns=required_columns)
print("\nКолонки в датасете после токенизации и очистки:")
print(tokenized_train_dataset.column_names)
print("\nРасчет весов классов для устранения дисбаланса...")
train_labels_np = np.array(tokenized_train_dataset['labels'])
class_weights = compute_class_weight(
class_weight='balanced',
classes=np.unique(train_labels_np),
y=train_labels_np
)
class_weights = torch.tensor(class_weights, dtype=torch.float)
print(f"Вычисленные веса классов: {class_weights}")
metric = evaluate.load("accuracy")
def compute_metrics(eval_pred):
logits, labels = eval_pred
predictions = np.argmax(logits, axis=-1)
return metric.compute(predictions=predictions, references=labels)
class CustomTrainer(Trainer):
def compute_loss(self, model, inputs, return_outputs=False, **kwargs):
labels = inputs.pop("labels")
outputs = model(**inputs)
logits = outputs.get("logits")
loss_fct = CrossEntropyLoss(weight=class_weights.to(logits.device))
loss = loss_fct(logits.view(-1, self.model.config.num_labels), labels.view(-1))
return (loss, outputs) if return_outputs else loss
print("\nНастройка и запуск процесса обучения...")
output_dir = "kinopoisk_rubert_fine_tuned"
repo_name = "NoNeet/TestSLM"
training_args = TrainingArguments(
output_dir=output_dir,
num_train_epochs=5,
per_device_train_batch_size=8,
per_device_eval_batch_size=8,
logging_steps=100,
eval_strategy="epoch",
save_strategy="epoch",
load_best_model_at_end=True,
report_to="none",
fp16=torch.cuda.is_available(),
learning_rate=2e-5,
push_to_hub=True,
hub_model_id=repo_name,
)
trainer = CustomTrainer(
model=model,
args=training_args,
train_dataset=tokenized_train_dataset,
eval_dataset=tokenized_eval_dataset,
compute_metrics=compute_metrics,
tokenizer=tokenizer
)
trainer.train()
print("\nИтоговая оценка модели на тестовом наборе:")
evaluation_results = trainer.evaluate()
print(f"Точность (Accuracy): {evaluation_results['eval_accuracy']:.4f}")
print("\nМодель обучена и готова к использованию!")
final_model_path = os.path.join(output_dir, "final_model")
print(f"\nСохранение модели и токенизатора в {final_model_path}...")
trainer.model.save_pretrained(final_model_path)
tokenizer.save_pretrained(final_model_path)
current_script_path = os.path.abspath(__file__)
destination_script_path = os.path.join(final_model_path, os.path.basename(current_script_path))
shutil.copyfile(current_script_path, destination_script_path)
print(f"Скрипт '{os.path.basename(current_script_path)}' сохранен в {destination_script_path}")
print("Модель и токенизатор успешно сохранены.")
print("\nЗагрузка модели на Hugging Face Hub...")
trainer.push_to_hub(commit_message="Initial model push with fine-tuned RuBERT on Kinopoisk dataset and training script")
print(f"Модель успешно загружена на Hugging Face Hub: https://huggingface.co/{repo_name}")
print(f"\nЗагрузка модели из {final_model_path} для тестирования...")
loaded_tokenizer = AutoTokenizer.from_pretrained(final_model_path)
loaded_model = AutoModelForSequenceClassification.from_pretrained(final_model_path)
classifier = pipeline(
"text-classification",
model=loaded_model,
tokenizer=loaded_tokenizer,
device=0 if torch.cuda.is_available() else -1,
)
positive_review = "Это лучший фильм, который я видел в этом году! Сюжет, актеры, музыка - все на высоте."
negative_review = "Полное разочарование. Непонятно, на что ушли деньги. Не советую смотреть."
mixed_review = "Фильм неплох, но конец немного подкачал."
neutral_review = "Обычный фильм, ничего особенного."
very_negative_review = "Худший фильм года, просто ужас. Пустая трата времени и денег."
very_positive_review = "Шедевр! Актерская игра просто невероятна, сюжет держит в напряжении до последней секунды."
sarcastic_review = "Конечно, это лучший фильм! Особенно если любишь скуку и отсутствие логики."
ambiguous_review = "Не могу сказать, что фильм плох, но и хорошим его не назовешь."
print(f"\nОтзыв: '{positive_review}'")
print(f"Результат: {classifier(positive_review)}")
print(f"\nОтзыв: '{negative_review}'")
print(f"Результат: {classifier(negative_review)}")
print(f"\nОтзыв: '{mixed_review}'")
print(f"Результат: {classifier(mixed_review)}")
print(f"\nОтзыв: '{neutral_review}'")
print(f"Результат: {classifier(neutral_review)}")
print(f"\nОтзыв: '{very_negative_review}'")
print(f"Результат: {classifier(very_negative_review)}")
print(f"\nОтзыв: '{very_positive_review}'")
print(f"Результат: {classifier(very_positive_review)}")
print(f"\nОтзыв: '{sarcastic_review}'")
print(f"Результат: {classifier(sarcastic_review)}")
print(f"\nОтзыв: '{ambiguous_review}'")
print(f"Результат: {classifier(ambiguous_review)}")
print("\n--- Финальная проверка распределения меток в датасетах для обучения ---")
print("Проверка распределения меток в tokenized_train_dataset:")
train_labels = tokenized_train_dataset['labels']
unique_train_labels, counts_train = np.unique(train_labels, return_counts=True)
print(f"Уникальные метки в тренировочном наборе: {unique_train_labels}, Распределение: {dict(zip(unique_train_labels, counts_train))}")
print("\nПроверка распределения меток в tokenized_eval_dataset:")
eval_labels = tokenized_eval_dataset['labels']
unique_eval_labels, counts_eval = np.unique(eval_labels, return_counts=True)
print(f"Уникальные метки в валидационном наборе: {unique_eval_labels}, Распределение: {dict(zip(unique_eval_labels, counts_eval))}")
print("\nНастройки меток в модели перед обучением (взяты из model.config):")
print("model.config.id2label:", model.config.id2label)
print("model.config.label2id:", model.config.label2id) |