File size: 15,884 Bytes
706a395
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "8d37f81d",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/Users/ivancarevic/Library/Python/3.9/lib/python/site-packages/urllib3/__init__.py:35: NotOpenSSLWarning: urllib3 v2 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'LibreSSL 2.8.3'. See: https://github.com/urllib3/urllib3/issues/3020\n",
      "  warnings.warn(\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "LSTM training...\n",
      "LSTM Epoch 1: Train loss 0.9166 | Validation loss 0.9009\n",
      "LSTM Epoch 5: Train loss 0.9075 | Validation loss 0.8981\n",
      "LSTM Epoch 10: Train loss 0.9015 | Validation loss 0.8975\n",
      "LSTM Epoch 15: Train loss 0.9015 | Validation loss 0.8989\n",
      "LSTM Epoch 20: Train loss 0.9000 | Validation loss 0.8957\n",
      "LSTM Epoch 25: Train loss 0.8955 | Validation loss 0.8964\n",
      "LSTM Epoch 30: Train loss 0.8940 | Validation loss 0.8950\n",
      "LSTM Epoch 35: Train loss 0.8903 | Validation loss 0.8952\n",
      "LSTM Epoch 40: Train loss 0.8852 | Validation loss 0.8968\n",
      "LSTM Epoch 45: Train loss 0.8830 | Validation loss 0.8928\n",
      "LSTM Epoch 50: Train loss 0.8804 | Validation loss 0.8953\n",
      "\n",
      "LSTM Classification report:\n",
      "               precision    recall  f1-score   support\n",
      "\n",
      "    positive     1.0000    0.0139    0.0274       216\n",
      "     neutral     0.5880    1.0000    0.7405       431\n",
      "    negative     1.0000    0.0532    0.1010        94\n",
      "\n",
      "    accuracy                         0.5924       741\n",
      "   macro avg     0.8627    0.3557    0.2897       741\n",
      "weighted avg     0.7604    0.5924    0.4515       741\n",
      "\n",
      "LSTM Confusion matrix:\n",
      " [[  3 213   0]\n",
      " [  0 431   0]\n",
      " [  0  89   5]]\n",
      "\n",
      "GRU training...\n",
      "GRU Epoch 1: Train loss 0.9175 | Validation loss 0.8988\n",
      "GRU Epoch 5: Train loss 0.9083 | Validation loss 0.8972\n",
      "GRU Epoch 10: Train loss 0.8926 | Validation loss 0.8841\n",
      "GRU Epoch 15: Train loss 0.7687 | Validation loss 0.8025\n",
      "GRU Epoch 20: Train loss 0.7075 | Validation loss 0.7651\n",
      "GRU Epoch 25: Train loss 0.6198 | Validation loss 0.8362\n",
      "GRU Epoch 30: Train loss 0.4990 | Validation loss 0.9217\n",
      "GRU Epoch 35: Train loss 0.3581 | Validation loss 1.2447\n",
      "GRU Epoch 40: Train loss 0.2617 | Validation loss 1.4024\n",
      "GRU Epoch 45: Train loss 0.1703 | Validation loss 1.6796\n",
      "GRU Epoch 50: Train loss 0.1398 | Validation loss 1.7962\n",
      "\n",
      "GRU Classification report:\n",
      "               precision    recall  f1-score   support\n",
      "\n",
      "    positive     0.8818    0.8287    0.8544       216\n",
      "     neutral     0.8824    0.9397    0.9101       431\n",
      "    negative     0.8228    0.6915    0.7514        94\n",
      "\n",
      "    accuracy                         0.8758       741\n",
      "   macro avg     0.8623    0.8200    0.8387       741\n",
      "weighted avg     0.8746    0.8758    0.8737       741\n",
      "\n",
      "GRU Confusion matrix:\n",
      " [[179  32   5]\n",
      " [ 17 405   9]\n",
      " [  7  22  65]]\n",
      "\n",
      "CNN training...\n",
      "CNN Epoch 1: Train loss 0.9127 | Validation loss 0.8888\n",
      "CNN Epoch 5: Train loss 0.8167 | Validation loss 0.8061\n",
      "CNN Epoch 10: Train loss 0.7162 | Validation loss 0.7756\n",
      "CNN Epoch 15: Train loss 0.6233 | Validation loss 0.7725\n",
      "CNN Epoch 20: Train loss 0.5443 | Validation loss 0.7931\n",
      "CNN Epoch 25: Train loss 0.4808 | Validation loss 0.7701\n",
      "CNN Epoch 30: Train loss 0.4096 | Validation loss 0.8236\n",
      "CNN Epoch 35: Train loss 0.3591 | Validation loss 0.8460\n",
      "CNN Epoch 40: Train loss 0.3101 | Validation loss 0.8653\n",
      "CNN Epoch 45: Train loss 0.2801 | Validation loss 0.8993\n",
      "CNN Epoch 50: Train loss 0.2406 | Validation loss 0.9453\n",
      "\n",
      "CNN Classification report:\n",
      "               precision    recall  f1-score   support\n",
      "\n",
      "    positive     0.9045    0.8333    0.8675       216\n",
      "     neutral     0.8842    0.9745    0.9272       431\n",
      "    negative     0.9552    0.6809    0.7950        94\n",
      "\n",
      "    accuracy                         0.8961       741\n",
      "   macro avg     0.9147    0.8296    0.8632       741\n",
      "weighted avg     0.8991    0.8961    0.8930       741\n",
      "\n",
      "CNN Confusion matrix:\n",
      " [[180  35   1]\n",
      " [  9 420   2]\n",
      " [ 10  20  64]]\n"
     ]
    }
   ],
   "source": [
    "# !pip install gensim scikit-learn pandas numpy torch tqdm\n",
    "\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "from torch.utils.data import Dataset, DataLoader\n",
    "from sklearn.metrics import classification_report, confusion_matrix\n",
    "from sklearn.model_selection import train_test_split\n",
    "from collections import Counter\n",
    "import gensim\n",
    "\n",
    "# --- UČITAVANJE I PODJELA PODATAKA ---\n",
    "full_df = pd.read_csv('TRAIN.csv')\n",
    "test2_df = pd.read_csv('test-2.csv')\n",
    "\n",
    "def get_text_column(df):\n",
    "    for col in df.columns:\n",
    "        if col.lower() in ['sentence', 'text']:\n",
    "            return col\n",
    "    raise ValueError(\"Nema stupca 'Sentence' ili 'Text'!\")\n",
    "\n",
    "text_col = get_text_column(full_df)\n",
    "\n",
    "# Stratified split: 95% train, 5% valid\n",
    "train_df, valid_df = train_test_split(full_df, test_size=0.05, stratify=full_df['Label'], random_state=42)\n",
    "\n",
    "# --- TOKENIZACIJA I VOKABULAR ---\n",
    "def tokenize(text):\n",
    "    return text.lower().split()\n",
    "\n",
    "counter = Counter()\n",
    "for text in train_df[text_col]:\n",
    "    counter.update(tokenize(text))\n",
    "vocab = {word: idx+2 for idx, (word, _) in enumerate(counter.most_common())}\n",
    "vocab['<unk>'] = 0\n",
    "vocab['<pad>'] = 1\n",
    "\n",
    "# --- EMBEDDING ---\n",
    "from gensim.models.fasttext import load_facebook_model\n",
    "\n",
    "embedding_path = 'cc.hr.300.bin'\n",
    "ft_model = load_facebook_model(embedding_path)\n",
    "embeddings = ft_model.wv  \n",
    "\n",
    "embedding_dim = embeddings.vector_size\n",
    "embedding_matrix = np.zeros((len(vocab), embedding_dim))\n",
    "for word, idx in vocab.items():\n",
    "    if word in embeddings:\n",
    "        embedding_matrix[idx] = embeddings[word]\n",
    "    else:\n",
    "        embedding_matrix[idx] = np.random.normal(scale=0.6, size=(embedding_dim, ))\n",
    "\n",
    "# --- DATASET ---\n",
    "class TextDataset(Dataset):\n",
    "    def __init__(self, df, text_col, vocab, max_len=50):\n",
    "        self.texts = df[text_col].tolist()\n",
    "        self.labels = df['Label'].tolist()\n",
    "        self.vocab = vocab\n",
    "        self.max_len = max_len\n",
    "    def __len__(self):\n",
    "        return len(self.texts)\n",
    "    def __getitem__(self, idx):\n",
    "        tokens = tokenize(self.texts[idx])\n",
    "        ids = [self.vocab.get(token, self.vocab['<unk>']) for token in tokens][:self.max_len]\n",
    "        ids += [self.vocab['<pad>']] * (self.max_len - len(ids))\n",
    "        return torch.tensor(ids), torch.tensor(self.labels[idx])\n",
    "\n",
    "max_len = 50\n",
    "batch_size = 32\n",
    "train_ds = TextDataset(train_df, text_col, vocab, max_len)\n",
    "valid_ds = TextDataset(valid_df, text_col, vocab, max_len)\n",
    "test2_text_col = get_text_column(test2_df)\n",
    "test2_ds = TextDataset(test2_df, test2_text_col, vocab, max_len)\n",
    "\n",
    "train_dl = DataLoader(train_ds, batch_size=batch_size, shuffle=True)\n",
    "valid_dl = DataLoader(valid_ds, batch_size=batch_size)\n",
    "test2_dl = DataLoader(test2_ds, batch_size=batch_size)\n",
    "\n",
    "# --- MODELI ---\n",
    "class LSTMClassifier(nn.Module):\n",
    "    def __init__(self, embedding_matrix, hidden_dim=256, num_classes=3, dropout=0.8):\n",
    "        super().__init__()\n",
    "        num_embeddings, embedding_dim = embedding_matrix.shape\n",
    "        self.embedding = nn.Embedding(num_embeddings, embedding_dim)\n",
    "        self.embedding.weight.data.copy_(torch.from_numpy(embedding_matrix))\n",
    "        self.embedding.weight.requires_grad = False\n",
    "        self.lstm = nn.LSTM(embedding_dim, hidden_dim, batch_first=True)\n",
    "        self.dropout = nn.Dropout(dropout)\n",
    "        self.fc = nn.Linear(hidden_dim, num_classes)\n",
    "    def forward(self, x):\n",
    "        x = self.embedding(x)\n",
    "        _, (hidden, _) = self.lstm(x)\n",
    "        out = self.dropout(hidden[-1])\n",
    "        return self.fc(out)\n",
    "\n",
    "class GRUClassifier(nn.Module):\n",
    "    def __init__(self, embedding_matrix, hidden_dim=256, num_classes=3, dropout=0.8):\n",
    "        super().__init__()\n",
    "        num_embeddings, embedding_dim = embedding_matrix.shape\n",
    "        self.embedding = nn.Embedding(num_embeddings, embedding_dim)\n",
    "        self.embedding.weight.data.copy_(torch.from_numpy(embedding_matrix))\n",
    "        self.embedding.weight.requires_grad = False\n",
    "        self.gru = nn.GRU(embedding_dim, hidden_dim, batch_first=True)\n",
    "        self.dropout = nn.Dropout(dropout)\n",
    "        self.fc = nn.Linear(hidden_dim, num_classes)\n",
    "    def forward(self, x):\n",
    "        x = self.embedding(x)\n",
    "        _, hidden = self.gru(x)\n",
    "        out = self.dropout(hidden[-1])\n",
    "        return self.fc(out)\n",
    "\n",
    "class CNNClassifier(nn.Module):\n",
    "    def __init__(self, embedding_matrix, num_filters=128, kernel_sizes=[3,4,5], num_classes=3, dropout=0.8):\n",
    "        super().__init__()\n",
    "        num_embeddings, embedding_dim = embedding_matrix.shape\n",
    "        self.embedding = nn.Embedding(num_embeddings, embedding_dim)\n",
    "        self.embedding.weight.data.copy_(torch.from_numpy(embedding_matrix))\n",
    "        self.embedding.weight.requires_grad = False\n",
    "        self.convs = nn.ModuleList([\n",
    "            nn.Conv2d(1, num_filters, (k, embedding_dim)) for k in kernel_sizes\n",
    "        ])\n",
    "        self.dropout = nn.Dropout(dropout)\n",
    "        self.fc = nn.Linear(num_filters * len(kernel_sizes), num_classes)\n",
    "    def forward(self, x):\n",
    "        x = self.embedding(x)\n",
    "        x = x.unsqueeze(1)\n",
    "        x = [torch.relu(conv(x)).squeeze(3) for conv in self.convs]\n",
    "        x = [torch.max(pool, dim=2)[0] for pool in x]\n",
    "        x = torch.cat(x, dim=1)\n",
    "        x = self.dropout(x)\n",
    "        return self.fc(x)\n",
    "\n",
    "# --- TRENING I VALIDACIJA ---\n",
    "def train_epoch(model, dataloader, optimizer, criterion, device):\n",
    "    model.train()\n",
    "    total_loss = 0\n",
    "    for x, y in dataloader:\n",
    "        x, y = x.to(device), y.to(device)\n",
    "        optimizer.zero_grad()\n",
    "        logits = model(x)\n",
    "        loss = criterion(logits, y)\n",
    "        loss.backward()\n",
    "        optimizer.step()\n",
    "        total_loss += loss.item()\n",
    "    return total_loss / len(dataloader)\n",
    "\n",
    "def eval_model(model, dataloader, device, criterion=None, return_loss=False):\n",
    "    model.eval()\n",
    "    preds, targets = [], []\n",
    "    total_loss = 0\n",
    "    with torch.no_grad():\n",
    "        for x, y in dataloader:\n",
    "            x, y = x.to(device), y.to(device)\n",
    "            logits = model(x)\n",
    "            if criterion and return_loss:\n",
    "                loss = criterion(logits, y)\n",
    "                total_loss += loss.item()\n",
    "            pred = logits.argmax(1).cpu().numpy()\n",
    "            preds.extend(pred)\n",
    "            targets.extend(y.cpu().numpy())\n",
    "    if return_loss and criterion:\n",
    "        return np.array(preds), np.array(targets), total_loss / len(dataloader)\n",
    "    return np.array(preds), np.array(targets)\n",
    "\n",
    "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n",
    "\n",
    "def run_training(model_class, name, epochs=50, dropout=0.8, lr=5e-4):\n",
    "    print(f\"\\n{name} training...\")\n",
    "    model = model_class(embedding_matrix, dropout=dropout).to(device)\n",
    "    optimizer = torch.optim.Adam(model.parameters(), lr=lr)\n",
    "    criterion = nn.CrossEntropyLoss()\n",
    "    for epoch in range(epochs):\n",
    "        train_loss = train_epoch(model, train_dl, optimizer, criterion, device)\n",
    "        _, _, val_loss = eval_model(model, valid_dl, device, criterion, return_loss=True)\n",
    "        if (epoch+1) % 5 == 0 or epoch == 0:\n",
    "            print(f\"{name} Epoch {epoch+1}: Train loss {train_loss:.4f} | Validation loss {val_loss:.4f}\")\n",
    "    preds, targets = eval_model(model, test2_dl, device)\n",
    "    report = classification_report(targets, preds, digits=4, output_dict=True, target_names=[\"positive\", \"neutral\", \"negative\"])\n",
    "    matrix = confusion_matrix(targets, preds)\n",
    "    print(f\"\\n{name} Classification report:\\n\", classification_report(targets, preds, digits=4, target_names=[\"positive\", \"neutral\", \"negative\"]))\n",
    "    print(f\"{name} Confusion matrix:\\n\", matrix)\n",
    "    return {\n",
    "        'precision': report['macro avg']['precision'],\n",
    "        'recall': report['macro avg']['recall'],\n",
    "        'f1': report['macro avg']['f1-score'],\n",
    "        'accuracy': report['accuracy'],\n",
    "        'confusion_matrix': matrix.tolist(),\n",
    "        'full_report': classification_report(targets, preds, digits=4, target_names=[\"positive\", \"neutral\", \"negative\"])\n",
    "    }\n",
    "\n",
    "# --- POKRETANJE ---\n",
    "lstm_results = run_training(LSTMClassifier, \"LSTM\", epochs=50, dropout=0.8, lr=5e-4)\n",
    "gru_results = run_training(GRUClassifier, \"GRU\", epochs=50, dropout=0.8, lr=5e-4)\n",
    "cnn_results = run_training(CNNClassifier, \"CNN\", epochs=50, dropout=0.8, lr=5e-4)\n",
    "\n",
    "# --- SPREMANJE ---\n",
    "with open('results.md', 'w', encoding='utf-8') as f:\n",
    "    for model_name, results in [('LSTM', lstm_results), ('GRU', gru_results), ('CNN', cnn_results)]:\n",
    "        f.write(f\"## {model_name}\\n\\n\")\n",
    "        f.write(f\"- Precision: {results['precision']:.4f}\\n\")\n",
    "        f.write(f\"- Recall: {results['recall']:.4f}\\n\")\n",
    "        f.write(f\"- F1: {results['f1']:.4f}\\n\")\n",
    "        f.write(f\"- Accuracy: {results['accuracy']:.4f}\\n\")\n",
    "        f.write(f\"- Confusion matrix: {results['confusion_matrix']}\\n\\n\")\n",
    "        f.write(f\"Full classification report:\\n{results['full_report']}\\n\\n\")\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "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.9.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}