Upload 4 files
Browse files- GRU/GRU+fasttext.py +221 -0
- GRU/LSTM+fasttext.py +205 -0
- GRU/croatian_gru (2).pt +3 -0
- GRU/vokabular_gru (1).pkl +3 -0
GRU/GRU+fasttext.py
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import collections
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import numpy as np
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
import torch.optim as optim
|
| 7 |
+
import tqdm
|
| 8 |
+
from sklearn.model_selection import StratifiedGroupKFold
|
| 9 |
+
from sklearn.metrics import accuracy_score, precision_recall_fscore_support, confusion_matrix
|
| 10 |
+
import os
|
| 11 |
+
import pickle
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
seed = 1234
|
| 15 |
+
np.random.seed(seed)
|
| 16 |
+
torch.manual_seed(seed)
|
| 17 |
+
torch.cuda.manual_seed(seed)
|
| 18 |
+
torch.backends.cudnn.deterministic = True
|
| 19 |
+
|
| 20 |
+
# 1. Load and Clean Dataset
|
| 21 |
+
df = pd.read_csv("Projekt1.csv", sep=";")
|
| 22 |
+
df = df[["review_id", "text", "label"]].dropna()
|
| 23 |
+
df["label"] = df["label"].str.lower().str.strip()
|
| 24 |
+
|
| 25 |
+
# Map the 5 Croatian classes
|
| 26 |
+
label_mapping = {"negative": 0, "neutral": 1, "positive": 2, "mixed": 3, "sarcasm": 4}
|
| 27 |
+
df["label"] = df["label"].map(label_mapping)
|
| 28 |
+
df = df.dropna().reset_index(drop=True)
|
| 29 |
+
|
| 30 |
+
# 2. 80% Train -> 20% Val, 20% Test
|
| 31 |
+
sgkf = StratifiedGroupKFold(n_splits=5, shuffle=True, random_state=seed)
|
| 32 |
+
train_idx, test_idx = next(sgkf.split(df,y=df["label"], groups=df["review_id"]))
|
| 33 |
+
df_train_tmp, df_test = df.iloc[train_idx], df.iloc[test_idx]
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
sgkf2 = StratifiedGroupKFold(n_splits=5, shuffle=True, random_state=seed)
|
| 37 |
+
final_train_idx, val_idx = next(sgkf2.split(df_train_tmp,y=df_train_tmp["label"],groups=df_train_tmp["review_id"]))
|
| 38 |
+
df_train = df_train_tmp.iloc[final_train_idx].reset_index(drop=True)
|
| 39 |
+
df_val = df_train_tmp.iloc[val_idx].reset_index(drop=True)
|
| 40 |
+
df_test = df_test.reset_index(drop=True)
|
| 41 |
+
|
| 42 |
+
# 3. Simple Tokenization & Vocab Build (Closest to your original style)
|
| 43 |
+
def tokenizer(text):
|
| 44 |
+
return str(text).lower().split()
|
| 45 |
+
|
| 46 |
+
max_length = 256
|
| 47 |
+
min_freq = 5
|
| 48 |
+
special_tokens = ["<unk>", "<pad>"]
|
| 49 |
+
|
| 50 |
+
# Build vocab from training tokens
|
| 51 |
+
token_counts = collections.Counter([tok for text in df_train["text"] for tok in tokenizer(text)])
|
| 52 |
+
vocab_words = [word for word, freq in token_counts.items() if freq >= min_freq]
|
| 53 |
+
vocab = special_tokens + vocab_words
|
| 54 |
+
|
| 55 |
+
word_to_id = {word: idx for idx, word in enumerate(vocab)}
|
| 56 |
+
unk_index, pad_index = word_to_id["<unk>"], word_to_id["<pad>"]
|
| 57 |
+
|
| 58 |
+
# 4. Numericalize Dataset
|
| 59 |
+
def process_dataset(dataframe):
|
| 60 |
+
data = []
|
| 61 |
+
for _, row in dataframe.iterrows():
|
| 62 |
+
tokens = tokenizer(row["text"])[:max_length]
|
| 63 |
+
length = max(len(tokens), 1) # Prevent 0 length crashes
|
| 64 |
+
ids = [word_to_id.get(tok, unk_index) for tok in tokens]
|
| 65 |
+
data.append({"ids": torch.tensor(ids, dtype=torch.long),
|
| 66 |
+
"length": torch.tensor(length),
|
| 67 |
+
"label": torch.tensor(row["label"], dtype=torch.long)})
|
| 68 |
+
return data
|
| 69 |
+
|
| 70 |
+
train_data = process_dataset(df_train)
|
| 71 |
+
valid_data = process_dataset(df_val)
|
| 72 |
+
test_data = process_dataset(df_test)
|
| 73 |
+
|
| 74 |
+
# 5. Collate and Data Loaders (Exactly like your original style)
|
| 75 |
+
def get_collate_fn(pad_index):
|
| 76 |
+
def collate_fn(batch):
|
| 77 |
+
batch_ids = nn.utils.rnn.pad_sequence([i["ids"] for i in batch], padding_value=pad_index, batch_first=True)
|
| 78 |
+
batch_length = torch.stack([i["length"] for i in batch])
|
| 79 |
+
batch_label = torch.stack([i["label"] for i in batch])
|
| 80 |
+
return {"ids": batch_ids, "length": batch_length, "label": batch_label}
|
| 81 |
+
return collate_fn
|
| 82 |
+
|
| 83 |
+
batch_size = 256
|
| 84 |
+
collate_fn = get_collate_fn(pad_index)
|
| 85 |
+
|
| 86 |
+
train_data_loader = torch.utils.data.DataLoader(train_data, batch_size=batch_size, shuffle=True, collate_fn=collate_fn)
|
| 87 |
+
valid_data_loader = torch.utils.data.DataLoader(valid_data, batch_size=batch_size, collate_fn=collate_fn)
|
| 88 |
+
test_data_loader = torch.utils.data.DataLoader(test_data, batch_size=batch_size, collate_fn=collate_fn)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
class GRU(nn.Module):
|
| 92 |
+
def __init__(self, vocab_size, embedding_dim, hidden_dim, output_dim, n_layers, bidirectional, dropout_rate, pad_index):
|
| 93 |
+
super().__init__()
|
| 94 |
+
self.embedding = nn.Embedding(vocab_size, embedding_dim, padding_idx=pad_index)
|
| 95 |
+
|
| 96 |
+
self.rnn = nn.GRU(embedding_dim, hidden_dim, n_layers, bidirectional=bidirectional, dropout=dropout_rate if n_layers > 1 else 0, batch_first=True)
|
| 97 |
+
self.fc = nn.Linear(hidden_dim * 2 if bidirectional else hidden_dim, output_dim)
|
| 98 |
+
self.dropout = nn.Dropout(dropout_rate)
|
| 99 |
+
|
| 100 |
+
def forward(self, ids, length):
|
| 101 |
+
embedded = self.dropout(self.embedding(ids))
|
| 102 |
+
packed_embedded = nn.utils.rnn.pack_padded_sequence(embedded, length.to("cpu"), batch_first=True, enforce_sorted=False)
|
| 103 |
+
packed_output, hidden = self.rnn(packed_embedded)
|
| 104 |
+
|
| 105 |
+
if self.rnn.bidirectional:
|
| 106 |
+
hidden = self.dropout(torch.cat([hidden[-1], hidden[-2]], dim=-1))
|
| 107 |
+
else:
|
| 108 |
+
hidden = self.dropout(hidden[-1])
|
| 109 |
+
return self.fc(hidden)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
model = GRU(len(vocab), 300, 256, 5, 2, True, 0.5, pad_index)
|
| 113 |
+
|
| 114 |
+
# 7. Simplified FastText Loading
|
| 115 |
+
try:
|
| 116 |
+
with open("cc.hr.300.vec", "r", encoding="utf-8") as f:
|
| 117 |
+
next(f) # Skip header
|
| 118 |
+
ft_embeddings = {}
|
| 119 |
+
for line in f:
|
| 120 |
+
parts = line.strip().split(" ")
|
| 121 |
+
ft_embeddings[parts[0]] = np.array(parts[1:], dtype=np.float32)
|
| 122 |
+
|
| 123 |
+
weights = np.random.normal(scale=0.6, size=(len(vocab), 300))
|
| 124 |
+
for idx, word in enumerate(vocab):
|
| 125 |
+
if word in ft_embeddings:
|
| 126 |
+
weights[idx] = ft_embeddings[word]
|
| 127 |
+
weights[pad_index] = np.zeros(300)
|
| 128 |
+
model.embedding.weight.data.copy_(torch.from_numpy(weights))
|
| 129 |
+
print("FastText Embeddings Loaded!")
|
| 130 |
+
except FileNotFoundError:
|
| 131 |
+
print("FastText file not found. Training with random weights.")
|
| 132 |
+
|
| 133 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 134 |
+
optimizer = optim.Adam(model.parameters(), lr=5e-4)
|
| 135 |
+
criterion = nn.CrossEntropyLoss().to(device)
|
| 136 |
+
model = model.to(device)
|
| 137 |
+
|
| 138 |
+
# 8. Updated Metrics Engine (Accuracy, Precision, Recall, F1)
|
| 139 |
+
def compute_metrics(all_preds, all_labels):
|
| 140 |
+
preds = np.concatenate(all_preds)
|
| 141 |
+
labels = np.concatenate(all_labels)
|
| 142 |
+
acc = accuracy_score(labels, preds)
|
| 143 |
+
prec, rec, f1, _ = precision_recall_fscore_support(labels, preds, average="weighted", zero_division=0)
|
| 144 |
+
cm = confusion_matrix(labels, preds, labels=[0, 1, 2, 3, 4])
|
| 145 |
+
|
| 146 |
+
return acc, prec, rec, f1,cm
|
| 147 |
+
|
| 148 |
+
# 9. Train and Evaluate Functions
|
| 149 |
+
def run_epoch(dataloader, model, criterion, optimizer=None, is_train=True):
|
| 150 |
+
if is_train:
|
| 151 |
+
model.train()
|
| 152 |
+
else:
|
| 153 |
+
model.eval()
|
| 154 |
+
|
| 155 |
+
epoch_losses = []
|
| 156 |
+
all_preds, all_labels = [], []
|
| 157 |
+
|
| 158 |
+
context = torch.enable_grad() if is_train else torch.no_grad()
|
| 159 |
+
with context:
|
| 160 |
+
for batch in tqdm.tqdm(dataloader, desc="Processing..."):
|
| 161 |
+
ids = batch["ids"].to(device)
|
| 162 |
+
length = batch["length"]
|
| 163 |
+
label = batch["label"].to(device)
|
| 164 |
+
|
| 165 |
+
prediction = model(ids, length)
|
| 166 |
+
loss = criterion(prediction, label)
|
| 167 |
+
|
| 168 |
+
if is_train:
|
| 169 |
+
optimizer.zero_grad()
|
| 170 |
+
loss.backward()
|
| 171 |
+
optimizer.step()
|
| 172 |
+
|
| 173 |
+
epoch_losses.append(loss.item())
|
| 174 |
+
all_preds.append(prediction.argmax(dim=-1).cpu().numpy())
|
| 175 |
+
all_labels.append(label.cpu().numpy())
|
| 176 |
+
|
| 177 |
+
acc, prec, rec, f1,cm = compute_metrics(all_preds, all_labels)
|
| 178 |
+
return np.mean(epoch_losses), acc, prec, rec, f1,cm
|
| 179 |
+
|
| 180 |
+
# 10. Training Loop
|
| 181 |
+
n_epochs = 10
|
| 182 |
+
best_valid_loss = float("inf")
|
| 183 |
+
|
| 184 |
+
for epoch in range(n_epochs):
|
| 185 |
+
train_loss, train_acc, _, _, train_f1, _ = run_epoch(train_data_loader, model, criterion, optimizer, is_train=True)
|
| 186 |
+
valid_loss, valid_acc, _, _, valid_f1, _ = run_epoch(valid_data_loader, model, criterion, is_train=False)
|
| 187 |
+
|
| 188 |
+
if valid_loss < best_valid_loss:
|
| 189 |
+
best_valid_loss = valid_loss
|
| 190 |
+
|
| 191 |
+
torch.save(model.state_dict(), "croatian_gru.pt")
|
| 192 |
+
|
| 193 |
+
with open("vokabular_gru.pkl", "wb") as f:
|
| 194 |
+
pickle.dump({
|
| 195 |
+
"word_to_id": word_to_id,
|
| 196 |
+
"label_mapping": label_mapping,
|
| 197 |
+
"max_length": max_length,
|
| 198 |
+
"unk_index": unk_index,
|
| 199 |
+
"pad_index": pad_index
|
| 200 |
+
}, f)
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
print(f"Epoch: {epoch+1} | Train Loss: {train_loss:.3f} | Train Acc: {train_acc*100:.1f}% | Train F1: {train_f1:.2f}")
|
| 204 |
+
print(f"Val Loss: {valid_loss:.3f} | Val Acc: {valid_acc*100:.1f}% | Val F1: {valid_f1:.2f}")
|
| 205 |
+
|
| 206 |
+
# 11. Final Test Evaluation
|
| 207 |
+
model.load_state_dict(torch.load("croatian_gru.pt"))
|
| 208 |
+
test_loss, test_acc, test_prec, test_rec, test_f1, test_cm = run_epoch(test_data_loader, model, criterion, is_train=False)
|
| 209 |
+
|
| 210 |
+
print("\n=== FINAL TEST METRICS ===")
|
| 211 |
+
print(f"Accuracy: {test_acc*100:.2f}%")
|
| 212 |
+
print(f"Precision: {test_prec:.3f}")
|
| 213 |
+
print(f"Recall: {test_rec:.3f}")
|
| 214 |
+
print(f"F1-Score: {test_f1:.3f}")
|
| 215 |
+
|
| 216 |
+
label_list = ["negative", "neutral", "positive", "mixed", "sarcasm"]
|
| 217 |
+
print("\nConfusion matrix:")
|
| 218 |
+
print(" " * 12 + " ".join(f"{lbl:10}" for lbl in label_list))
|
| 219 |
+
for i, lbl in enumerate(label_list):
|
| 220 |
+
print(f"{lbl:12} " + " ".join(f"{test_cm[i, j]:10d}" for j in range(len(label_list))))
|
| 221 |
+
|
GRU/LSTM+fasttext.py
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import collections
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import numpy as np
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
import torch.optim as optim
|
| 7 |
+
import tqdm
|
| 8 |
+
from sklearn.model_selection import StratifiedGroupKFold
|
| 9 |
+
from sklearn.metrics import accuracy_score, precision_recall_fscore_support, confusion_matrix
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
seed = 1234
|
| 13 |
+
np.random.seed(seed)
|
| 14 |
+
torch.manual_seed(seed)
|
| 15 |
+
torch.cuda.manual_seed(seed)
|
| 16 |
+
torch.backends.cudnn.deterministic = True
|
| 17 |
+
|
| 18 |
+
# 1. Load and Clean Dataset
|
| 19 |
+
df = pd.read_csv("Projekt1.csv", sep=";")
|
| 20 |
+
df = df[["review_id", "text", "label"]].dropna()
|
| 21 |
+
df["label"] = df["label"].str.lower().str.strip()
|
| 22 |
+
|
| 23 |
+
# Map the 5 Croatian classes
|
| 24 |
+
label_mapping = {"negative": 0, "neutral": 1, "positive": 2, "mixed": 3, "sarcasm": 4}
|
| 25 |
+
df["label"] = df["label"].map(label_mapping)
|
| 26 |
+
df = df.dropna().reset_index(drop=True)
|
| 27 |
+
|
| 28 |
+
# 2. 80% Train -> 20% Val, 20% Test
|
| 29 |
+
sgkf = StratifiedGroupKFold(n_splits=5, shuffle=True, random_state=seed)
|
| 30 |
+
train_idx, test_idx = next(sgkf.split(df,y=df["label"], groups=df["review_id"]))
|
| 31 |
+
df_train_tmp, df_test = df.iloc[train_idx], df.iloc[test_idx]
|
| 32 |
+
|
| 33 |
+
sgkf2 = StratifiedGroupKFold(n_splits=5, shuffle=True, random_state=seed)
|
| 34 |
+
final_train_idx, val_idx = next(sgkf2.split(df_train_tmp,y=df_train_tmp["label"],groups=df_train_tmp["review_id"]))
|
| 35 |
+
df_train = df_train_tmp.iloc[final_train_idx].reset_index(drop=True)
|
| 36 |
+
df_val = df_train_tmp.iloc[val_idx].reset_index(drop=True)
|
| 37 |
+
df_test = df_test.reset_index(drop=True)
|
| 38 |
+
|
| 39 |
+
# 3. Simple Tokenization & Vocab Build (Closest to your original style)
|
| 40 |
+
def tokenizer(text):
|
| 41 |
+
return str(text).lower().split()
|
| 42 |
+
|
| 43 |
+
max_length = 256
|
| 44 |
+
min_freq = 5
|
| 45 |
+
special_tokens = ["<unk>", "<pad>"]
|
| 46 |
+
|
| 47 |
+
# Build vocab from training tokens
|
| 48 |
+
token_counts = collections.Counter([tok for text in df_train["text"] for tok in tokenizer(text)])
|
| 49 |
+
vocab_words = [word for word, freq in token_counts.items() if freq >= min_freq]
|
| 50 |
+
vocab = special_tokens + vocab_words
|
| 51 |
+
|
| 52 |
+
word_to_id = {word: idx for idx, word in enumerate(vocab)}
|
| 53 |
+
unk_index, pad_index = word_to_id["<unk>"], word_to_id["<pad>"]
|
| 54 |
+
|
| 55 |
+
# 4. Numericalize Dataset
|
| 56 |
+
def process_dataset(dataframe):
|
| 57 |
+
data = []
|
| 58 |
+
for _, row in dataframe.iterrows():
|
| 59 |
+
tokens = tokenizer(row["text"])[:max_length]
|
| 60 |
+
length = max(len(tokens), 1) # Prevent 0 length crashes
|
| 61 |
+
ids = [word_to_id.get(tok, unk_index) for tok in tokens]
|
| 62 |
+
data.append({"ids": torch.tensor(ids, dtype=torch.long),
|
| 63 |
+
"length": torch.tensor(length),
|
| 64 |
+
"label": torch.tensor(row["label"], dtype=torch.long)})
|
| 65 |
+
return data
|
| 66 |
+
|
| 67 |
+
train_data = process_dataset(df_train)
|
| 68 |
+
valid_data = process_dataset(df_val)
|
| 69 |
+
test_data = process_dataset(df_test)
|
| 70 |
+
|
| 71 |
+
# 5. Collate and Data Loaders (Exactly like your original style)
|
| 72 |
+
def get_collate_fn(pad_index):
|
| 73 |
+
def collate_fn(batch):
|
| 74 |
+
batch_ids = nn.utils.rnn.pad_sequence([i["ids"] for i in batch], padding_value=pad_index, batch_first=True)
|
| 75 |
+
batch_length = torch.stack([i["length"] for i in batch])
|
| 76 |
+
batch_label = torch.stack([i["label"] for i in batch])
|
| 77 |
+
return {"ids": batch_ids, "length": batch_length, "label": batch_label}
|
| 78 |
+
return collate_fn
|
| 79 |
+
|
| 80 |
+
batch_size = 256
|
| 81 |
+
collate_fn = get_collate_fn(pad_index)
|
| 82 |
+
|
| 83 |
+
train_data_loader = torch.utils.data.DataLoader(train_data, batch_size=batch_size, shuffle=True, collate_fn=collate_fn)
|
| 84 |
+
valid_data_loader = torch.utils.data.DataLoader(valid_data, batch_size=batch_size, collate_fn=collate_fn)
|
| 85 |
+
test_data_loader = torch.utils.data.DataLoader(test_data, batch_size=batch_size, collate_fn=collate_fn)
|
| 86 |
+
|
| 87 |
+
# 6. LSTM Model Architecture
|
| 88 |
+
class LSTM(nn.Module):
|
| 89 |
+
def __init__(self, vocab_size, embedding_dim, hidden_dim, output_dim, n_layers, bidirectional, dropout_rate, pad_index):
|
| 90 |
+
super().__init__()
|
| 91 |
+
self.embedding = nn.Embedding(vocab_size, embedding_dim, padding_idx=pad_index)
|
| 92 |
+
self.lstm = nn.LSTM(embedding_dim, hidden_dim, n_layers, bidirectional=bidirectional, dropout=dropout_rate if n_layers > 1 else 0, batch_first=True)
|
| 93 |
+
self.fc = nn.Linear(hidden_dim * 2 if bidirectional else hidden_dim, output_dim)
|
| 94 |
+
self.dropout = nn.Dropout(dropout_rate)
|
| 95 |
+
|
| 96 |
+
def forward(self, ids, length):
|
| 97 |
+
embedded = self.dropout(self.embedding(ids))
|
| 98 |
+
packed_embedded = nn.utils.rnn.pack_padded_sequence(embedded, length.to("cpu"), batch_first=True, enforce_sorted=False)
|
| 99 |
+
packed_output, (hidden, cell) = self.lstm(packed_embedded)
|
| 100 |
+
|
| 101 |
+
if self.lstm.bidirectional:
|
| 102 |
+
hidden = self.dropout(torch.cat([hidden[-1], hidden[-2]], dim=-1))
|
| 103 |
+
else:
|
| 104 |
+
hidden = self.dropout(hidden[-1])
|
| 105 |
+
return self.fc(hidden)
|
| 106 |
+
|
| 107 |
+
# Initialize Model (5 output classes)
|
| 108 |
+
model = LSTM(len(vocab), 300, 256, 5, 2, True, 0.5, pad_index)
|
| 109 |
+
|
| 110 |
+
# 7. Simplified FastText Loading
|
| 111 |
+
# Place your 'cc.hr.300.vec' file in the same folder
|
| 112 |
+
try:
|
| 113 |
+
with open("cc.hr.300.vec", "r", encoding="utf-8") as f:
|
| 114 |
+
next(f) # Skip header
|
| 115 |
+
ft_embeddings = {}
|
| 116 |
+
for line in f:
|
| 117 |
+
parts = line.strip().split(" ")
|
| 118 |
+
ft_embeddings[parts[0]] = np.array(parts[1:], dtype=np.float32)
|
| 119 |
+
|
| 120 |
+
weights = np.random.normal(scale=0.6, size=(len(vocab), 300))
|
| 121 |
+
for idx, word in enumerate(vocab):
|
| 122 |
+
if word in ft_embeddings:
|
| 123 |
+
weights[idx] = ft_embeddings[word]
|
| 124 |
+
weights[pad_index] = np.zeros(300)
|
| 125 |
+
model.embedding.weight.data.copy_(torch.from_numpy(weights))
|
| 126 |
+
print("FastText Embeddings Loaded!")
|
| 127 |
+
except FileNotFoundError:
|
| 128 |
+
print("FastText file not found. Training with random weights.")
|
| 129 |
+
|
| 130 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 131 |
+
optimizer = optim.Adam(model.parameters(), lr=5e-4)
|
| 132 |
+
criterion = nn.CrossEntropyLoss().to(device)
|
| 133 |
+
model = model.to(device)
|
| 134 |
+
|
| 135 |
+
# 8. Updated Metrics Engine (Accuracy, Precision, Recall, F1)
|
| 136 |
+
def compute_metrics(all_preds, all_labels):
|
| 137 |
+
preds = np.concatenate(all_preds)
|
| 138 |
+
labels = np.concatenate(all_labels)
|
| 139 |
+
acc = accuracy_score(labels, preds)
|
| 140 |
+
prec, rec, f1, _ = precision_recall_fscore_support(labels, preds, average="weighted", zero_division=0)
|
| 141 |
+
cm = confusion_matrix(labels, preds, labels=[0, 1, 2, 3, 4])
|
| 142 |
+
return acc, prec, rec, f1, cm
|
| 143 |
+
|
| 144 |
+
# 9. Train and Evaluate Functions
|
| 145 |
+
def run_epoch(dataloader, model, criterion, optimizer=None, is_train=True):
|
| 146 |
+
if is_train:
|
| 147 |
+
model.train()
|
| 148 |
+
else:
|
| 149 |
+
model.eval()
|
| 150 |
+
|
| 151 |
+
epoch_losses = []
|
| 152 |
+
all_preds, all_labels = [], []
|
| 153 |
+
|
| 154 |
+
context = torch.enable_grad() if is_train else torch.no_grad()
|
| 155 |
+
with context:
|
| 156 |
+
for batch in tqdm.tqdm(dataloader, desc="Processing..."):
|
| 157 |
+
ids = batch["ids"].to(device)
|
| 158 |
+
length = batch["length"]
|
| 159 |
+
label = batch["label"].to(device)
|
| 160 |
+
|
| 161 |
+
prediction = model(ids, length)
|
| 162 |
+
loss = criterion(prediction, label)
|
| 163 |
+
|
| 164 |
+
if is_train:
|
| 165 |
+
optimizer.zero_grad()
|
| 166 |
+
loss.backward()
|
| 167 |
+
optimizer.step()
|
| 168 |
+
|
| 169 |
+
epoch_losses.append(loss.item())
|
| 170 |
+
all_preds.append(prediction.argmax(dim=-1).cpu().numpy())
|
| 171 |
+
all_labels.append(label.cpu().numpy())
|
| 172 |
+
|
| 173 |
+
acc, prec, rec, f1,cm = compute_metrics(all_preds, all_labels)
|
| 174 |
+
return np.mean(epoch_losses), acc, prec, rec, f1,cm
|
| 175 |
+
|
| 176 |
+
# 10. Training Loop
|
| 177 |
+
n_epochs = 10
|
| 178 |
+
best_valid_loss = float("inf")
|
| 179 |
+
|
| 180 |
+
for epoch in range(n_epochs):
|
| 181 |
+
train_loss, train_acc, _, _, train_f1, _ = run_epoch(train_data_loader, model, criterion, optimizer, is_train=True)
|
| 182 |
+
valid_loss, valid_acc, _, _, valid_f1, _ = run_epoch(valid_data_loader, model, criterion, is_train=False)
|
| 183 |
+
|
| 184 |
+
if valid_loss < best_valid_loss:
|
| 185 |
+
best_valid_loss = valid_loss
|
| 186 |
+
torch.save(model.state_dict(), "lstm_croatian.pt")
|
| 187 |
+
|
| 188 |
+
print(f"Epoch: {epoch+1} | Train Loss: {train_loss:.3f} | Train Acc: {train_acc*100:.1f}% | Train F1: {train_f1:.2f}")
|
| 189 |
+
print(f"Val Loss: {valid_loss:.3f} | Val Acc: {valid_acc*100:.1f}% | Val F1: {valid_f1:.2f}")
|
| 190 |
+
|
| 191 |
+
# 11. Final Test Evaluation
|
| 192 |
+
model.load_state_dict(torch.load("lstm_croatian.pt"))
|
| 193 |
+
test_loss, test_acc, test_prec, test_rec, test_f1, test_cm = run_epoch(test_data_loader, model, criterion, is_train=False)
|
| 194 |
+
|
| 195 |
+
print("\n=== FINAL TEST METRICS ===")
|
| 196 |
+
print(f"Accuracy: {test_acc*100:.2f}%")
|
| 197 |
+
print(f"Precision: {test_prec:.3f}")
|
| 198 |
+
print(f"Recall: {test_rec:.3f}")
|
| 199 |
+
print(f"F1-Score: {test_f1:.3f}")
|
| 200 |
+
|
| 201 |
+
label_list = ["negative", "neutral", "positive", "mixed", "sarcasm"]
|
| 202 |
+
print("\nConfusion matrix:")
|
| 203 |
+
print(" " * 12 + " ".join(f"{lbl:10}" for lbl in label_list))
|
| 204 |
+
for i, lbl in enumerate(label_list):
|
| 205 |
+
print(f"{lbl:12} " + " ".join(f"{test_cm[i, j]:10d}" for j in range(len(label_list))))
|
GRU/croatian_gru (2).pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0cd972c8748731b4e228af34ee809c04a31c590f5b348c8007a63338c7c8fbda
|
| 3 |
+
size 11588623
|
GRU/vokabular_gru (1).pkl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d4b72965028fdc14628b16c85eae7488e8de89f1446ae1753b7c7ac3e40131b8
|
| 3 |
+
size 36078
|