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
Download final_model/NLP.py from NoNeet/TestSLM: direct link, hf CLI and curl.
- Browser
- Download file 10.6 kB
-
https://huggingface.co/NoNeet/TestSLM/resolve/main/final_model/NLP.py
- Command line
-
hf download hf://NoNeet/TestSLM/final_model/NLP.py
-
curl -L -o NLP.py https://huggingface.co/NoNeet/TestSLM/resolve/main/final_model/NLP.py
10.6 kB
| 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) |