File size: 12,141 Bytes
ab2adfb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d355949
 
ab2adfb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
import numpy as np
import torch
import torch.nn as nn
# import torch.nn.functional as F
import torch.optim as optim
# from torch.autograd import Variable
#import torch.distributed as dist

# import time
import os
import re
# import sys
# import io

from tqdm import tqdm
import nltk

from lstm_model_new import LSTM_model, BiLSTMModel
from max_ent_model import MaxEntropyModel
from svm_model import SVM

nltk.download('punkt')


class Trainer(object):
    def __init__(self, vocab_size, sequence_len, batch_size, nn_epochs, model_type):
        
        # vocab_size = 8000
        # sequence_len = 150
        
        self.vocab_size = vocab_size
        self.vocab_sizeb = self.vocab_size + 1
        
        self.sequence_len = sequence_len
        self.model_type = model_type
        
        self.batch_size = batch_size
        self.nn_epochs = nn_epochs
        
        self.processed_data_folder = "../preprocessed_data/"
        
        self._load_data()
        
        self._get_model()
        
        # self._setup_optimizer()
        
        
        pass
    
    
    
    def _load_data(self, ):
        
        dict_fn = "yelp_dictionary.npy"
        
        id_to_word = np.load(dict_fn, allow_pickle=True) # .item()
        
        print(type(id_to_word))
        print(id_to_word[0], len(id_to_word))
        
        word_to_id = {
            id_to_word[idx]: idx for idx in range(len(id_to_word))
        }
        
        # word_to_id = {v: k for k, v in id_to_word.items()}
        self.word_to_id = word_to_id
        
        # x_train = np.load('../preprocessed_data/x_train.npy')
        # y_train = np.load('../preprocessed_data/y_train.npy')

        # #x_train = x_train[:10000]
        # #y_train = y_train[:10000]
        # x_test = np.load('../preprocessed_data/x_test.npy')
        # y_test = np.load('../preprocessed_data/y_test.npy')


        # x_train_path = os.path.join(self.processed_data_folder, "x_train.npy")
        # y_train_path = os.path.join(self.processed_data_folder, "y_train.npy")
        # x_test_path = os.path.join(self.processed_data_folder, "x_test.npy")
        # y_test_path = os.path.join(self.processed_data_folder, "y_test.npy")
        
        # x_train = np.load(x_train_path)
        # y_train = np.load(y_train_path)
        # x_test = np.load(x_test_path)
        # y_test = np.load(y_test_path)
        # self.x_train = x_train
        # self.y_train = y_train
        # self.x_test = x_test
        # self.y_test = y_test
        
    def _get_model(self, ):
        if self.model_type == "lstm":
            self.model = LSTM_model(self.vocab_sizeb, 800)
        elif self.model_type == "bilstm":
            self.model = BiLSTMModel(self.vocab_sizeb, 800)
        elif self.model_type == "max_ent":
            self.model = MaxEntropyModel()
        elif self.model_type == "svm":
            self.model = SVM()
        else:
            raise ValueError("Model type not supported")

        # self.model.cuda()
        
        if self.model_type in ['lstm', 'bilstm']:
            # self.model = self.model.cuda()
        
            model_ckpt_fn = f"{self.model_type}.pth"
            self.model.load_state_dict(torch.load(model_ckpt_fn, map_location=torch.device('cpu')))
        elif self.model_type in ['max_ent']:
            model_ckpt_fn = f"{self.model_type}_ckpt.npy" # max_ent #
            model_params = np.load(model_ckpt_fn, allow_pickle=True).item()
            features = model_params["features"]
            weights = model_params["weights"]
            
            self.model.weights = weights # .tolist()
            # print(f"self.model.weights: {self.model.weights[:10]}")
            self.model.last_weights = weights # .tolist()
            
            self.model.features = features
            # print(f"self.model.features: {list(self.model.features.keys())[:10]}")
        
        elif self.model_type in ['svm']:
            model_ckpt_fn = f"{self.model_type}_weights.npy"
            model_params = np.load(model_ckpt_fn, allow_pickle=True).item()
            w = model_params['w']
            b = model_params['b']
            self.model.svm_model.w = w
            self.model.svm_model.b = b
        
        else:
            raise ValueError("Model type not supported")
            
            
            
            
    
    def _setup_optimizer(self, ):
        self.lr = 0.001
        self.opt = optim.Adam(self.model.parameters(), lr=self.lr)
        
    def _train(self, ):
        train_losses = []
        train_accs = []
        test_accs = [0.0]
        
        for epoch in range(self.nn_epochs):
            print(f"Epoch: {epoch}")
            self.model.train()
            
            nn_acc = 0
            nn_total = 0
            epoch_loss = 0.0
            
            
            train_permutation_idxes = np.random.permutation(self.y_train.shape[0])
            
            for i in tqdm(range(0, len(self.y_train), self.batch_size)):
                batched_x = self.x_train[train_permutation_idxes[i: i + self.batch_size]]
                batched_y = self.y_train[train_permutation_idxes[i: i + self.batch_size]]
                
                data = torch.from_numpy(batched_x).long().cuda()   
                target = torch.from_numpy(batched_y).float().cuda()
                
                self.opt.zero_grad()
                loss, predicted_labels = self.model(data, target)
                loss.backward()
                
                norm = nn.utils.clip_grad_norm_(self.model.parameters(), 2.0)
                self.opt.step()
                
                predicted_labels = predicted_labels >= 0
                gts = target >= 0.5
                acc = torch.sum((predicted_labels == gts).float()).item()
                
                nn_acc += acc
                epoch_loss += loss.item()
                nn_total += len(batched_y)
            
            train_acc = float(nn_acc) / float(nn_total)   
            train_loss = epoch_loss / float(self.batch_size)
            
            train_losses.append(train_loss)
            train_accs.append(train_acc)
            
            print(f"[Epoch {epoch}] Train Loss: {train_loss}, Train Acc: {train_acc}")       
            
            self._test()          
    
    
    def _process_text(self, input_text):
        text = re.sub('[^a-zA-Z \']', '', re.sub('\\\\n', ' ', ','.join(input_text))).lower()
        tokens = nltk.word_tokenize(text)
        token_ids = [ self.word_to_id.get(token, -1) + 1 for token in tokens ]
        token_ids = np.array(token_ids)
        
        token_ids[token_ids > self.vocab_size] = 0
        if token_ids.shape[0] > self.sequence_len:
            start_index = np.random.randint(token_ids.shape[0 ]- self.sequence_len + 1)
            token_ids = token_ids[start_index: (start_index + self.sequence_len)]
        else:
            token_ids = np.concatenate([token_ids, np.zeros(self.sequence_len - token_ids.shape[0])])
        return token_ids
    
    def _process_text_maxent(self, input_text):
        text = re.sub('[^a-zA-Z \']', '', re.sub('\\\\n', ' ', ','.join(input_text))).lower()
        tokens = nltk.word_tokenize(text)
        token_ids = [ self.word_to_id.get(token, -1) + 1 for token in tokens ]
        # token_ids = np.array(token_ids)
        token_ids = [ str(word_idx) for word_idx in token_ids ]
        
        return token_ids
        
        # token_ids[token_ids > self.vocab_size] = 0
        # return token_ids
    
    def _process_text_svm(self, input_text):
        text = re.sub('[^a-zA-Z \']', '', re.sub('\\\\n', ' ', ','.join(input_text))).lower()
        tokens = self.model.vectorizer.transform([text]).toarray()
        # tokens = nltk.word_tokenize(text)
        # token_ids = [ self.word_to_id.get(token, -1) + 1 for token in tokens ]
        # # token_ids = np.array(token_ids)
        # token_ids = [ str(word_idx) for word_idx in token_ids ]
        
        return tokens
        
    def predict_maxent(self, input_text):
        
        text_ids = self._process_text_maxent(input_text)
        
        prob = self.model.calculate_probability(text_ids)
        prob.sort(reverse=True)
        # print(label, prob)
        print(prob)
        ##### Calculate whether the prediction is correct #####
        maxx_prob_idx = int(prob[0][1])
        
        # data = torch.from_numpy(text_ids).long() # .cuda()
        # data = data.unsqueeze(0)
        
        
        # target = torch.zeros((data.size(0), ), dtype=torch.float)
        
        # # print(f"data: {data.shape}, target: {target.shape}")
        
        # with torch.no_grad():
        #     loss, predicted_labels = self.model(data, target)
        # predicted_labels = predicted_labels >= 0
        
        if maxx_prob_idx == 2:
            return "Positive"
        else:
            return "Negative"
        
    def predict_svm(self, input_text):
        
        text_ids = self._process_text_svm(input_text)
        
        predicted_label = self.model.svm_model.predict(text_ids)
        
        if float(predicted_label[0]) > 0:
            return "Positive"
        else:
            return "Negative"
        
        # prob = self.model.calculate_probability(text_ids)
        # prob.sort(reverse=True)
        # # print(label, prob)
        # print(prob)
        # ##### Calculate whether the prediction is correct #####
        # maxx_prob_idx = int(prob[0][1])
        
        # # data = torch.from_numpy(text_ids).long() # .cuda()
        # # data = data.unsqueeze(0)
        
        
        # # target = torch.zeros((data.size(0), ), dtype=torch.float)
        
        # # # print(f"data: {data.shape}, target: {target.shape}")
        
        # # with torch.no_grad():
        # #     loss, predicted_labels = self.model(data, target)
        # # predicted_labels = predicted_labels >= 0
        
        # if maxx_prob_idx == 2:
        #     return "Positive"
        # else:
        #     return "Negative"
        
    
    def predict(self, input_text):
        
        text_ids = self._process_text(input_text)
        
        data = torch.from_numpy(text_ids).long() # .cuda()
        data = data.unsqueeze(0)
        
        
        target = torch.zeros((data.size(0), ), dtype=torch.float)
        
        # print(f"data: {data.shape}, target: {target.shape}")
        
        with torch.no_grad():
            loss, predicted_labels = self.model(data, target)
        predicted_labels = predicted_labels >= 0
        
        if predicted_labels.item():
            return "Positive"
        else:
            return "Negative"
        
        # return predicted_labels.item()
        
        
    def _test(self, ):
        self.model.eval()
        
        nn_acc = 0
        loss = 0
        
        nn_total = 0
        
        test_permutation_idxes = np.random.permutation(self.y_test.shape[0])
        for i in tqdm(range(0, len(self.y_test), self.batch_size)):
            batched_x = self.x_test[test_permutation_idxes[i: i + self.batch_size]]
            batched_y = self.y_test[test_permutation_idxes[i: i + self.batch_size]]
            
            data = torch.from_numpy(batched_x).long().cuda()
            target = torch.from_numpy(batched_y).float().cuda()
            
            with torch.no_grad():
                loss, predicted_labels = self.model(data, target)
            
            predicted_labels = predicted_labels >= 0
            gts = target >= 0.5
            acc = torch.sum((predicted_labels == gts).float()).item()
            
            nn_acc += acc
            nn_total += len(batched_y)
        
        acc = float(nn_acc) / float(nn_total)
        print(f"Test Acc: {acc}")

if __name__=='__main__':
    
    vocab_size = 8000
    sequence_len = 150
    
    # batch_size = 1024
    batch_size = 256
    nn_epochs = 20
    model_type = "lstm"
    
    model_type = "bilstm"
    
    trainer = Trainer(vocab_size, sequence_len, batch_size, nn_epochs, model_type)
    trainer._train()
    
    # CUDA_VISIBLE_DEVICES=0 python trainer.py