Spaces:
Sleeping

File size: 5,553 Bytes
4272bda
 
 
fe45c80
4272bda
 
 
 
 
 
fe45c80
 
 
4272bda
fe45c80
 
 
4272bda
 
 
fe45c80
 
4272bda
 
fe45c80
 
4272bda
 
 
fe45c80
4272bda
 
fe45c80
 
4272bda
fe45c80
4272bda
fe45c80
 
4272bda
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe45c80
 
4272bda
 
 
 
 
 
fe45c80
4272bda
 
 
 
 
 
 
 
 
 
fe45c80
 
4272bda
 
 
 
fe45c80
 
4272bda
 
 
 
fe45c80
 
4272bda
fe45c80
 
4272bda
fe45c80
4272bda
 
 
 
 
 
 
 
 
 
 
 
 
 
fe45c80
4272bda
 
 
 
fe45c80
 
 
 
 
 
4272bda
 
fe45c80
 
4272bda
fe45c80
4272bda
 
fe45c80
4272bda
fe45c80
4272bda
fe45c80
 
4272bda
 
fe45c80
4272bda
 
 
 
 
 
 
 
fe45c80
4272bda
 
fe45c80
4272bda
 
 
 
fe45c80
4272bda
fe45c80
4272bda
 
fe45c80
 
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
import os
import joblib
import torch
from src.config import langs_dir, models_name

cwd = os.getcwd()


class ModelArgs:
    input_size: int
    hidden_size: int  # rnn
    num_layers: int = 1  # rnn
    hidden_layers: list  # mlp
    output_size: int
    nonlinearity: str = "tanh"  # 'tanh' | 'relu'
    dropout: int = 0


class MLPClassifier:
    def __init__(self, model):
        self.model = model  # MLPModelCustom()

    def predict(self, x: torch.Tensor):
        self.model.eval()
        with torch.torch.no_grad():  # no calcular gradiente
            output = self.model(x)  # (batch_size, output_size)
            pred = torch.nn.functional.softmax(output, dim=1).squeeze()
            return [torch.argmax(pred).tolist()]


class RNNClassifier:
    def __init__(self, base_model):
        self.model = base_model  # MLPModelCustom()

    def predict(self, x: torch.Tensor, length):
        self.model.eval()  # Desactiva Dropout

        with torch.torch.no_grad():  # no calcular gradiente
            output = self.model(x, length)  # (batch_size, output_size)
            pred = torch.nn.functional.softmax(output, dim=1).squeeze()
            return [torch.argmax(pred).tolist()]


es_model_args = ModelArgs()
es_model_args.hidden_layers = [128, 64]
es_model_args.hidden_size = 128
es_model_args.num_layers = 2
es_model_args.output_size = 3
es_model_args.dropout = 0.20

en_model_args = ModelArgs()
en_model_args.hidden_layers = [128, 64]
en_model_args.hidden_size = 128
en_model_args.num_layers = 2
en_model_args.output_size = 3
en_model_args.dropout = 0.20

model_args = {"es": es_model_args, "en": en_model_args}


def get_model(lang, model_name, embedding_model=None):
    dir_name = langs_dir[lang]
    model_path = models_name[model_name]

    path = os.path.join(cwd, dir_name, model_path)

    if model_name in {"SVM", "NB", "LR", "SWEM"}:
        return joblib.load(path)

    device = "cpu"
    args = model_args[lang]
    args.input_size = embedding_model.vector_size()

    if model_name == "MLP":
        model = MLPModelCustom(args)
        state_dict = torch.load(path, map_location=device)
        # model.load_state_dict(state_dict)
        model.load_state_dict(state_dict["model_state_dict"])
        return MLPClassifier(model)
    if model_name == "RNN":
        model = RNNModel(args)
        state_dict = torch.load(path, map_location=device)
        # model.load_state_dict(state_dict)
        model.load_state_dict(state_dict["model_state_dict"])
        return RNNClassifier(model)
    if model_name == "LSTM":
        model = LSTMModel(args)
        state_dict = torch.load(path, map_location=device)
        # model.load_state_dict(state_dict)
        model.load_state_dict(state_dict["model_state_dict"])
        return RNNClassifier(model)


class MLPModelCustom(torch.nn.Module):
    def __init__(self, model_args):
        super().__init__()
        layers = []
        previous_dim = model_args.input_size
        for hidden_dim in model_args.hidden_layers:
            layers.append(torch.nn.Linear(previous_dim, hidden_dim))
            layers.append(torch.nn.ReLU())
            layers.append(torch.nn.Dropout(model_args.dropout))
            previous_dim = hidden_dim
        layers.append(torch.nn.Linear(previous_dim, model_args.output_size))
        self.network = torch.nn.Sequential(*layers)

    def forward(self, x):
        return self.network(x)


class RNNModel(torch.nn.Module):
    def __init__(self, model_args: ModelArgs):
        super().__init__()
        self.rnn = torch.nn.RNN(
            input_size=model_args.input_size,  # Número de características por palabra | Tamaño de los embeddings
            hidden_size=model_args.hidden_size,  # Número de características/neuronas de la capa recurrente
            num_layers=model_args.num_layers,  # Núumero de capas recurrentes
            nonlinearity=model_args.nonlinearity,  # 'relu' deafult: 'tanh'
            dropout=model_args.dropout,  # Porcentaje de neuronas desactivadas durante el entrenamiento
            batch_first=True,  # Los tensores de entrada y salida tienen las dimensiones (batch, seq, feature)
        )
        self.fc = torch.nn.Linear(
            model_args.hidden_size,  # Número de características de entrada
            model_args.output_size,  # Número de clases
        )

    def forward(self, x, lengths):
        packed_x = torch.nn.utils.rnn.pack_padded_sequence(
            x, lengths, batch_first=True, enforce_sorted=False
        )

        packed_output, hidden = self.rnn(packed_x)

        h_n = hidden[-1]  # tomar la salida de la última capa rnn
        return self.fc(h_n)


class LSTMModel(torch.nn.Module):
    def __init__(self, model_args: ModelArgs):
        super().__init__()
        self.lstm = torch.nn.LSTM(
            input_size=model_args.input_size,
            hidden_size=model_args.hidden_size,
            num_layers=model_args.num_layers,
            dropout=model_args.dropout,
            batch_first=True,
        )
        self.fc = torch.nn.Linear(
            in_features=model_args.hidden_size, out_features=model_args.output_size
        )

    def forward(self, x, lengths):
        packed_input_sequences = torch.nn.utils.rnn.pack_padded_sequence(
            x, lengths, batch_first=True, enforce_sorted=False
        )

        packed_output_sequences, (hidden, cell) = self.lstm(packed_input_sequences)

        h_n = hidden[-1]  # Tomar el estado oculto final de la última capa
        return self.fc(h_n)  # (batch_size, output_size)