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
Initial model push with fine-tuned RuBERT on Kinopoisk dataset and training script
Browse files- README.md +66 -202
- final_model/NLP.py +225 -0
- final_model/config.json +38 -0
- final_model/model.safetensors +3 -0
- final_model/special_tokens_map.json +7 -0
- final_model/tokenizer.json +0 -0
- final_model/tokenizer_config.json +58 -0
- final_model/vocab.txt +0 -0
- model.safetensors +1 -1
README.md
CHANGED
|
@@ -1,202 +1,66 @@
|
|
| 1 |
-
---
|
| 2 |
-
library_name: transformers
|
| 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 |
-
### Recommendations
|
| 68 |
-
|
| 69 |
-
<!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
|
| 70 |
-
|
| 71 |
-
Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
|
| 72 |
-
|
| 73 |
-
## How to Get Started with the Model
|
| 74 |
-
|
| 75 |
-
Use the code below to get started with the model.
|
| 76 |
-
|
| 77 |
-
[More Information Needed]
|
| 78 |
-
|
| 79 |
-
## Training Details
|
| 80 |
-
|
| 81 |
-
### Training Data
|
| 82 |
-
|
| 83 |
-
<!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
|
| 84 |
-
|
| 85 |
-
[More Information Needed]
|
| 86 |
-
|
| 87 |
-
### Training Procedure
|
| 88 |
-
|
| 89 |
-
<!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
|
| 90 |
-
|
| 91 |
-
#### Preprocessing [optional]
|
| 92 |
-
|
| 93 |
-
[More Information Needed]
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
#### Training Hyperparameters
|
| 97 |
-
|
| 98 |
-
- **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
|
| 99 |
-
|
| 100 |
-
#### Speeds, Sizes, Times [optional]
|
| 101 |
-
|
| 102 |
-
<!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
|
| 103 |
-
|
| 104 |
-
[More Information Needed]
|
| 105 |
-
|
| 106 |
-
## Evaluation
|
| 107 |
-
|
| 108 |
-
<!-- This section describes the evaluation protocols and provides the results. -->
|
| 109 |
-
|
| 110 |
-
### Testing Data, Factors & Metrics
|
| 111 |
-
|
| 112 |
-
#### Testing Data
|
| 113 |
-
|
| 114 |
-
<!-- This should link to a Dataset Card if possible. -->
|
| 115 |
-
|
| 116 |
-
[More Information Needed]
|
| 117 |
-
|
| 118 |
-
#### Factors
|
| 119 |
-
|
| 120 |
-
<!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
|
| 121 |
-
|
| 122 |
-
[More Information Needed]
|
| 123 |
-
|
| 124 |
-
#### Metrics
|
| 125 |
-
|
| 126 |
-
<!-- These are the evaluation metrics being used, ideally with a description of why. -->
|
| 127 |
-
|
| 128 |
-
[More Information Needed]
|
| 129 |
-
|
| 130 |
-
### Results
|
| 131 |
-
|
| 132 |
-
[More Information Needed]
|
| 133 |
-
|
| 134 |
-
#### Summary
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
## Model Examination [optional]
|
| 139 |
-
|
| 140 |
-
<!-- Relevant interpretability work for the model goes here -->
|
| 141 |
-
|
| 142 |
-
[More Information Needed]
|
| 143 |
-
|
| 144 |
-
## Environmental Impact
|
| 145 |
-
|
| 146 |
-
<!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
|
| 147 |
-
|
| 148 |
-
Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
|
| 149 |
-
|
| 150 |
-
- **Hardware Type:** [More Information Needed]
|
| 151 |
-
- **Hours used:** [More Information Needed]
|
| 152 |
-
- **Cloud Provider:** [More Information Needed]
|
| 153 |
-
- **Compute Region:** [More Information Needed]
|
| 154 |
-
- **Carbon Emitted:** [More Information Needed]
|
| 155 |
-
|
| 156 |
-
## Technical Specifications [optional]
|
| 157 |
-
|
| 158 |
-
### Model Architecture and Objective
|
| 159 |
-
|
| 160 |
-
[More Information Needed]
|
| 161 |
-
|
| 162 |
-
### Compute Infrastructure
|
| 163 |
-
|
| 164 |
-
[More Information Needed]
|
| 165 |
-
|
| 166 |
-
#### Hardware
|
| 167 |
-
|
| 168 |
-
[More Information Needed]
|
| 169 |
-
|
| 170 |
-
#### Software
|
| 171 |
-
|
| 172 |
-
[More Information Needed]
|
| 173 |
-
|
| 174 |
-
## Citation [optional]
|
| 175 |
-
|
| 176 |
-
<!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
|
| 177 |
-
|
| 178 |
-
**BibTeX:**
|
| 179 |
-
|
| 180 |
-
[More Information Needed]
|
| 181 |
-
|
| 182 |
-
**APA:**
|
| 183 |
-
|
| 184 |
-
[More Information Needed]
|
| 185 |
-
|
| 186 |
-
## Glossary [optional]
|
| 187 |
-
|
| 188 |
-
<!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
|
| 189 |
-
|
| 190 |
-
[More Information Needed]
|
| 191 |
-
|
| 192 |
-
## More Information [optional]
|
| 193 |
-
|
| 194 |
-
[More Information Needed]
|
| 195 |
-
|
| 196 |
-
## Model Card Authors [optional]
|
| 197 |
-
|
| 198 |
-
[More Information Needed]
|
| 199 |
-
|
| 200 |
-
## Model Card Contact
|
| 201 |
-
|
| 202 |
-
[More Information Needed]
|
|
|
|
| 1 |
+
---
|
| 2 |
+
library_name: transformers
|
| 3 |
+
license: apache-2.0
|
| 4 |
+
base_model: sberbank-ai/rubert-base
|
| 5 |
+
tags:
|
| 6 |
+
- generated_from_trainer
|
| 7 |
+
metrics:
|
| 8 |
+
- accuracy
|
| 9 |
+
model-index:
|
| 10 |
+
- name: TestSLM
|
| 11 |
+
results: []
|
| 12 |
+
---
|
| 13 |
+
|
| 14 |
+
<!-- This model card has been generated automatically according to the information the Trainer had access to. You
|
| 15 |
+
should probably proofread and complete it, then remove this comment. -->
|
| 16 |
+
|
| 17 |
+
# TestSLM
|
| 18 |
+
|
| 19 |
+
This model is a fine-tuned version of [sberbank-ai/rubert-base](https://huggingface.co/sberbank-ai/rubert-base) on an unknown dataset.
|
| 20 |
+
It achieves the following results on the evaluation set:
|
| 21 |
+
- Loss: 0.2956
|
| 22 |
+
- Accuracy: 0.971
|
| 23 |
+
|
| 24 |
+
## Model description
|
| 25 |
+
|
| 26 |
+
More information needed
|
| 27 |
+
|
| 28 |
+
## Intended uses & limitations
|
| 29 |
+
|
| 30 |
+
More information needed
|
| 31 |
+
|
| 32 |
+
## Training and evaluation data
|
| 33 |
+
|
| 34 |
+
More information needed
|
| 35 |
+
|
| 36 |
+
## Training procedure
|
| 37 |
+
|
| 38 |
+
### Training hyperparameters
|
| 39 |
+
|
| 40 |
+
The following hyperparameters were used during training:
|
| 41 |
+
- learning_rate: 2e-05
|
| 42 |
+
- train_batch_size: 8
|
| 43 |
+
- eval_batch_size: 8
|
| 44 |
+
- seed: 42
|
| 45 |
+
- optimizer: Use OptimizerNames.ADAMW_TORCH_FUSED with betas=(0.9,0.999) and epsilon=1e-08 and optimizer_args=No additional optimizer arguments
|
| 46 |
+
- lr_scheduler_type: linear
|
| 47 |
+
- num_epochs: 5
|
| 48 |
+
- mixed_precision_training: Native AMP
|
| 49 |
+
|
| 50 |
+
### Training results
|
| 51 |
+
|
| 52 |
+
| Training Loss | Epoch | Step | Validation Loss | Accuracy |
|
| 53 |
+
|:-------------:|:-----:|:----:|:---------------:|:--------:|
|
| 54 |
+
| 0.3106 | 1.0 | 500 | 0.5177 | 0.955 |
|
| 55 |
+
| 0.1336 | 2.0 | 1000 | 0.2956 | 0.971 |
|
| 56 |
+
| 0.0701 | 3.0 | 1500 | 0.3801 | 0.968 |
|
| 57 |
+
| 0.0003 | 4.0 | 2000 | 0.3441 | 0.971 |
|
| 58 |
+
| 0.0045 | 5.0 | 2500 | 0.3358 | 0.973 |
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
### Framework versions
|
| 62 |
+
|
| 63 |
+
- Transformers 4.57.0
|
| 64 |
+
- Pytorch 2.9.0.dev20250628+cu128
|
| 65 |
+
- Datasets 4.1.1
|
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
from datasets import load_dataset
|
| 3 |
+
from transformers import (
|
| 4 |
+
AutoTokenizer,
|
| 5 |
+
AutoModelForSequenceClassification,
|
| 6 |
+
TrainingArguments,
|
| 7 |
+
Trainer,
|
| 8 |
+
pipeline,
|
| 9 |
+
PushToHubCallback
|
| 10 |
+
)
|
| 11 |
+
import evaluate
|
| 12 |
+
import torch
|
| 13 |
+
from torch.nn import CrossEntropyLoss
|
| 14 |
+
from sklearn.utils import compute_class_weight
|
| 15 |
+
import os
|
| 16 |
+
import shutil
|
| 17 |
+
|
| 18 |
+
print("Загрузка и разделение датасета 'blinoff/kinopoisk'...")
|
| 19 |
+
raw_dataset = load_dataset("blinoff/kinopoisk", split='train')
|
| 20 |
+
dataset_splits = raw_dataset.train_test_split(test_size=0.2, seed=42)
|
| 21 |
+
|
| 22 |
+
print("\nФильтрация датасета для бинарной классификации и преобразование меток...")
|
| 23 |
+
|
| 24 |
+
dataset_splits_filtered = dataset_splits.filter(lambda example: example['grade3'] != 'Neutral')
|
| 25 |
+
|
| 26 |
+
def map_labels(example):
|
| 27 |
+
if example['grade3'] == 'Good':
|
| 28 |
+
example['grade3'] = 1
|
| 29 |
+
elif example['grade3'] == 'Bad':
|
| 30 |
+
example['grade3'] = 0
|
| 31 |
+
return example
|
| 32 |
+
|
| 33 |
+
dataset_splits_mapped = dataset_splits_filtered.map(map_labels)
|
| 34 |
+
|
| 35 |
+
print("Выбор небольших подвыборок для демонстрации...")
|
| 36 |
+
train_dataset = dataset_splits_mapped["train"].shuffle(seed=42).select(range(4000))
|
| 37 |
+
eval_dataset = dataset_splits_mapped["test"].shuffle(seed=42).select(range(1000))
|
| 38 |
+
|
| 39 |
+
print("Данные отфильтрованы и преобразованы. Оставшиеся метки в train_dataset:", set(train_dataset['grade3']))
|
| 40 |
+
print("Данные отфильтрованы и преобразованы. Оставшиеся метки в eval_dataset:", set(eval_dataset['grade3']))
|
| 41 |
+
|
| 42 |
+
model_name = "sberbank-ai/rubert-base"
|
| 43 |
+
print(f"\nЗагрузка русской модели {model_name}...")
|
| 44 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 45 |
+
id2label = {0: "НЕГАТИВНЫЙ", 1: "ПОЗИТИВНЫЙ"}
|
| 46 |
+
label2id = {"НЕГАТИВНЫЙ": 0, "ПОЗИТИВНЫЙ": 1}
|
| 47 |
+
|
| 48 |
+
model = AutoModelForSequenceClassification.from_pretrained(
|
| 49 |
+
model_name,
|
| 50 |
+
num_labels=2,
|
| 51 |
+
id2label=id2label,
|
| 52 |
+
label2id=label2id
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
def tokenize_function(examples):
|
| 56 |
+
return tokenizer(examples["content"], padding="max_length", truncation=True, max_length=512)
|
| 57 |
+
|
| 58 |
+
print("\nПрименение токенизатора к данным...")
|
| 59 |
+
|
| 60 |
+
tokenized_train_dataset = train_dataset.map(
|
| 61 |
+
tokenize_function,
|
| 62 |
+
batched=True,
|
| 63 |
+
)
|
| 64 |
+
tokenized_eval_dataset = eval_dataset.map(
|
| 65 |
+
tokenize_function,
|
| 66 |
+
batched=True,
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
tokenized_train_dataset = tokenized_train_dataset.rename_column("grade3", "labels")
|
| 70 |
+
tokenized_eval_dataset = tokenized_eval_dataset.rename_column("grade3", "labels")
|
| 71 |
+
|
| 72 |
+
required_columns = ['input_ids', 'attention_mask', 'labels']
|
| 73 |
+
|
| 74 |
+
if 'token_type_ids' in tokenized_train_dataset.column_names:
|
| 75 |
+
required_columns.append('token_type_ids')
|
| 76 |
+
else:
|
| 77 |
+
if tokenized_train_dataset and 'token_type_ids' in tokenized_train_dataset[0]:
|
| 78 |
+
required_columns.append('token_type_ids')
|
| 79 |
+
else:
|
| 80 |
+
print("Внимание: 'token_type_ids' не найдены в токенизированных данных.")
|
| 81 |
+
|
| 82 |
+
def cast_labels_to_long(examples):
|
| 83 |
+
return {"labels": torch.tensor(examples["labels"], dtype=torch.long)}
|
| 84 |
+
|
| 85 |
+
tokenized_train_dataset = tokenized_train_dataset.map(cast_labels_to_long, batched=True)
|
| 86 |
+
tokenized_eval_dataset = tokenized_eval_dataset.map(cast_labels_to_long, batched=True)
|
| 87 |
+
|
| 88 |
+
tokenized_train_dataset.set_format(type="torch", columns=required_columns)
|
| 89 |
+
tokenized_eval_dataset.set_format(type="torch", columns=required_columns)
|
| 90 |
+
|
| 91 |
+
print("\nКолонки в датасете после токенизации и очистки:")
|
| 92 |
+
print(tokenized_train_dataset.column_names)
|
| 93 |
+
|
| 94 |
+
print("\nРасчет весов классов для устранения дисбаланса...")
|
| 95 |
+
train_labels_np = np.array(tokenized_train_dataset['labels'])
|
| 96 |
+
class_weights = compute_class_weight(
|
| 97 |
+
class_weight='balanced',
|
| 98 |
+
classes=np.unique(train_labels_np),
|
| 99 |
+
y=train_labels_np
|
| 100 |
+
)
|
| 101 |
+
class_weights = torch.tensor(class_weights, dtype=torch.float)
|
| 102 |
+
print(f"Вычисленные веса классов: {class_weights}")
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
metric = evaluate.load("accuracy")
|
| 106 |
+
def compute_metrics(eval_pred):
|
| 107 |
+
logits, labels = eval_pred
|
| 108 |
+
predictions = np.argmax(logits, axis=-1)
|
| 109 |
+
return metric.compute(predictions=predictions, references=labels)
|
| 110 |
+
|
| 111 |
+
class CustomTrainer(Trainer):
|
| 112 |
+
def compute_loss(self, model, inputs, return_outputs=False, **kwargs):
|
| 113 |
+
labels = inputs.pop("labels")
|
| 114 |
+
outputs = model(**inputs)
|
| 115 |
+
logits = outputs.get("logits")
|
| 116 |
+
loss_fct = CrossEntropyLoss(weight=class_weights.to(logits.device))
|
| 117 |
+
loss = loss_fct(logits.view(-1, self.model.config.num_labels), labels.view(-1))
|
| 118 |
+
return (loss, outputs) if return_outputs else loss
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
print("\nНастройка и запуск процесса обучения...")
|
| 122 |
+
output_dir = "kinopoisk_rubert_fine_tuned"
|
| 123 |
+
repo_name = "NoNeet/TestSLM"
|
| 124 |
+
|
| 125 |
+
training_args = TrainingArguments(
|
| 126 |
+
output_dir=output_dir,
|
| 127 |
+
num_train_epochs=5,
|
| 128 |
+
per_device_train_batch_size=8,
|
| 129 |
+
per_device_eval_batch_size=8,
|
| 130 |
+
logging_steps=100,
|
| 131 |
+
eval_strategy="epoch",
|
| 132 |
+
save_strategy="epoch",
|
| 133 |
+
load_best_model_at_end=True,
|
| 134 |
+
report_to="none",
|
| 135 |
+
fp16=torch.cuda.is_available(),
|
| 136 |
+
learning_rate=2e-5,
|
| 137 |
+
push_to_hub=True,
|
| 138 |
+
hub_model_id=repo_name,
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
trainer = CustomTrainer(
|
| 142 |
+
model=model,
|
| 143 |
+
args=training_args,
|
| 144 |
+
train_dataset=tokenized_train_dataset,
|
| 145 |
+
eval_dataset=tokenized_eval_dataset,
|
| 146 |
+
compute_metrics=compute_metrics,
|
| 147 |
+
tokenizer=tokenizer
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
trainer.train()
|
| 151 |
+
|
| 152 |
+
print("\nИтоговая оценка модели на тестовом наборе:")
|
| 153 |
+
evaluation_results = trainer.evaluate()
|
| 154 |
+
print(f"Точность (Accuracy): {evaluation_results['eval_accuracy']:.4f}")
|
| 155 |
+
|
| 156 |
+
print("\nМодель обучена и готова к использованию!")
|
| 157 |
+
|
| 158 |
+
final_model_path = os.path.join(output_dir, "final_model")
|
| 159 |
+
print(f"\nСохранение модели и токенизатора в {final_model_path}...")
|
| 160 |
+
trainer.model.save_pretrained(final_model_path)
|
| 161 |
+
tokenizer.save_pretrained(final_model_path)
|
| 162 |
+
|
| 163 |
+
current_script_path = os.path.abspath(__file__)
|
| 164 |
+
destination_script_path = os.path.join(final_model_path, os.path.basename(current_script_path))
|
| 165 |
+
shutil.copyfile(current_script_path, destination_script_path)
|
| 166 |
+
print(f"Скрипт '{os.path.basename(current_script_path)}' сохранен в {destination_script_path}")
|
| 167 |
+
|
| 168 |
+
print("Модель и токенизатор успешно сохранены.")
|
| 169 |
+
|
| 170 |
+
print("\nЗагрузка модели на Hugging Face Hub...")
|
| 171 |
+
trainer.push_to_hub(commit_message="Initial model push with fine-tuned RuBERT on Kinopoisk dataset and training script")
|
| 172 |
+
print(f"Модель успешно загружена на Hugging Face Hub: https://huggingface.co/{repo_name}")
|
| 173 |
+
|
| 174 |
+
print(f"\nЗагрузка модели из {final_model_path} для тестирования...")
|
| 175 |
+
loaded_tokenizer = AutoTokenizer.from_pretrained(final_model_path)
|
| 176 |
+
loaded_model = AutoModelForSequenceClassification.from_pretrained(final_model_path)
|
| 177 |
+
|
| 178 |
+
classifier = pipeline(
|
| 179 |
+
"text-classification",
|
| 180 |
+
model=loaded_model,
|
| 181 |
+
tokenizer=loaded_tokenizer,
|
| 182 |
+
device=0 if torch.cuda.is_available() else -1,
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
+
positive_review = "Это лучший фильм, который я видел в этом году! Сюжет, актеры, музыка - все на высоте."
|
| 186 |
+
negative_review = "Полное разочарование. Непонятно, на что ушли деньги. Не советую смотреть."
|
| 187 |
+
mixed_review = "Фильм неплох, но конец немного подкачал."
|
| 188 |
+
neutral_review = "Обычный фильм, ничего особенного."
|
| 189 |
+
very_negative_review = "Худший фильм года, просто ужас. Пустая трата времени и денег."
|
| 190 |
+
very_positive_review = "Шедевр! Актерская игра просто невероятна, сюжет держит в напряжении до последней секунды."
|
| 191 |
+
sarcastic_review = "Конечно, это лучший фильм! Особенно если любишь скуку и отсутствие логики."
|
| 192 |
+
ambiguous_review = "Не могу сказать, что фильм плох, но и хорошим его не назовешь."
|
| 193 |
+
|
| 194 |
+
print(f"\nОтзыв: '{positive_review}'")
|
| 195 |
+
print(f"Результат: {classifier(positive_review)}")
|
| 196 |
+
print(f"\nОтзыв: '{negative_review}'")
|
| 197 |
+
print(f"Результат: {classifier(negative_review)}")
|
| 198 |
+
print(f"\nОтзыв: '{mixed_review}'")
|
| 199 |
+
print(f"Результат: {classifier(mixed_review)}")
|
| 200 |
+
print(f"\nОтзыв: '{neutral_review}'")
|
| 201 |
+
print(f"Результат: {classifier(neutral_review)}")
|
| 202 |
+
print(f"\nОтзыв: '{very_negative_review}'")
|
| 203 |
+
print(f"Результат: {classifier(very_negative_review)}")
|
| 204 |
+
print(f"\nОтзыв: '{very_positive_review}'")
|
| 205 |
+
print(f"Результат: {classifier(very_positive_review)}")
|
| 206 |
+
print(f"\nОтзыв: '{sarcastic_review}'")
|
| 207 |
+
print(f"Результат: {classifier(sarcastic_review)}")
|
| 208 |
+
print(f"\nОтзыв: '{ambiguous_review}'")
|
| 209 |
+
print(f"Результат: {classifier(ambiguous_review)}")
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
print("\n--- Финальная проверка распределения меток в датасетах для обучения ---")
|
| 213 |
+
print("Проверка распределения меток в tokenized_train_dataset:")
|
| 214 |
+
train_labels = tokenized_train_dataset['labels']
|
| 215 |
+
unique_train_labels, counts_train = np.unique(train_labels, return_counts=True)
|
| 216 |
+
print(f"Уникальные метки в тренировочном наборе: {unique_train_labels}, Распределение: {dict(zip(unique_train_labels, counts_train))}")
|
| 217 |
+
|
| 218 |
+
print("\nПроверка распределения меток в tokenized_eval_dataset:")
|
| 219 |
+
eval_labels = tokenized_eval_dataset['labels']
|
| 220 |
+
unique_eval_labels, counts_eval = np.unique(eval_labels, return_counts=True)
|
| 221 |
+
print(f"Уникальные метки в валидационном наборе: {unique_eval_labels}, Распределение: {dict(zip(unique_eval_labels, counts_eval))}")
|
| 222 |
+
|
| 223 |
+
print("\nНастройки меток в модели перед обучением (взяты из model.config):")
|
| 224 |
+
print("model.config.id2label:", model.config.id2label)
|
| 225 |
+
print("model.config.label2id:", model.config.label2id)
|
final_model/config.json
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"BertForSequenceClassification"
|
| 4 |
+
],
|
| 5 |
+
"attention_probs_dropout_prob": 0.1,
|
| 6 |
+
"classifier_dropout": null,
|
| 7 |
+
"directionality": "bidi",
|
| 8 |
+
"dtype": "float32",
|
| 9 |
+
"hidden_act": "gelu",
|
| 10 |
+
"hidden_dropout_prob": 0.1,
|
| 11 |
+
"hidden_size": 768,
|
| 12 |
+
"id2label": {
|
| 13 |
+
"0": "\u041d\u0415\u0413\u0410\u0422\u0418\u0412\u041d\u042b\u0419",
|
| 14 |
+
"1": "\u041f\u041e\u0417\u0418\u0422\u0418\u0412\u041d\u042b\u0419"
|
| 15 |
+
},
|
| 16 |
+
"initializer_range": 0.02,
|
| 17 |
+
"intermediate_size": 3072,
|
| 18 |
+
"label2id": {
|
| 19 |
+
"\u041d\u0415\u0413\u0410\u0422\u0418\u0412\u041d\u042b\u0419": 0,
|
| 20 |
+
"\u041f\u041e\u0417\u0418\u0422\u0418\u0412\u041d\u042b\u0419": 1
|
| 21 |
+
},
|
| 22 |
+
"layer_norm_eps": 1e-12,
|
| 23 |
+
"max_position_embeddings": 512,
|
| 24 |
+
"model_type": "bert",
|
| 25 |
+
"num_attention_heads": 12,
|
| 26 |
+
"num_hidden_layers": 12,
|
| 27 |
+
"pad_token_id": 0,
|
| 28 |
+
"pooler_fc_size": 768,
|
| 29 |
+
"pooler_num_attention_heads": 12,
|
| 30 |
+
"pooler_num_fc_layers": 3,
|
| 31 |
+
"pooler_size_per_head": 128,
|
| 32 |
+
"pooler_type": "first_token_transform",
|
| 33 |
+
"position_embedding_type": "absolute",
|
| 34 |
+
"transformers_version": "4.57.0",
|
| 35 |
+
"type_vocab_size": 2,
|
| 36 |
+
"use_cache": true,
|
| 37 |
+
"vocab_size": 120138
|
| 38 |
+
}
|
final_model/model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6400c2462fab85c65a51254fe5c0ebf079ea586a27597014b76227fd0d2fdc70
|
| 3 |
+
size 713259008
|
final_model/special_tokens_map.json
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cls_token": "[CLS]",
|
| 3 |
+
"mask_token": "[MASK]",
|
| 4 |
+
"pad_token": "[PAD]",
|
| 5 |
+
"sep_token": "[SEP]",
|
| 6 |
+
"unk_token": "[UNK]"
|
| 7 |
+
}
|
final_model/tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
final_model/tokenizer_config.json
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"added_tokens_decoder": {
|
| 3 |
+
"0": {
|
| 4 |
+
"content": "[PAD]",
|
| 5 |
+
"lstrip": false,
|
| 6 |
+
"normalized": false,
|
| 7 |
+
"rstrip": false,
|
| 8 |
+
"single_word": false,
|
| 9 |
+
"special": true
|
| 10 |
+
},
|
| 11 |
+
"100": {
|
| 12 |
+
"content": "[UNK]",
|
| 13 |
+
"lstrip": false,
|
| 14 |
+
"normalized": false,
|
| 15 |
+
"rstrip": false,
|
| 16 |
+
"single_word": false,
|
| 17 |
+
"special": true
|
| 18 |
+
},
|
| 19 |
+
"101": {
|
| 20 |
+
"content": "[CLS]",
|
| 21 |
+
"lstrip": false,
|
| 22 |
+
"normalized": false,
|
| 23 |
+
"rstrip": false,
|
| 24 |
+
"single_word": false,
|
| 25 |
+
"special": true
|
| 26 |
+
},
|
| 27 |
+
"102": {
|
| 28 |
+
"content": "[SEP]",
|
| 29 |
+
"lstrip": false,
|
| 30 |
+
"normalized": false,
|
| 31 |
+
"rstrip": false,
|
| 32 |
+
"single_word": false,
|
| 33 |
+
"special": true
|
| 34 |
+
},
|
| 35 |
+
"103": {
|
| 36 |
+
"content": "[MASK]",
|
| 37 |
+
"lstrip": false,
|
| 38 |
+
"normalized": false,
|
| 39 |
+
"rstrip": false,
|
| 40 |
+
"single_word": false,
|
| 41 |
+
"special": true
|
| 42 |
+
}
|
| 43 |
+
},
|
| 44 |
+
"clean_up_tokenization_spaces": true,
|
| 45 |
+
"cls_token": "[CLS]",
|
| 46 |
+
"do_basic_tokenize": true,
|
| 47 |
+
"do_lower_case": true,
|
| 48 |
+
"extra_special_tokens": {},
|
| 49 |
+
"mask_token": "[MASK]",
|
| 50 |
+
"model_max_length": 1000000000000000019884624838656,
|
| 51 |
+
"never_split": null,
|
| 52 |
+
"pad_token": "[PAD]",
|
| 53 |
+
"sep_token": "[SEP]",
|
| 54 |
+
"strip_accents": null,
|
| 55 |
+
"tokenize_chinese_chars": true,
|
| 56 |
+
"tokenizer_class": "BertTokenizer",
|
| 57 |
+
"unk_token": "[UNK]"
|
| 58 |
+
}
|
final_model/vocab.txt
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
model.safetensors
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
size 713259008
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6400c2462fab85c65a51254fe5c0ebf079ea586a27597014b76227fd0d2fdc70
|
| 3 |
size 713259008
|