hienntd commited on
Commit
c2a30b3
1 Parent(s): 1f62012
app.py ADDED
@@ -0,0 +1,576 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Streamlit
2
+ import streamlit as st
3
+ import os
4
+ import pandas as pd
5
+ import pickle
6
+ import json
7
+ # Preprocessing
8
+ import re
9
+ import phonlp
10
+ import underthesea
11
+ import re
12
+
13
+ # Visualize
14
+ import numpy as np
15
+
16
+
17
+ # Model
18
+ import tensorflow as tf
19
+ from tensorflow.keras.preprocessing.sequence import pad_sequences
20
+ from tensorflow.keras.models import load_model
21
+ from transformers import AutoModel, AutoTokenizer
22
+ import torch
23
+ import torch.nn as nn
24
+ from sklearn.model_selection import StratifiedKFold
25
+
26
+ # Evaluate
27
+ from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
28
+
29
+ # Set up the Streamlit page
30
+ st.set_page_config(layout='wide')
31
+
32
+ # Define variables
33
+ PREPROCESSED_DATA = "data/val_data_162k.json"
34
+ device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
35
+ N_SPLITS = 5
36
+ skf = StratifiedKFold(n_splits=N_SPLITS)
37
+
38
+ # Define class names
39
+ class_names = ['Cong nghe', 'Doi song', 'Giai tri', 'Giao duc', 'Khoa hoc', 'Kinh te',
40
+ 'Nha dat', 'Phap luat', 'The gioi', 'The thao', 'Van hoa', 'Xa hoi', 'Xe co']
41
+
42
+ # Define the NewsClassifier class for BERT-based models
43
+ class NewsClassifier(nn.Module):
44
+ def __init__(self, n_classes, model_name):
45
+ super(NewsClassifier, self).__init__()
46
+ # Load a pre-trained BERT model
47
+ self.bert = AutoModel.from_pretrained(model_name)
48
+ # Dropout layer to prevent overfitting
49
+ self.drop = nn.Dropout(p=0.3)
50
+ # Fully-connected layer to convert BERT's hidden state to the number of classes to predict
51
+ self.fc = nn.Linear(self.bert.config.hidden_size, n_classes)
52
+ # Initialize weights and biases of the fully-connected layer using the normal distribution method
53
+ nn.init.normal_(self.fc.weight, std=0.02)
54
+ nn.init.normal_(self.fc.bias, 0)
55
+
56
+ def forward(self, input_ids, attention_mask):
57
+ # Get the output from the BERT model
58
+ last_hidden_state, output = self.bert(
59
+ input_ids=input_ids,
60
+ attention_mask=attention_mask,
61
+ return_dict=False
62
+ )
63
+ # Apply dropout
64
+ x = self.drop(output)
65
+ # Pass through the fully-connected layer to get predictions
66
+ x = self.fc(x)
67
+ return x
68
+
69
+ @st.cache_data
70
+ def load_models(model_type):
71
+ models = None
72
+ model = None
73
+
74
+ if model_type == 'phobertbase':
75
+ models = []
76
+ for fold in range(skf.n_splits):
77
+ model = NewsClassifier(n_classes=13, model_name='vinai/phobert-base-v2')
78
+ model.to(device)
79
+ model.load_state_dict(torch.load(f'models/phobert_256_fold{fold+1}.pth', map_location=device))
80
+ model.eval()
81
+ models.append(model)
82
+ tokenizer = AutoTokenizer.from_pretrained("vinai/phobert-base-v2")
83
+ max_len = 256
84
+ elif model_type == 'longformer':
85
+ models = []
86
+ for fold in range(skf.n_splits):
87
+ model = NewsClassifier(n_classes=13, model_name='bluenguyen/longformer-phobert-base-4096')
88
+ model.to(device)
89
+ model.load_state_dict(torch.load(f'models/phobert_fold{fold+1}.pth', map_location=device))
90
+ model.eval()
91
+ models.append(model)
92
+ tokenizer = AutoTokenizer.from_pretrained("bluenguyen/longformer-phobert-base-4096")
93
+ max_len = 512
94
+ elif model_type == 'bilstm_phobertbase':
95
+ model = load_model("models/bilstm_phobertbase.h5", compile=False)
96
+ tokenizer = AutoTokenizer.from_pretrained("vinai/phobert-base-v2")
97
+ max_len = 256
98
+ else:
99
+ raise ValueError("Invalid model type specified.")
100
+
101
+ if models is not None:
102
+ return models, tokenizer, max_len
103
+ else:
104
+ return model, tokenizer, max_len
105
+
106
+
107
+
108
+ # Function to preprocess text using PhonLP and Underthesea
109
+ def preprocess_text(text):
110
+ nlp_model = phonlp.load(save_dir="./phonlp")
111
+ text = re.sub(r'[^\w\s.]', '', text)
112
+ sentences = underthesea.sent_tokenize(text)
113
+ preprocessed_words = []
114
+ for sentence in sentences:
115
+ try:
116
+ word_tokens = underthesea.word_tokenize(sentence, format="text")
117
+ tags = nlp_model.annotate(word_tokens, batch_size=64)
118
+ filtered_words = [word.lower() for word, tag in zip(tags[0][0], tags[1][0]) if tag[0] not in ['M', 'X', 'CH']
119
+ and word not in ["'", ","]]
120
+ preprocessed_words.extend(filtered_words)
121
+ except Exception as e:
122
+ pass
123
+ return ' '.join(preprocessed_words)
124
+
125
+ # Function to tokenize text using BERT tokenizer
126
+ def tokenize_text(text, tokenizer, max_len=256):
127
+ tokenized = tokenizer.encode_plus(
128
+ text,
129
+ max_length=max_len,
130
+ truncation=True,
131
+ add_special_tokens=True,
132
+ padding='max_length',
133
+ return_attention_mask=True,
134
+ return_token_type_ids=False,
135
+ return_tensors='pt',
136
+ )
137
+ return tokenized['input_ids'], tokenized['attention_mask']
138
+
139
+ # Function to get BERT features
140
+ def get_bert_features(input_ids, attention_mask, phobert):
141
+ with torch.no_grad():
142
+ last_hidden_states = phobert(input_ids=input_ids, attention_mask=attention_mask)
143
+ features = last_hidden_states[0][:, 0, :].numpy()
144
+ return features
145
+
146
+ # Function to predict label using BiLSTM model
147
+ def predict_label(text, tokenizer, phobert, model, class_names, max_len):
148
+ processed_text = preprocess_text(text)
149
+ input_ids, attention_mask = tokenize_text(processed_text, tokenizer, max_len)
150
+ input_ids = torch.tensor(input_ids).to(torch.long).to(device)
151
+ attention_mask = torch.tensor(attention_mask).to(torch.long).to(device)
152
+
153
+ with torch.no_grad():
154
+ features = get_bert_features(input_ids, attention_mask, phobert)
155
+ features = np.expand_dims(features, axis=1)
156
+ prediction = model.predict(features)
157
+
158
+ predicted_label_index = np.argmax(prediction, axis=1)[0]
159
+ predicted_label = class_names[predicted_label_index]
160
+
161
+ confidence_scores = {class_names[i]: float(prediction[0][i]) for i in range(len(prediction[0]))}
162
+ confidence_df = pd.DataFrame([confidence_scores])
163
+ confidence_df = confidence_df.melt(var_name='Label', value_name='Confidence')
164
+
165
+ return predicted_label, confidence_df
166
+
167
+ # Function to infer predictions using ensemble of BERT-based models
168
+ def infer(text, tokenizer, models, class_names, max_len):
169
+ tokenized = tokenizer.encode_plus(
170
+ text,
171
+ max_length=max_len,
172
+ truncation=True,
173
+ add_special_tokens=True,
174
+ padding='max_length',
175
+ return_attention_mask=True,
176
+ return_token_type_ids=False,
177
+ return_tensors='pt',
178
+ )
179
+ input_ids = tokenized['input_ids'].to(device)
180
+ attention_mask = tokenized['attention_mask'].to(device)
181
+
182
+ with torch.no_grad():
183
+ all_outputs = []
184
+ for model in models:
185
+ model.eval()
186
+ output = model(input_ids, attention_mask)
187
+ all_outputs.append(output)
188
+
189
+ all_outputs = torch.stack(all_outputs)
190
+ mean_output = all_outputs.mean(0)
191
+ _, predicted = torch.max(mean_output, dim=1)
192
+
193
+ confidence_scores = mean_output.softmax(dim=1).cpu().numpy()
194
+ confidence_df = pd.DataFrame([confidence_scores[0]], columns=class_names)
195
+ confidence_df = confidence_df.melt(var_name='Label', value_name='Confidence')
196
+ predicted_label = class_names[predicted.item()]
197
+
198
+ return confidence_df, predicted_label
199
+
200
+ # Function to load BERT model and tokenizer
201
+ def load_bert():
202
+ phobert = AutoModel.from_pretrained("vinai/phobert-base-v2")
203
+ tokenizer = AutoTokenizer.from_pretrained("vinai/phobert-base-v2", use_fast=False)
204
+ return phobert, tokenizer
205
+
206
+ # Function to plot HTML data
207
+ def plot_data(train_html_path, test_html_path, val_html_path):
208
+ if not (os.path.exists(train_html_path) and os.path.exists(test_html_path) and os.path.exists(val_html_path)):
209
+ st.error("HTML files not found.")
210
+ return
211
+
212
+ with open(train_html_path, "r", encoding="utf-8") as f_train:
213
+ train_content = f_train.read()
214
+ st.components.v1.html(train_content, height=600, scrolling=True)
215
+
216
+ with open(test_html_path, "r", encoding="utf-8") as f_test:
217
+ test_content = f_test.read()
218
+ st.components.v1.html(test_content, height=600, scrolling=True)
219
+
220
+ with open(val_html_path, "r", encoding="utf-8") as f_val:
221
+ val_content = f_val.read()
222
+ st.components.v1.html(val_content, height=600, scrolling=True)
223
+
224
+
225
+
226
+
227
+
228
+ def main():
229
+
230
+ #st.title("News Classifier App")
231
+ activities = ["Introduction", "Text Preprocessing", "Feature Extraction", "Train and Evaluate Models", "Prediction"]
232
+ choice = st.sidebar.selectbox("Choose Activity", activities)
233
+
234
+ # Preprocessing data
235
+ if choice == "Text Preprocessing":
236
+ st.info("Text Preprocessing")
237
+ preprocessing_task = ["No Options", "Data Overview", "Process Text Demo", "Load Preprocessed Data"]
238
+ task_choice = st.selectbox("Choose Task", preprocessing_task)
239
+ if task_choice == "Data Overview":
240
+ st.markdown("This dataset consists of Vietnamese news articles collected from various Vietnamese online news portals such as Thanh Nien, VNExpress, BaoMoi, etc. The dataset was originally sourced from a MongoDB dump containing over 20 million articles.")
241
+ st.markdown("From this large dataset, our team extracted approximately 162,000 articles categorized into 13 distinct categorie and split into training, test and validation sets after preprocessing the data with 70%, 15% and 15% respectively.")
242
+ st.markdown("Link to dataset: https://github.com/binhvq/news-corpus")
243
+ st.image("images/sample_data.png", caption="Sample original data", use_column_width=True)
244
+ summary_df = pd.read_csv("assets/summary_data.csv")
245
+ st.dataframe(summary_df)
246
+ train_images = "images/article_by_categories_train_data.html"
247
+ test_images = "images/article_by_categories_test_data.html"
248
+ val_images = "images/article_by_categories_val_data.html"
249
+ plot_data(train_images, test_images, val_images)
250
+ st.image("images/token_length_distribution.png",caption="Distribution of Token Count per Sentence", use_column_width=True)
251
+ elif task_choice == "Process Text Demo":
252
+ st.markdown("**Preprocessing Steps:**")
253
+ st.markdown("- Standardize Vietnamese words, convert to lower case")
254
+ st.markdown("- Utilize techniques such as regular expressions to remove unwanted elements: html, links, emails, numbers,...")
255
+ st.markdown("- Employ a POS tagging tool to determine the grammatical category of each word in the sentence and filter out important components")
256
+
257
+ news_text = st.text_area("Enter Text","Type Here")
258
+ if st.button("Execute"):
259
+ st.subheader("Original Text")
260
+ st.info(news_text)
261
+ preprocessed_news = preprocess_text(news_text)
262
+ st.subheader("Preprocessed Text")
263
+ st.success(preprocessed_news)
264
+ elif task_choice == "Load Preprocessed Data":
265
+ df = pd.read_json(PREPROCESSED_DATA, encoding='utf-8', lines=True)
266
+ st.dataframe(df.head(20), use_container_width=True)
267
+
268
+ # Feature Extration
269
+ if choice == "Feature Extraction":
270
+ st.info("Feature Extraction")
271
+
272
+ feature_extraction_task = ["No Options", "PhoBert"]
273
+ task_choice = st.selectbox("Choose Model",feature_extraction_task)
274
+ if task_choice == "PhoBert":
275
+ st.markdown("**Feature Extraction Steps:**")
276
+ st.markdown("- Tokenize using PhoBert's Tokenizer. Note that when tokenizing we will add two special tokens, [CLS] and [SEP] at the beginning and end of the sentence.")
277
+ st.markdown("- Insert the tokenized text sentence into the model with the attention mask. Attention mask helps the model only focus on words in the sentence and ignore words with additional padding. Added words are marked = 0")
278
+ st.markdown("- Take the output and take the first output vector (which is in the special token position [CLS]) as a feature for the sentence to train or predict (depending on the phase).")
279
+ phobert, tokenizer = load_bert()
280
+ text = st.text_area("Enter Text","Type Here")
281
+ if st.button("Execute"):
282
+ st.subheader("Sentence to ids")
283
+ padded, attention_mask = tokenize_text([text], tokenizer, max_len=256)
284
+ st.write("Padded Sequence:", padded)
285
+ st.write("Attention Mask:", attention_mask)
286
+
287
+ st.subheader("Vector Embedding of Sentence")
288
+ v_features = get_vector_embedding(padded, attention_mask, phobert)
289
+ st.write("Vector Embedding:", v_features)
290
+
291
+
292
+ if choice == "Prediction":
293
+ st.info("Predict with new text")
294
+
295
+ all_dl_models = ["No Options", "BiLSTM + phobertbase", "longformer-phobertbase", "phobertbase"]
296
+ model_choice = st.selectbox("Choose Model", all_dl_models)
297
+
298
+ if model_choice == "BiLSTM + phobertbase":
299
+ model, tokenizer, max_len, phobert = load_models(model_type="bilstm_phobertbase")
300
+ news_text = st.text_area("Enter Text", "Type Here")
301
+ if st.button("Classify"):
302
+ st.header("Original Text")
303
+ st.info(news_text)
304
+ st.header("Predict")
305
+ processed_news = preprocess_text(news_text)
306
+ predicted_label, confidence_df = predict_label(processed_news, tokenizer, phobert, model, class_names, max_len)
307
+ st.subheader("Confidence Per Label")
308
+ st.dataframe(confidence_df, use_container_width=True)
309
+ st.subheader("Predicted Label")
310
+ st.success(predicted_label)
311
+
312
+ if model_choice == "longformer-phobertbase":
313
+ models, tokenizer, max_len = load_models(model_type="longformer")
314
+ news_text = st.text_area("Enter Text", "Type Here")
315
+ if st.button("Classify"):
316
+ st.header("Original Text")
317
+ st.info(news_text)
318
+ st.header("Predict")
319
+ df_confidence, predicted_label = infer(news_text, tokenizer, models, class_names, max_len)
320
+ st.subheader("Confidence Per Label")
321
+ st.dataframe(df_confidence, use_container_width=True)
322
+ st.subheader("Predicted Label")
323
+ st.success(predicted_label)
324
+ if model_choice == "phobertbase":
325
+ models, tokenizer, max_len = load_models(model_type="phobertbase")
326
+ news_text = st.text_area("Enter Text", "Type Here")
327
+ if st.button("Classify"):
328
+ st.header("Original Text")
329
+ st.info(news_text)
330
+ st.header("Predict")
331
+ df_confidence, predicted_label = infer(news_text, tokenizer, models, class_names, max_len)
332
+ st.subheader("Confidence Per Label")
333
+ st.dataframe(df_confidence, use_container_width=True)
334
+ st.subheader("Predicted Label")
335
+ st.success(predicted_label)
336
+ if choice == "Train and Evaluate Models":
337
+ st.info("Train and Evaluate Models")
338
+ training_task = ["No Options", "Model Definitions", "Hyperparameters", "Result of Evaluation"]
339
+ training_choice = st.selectbox("Choose Options", training_task)
340
+ if training_choice == "Model Definitions":
341
+ st.subheader("Longformer-phobertbase Model and Phobertbase Model")
342
+ # Display model architecture
343
+ st.code("""
344
+ class NewsClassifier(nn.Module):
345
+ def __init__(self, n_classes, model_name):
346
+ super(NewsClassifier, self).__init__()
347
+ # Load a pre-trained BERT model
348
+ self.bert = AutoModel.from_pretrained(model_name)
349
+ # Dropout layer to prevent overfitting
350
+ self.drop = nn.Dropout(p=0.3)
351
+ # Fully-connected layer to convert BERT's hidden state to the number of classes to predict
352
+ self.fc = nn.Linear(self.bert.config.hidden_size, n_classes)
353
+ # Initialize weights and biases of the fully-connected layer using the normal distribution method
354
+ nn.init.normal_(self.fc.weight, std=0.02)
355
+ nn.init.normal_(self.fc.bias, 0)
356
+
357
+ def forward(self, input_ids, attention_mask):
358
+ # Get the output from the BERT model
359
+ last_hidden_state, output = self.bert(
360
+ input_ids=input_ids,
361
+ attention_mask=attention_mask,
362
+ return_dict=False
363
+ )
364
+ # Apply dropout
365
+ x = self.drop(output)
366
+ # Pass through the fully-connected layer to get predictions
367
+ x = self.fc(x)
368
+ return x
369
+ """, language='python')
370
+ # Explanation for each layer
371
+ st.markdown("""
372
+ - **Dropout Layer**: The dropout layer with a dropout probability of 0.3 helps prevent overfitting during training.
373
+ - **Fully-connected Layer**: The fully-connected layer (`self.fc`) converts the output of the BERT model to a set of class predictions corresponding to the number of classes. This is achieved by a linear transformation using the BERT hidden size as the input dimension and the number of classes (`n_classes`) as the output dimension.
374
+ - **Weight Initialization**: The weights and biases of the fully-connected layer are initialized using a normal distribution to facilitate better training.
375
+ - **Forward Method**: In the forward method, the BERT model is called with the input IDs and attention mask. The output is passed through the dropout layer and then through the fully-connected layer to produce the final predictions.
376
+ """)
377
+
378
+ st.subheader("BiLSTM Model with Phobert feature extraction")
379
+ # Display model architecture
380
+ st.image("images/bilstm_phobertbase_summary.png")
381
+
382
+ # Explanation for each layer
383
+ st.markdown("""
384
+ **Input Layer (input_1):** This layer accepts the input data and prepares it for further processing by the model.
385
+ It receives input in the shape (None, 1, 768), where `None` represents the batch size, `1` represents the sequence length (or time steps), and `768` represents the feature dimension.
386
+
387
+ **Bidirectional LSTM Layer (bidirectional):** This layer processes the input sequence bidirectionally, combining information from both past and future states to enhance learning.
388
+ It takes input in the shape (None, 1, 768) and outputs (None, 1, 448), reducing the feature dimension to `448`.
389
+
390
+ **Dropout Layer (dropout):** Dropout is applied to regularize the model by randomly setting a fraction of input units to zero during training, preventing overfitting.
391
+ It takes input in the shape (None, 1, 448) and outputs (None, 1, 448), maintaining the same shape as the input.
392
+
393
+ **Second Bidirectional LSTM Layer (bidirectional_1):** Another BiLSTM layer further refines the sequence representation by processing it bidirectionally again.
394
+ It takes input in the shape (None, 1, 448) and outputs (None, 1, 288), reducing the feature dimension to `288`.
395
+
396
+ **Second Dropout Layer (dropout_1):** Another dropout layer is applied to further regularize the model after the second BiLSTM layer.
397
+ It takes input in the shape (None, 288) and outputs (None, 288), maintaining the same shape as the input.
398
+
399
+ **Dense Layer (dense):** This fully connected layer applies a non-linear transformation to the extracted features, aiding in capturing complex patterns in the data.
400
+ It takes input in the shape (None, 288) and outputs (None, 160), reducing the dimensionality of the data to `160`.
401
+
402
+ **Output Dense Layer (dense_1):** The final dense layer with softmax activation produces probabilities across multiple classes, making predictions based on the learned features.
403
+ It takes input in the shape (None, 160) and outputs (None, 13), corresponding to the number of classes in the classification task.
404
+ """)
405
+ if training_choice == "Hyperparameters":
406
+ dl_model = ["No Options", "BiLSTM + phobertbase", "longformer-phobertbase and phobertbase"]
407
+ model_choice = st.selectbox("Choose Model", dl_model)
408
+ if st.button("Show Result"):
409
+ if model_choice == "BiLSTM + phobertbase":
410
+ st.header("Optuna Hyperparameter Optimization")
411
+ st.markdown("""
412
+ We used `Optuna` for hyperparameter optimization due to its efficiency and advanced search algorithms. It automates the optimization process, reducing manual effort and improving model performance.
413
+
414
+ The study is set to `maximize` the target metric. `TPESampler` is used for efficient and adaptive search, while `HyperbandPruner` stops unpromising trials early to save resources and speed up the optimization process.
415
+ """)
416
+
417
+ # Explanation of Optuna terms
418
+ st.subheader("Understanding Optuna Terms")
419
+ st.markdown("""
420
+ **Pruner Trials:** These are trials that Optuna has pruned during the optimization process to reduce resource consumption. Pruning helps discard trials that are unlikely to yield better results or are taking too long to converge.
421
+
422
+ **Complete Trials:** These trials are successfully completed by Optuna and have provided valid results. Optuna uses these trials to evaluate and select the best hyperparameters based on the defined optimization objective.
423
+
424
+ **Failed Trials:** Trials that have encountered errors or failed to complete due to technical issues or improper configurations. These trials do not contribute valid results to the optimization process.
425
+ """)
426
+
427
+ # Load and display trial information
428
+ trials = pd.read_csv("assets/study_bilstm_256_trials.csv")
429
+ st.subheader("Number of Completed Trials out of 100 trials")
430
+ st.dataframe(trials.style.format(precision=6), height=600, hide_index=True, use_container_width=True)
431
+
432
+ # Load best hyperparameters and display
433
+ with open("hyperparameters/BiLSTM_phobertbase.json", 'r', encoding='utf-8') as file:
434
+ bilstm_phobertbase_best_param = json.load(file)
435
+ bilstm_phobertbase_best_param_df = pd.DataFrame([bilstm_phobertbase_best_param])
436
+ st.subheader("Best Hyperparameters")
437
+ st.dataframe(bilstm_phobertbase_best_param_df.style.format(precision=6), hide_index=True, use_container_width=True)
438
+
439
+ # Display optimization history plot with title
440
+ st.subheader("Optimization History Plot")
441
+ with open("images/study_bilstm_phobertbase_optimize_history.html", "r", encoding="utf-8") as f:
442
+ content = f.read()
443
+ st.components.v1.html(content, height=600, scrolling=True)
444
+
445
+ if model_choice == "longformer-phobertbase and phobertbase":
446
+
447
+ with open("./hyperparameters/phobertbase.json", 'r', encoding='utf-8') as file:
448
+ param = json.load(file)
449
+ param_df = pd.DataFrame([param])
450
+ st.subheader("Best Hyperparamters")
451
+ st.dataframe(param_df.style.format(precision=6), hide_index=True, use_container_width=True)
452
+ if training_choice == "Result of Evaluation":
453
+ st.markdown("To evaluate the performance of our models, we used several key metrics:")
454
+ st.markdown("1. **Accuracy**: The proportion of correctly classified instances among the total instances.")
455
+ st.markdown("2. **Precision**: The proportion of true positives among all positive predictions, indicating the accuracy of the positive predictions.")
456
+ st.markdown("3. **Recall**: The proportion of true positives among all actual positives, reflecting the model's ability to capture all relevant instances.")
457
+ st.markdown("4. **F1-score**: The harmonic mean of precision and recall, providing a balance between the two metrics.")
458
+ st.markdown("5. **Confusion Matrix**: A table that displays the true positives, true negatives, false positives, and false negatives, used to evaluate the overall performance and error types of the model.")
459
+ task = ["No Options", "Overall", "Evaluate per Label"]
460
+ task_choice = st.selectbox("Choose Options", task)
461
+ if task_choice == "Overall":
462
+ result = pd.read_csv("assets/model_results.csv")
463
+ st.dataframe(result, height=150, hide_index=True, use_container_width=True)
464
+ if task_choice == "Evaluate per Label":
465
+ st.subheader("Confusion Matrix Comparison")
466
+ col1, col2, col3 = st.columns(3)
467
+
468
+ with col1:
469
+ st.image("images/confusion_matrix_bilstm_phobertbase.png", caption="BiLSTM with PhoBert feature extraction", use_column_width=True)
470
+
471
+ with col2:
472
+ st.image("images/confusion_matrix_phobertbase.png", caption="phobertbase", use_column_width=True)
473
+
474
+ with col3:
475
+ st.image("images/confusion_matrix_longformer.png", caption="longformer-phobertbase", use_column_width=True)
476
+
477
+ st.subheader("Classification Report Comparison")
478
+ col4, col5, col6 = st.columns(3)
479
+
480
+ with col4:
481
+ st.markdown("**BiLSTM with PhoBert feature extraction**")
482
+ bilstm_report = pd.read_csv("assets/classification_report_bilstm_phobertbase.csv")
483
+ st.dataframe(bilstm_report, height=600, hide_index=True, use_container_width=True)
484
+
485
+ with col5:
486
+ st.markdown("**phobertbase**")
487
+ phobertbase_report = pd.read_csv("assets/classification_report_phobertbase.csv")
488
+ st.dataframe(phobertbase_report, height=600, hide_index=True, use_container_width=True)
489
+
490
+ with col6:
491
+ st.markdown("**longformer-phobertbase**")
492
+ longformer_report = pd.read_csv("assets/classification_report_longformer.csv")
493
+ st.dataframe(longformer_report, height=600, hide_index=True, use_container_width=True)
494
+ if choice == "Introduction":
495
+ st.markdown(
496
+ """
497
+ <style>
498
+ .title {
499
+ font-size: 35px;
500
+ font-weight: bold;
501
+ text-align: center;
502
+ color: #2c3e50;
503
+ margin-top: 0px;
504
+ }
505
+ .university {
506
+ font-size: 30px;
507
+ font-weight: bold;
508
+ text-align: center;
509
+ color: #34495e;
510
+ margin-top: 0px;
511
+ }
512
+ .faculty {
513
+ font-size: 30px;
514
+ font-weight: bold;
515
+ text-align: center;
516
+ color: #34495e;
517
+ margin-bottom: 20px;
518
+ }
519
+ .subtitle {
520
+ font-size: 24px;
521
+ font-weight: bold;
522
+ text-align: center;
523
+ color: #34495e;
524
+ margin-bottom: 10px;
525
+ }
526
+ .student-info, .instructor-info {
527
+ font-size: 18px;
528
+ text-align: center;
529
+ color: #7f8c8d;
530
+ margin: 10px 20px;
531
+ }
532
+ .note {
533
+ font-size: 16px;
534
+ color: #95a5a6;
535
+ margin-top: 20px;
536
+ font-style: italic;
537
+ text-align: left;
538
+ margin: 20px;
539
+ }
540
+
541
+ </style>
542
+ """,
543
+ unsafe_allow_html=True
544
+ )
545
+
546
+ st.markdown('<div class="university">HCMC University of Technology and Education</div>', unsafe_allow_html=True)
547
+ st.markdown('<div class="faculty">Faculty of Information Technology</div>', unsafe_allow_html=True)
548
+
549
+ # Use Streamlit's st.image to display the logos
550
+ left_co, cent_co,last_co, t, f, s, s = st.columns(7)
551
+ with t:
552
+ st.image("images/logo.png")
553
+
554
+ st.markdown('<div class="subtitle">Graduation Thesis</div>', unsafe_allow_html=True)
555
+ st.markdown('<div class="title">Vietnamese News and Articles Classification using PhoBERT</div>', unsafe_allow_html=True)
556
+
557
+ st.markdown(
558
+ """
559
+ <div class="student-info">
560
+ <p>Nguyen Thi Dieu Hien - 20133040</p>
561
+ <p>Bui Tan Dat - 20133033</p>
562
+ </div>
563
+
564
+ <div class="instructor-info">
565
+ <p>Instructor: PhD. Nguyen Thanh Son</p>
566
+ </div>
567
+
568
+ <div class="note">
569
+ Note: This is an interactive web application to demonstrate various tasks related to news classification using deep learning models. Choose an activity from the sidebar to get started.
570
+ </div>
571
+ """,
572
+ unsafe_allow_html=True
573
+ )
574
+
575
+ if __name__ == '__main__':
576
+ main()
feature_extraction.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pickle
2
+ from transformers import AutoModel, AutoTokenizer
3
+ from tqdm import tqdm
4
+ import pandas as pd
5
+ import torch
6
+ import numpy as np
7
+ from pyspark.sql import SparkSession
8
+ import time
9
+
10
+ # Paths to JSON data files
11
+ TRAIN_DATA = "data/train_data_162k.json"
12
+ TEST_DATA = "data/test_data_162k.json"
13
+ VAL_DATA = "data/val_data_162k.json"
14
+
15
+ # Function to load BERT model and tokenizer
16
+ def load_bert():
17
+ v_phobert = AutoModel.from_pretrained("vinai/phobert-base-v2")
18
+ v_tokenizer = AutoTokenizer.from_pretrained("vinai/phobert-base-v2", use_fast=False)
19
+ return v_phobert, v_tokenizer
20
+
21
+ # Load BERT model and tokenizer
22
+ phobert, tokenizer = load_bert()
23
+ print("Load model done!")
24
+
25
+ # Initialize SparkSession
26
+ spark = SparkSession.builder \
27
+ .appName("Feature Extraction") \
28
+ .master("local[*]") \
29
+ .config("spark.executor.memory", "50g") \
30
+ .config("spark.executor.instances", "4") \
31
+ .config("spark.executor.cores", "12") \
32
+ .config("spark.memory.offHeap.enabled", True) \
33
+ .config("spark.driver.memory", "50g") \
34
+ .config("spark.memory.offHeap.size", "16g") \
35
+ .config("spark.ui.showConsoleProgress", False) \
36
+ .config("spark.driver.maxResultSize", "16g") \
37
+ .config("spark.log.level", "ERROR") \
38
+ .getOrCreate()
39
+
40
+ # Load JSON data into Spark DataFrames
41
+ train_data = spark.read.json(TRAIN_DATA)
42
+ test_data = spark.read.json(TEST_DATA)
43
+ val_data = spark.read.json(VAL_DATA)
44
+ print("Load data done!")
45
+
46
+ # Function to extract BERT features from text
47
+ def make_bert_features(v_text):
48
+ v_tokenized = []
49
+ max_len = 256 # Maximum sequence length
50
+
51
+ # Use tqdm to display progress
52
+ for i_text in v_text:
53
+ # Tokenize using BERT tokenizer
54
+ line = tokenizer.encode(i_text, truncation=True)
55
+ v_tokenized.append(line)
56
+
57
+ # Pad sequences to ensure consistent length
58
+ padded = []
59
+ for i in v_tokenized:
60
+ if len(i) < max_len:
61
+ padded.append(i + [1] * (max_len - len(i))) # Padding with 1s
62
+ else:
63
+ padded.append(i[:max_len]) # Truncate if sequence is too long
64
+
65
+ padded = np.array(padded)
66
+
67
+ # Create attention mask
68
+ attention_mask = np.where(padded == 1, 0, 1)
69
+
70
+ # Convert to PyTorch tensors
71
+ padded = torch.tensor(padded).to(torch.long)
72
+ attention_mask = torch.tensor(attention_mask)
73
+
74
+ # Obtain features from BERT
75
+ with torch.no_grad():
76
+ last_hidden_states = phobert(input_ids=padded, attention_mask=attention_mask)
77
+
78
+ v_features = last_hidden_states[0][:, 0, :].numpy()
79
+ print(v_features.shape)
80
+ return v_features
81
+
82
+ # Extract BERT features for train, test, and validation datasets
83
+ train_features = train_data.select("processed_content").rdd.map(make_bert_features)
84
+ test_features = test_data.select("processed_content").rdd.map(make_bert_features)
85
+ val_features = val_data.select("processed_content").rdd.map(make_bert_features)
86
+
87
+ # Convert category column to lists
88
+ category_list_train = train_data.select("category").rdd.flatMap(lambda x: x).collect()
89
+ category_list_test = test_data.select("category").rdd.flatMap(lambda x: x).collect()
90
+ category_list_val = val_data.select("category").rdd.flatMap(lambda x: x).collect()
91
+
92
+ # Convert to one-hot encoding using pd.get_dummies()
93
+ y_train = pd.get_dummies(category_list_train)
94
+ y_test = pd.get_dummies(category_list_test)
95
+ y_val = pd.get_dummies(category_list_val)
96
+
97
+ # Save data to file using pickle
98
+ start_time = time.time()
99
+ print("Saving to file")
100
+ data_dict = {
101
+ 'X_train': train_features.collect(),
102
+ 'X_test': test_features.collect(),
103
+ 'X_val': val_features.collect(),
104
+ 'y_train': y_train,
105
+ 'y_test': y_test,
106
+ 'y_val': y_val
107
+ }
108
+
109
+ # Save dictionary to pickle file
110
+ with open('data/features_162k_phobertbase_v2.pkl', 'wb') as f:
111
+ pickle.dump(data_dict, f)
112
+
113
+ end_time = time.time()
114
+ duration = end_time - start_time
115
+ print(f'Total feature extraction time: {duration:.2f} seconds')
116
+ print("Done!")
finetune_PhoBert.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
finetune_PhoBert.py ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+ import pandas as pd
4
+
5
+ from sklearn.model_selection import StratifiedKFold
6
+ from sklearn.metrics import classification_report, confusion_matrix
7
+
8
+ import torch.nn as nn
9
+ from torch.optim import AdamW
10
+ from torch.utils.data import Dataset, DataLoader
11
+
12
+ from transformers import get_linear_schedule_with_warmup, AutoTokenizer, AutoModel, logging
13
+
14
+ import warnings
15
+ import time
16
+ import pickle
17
+ warnings.filterwarnings("ignore")
18
+
19
+ logging.set_verbosity_error()
20
+
21
+ # Function to set seed for reproducibility
22
+ def seed_everything(seed_value):
23
+ np.random.seed(seed_value) # Set seed for numpy random numbers
24
+ torch.manual_seed(seed_value) # Set seed for PyTorch random numbers
25
+
26
+ if torch.cuda.is_available(): # If CUDA is available, set CUDA seed
27
+ torch.cuda.manual_seed(seed_value)
28
+ torch.cuda.manual_seed_all(seed_value)
29
+ torch.backends.cudnn.deterministic = True # Ensure deterministic behavior
30
+ torch.backends.cudnn.benchmark = True # Improve performance by allowing cudnn benchmarking
31
+
32
+ seed_everything(86) # Set seed value for reproducibility
33
+
34
+ model_name = "bluenguyen/longformer-phobert-base-4096" # Pretrained model name
35
+ max_len = 512 # Maximum sequence length for tokenizer (512, but can use 256 if phobertbase)
36
+ n_classes = 13 # Number of output classes
37
+ tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=False) # Load tokenizer
38
+
39
+ device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') # Set device to GPU if available, otherwise CPU
40
+ EPOCHS = 5 # Number of training epochs
41
+ N_SPLITS = 5 # Number of folds for cross-validation
42
+
43
+ TRAIN_PATH = "data/train_data_162k.json"
44
+ TEST_PATH = "data/test_data_162k.json"
45
+ VAL_PATH = "data/val_data_162k.json"
46
+
47
+ # Function to read data from JSON file
48
+ def get_data(path):
49
+ df = pd.read_json(path, lines=True)
50
+ return df
51
+
52
+ # Read the data from JSON files
53
+ train_df = get_data(TRAIN_PATH)
54
+ test_df = get_data(TEST_PATH)
55
+ valid_df = get_data(VAL_PATH)
56
+
57
+ # Combine train and validation data
58
+ train_df = pd.concat([train_df, valid_df], ignore_index=True)
59
+
60
+ # Apply StratifiedKFold
61
+ skf = StratifiedKFold(n_splits=N_SPLITS)
62
+ for fold, (_, val_) in enumerate(skf.split(X=train_df, y=train_df.category)):
63
+ train_df.loc[val_, "kfold"] = fold
64
+
65
+ class NewsDataset(Dataset):
66
+ def __init__(self, df, tokenizer, max_len):
67
+ self.df = df
68
+ self.max_len = max_len
69
+ self.tokenizer = tokenizer
70
+
71
+ def __len__(self):
72
+ return len(self.df)
73
+
74
+ def __getitem__(self, index):
75
+ """
76
+ To customize dataset, inherit from Dataset class and implement
77
+ __len__ & __getitem__
78
+ __getitem__ should return
79
+ data:
80
+ input_ids
81
+ attention_masks
82
+ text
83
+ targets
84
+ """
85
+ row = self.df.iloc[index]
86
+ text, label = self.get_input_data(row)
87
+
88
+ # Encode_plus will:
89
+ # (1) split text into token
90
+ # (2) Add the '[CLS]' and '[SEP]' token to the start and end
91
+ # (3) Truncate/Pad sentence to max length
92
+ # (4) Map token to their IDS
93
+ # (5) Create attention mask
94
+ # (6) Return a dictionary of outputs
95
+ encoding = self.tokenizer.encode_plus(
96
+ text,
97
+ truncation=True,
98
+ add_special_tokens=True,
99
+ max_length=self.max_len,
100
+ padding='max_length',
101
+ return_attention_mask=True,
102
+ return_token_type_ids=False,
103
+ return_tensors='pt',
104
+ )
105
+
106
+ return {
107
+ 'text': text,
108
+ 'input_ids': encoding['input_ids'].flatten(),
109
+ 'attention_masks': encoding['attention_mask'].flatten(),
110
+ 'targets': torch.tensor(label, dtype=torch.long),
111
+ }
112
+
113
+
114
+ def labelencoder(self, text):
115
+ label_map = {
116
+ 'Cong nghe': 0, 'Doi song': 1, 'Giai tri': 2, 'Giao duc': 3, 'Khoa hoc': 4,
117
+ 'Kinh te': 5, 'Nha dat': 6, 'Phap luat': 7, 'The gioi': 8, 'The thao': 9,
118
+ 'Van hoa': 10, 'Xa hoi': 11, 'Xe co': 12
119
+ }
120
+ return label_map.get(text, -1)
121
+
122
+ def get_input_data(self, row):
123
+ text = row['processed_content']
124
+ label = self.labelencoder(row['category'])
125
+ return text, label
126
+
127
+ class NewsClassifier(nn.Module):
128
+ def __init__(self, n_classes, model_name):
129
+ super(NewsClassifier, self).__init__()
130
+ # Load a pre-trained BERT model
131
+ self.bert = AutoModel.from_pretrained(model_name)
132
+ # Dropout layer to prevent overfitting
133
+ self.drop = nn.Dropout(p=0.3)
134
+ # Fully-connected layer to convert BERT's hidden state to the number of classes to predict
135
+ self.fc = nn.Linear(self.bert.config.hidden_size, n_classes)
136
+ # Initialize weights and biases of the fully-connected layer using the normal distribution method
137
+ nn.init.normal_(self.fc.weight, std=0.02)
138
+ nn.init.normal_(self.fc.bias, 0)
139
+
140
+ def forward(self, input_ids, attention_mask):
141
+ # Get the output from the BERT model
142
+ last_hidden_state, output = self.bert(
143
+ input_ids=input_ids,
144
+ attention_mask=attention_mask,
145
+ return_dict=False
146
+ )
147
+ # Apply dropout
148
+ x = self.drop(output)
149
+ # Pass through the fully-connected layer to get predictions
150
+ x = self.fc(x)
151
+ return x
152
+
153
+ def prepare_loaders(df, fold):
154
+ df_train = df[df.kfold != fold].reset_index(drop=True)
155
+ df_valid = df[df.kfold == fold].reset_index(drop=True)
156
+
157
+ train_dataset = NewsDataset(df_train, tokenizer, max_len)
158
+ valid_dataset = NewsDataset(df_valid, tokenizer, max_len)
159
+
160
+ train_loader = DataLoader(train_dataset, batch_size=16, shuffle=True, num_workers=2)
161
+ valid_loader = DataLoader(valid_dataset, batch_size=16, shuffle=True, num_workers=2)
162
+
163
+ return train_loader, valid_loader
164
+
165
+ # Function to train the model for one epoch
166
+ def train(model, criterion, optimizer, train_loader, lr_scheduler):
167
+ model.train() # Set the model to training mode
168
+ losses = [] # List to store losses during training
169
+ correct = 0 # Variable to store number of correct predictions
170
+
171
+ # Iterate over batches in the training data loader
172
+ for batch_idx, data in enumerate(train_loader):
173
+ input_ids = data['input_ids'].to(device) # Move input_ids to GPU/CPU
174
+ attention_mask = data['attention_masks'].to(device) # Move attention_mask to GPU/CPU
175
+ targets = data['targets'].to(device) # Move targets to GPU/CPU
176
+
177
+ optimizer.zero_grad() # Clear gradients from previous iteration
178
+ outputs = model( # Forward pass through the model
179
+ input_ids=input_ids,
180
+ attention_mask=attention_mask
181
+ )
182
+
183
+ loss = criterion(outputs, targets) # Calculate the loss
184
+ _, pred = torch.max(outputs, dim=1) # Get the predicted labels
185
+
186
+ correct += torch.sum(pred == targets) # Count correct predictions
187
+ losses.append(loss.item()) # Append the current loss value to losses list
188
+ loss.backward() # Backpropagation: compute gradients
189
+ nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0) # Clip gradients to prevent exploding gradients
190
+ optimizer.step() # Update model parameters
191
+ lr_scheduler.step() # Update learning rate scheduler
192
+
193
+ # Print training progress every 1000 batches
194
+ if batch_idx % 1000 == 0:
195
+ print(f'Batch {batch_idx}/{len(train_loader)} - Loss: {loss.item():.4f}, Accuracy: {correct.double() / ((batch_idx + 1) * train_loader.batch_size):.4f}')
196
+
197
+ train_accuracy = correct.double() / len(train_loader.dataset) # Calculate training accuracy
198
+ avg_loss = np.mean(losses) # Calculate average loss
199
+ print(f'Train Accuracy: {train_accuracy:.4f} Loss: {avg_loss:.4f}')
200
+
201
+ # Function to evaluate the model
202
+ def eval(model, criterion, valid_loader, test_loader=None):
203
+ model.eval() # Set the model to evaluation mode
204
+ losses = [] # List to store losses during evaluation
205
+ correct = 0 # Variable to store number of correct predictions
206
+
207
+ with torch.no_grad(): # Disable gradient calculation for evaluation
208
+ data_loader = test_loader if test_loader else valid_loader # Choose between test and validation data loader
209
+ for batch_idx, data in enumerate(data_loader):
210
+ input_ids = data['input_ids'].to(device) # Move input_ids to GPU/CPU
211
+ attention_mask = data['attention_masks'].to(device) # Move attention_mask to GPU/CPU
212
+ targets = data['targets'].to(device) # Move targets to GPU/CPU
213
+
214
+ outputs = model( # Forward pass through the model
215
+ input_ids=input_ids,
216
+ attention_mask=attention_mask
217
+ )
218
+
219
+ loss = criterion(outputs, targets) # Calculate the loss
220
+ _, pred = torch.max(outputs, dim=1) # Get the predicted labels
221
+
222
+ correct += torch.sum(pred == targets) # Count correct predictions
223
+ losses.append(loss.item()) # Append the current loss value to losses list
224
+
225
+ dataset_size = len(test_loader.dataset) if test_loader else len(valid_loader.dataset) # Determine dataset size
226
+ accuracy = correct.double() / dataset_size # Calculate accuracy
227
+ avg_loss = np.mean(losses) # Calculate average loss
228
+
229
+ # Print evaluation results (either test or validation)
230
+ if test_loader:
231
+ print(f'Test Accuracy: {accuracy:.4f} Loss: {avg_loss:.4f}')
232
+ else:
233
+ print(f'Valid Accuracy: {accuracy:.4f} Loss: {avg_loss:.4f}')
234
+
235
+ return accuracy # Return accuracy for further analysis or logging
236
+
237
+ total_start_time = time.time()
238
+
239
+ # Main training loop
240
+ for fold in range(skf.n_splits):
241
+ print(f'----------- Fold: {fold + 1} ------------------')
242
+ train_loader, valid_loader = prepare_loaders(train_df, fold=fold)
243
+ model = NewsClassifier(n_classes=13).to(device)
244
+ criterion = nn.CrossEntropyLoss()
245
+ optimizer = AdamW(model.parameters(), lr=2e-5)
246
+
247
+ lr_scheduler = get_linear_schedule_with_warmup(
248
+ optimizer,
249
+ num_warmup_steps=0,
250
+ num_training_steps=len(train_loader) * EPOCHS
251
+ )
252
+ best_acc = 0
253
+
254
+ for epoch in range(EPOCHS):
255
+ print(f'Epoch {epoch + 1}/{EPOCHS}')
256
+ print('-' * 30)
257
+
258
+ train(model, criterion, optimizer, train_loader, lr_scheduler)
259
+ val_acc = eval(model, criterion, valid_loader)
260
+
261
+ if val_acc > best_acc:
262
+ torch.save(model.state_dict(), f'phobert_fold{fold + 1}.pth')
263
+ best_acc = val_acc
264
+ print(f'Best Accuracy for Fold {fold + 1}: {best_acc:.4f}')
265
+ print()
266
+ print(f'Finished Fold {fold + 1} with Best Accuracy: {best_acc:.4f}')
267
+ print('--------------------------------------')
268
+
269
+
270
+ total_end_time = time.time()
271
+
272
+ total_duration = total_end_time - total_start_time
273
+ print(f'Total training time: {total_duration:.2f} seconds')
optimize_bilstm.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import optuna
2
+ import numpy as np
3
+ import pandas as pd
4
+ import json
5
+ import tensorflow as tf
6
+ from tensorflow.compat.v1 import ConfigProto
7
+ from tensorflow.compat.v1 import InteractiveSession
8
+ from tensorflow.keras.models import Sequential
9
+ from tensorflow.keras.layers import Input, Bidirectional, LSTM, Dropout, Dense
10
+ from tensorflow.keras.optimizers import Adam
11
+ from optuna.integration import TFKerasPruningCallback
12
+ import pickle
13
+ from optuna.visualization import plot_optimization_history
14
+ import optuna.visualization as ov
15
+ from optuna.trial import TrialState
16
+
17
+ config = ConfigProto()
18
+ config.gpu_options.allow_growth = True
19
+ session = InteractiveSession(config=config)
20
+
21
+ """### **Load data**"""
22
+
23
+ # Load dữ liệu từ file pickle
24
+ with open('data/features_162k_phobertbase.pkl', 'rb') as f:
25
+ data_dict = pickle.load(f)
26
+
27
+ # Trích xuất các đặc trưng và nhãn từ dictionary
28
+ X_train = np.array(data_dict['X_train'])
29
+ X_val = np.array(data_dict['X_val'])
30
+ X_test = np.array(data_dict['X_test'])
31
+ y_train = data_dict['y_train']
32
+ y_val = data_dict['y_val']
33
+ y_test = data_dict['y_test']
34
+
35
+ y_train = y_train.values.astype(int)
36
+ y_test = y_test.values.astype(int)
37
+ y_val = y_val.values.astype(int)
38
+
39
+ """##**Build Model**"""
40
+
41
+ # Define the BiLSTM model architecture
42
+ def build_bilstm_model(lstm_units_1, lstm_units_2, dense_units, dropout_rate, learning_rate):
43
+ model = Sequential()
44
+ model.add(Input(shape=(X_train.shape[1], X_train.shape[2])))
45
+ # Lớp LSTM 1 với dropout
46
+ model.add(Bidirectional(LSTM(lstm_units_1, return_sequences=True)))
47
+ model.add(Dropout(dropout_rate))
48
+ # Lớp LSTM 2 với dropout
49
+ model.add(Bidirectional(LSTM(lstm_units_2, return_sequences=False)))
50
+ model.add(Dropout(dropout_rate))
51
+ # Lớp Dense với dropout và kích hoạt ReLU
52
+ model.add(Dense(dense_units, activation='relu'))
53
+ model.add(Dropout(dropout_rate))
54
+ # Lớp Dense cuối cùng với kích hoạt softmax
55
+ model.add(Dense(y_train.shape[1], activation='softmax'))
56
+ # Sử dụng tối ưu hóa Adam với learning rate được truyền vào
57
+ optimizer = Adam(learning_rate=learning_rate)
58
+ # Biên soạn mô hình
59
+ model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['accuracy'])
60
+
61
+ return model
62
+
63
+ """##**Create objective**"""
64
+
65
+ # Define the objective function for optimization
66
+ def objective_bilstm(trial):
67
+ lstm_units_1 = trial.suggest_int('lstm_units_1', 64, 512, step=32)
68
+ lstm_units_2 = trial.suggest_int('lstm_units_2', lstm_units_1//2, lstm_units_1, step=32)
69
+ dense_units = trial.suggest_int('dense_units', 64, 512, step=32)
70
+ dropout_rate = trial.suggest_float('dropout_rate', 0.2, 0.5, step=0.1)
71
+ learning_rate = trial.suggest_float('learning_rate', 1e-5, 1e-2, log=True)
72
+ epochs = trial.suggest_int('epochs', 10, 30, step=10)
73
+ batch_size = trial.suggest_int('batch_size', 64, 256, step=32)
74
+
75
+ print(f"Trying hyperparameters: lstm_units_1={lstm_units_1}, lstm_units_2={lstm_units_2}, dense_units={dense_units}, "
76
+ f"dropout_rate={dropout_rate}, learning_rate={learning_rate}, batch_size={batch_size}")
77
+
78
+ model = build_bilstm_model(lstm_units_1, lstm_units_2, dense_units, dropout_rate, learning_rate)
79
+
80
+ model.fit(X_train, y_train, epochs=epochs, batch_size=batch_size,
81
+ validation_data=(X_val, y_val), callbacks=[TFKerasPruningCallback(trial, "val_loss")], verbose=1)
82
+
83
+ _, accuracy = model.evaluate(X_test, y_test, verbose=0)
84
+
85
+ return accuracy
86
+
87
+ """##**Study to find hyperparameters**"""
88
+
89
+ # Create an Optuna study for optimization
90
+ study_bilstm = optuna.create_study(direction="maximize", sampler=optuna.samplers.TPESampler(), pruner=optuna.pruners.HyperbandPruner())
91
+ study_bilstm.optimize(lambda trial: objective_bilstm(trial), n_trials=100)
92
+
93
+ # Save completed trials to a CSV file
94
+ complete_trials = study_bilstm.trials_dataframe()[study_bilstm.trials_dataframe()['state'] == 'COMPLETE']
95
+ complete_trials.to_csv("assets/study_bilstm_256_trials.csv", index=False)
96
+
97
+ # Extract the best hyperparameters
98
+ best_hyperparameters_bilstm = study_bilstm.best_trial.params
99
+
100
+ # Save the best hyperparameters to a JSON file
101
+ with open('hyperparameters/BiLSTM_phobertbase.json', 'w') as file:
102
+ json.dump(best_hyperparameters_bilstm, file)
103
+
104
+ plot_optimization_history(study_bilstm)
105
+
106
+ html_file_path = "images/study_bilstm_phobertbase_optimize_history.html"
107
+ # Plot and save the optimization history plot as an HTML file
108
+ ov.plot_optimization_history(study_bilstm).write_html(html_file_path)
109
+ plot_optimization_history(study_bilstm)
preprocess_data.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import phonlp
2
+ import underthesea
3
+ from pyspark.sql import SparkSession
4
+ from pyspark.sql.functions import udf, StringType
5
+ import re
6
+
7
+ # Paths to original and processed data files
8
+ ORIGINAL_DATA = "./data/news_v2/news_v2.json"
9
+ PROCESSED_DATA = "./data/processed_data/final_data.json"
10
+
11
+ # Load NLP model
12
+ nlp_model = phonlp.load(save_dir="./phonlp")
13
+
14
+ # Initialize SparkSession
15
+ spark = SparkSession.builder \
16
+ .appName("Preprocessing") \
17
+ .master("local[*]") \
18
+ .config("spark.executor.memory", "8g") \
19
+ .config("spark.executor.instances", "64") \
20
+ .config("spark.executor.cores", "1") \
21
+ .config("spark.memory.offHeap.enabled", True) \
22
+ .config("spark.driver.memory", "50g") \
23
+ .config("spark.memory.offHeap.size", "16g") \
24
+ .config("spark.ui.showConsoleProgress", False) \
25
+ .config("spark.driver.maxResultSize", "8g") \
26
+ .config("spark.log.level", "ERROR") \
27
+ .getOrCreate()
28
+
29
+ print("Loading data....")
30
+ df = spark.read.json(ORIGINAL_DATA)
31
+
32
+ # Function to preprocess text
33
+ def preprocess_text(text):
34
+ text = re.sub(r'[^\w\s.]', '', text) # Remove special characters
35
+ # Tokenize text into sentences
36
+ sentences = underthesea.sent_tokenize(text)
37
+
38
+ # List to store preprocessed words
39
+ preprocessed_words = []
40
+
41
+ # Iterate through each sentence
42
+ for sentence in sentences:
43
+ try:
44
+ word_tokens = underthesea.word_tokenize(sentence, format="text")
45
+ # Tokenize words and perform POS tagging
46
+ tags = nlp_model.annotate(word_tokens, batch_size=64)
47
+
48
+ # Filter words based on POS tags
49
+ filtered_words = [word.lower() for word, tag in zip(tags[0][0], tags[1][0]) if tag[0] not in ['M', 'X', 'CH']
50
+ and word not in ["'", ","]]
51
+
52
+ # Append filtered words to the result list
53
+ preprocessed_words.extend(filtered_words)
54
+ except Exception as e:
55
+ pass
56
+
57
+ # Convert list of words to string and return
58
+ return ' '.join(preprocessed_words)
59
+
60
+ # Register preprocess_text function as a Spark UDF
61
+ preprocess_udf = udf(lambda text: preprocess_text(text), StringType())
62
+
63
+ # Add "processed_content" column to DataFrame by applying preprocess_text function to "content" column
64
+ df_processed = df.withColumn("processed_content", preprocess_udf(df["content"]))
65
+
66
+ # Select "processed_content" and "category" columns from DataFrame
67
+ selected_columns = ["processed_content", "category"]
68
+ df_selected = df_processed.select(selected_columns)
69
+
70
+ # Number of partitions
71
+ num_partitions = 1024
72
+
73
+ # Write DataFrame with specified number of partitions
74
+ df_selected.repartition(num_partitions).coalesce(1).write.json(PROCESSED_DATA)
requirements.txt ADDED
@@ -0,0 +1,516 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ absl-py==1.4.0
2
+ aiohttp==3.9.5
3
+ aiosignal==1.3.1
4
+ alabaster==0.7.16
5
+ albumentations==1.3.1
6
+ altair==4.2.2
7
+ annotated-types==0.7.0
8
+ anyio==3.7.1
9
+ argon2-cffi==23.1.0
10
+ argon2-cffi-bindings==21.2.0
11
+ array_record==0.5.1
12
+ arviz==0.15.1
13
+ astropy==5.3.4
14
+ astunparse==1.6.3
15
+ async-timeout==4.0.3
16
+ atpublic==4.1.0
17
+ attrs==23.2.0
18
+ audioread==3.0.1
19
+ autograd==1.6.2
20
+ Babel==2.15.0
21
+ backcall==0.2.0
22
+ beautifulsoup4==4.12.3
23
+ bidict==0.23.1
24
+ bigframes==1.10.0
25
+ bleach==6.1.0
26
+ blinker==1.4
27
+ blis==0.7.11
28
+ blosc2==2.0.0
29
+ bokeh==3.3.4
30
+ bqplot==0.12.43
31
+ branca==0.7.2
32
+ build==1.2.1
33
+ CacheControl==0.14.0
34
+ cachetools==5.3.3
35
+ catalogue==2.0.10
36
+ certifi==2024.6.2
37
+ cffi==1.16.0
38
+ chardet==5.2.0
39
+ charset-normalizer==3.3.2
40
+ chex==0.1.86
41
+ click==8.1.7
42
+ click-plugins==1.1.1
43
+ cligj==0.7.2
44
+ cloudpathlib==0.18.1
45
+ cloudpickle==2.2.1
46
+ cmake==3.27.9
47
+ cmdstanpy==1.2.4
48
+ colorcet==3.1.0
49
+ colorlover==0.3.0
50
+ colour==0.1.5
51
+ community==1.0.0b1
52
+ confection==0.1.5
53
+ cons==0.4.6
54
+ contextlib2==21.6.0
55
+ contourpy==1.2.1
56
+ cryptography==42.0.8
57
+ cuda-python==12.2.1
58
+ cudf-cu12==24.4.1
59
+ cufflinks==0.17.3
60
+ cupy-cuda12x==12.2.0
61
+ cvxopt==1.3.2
62
+ cvxpy==1.3.4
63
+ cycler==0.12.1
64
+ cymem==2.0.8
65
+ Cython==3.0.10
66
+ dask==2023.8.1
67
+ datascience==0.17.6
68
+ db-dtypes==1.2.0
69
+ dbus-python==1.2.18
70
+ debugpy==1.6.6
71
+ decorator==4.4.2
72
+ defusedxml==0.7.1
73
+ distributed==2023.8.1
74
+ distro==1.7.0
75
+ dlib==19.24.4
76
+ dm-tree==0.1.8
77
+ docstring_parser==0.16
78
+ docutils==0.18.1
79
+ dopamine_rl==4.0.9
80
+ duckdb==0.10.3
81
+ earthengine-api==0.1.409
82
+ easydict==1.13
83
+ ecos==2.0.14
84
+ editdistance==0.6.2
85
+ eerepr==0.0.4
86
+ en-core-web-sm==3.7.1
87
+ entrypoints==0.4
88
+ et-xmlfile==1.1.0
89
+ etils==1.7.0
90
+ etuples==0.3.9
91
+ exceptiongroup==1.2.1
92
+ fastai==2.7.15
93
+ fastcore==1.5.48
94
+ fastdownload==0.0.7
95
+ fastjsonschema==2.20.0
96
+ fastprogress==1.0.3
97
+ fastrlock==0.8.2
98
+ filelock==3.15.4
99
+ fiona==1.9.6
100
+ firebase-admin==5.3.0
101
+ Flask==2.2.5
102
+ flatbuffers==24.3.25
103
+ flax==0.8.4
104
+ folium==0.14.0
105
+ fonttools==4.53.0
106
+ frozendict==2.4.4
107
+ frozenlist==1.4.1
108
+ fsspec==2023.6.0
109
+ future==0.18.3
110
+ gast==0.6.0
111
+ gcsfs==2023.6.0
112
+ GDAL==3.6.4
113
+ gdown==5.1.0
114
+ geemap==0.32.1
115
+ gensim==4.3.2
116
+ geocoder==1.38.1
117
+ geographiclib==2.0
118
+ geopandas==0.13.2
119
+ geopy==2.3.0
120
+ gin-config==0.5.0
121
+ gitdb==4.0.11
122
+ GitPython==3.1.43
123
+ glob2==0.7
124
+ google==2.0.3
125
+ google-ai-generativelanguage==0.6.4
126
+ google-api-core==2.16.2
127
+ google-api-python-client==2.84.0
128
+ google-auth==2.27.0
129
+ google-auth-httplib2==0.1.1
130
+ google-auth-oauthlib==1.2.0
131
+ google-cloud-aiplatform==1.57.0
132
+ google-cloud-bigquery==3.21.0
133
+ google-cloud-bigquery-connection==1.12.1
134
+ google-cloud-bigquery-storage==2.25.0
135
+ google-cloud-bigtable==2.24.0
136
+ google-cloud-core==2.3.3
137
+ google-cloud-datastore==2.15.2
138
+ google-cloud-firestore==2.11.1
139
+ google-cloud-functions==1.13.3
140
+ google-cloud-iam==2.15.0
141
+ google-cloud-language==2.13.3
142
+ google-cloud-resource-manager==1.12.3
143
+ google-cloud-storage==2.8.0
144
+ google-cloud-translate==3.11.3
145
+ google-colab==1.0.0
146
+ google-crc32c==1.5.0
147
+ google-generativeai==0.5.4
148
+ google-pasta==0.2.0
149
+ google-resumable-media==2.7.1
150
+ googleapis-common-protos==1.63.2
151
+ googledrivedownloader==0.4
152
+ graphviz==0.20.3
153
+ greenlet==3.0.3
154
+ grpc-google-iam-v1==0.13.1
155
+ grpcio==1.64.1
156
+ grpcio-status==1.48.2
157
+ gspread==6.0.2
158
+ gspread-dataframe==3.3.1
159
+ gym==0.25.2
160
+ gym-notices==0.0.8
161
+ h5netcdf==1.3.0
162
+ h5py==3.9.0
163
+ holidays==0.51
164
+ holoviews==1.17.1
165
+ html5lib==1.1
166
+ httpimport==1.3.1
167
+ httplib2==0.22.0
168
+ huggingface-hub==0.23.4
169
+ humanize==4.7.0
170
+ hyperopt==0.2.7
171
+ ibis-framework==8.0.0
172
+ idna==3.7
173
+ imageio==2.31.6
174
+ imageio-ffmpeg==0.5.1
175
+ imagesize==1.4.1
176
+ imbalanced-learn==0.10.1
177
+ imgaug==0.4.0
178
+ immutabledict==4.2.0
179
+ importlib_metadata==8.0.0
180
+ importlib_resources==6.4.0
181
+ imutils==0.5.4
182
+ inflect==7.0.0
183
+ iniconfig==2.0.0
184
+ intel-openmp==2023.2.4
185
+ ipyevents==2.0.2
186
+ ipyfilechooser==0.6.0
187
+ ipykernel==5.5.6
188
+ ipyleaflet==0.18.2
189
+ ipyparallel==8.8.0
190
+ ipython==7.34.0
191
+ ipython-genutils==0.2.0
192
+ ipython-sql==0.5.0
193
+ ipytree==0.2.2
194
+ ipywidgets==7.7.1
195
+ itsdangerous==2.2.0
196
+ jax==0.4.26
197
+ jaxlib==0.4.26+cuda12.cudnn89
198
+ jeepney==0.7.1
199
+ jellyfish==1.0.4
200
+ jieba==0.42.1
201
+ Jinja2==3.1.4
202
+ joblib==1.4.2
203
+ jsonpickle==3.2.2
204
+ jsonschema==4.19.2
205
+ jsonschema-specifications==2023.12.1
206
+ jupyter-client==6.1.12
207
+ jupyter-console==6.1.0
208
+ jupyter_core==5.7.2
209
+ jupyter-server==1.24.0
210
+ jupyterlab_pygments==0.3.0
211
+ jupyterlab_widgets==3.0.11
212
+ kaggle==1.6.14
213
+ kagglehub==0.2.5
214
+ keras==2.15.0
215
+ keyring==23.5.0
216
+ kiwisolver==1.4.5
217
+ langcodes==3.4.0
218
+ language_data==1.2.0
219
+ launchpadlib==1.10.16
220
+ lazr.restfulclient==0.14.4
221
+ lazr.uri==1.0.6
222
+ lazy_loader==0.4
223
+ libclang==18.1.1
224
+ librosa==0.10.2.post1
225
+ lightgbm==4.1.0
226
+ linkify-it-py==2.0.3
227
+ llvmlite==0.41.1
228
+ locket==1.0.0
229
+ logical-unification==0.4.6
230
+ lxml==4.9.4
231
+ malloy==2023.1067
232
+ marisa-trie==1.2.0
233
+ Markdown==3.6
234
+ markdown-it-py==3.0.0
235
+ MarkupSafe==2.1.5
236
+ matplotlib==3.7.1
237
+ matplotlib-inline==0.1.7
238
+ matplotlib-venn==0.11.10
239
+ mdit-py-plugins==0.4.1
240
+ mdurl==0.1.2
241
+ miniKanren==1.0.3
242
+ missingno==0.5.2
243
+ mistune==0.8.4
244
+ mizani==0.9.3
245
+ mkl==2023.2.0
246
+ ml-dtypes==0.2.0
247
+ mlxtend==0.22.0
248
+ more-itertools==10.1.0
249
+ moviepy==1.0.3
250
+ mpmath==1.3.0
251
+ msgpack==1.0.8
252
+ multidict==6.0.5
253
+ multipledispatch==1.0.0
254
+ multitasking==0.0.11
255
+ murmurhash==1.0.10
256
+ music21==9.1.0
257
+ natsort==8.4.0
258
+ nbclassic==1.1.0
259
+ nbclient==0.10.0
260
+ nbconvert==6.5.4
261
+ nbformat==5.10.4
262
+ nest-asyncio==1.6.0
263
+ networkx==3.3
264
+ nibabel==4.0.2
265
+ nltk==3.8.1
266
+ notebook==6.5.5
267
+ notebook_shim==0.2.4
268
+ numba==0.58.1
269
+ numexpr==2.10.1
270
+ numpy==1.25.2
271
+ nvidia-cublas-cu12==12.1.3.1
272
+ nvidia-cuda-cupti-cu12==12.1.105
273
+ nvidia-cuda-nvrtc-cu12==12.1.105
274
+ nvidia-cuda-runtime-cu12==12.1.105
275
+ nvidia-cudnn-cu12==8.9.2.26
276
+ nvidia-cufft-cu12==11.0.2.54
277
+ nvidia-curand-cu12==10.3.2.106
278
+ nvidia-cusolver-cu12==11.4.5.107
279
+ nvidia-cusparse-cu12==12.1.0.106
280
+ nvidia-nccl-cu12==2.20.5
281
+ nvidia-nvjitlink-cu12==12.5.82
282
+ nvidia-nvtx-cu12==12.1.105
283
+ nvtx==0.2.10
284
+ oauth2client==4.1.3
285
+ oauthlib==3.2.2
286
+ opencv-contrib-python==4.8.0.76
287
+ opencv-python==4.8.0.76
288
+ opencv-python-headless==4.10.0.84
289
+ openpyxl==3.1.5
290
+ opt-einsum==3.3.0
291
+ optax==0.2.2
292
+ orbax-checkpoint==0.4.4
293
+ osqp==0.6.2.post8
294
+ packaging==24.1
295
+ pandas==2.0.3
296
+ pandas-datareader==0.10.0
297
+ pandas-gbq==0.19.2
298
+ pandas-stubs==2.0.3.230814
299
+ pandocfilters==1.5.1
300
+ panel==1.3.8
301
+ param==2.1.1
302
+ parso==0.8.4
303
+ parsy==2.1
304
+ partd==1.4.2
305
+ pathlib==1.0.1
306
+ patsy==0.5.6
307
+ peewee==3.17.5
308
+ pexpect==4.9.0
309
+ phonlp==0.3.4
310
+ pickleshare==0.7.5
311
+ Pillow==9.4.0
312
+ pip==23.1.2
313
+ pip-tools==6.13.0
314
+ platformdirs==4.2.2
315
+ plotly==5.15.0
316
+ plotnine==0.12.4
317
+ pluggy==1.5.0
318
+ polars==0.20.2
319
+ pooch==1.8.2
320
+ portpicker==1.5.2
321
+ prefetch-generator==1.0.3
322
+ preshed==3.0.9
323
+ prettytable==3.10.0
324
+ proglog==0.1.10
325
+ progressbar2==4.2.0
326
+ prometheus_client==0.20.0
327
+ promise==2.3
328
+ prompt_toolkit==3.0.47
329
+ prophet==1.1.5
330
+ proto-plus==1.24.0
331
+ protobuf==3.20.3
332
+ psutil==5.9.5
333
+ psycopg2==2.9.9
334
+ ptyprocess==0.7.0
335
+ py-cpuinfo==9.0.0
336
+ py4j==0.10.9.7
337
+ pyarrow==14.0.2
338
+ pyarrow-hotfix==0.6
339
+ pyasn1==0.6.0
340
+ pyasn1_modules==0.4.0
341
+ pycocotools==2.0.8
342
+ pycparser==2.22
343
+ pydantic==2.7.4
344
+ pydantic_core==2.18.4
345
+ pydata-google-auth==1.8.2
346
+ pydeck==0.9.1
347
+ pydot==1.4.2
348
+ pydot-ng==2.0.0
349
+ pydotplus==2.0.2
350
+ PyDrive==1.3.1
351
+ PyDrive2==1.6.3
352
+ pyerfa==2.0.1.4
353
+ pygame==2.6.0
354
+ Pygments==2.16.1
355
+ PyGObject==3.42.1
356
+ PyJWT==2.3.0
357
+ pymc==5.10.4
358
+ pymystem3==0.2.0
359
+ pynvjitlink-cu12==0.2.4
360
+ PyOpenGL==3.1.7
361
+ pyOpenSSL==24.1.0
362
+ pyparsing==3.1.2
363
+ pyperclip==1.9.0
364
+ pyproj==3.6.1
365
+ pyproject_hooks==1.1.0
366
+ pyshp==2.3.1
367
+ PySocks==1.7.1
368
+ pytensor==2.18.6
369
+ pytest==7.4.4
370
+ python-apt==0.0.0
371
+ python-box==7.2.0
372
+ python-crfsuite==0.9.10
373
+ python-dateutil==2.8.2
374
+ python-louvain==0.16
375
+ python-slugify==8.0.4
376
+ python-utils==3.8.2
377
+ pytz==2023.4
378
+ pyviz_comms==3.0.2
379
+ PyWavelets==1.6.0
380
+ PyYAML==6.0.1
381
+ pyzmq==24.0.1
382
+ qdldl==0.1.7.post4
383
+ qudida==0.0.4
384
+ ratelim==0.1.6
385
+ referencing==0.35.1
386
+ regex==2024.5.15
387
+ requests==2.31.0
388
+ requests-oauthlib==1.3.1
389
+ requirements-parser==0.9.0
390
+ rich==13.7.1
391
+ rmm-cu12==24.4.0
392
+ rpds-py==0.18.1
393
+ rpy2==3.4.2
394
+ rsa==4.9
395
+ safetensors==0.4.3
396
+ scikit-image==0.19.3
397
+ scikit-learn==1.2.2
398
+ scipy==1.11.4
399
+ scooby==0.10.0
400
+ scs==3.2.5
401
+ seaborn==0.13.1
402
+ SecretStorage==3.3.1
403
+ Send2Trash==1.8.3
404
+ sentencepiece==0.1.99
405
+ session-info==1.0.0
406
+ setuptools==67.7.2
407
+ shapely==2.0.4
408
+ shellingham==1.5.4
409
+ simple_parsing==0.1.5
410
+ six==1.16.0
411
+ sklearn-pandas==2.2.0
412
+ smart-open==7.0.4
413
+ smmap==5.0.1
414
+ sniffio==1.3.1
415
+ snowballstemmer==2.2.0
416
+ sortedcontainers==2.4.0
417
+ soundfile==0.12.1
418
+ soupsieve==2.5
419
+ soxr==0.3.7
420
+ spacy==3.7.5
421
+ spacy-legacy==3.0.12
422
+ spacy-loggers==1.0.5
423
+ Sphinx==5.0.2
424
+ sphinxcontrib-applehelp==1.0.8
425
+ sphinxcontrib-devhelp==1.0.6
426
+ sphinxcontrib-htmlhelp==2.0.5
427
+ sphinxcontrib-jsmath==1.0.1
428
+ sphinxcontrib-qthelp==1.0.7
429
+ sphinxcontrib-serializinghtml==1.1.10
430
+ SQLAlchemy==2.0.31
431
+ sqlglot==20.11.0
432
+ sqlparse==0.5.0
433
+ srsly==2.4.8
434
+ stanio==0.5.0
435
+ statsmodels==0.14.2
436
+ stdlib-list==0.10.0
437
+ streamlit==1.36.0
438
+ StrEnum==0.4.15
439
+ sympy==1.12.1
440
+ tables==3.8.0
441
+ tabulate==0.9.0
442
+ tbb==2021.13.0
443
+ tblib==3.0.0
444
+ tenacity==8.4.2
445
+ tensorboard==2.15.2
446
+ tensorboard-data-server==0.7.2
447
+ tensorflow==2.15.0
448
+ tensorflow-datasets==4.9.6
449
+ tensorflow-estimator==2.15.0
450
+ tensorflow-gcs-config==2.15.0
451
+ tensorflow-hub==0.16.1
452
+ tensorflow-io-gcs-filesystem==0.37.0
453
+ tensorflow-metadata==1.15.0
454
+ tensorflow-probability==0.23.0
455
+ tensorstore==0.1.45
456
+ termcolor==2.4.0
457
+ terminado==0.18.1
458
+ text-unidecode==1.3
459
+ textblob==0.17.1
460
+ tf_keras==2.15.1
461
+ tf-slim==1.1.0
462
+ thinc==8.2.5
463
+ threadpoolctl==3.5.0
464
+ tifffile==2024.6.18
465
+ tinycss2==1.3.0
466
+ tokenizers==0.19.1
467
+ toml==0.10.2
468
+ tomli==2.0.1
469
+ toolz==0.12.1
470
+ torch==2.3.0+cu121
471
+ torchaudio==2.3.0+cu121
472
+ torchsummary==1.5.1
473
+ torchtext==0.18.0
474
+ torchvision==0.18.0+cu121
475
+ tornado==6.3.3
476
+ tqdm==4.66.4
477
+ traitlets==5.7.1
478
+ traittypes==0.2.1
479
+ transformers==4.41.2
480
+ triton==2.3.0
481
+ tweepy==4.14.0
482
+ typer==0.12.3
483
+ types-pytz==2024.1.0.20240417
484
+ types-setuptools==70.1.0.20240627
485
+ typing_extensions==4.12.2
486
+ tzdata==2024.1
487
+ tzlocal==5.2
488
+ uc-micro-py==1.0.3
489
+ underthesea==6.8.4
490
+ underthesea_core==1.0.4
491
+ uritemplate==4.1.1
492
+ urllib3==2.0.7
493
+ vega-datasets==0.9.0
494
+ wadllib==1.3.6
495
+ wasabi==1.1.3
496
+ watchdog==4.0.1
497
+ wcwidth==0.2.13
498
+ weasel==0.4.1
499
+ webcolors==24.6.0
500
+ webencodings==0.5.1
501
+ websocket-client==1.8.0
502
+ Werkzeug==3.0.3
503
+ wheel==0.43.0
504
+ widgetsnbextension==3.6.6
505
+ wordcloud==1.9.3
506
+ wrapt==1.14.1
507
+ xarray==2023.7.0
508
+ xarray-einstats==0.7.0
509
+ xgboost==2.0.3
510
+ xlrd==2.0.1
511
+ xyzservices==2024.6.0
512
+ yarl==1.9.4
513
+ yellowbrick==1.5
514
+ yfinance==0.2.40
515
+ zict==3.0.0
516
+ zipp==3.19.2
train_BiLSTM.ipynb ADDED
The diff for this file is too large to render. See raw diff