File size: 4,746 Bytes
104f15a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import pandas as pd
import torch
import torch.nn as nn
import torch.optim as optim
from gensim.models.fasttext import load_facebook_model
from torch.utils.data import DataLoader, Dataset
import numpy as np

FASTTEXT_PATH = "FastText.bin"
TRAIN_PATH = "TRAIN.tsv"
TEST_PATH = "Test-1.tsv"

print("Učitavanje FastText modela...")
ft_model = load_facebook_model(FASTTEXT_PATH)
embedding_dim = ft_model.vector_size

def tokenize(text):
    return text.lower().split()

class FastTextDataset(Dataset):
    def __init__(self, texts, labels):
        self.texts = [tokenize(text) for text in texts]
        self.labels = labels

    def __len__(self):
        return len(self.labels)

    def __getitem__(self, idx):
        tokens = self.texts[idx]
        vectors = [ft_model.wv[token] if token in ft_model.wv else np.zeros(embedding_dim) for token in tokens]
        max_len = 50
        if len(vectors) > max_len:
            vectors = vectors[:max_len]
        else:
            vectors += [np.zeros(embedding_dim)] * (max_len - len(vectors))
        return torch.tensor(vectors, dtype=torch.float32), torch.tensor(self.labels[idx], dtype=torch.long)

class CNNClassifier(nn.Module):
    def __init__(self, embedding_dim, num_classes):
        super(CNNClassifier, self).__init__()
        self.conv1 = nn.Conv1d(embedding_dim, 100, kernel_size=3, padding=1)
        self.relu = nn.ReLU()
        self.pool = nn.AdaptiveMaxPool1d(1)
        self.dropout = nn.Dropout(0.5)
        self.fc = nn.Linear(100, num_classes)

    def forward(self, x):
        x = x.permute(0, 2, 1)
        x = self.relu(self.conv1(x))
        x = self.pool(x).squeeze(2)
        x = self.dropout(x)
        return self.fc(x)

class LSTMClassifier(nn.Module):
    def __init__(self, embedding_dim, hidden_dim, num_classes):
        super(LSTMClassifier, self).__init__()
        self.lstm = nn.LSTM(embedding_dim, hidden_dim, batch_first=True, bidirectional=True)
        self.dropout = nn.Dropout(0.5)
        self.fc = nn.Linear(hidden_dim * 2, num_classes)

    def forward(self, x):
        _, (hn, _) = self.lstm(x)
        x = torch.cat((hn[-2], hn[-1]), dim=1)  # concatenate forward and backward hidden states
        x = self.dropout(x)
        return self.fc(x)

print("Učitavanje podataka...")
train_df = pd.read_csv(TRAIN_PATH, sep="\t").rename(columns={"Sentence": "text", "Label": "label"})
test_df = pd.read_csv(TEST_PATH, sep="\t").rename(columns={"Sentence": "text", "Label": "label"})
train_df["label"] = train_df["label"].astype(int)
test_df["label"] = test_df["label"].astype(int)

num_classes = train_df["label"].nunique()

train_dataset = FastTextDataset(train_df["text"].tolist(), train_df["label"].tolist())
test_dataset = FastTextDataset(test_df["text"].tolist(), test_df["label"].tolist())

train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=32)

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

def train(model, loader, optimizer, criterion):
    model.train()
    total_loss = 0
    for x, y in loader:
        x, y = x.to(device), y.to(device)
        optimizer.zero_grad()
        output = model(x)
        loss = criterion(output, y)
        loss.backward()
        optimizer.step()
        total_loss += loss.item()
    return total_loss / len(loader)

def evaluate(model, loader):
    model.eval()
    correct = total = 0
    with torch.no_grad():
        for x, y in loader:
            x, y = x.to(device), y.to(device)
            output = model(x)
            preds = torch.argmax(output, dim=1)
            correct += (preds == y).sum().item()
            total += y.size(0)
    return correct / total

for model_type in ["LSTM", "CNN"]:
    print(f"\n==============================")
    print(f"Treniramo model: {model_type}")
    print(f"==============================")

    if model_type == "LSTM":
        model = LSTMClassifier(embedding_dim, hidden_dim=256, num_classes=num_classes)
    else:
        model = CNNClassifier(embedding_dim, num_classes=num_classes)

    model = model.to(device)
    optimizer = optim.Adam(model.parameters(), lr=1e-3)
    criterion = nn.CrossEntropyLoss()

    for epoch in range(1, 11):
        train_loss = train(model, train_loader, optimizer, criterion)
        test_acc = evaluate(model, test_loader)
        print(f"{model_type} | Epoch {epoch} | Loss: {train_loss:.4f} | Test Accuracy: {test_acc:.4f}")

    model_path = f"fasttext_{model_type.lower()}.pt"
    torch.save(model.state_dict(), model_path)
    print(f"{model_type} model spremljen kao: {model_path}")