File size: 9,118 Bytes
2a591a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Восстановим константы, словарь и модели из прошлого нотубка"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import pandas as pd\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.nn.functional as F\n",
    "from torch.utils.data import DataLoader, TensorDataset\n",
    "\n",
    "from src.models.models import TransformerClassifier, LSTMClassifier, CustomMambaClassifier, SimpleMambaBlock\n",
    "from src.data_utils.config import DatasetConfig\n",
    "from src.data_utils.dataset_params import DatasetName\n",
    "from src.data_utils.dataset_generator import DatasetGenerator\n",
    "\n",
    "MAX_SEQ_LEN = 300\n",
    "EMBEDDING_DIM = 128\n",
    "BATCH_SIZE = 32 \n",
    "NUM_CLASSES = 2\n",
    "SAVE_DIR = \"../pretrained_comparison\" \n",
    "DATA_DIR = \"../datasets\" \n",
    "DEVICE = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
    "\n",
    "config = DatasetConfig(load_from_disk=True, path_to_data=DATA_DIR)\n",
    "generator = DatasetGenerator(DatasetName.IMDB, config=config)\n",
    "\n",
    "_, _, _ = generator.generate_dataset() \n",
    "vocab = generator.vocab\n",
    "VOCAB_SIZE = len(vocab)\n",
    "text_processor = generator.get_text_processor()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Возьмем всопомгательную функцию из пролшло нотубка"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.metrics import accuracy_score, precision_recall_fscore_support\n",
    "\n",
    "def evaluate_on_test(model, test_loader, device, criterion):\n",
    "    model.eval()\n",
    "    total_test_loss = 0\n",
    "    all_preds = []\n",
    "    all_labels = []\n",
    "\n",
    "    with torch.no_grad():\n",
    "        for batch_X, batch_y in test_loader:\n",
    "            batch_X, batch_y = batch_X.to(device), batch_y.to(device)\n",
    "            outputs = model(batch_X)\n",
    "            loss = criterion(outputs, batch_y)\n",
    "            total_test_loss += loss.item()\n",
    "            \n",
    "            _, predicted = torch.max(outputs.data, 1)\n",
    "            all_preds.extend(predicted.cpu().numpy())\n",
    "            all_labels.extend(batch_y.cpu().numpy())\n",
    "            \n",
    "    avg_test_loss = total_test_loss / len(test_loader)\n",
    "        \n",
    "    accuracy = accuracy_score(all_labels, all_preds)\n",
    "    precision, recall, f1, _ = precision_recall_fscore_support(all_labels, all_preds, average='binary')\n",
    "    \n",
    "    return {'loss': avg_test_loss, 'accuracy': accuracy, 'precision': precision, 'recall': recall, 'f1_score': f1}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Создадим генератор датасета и передадим в него уже готовый текстовый процессор, заберем датасет из другого распределения"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "def create_dataloader(X, y, batch_size, shuffle=True):\n",
    "    X_tensor = torch.as_tensor(X, dtype=torch.long)\n",
    "    y_tensor = torch.as_tensor(y, dtype=torch.long)\n",
    "    dataset = TensorDataset(X_tensor, y_tensor)\n",
    "    return DataLoader(dataset, batch_size=batch_size, shuffle=shuffle)\n",
    "\n",
    "text_processor = generator.get_text_processor()\n",
    "config_polarity = DatasetConfig(\n",
    "    load_from_disk=True,\n",
    "    path_to_data=\"../datasets\",\n",
    "    train_size=25000,  # взяли весь датасет\n",
    "    val_size=12500,\n",
    "    test_size=12500,\n",
    "    build_vocab=False\n",
    ")\n",
    "generator_polarity = DatasetGenerator(DatasetName.POLARITY, config=config_polarity)\n",
    "generator_polarity.vocab = generator.vocab\n",
    "generator_polarity.id2word = generator.id2word\n",
    "generator_polarity.text_processor = text_processor\n",
    "(X_train, y_train), (X_val, y_val), (X_test, y_test) = generator_polarity.generate_dataset()\n",
    "\n",
    "\n",
    "test_loader = create_dataloader(X_test, y_test, BATCH_SIZE, shuffle=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Восстановим конфигурации конфигов моделей из прошлого нотубка"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "model_configs = {\n",
    "    \"CustomMamba\": {\n",
    "        \"class\": CustomMambaClassifier,\n",
    "        \"params\": {'vocab_size': VOCAB_SIZE, 'd_model': EMBEDDING_DIM, 'd_state': 8, \n",
    "                   'd_conv': 4, 'num_layers': 2, 'num_classes': NUM_CLASSES},\n",
    "    },\n",
    "    \"Lib_LSTM\": {\n",
    "        \"class\": LSTMClassifier,\n",
    "        \"params\": {'vocab_size': VOCAB_SIZE, 'embed_dim': EMBEDDING_DIM, 'hidden_dim': 128, \n",
    "                   'num_layers': 2, 'num_classes': NUM_CLASSES, 'dropout': 0.5},\n",
    "    },\n",
    "    \"Lib_Transformer\": {\n",
    "        \"class\": TransformerClassifier,\n",
    "        \"params\": {'vocab_size': VOCAB_SIZE, 'embed_dim': EMBEDDING_DIM, 'num_heads': 4, \n",
    "                   'num_layers': 2, 'num_classes': NUM_CLASSES, 'max_seq_len': MAX_SEQ_LEN},\n",
    "    },\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Теперь посмотрим на результаты"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/gab1k/.cache/pypoetry/virtualenvs/monkey-coding-dl-project-F4QJzkF_-py3.12/lib/python3.12/site-packages/torch/nn/modules/transformer.py:505: UserWarning: The PyTorch API of nested tensors is in prototype stage and will change in the near future. We recommend specifying layout=torch.jagged when constructing a nested tensor, as this layout receives active development, has better operator coverage, and works with torch.compile. (Triggered internally at /pytorch/aten/src/ATen/NestedTensorImpl.cpp:178.)\n",
      "  output = torch._nested_tensor_from_mask(\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "--- Итоговая таблица сравнения моделей на тестовых данных ---\n",
      "                     loss  accuracy  precision    recall  f1_score\n",
      "CustomMamba      0.583675   0.70344   0.653410  0.871734  0.746945\n",
      "Lib_LSTM         0.675894   0.59520   0.574803  0.744423  0.648709\n",
      "Lib_Transformer  0.618924   0.66432   0.612190  0.904238  0.730091\n"
     ]
    }
   ],
   "source": [
    "results = {}\n",
    "for model_name, config in model_configs.items():        \n",
    "    model_path = os.path.join(SAVE_DIR, f\"best_model_{model_name.lower()}.pth\")            \n",
    "    model = config['class'](**config['params']).to(DEVICE)\n",
    "\n",
    "    model.load_state_dict(torch.load(model_path, map_location=DEVICE))\n",
    "    criterion = nn.CrossEntropyLoss()\n",
    "    test_metrics = evaluate_on_test(model, test_loader, DEVICE, criterion)\n",
    "    results[model_name] = test_metrics\n",
    "    \n",
    "results_df = pd.DataFrame(results).T\n",
    "print(\"\\n\\n--- Итоговая таблица сравнения моделей на тестовых данных ---\")\n",
    "print(results_df.to_string())\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Снимали тут на \"игрушечных данных\". На даже на них видно, что:\n",
    " - accuracy выше всего на Mamba\n",
    " - Трансформер справился тоже неплохо\n",
    " - LSTM опять проиграл\n",
    "\n",
    "В следующем нотбуке обучим Mamba и Transformer на всем датасете и снимем качество на втором. Та модель, которая будет лучше, \"поедет в продакшн\" "
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "monkey-coding-dl-project-F4QJzkF_-py3.12",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}