Spaces:
Build error
Build error
init project
Browse files- .gitignore +91 -0
- LICENSE +10 -0
- notebooks/0.0-create-sliding-window.ipynb +381 -0
- notebooks/0.1-find-dirty-data.ipynb +2071 -0
- notebooks/0.2-create-stage1-ranking.ipynb +0 -0
- notebooks/0.3-create-stage2-ranking.ipynb +1 -0
- notebooks/0.4-find-redirects.ipynb +0 -0
- notebooks/1.0-train-bm25-stage1.ipynb +1 -0
- notebooks/1.1-train-bm25-stage2.ipynb +1 -0
- notebooks/1.2-train-pairwise-stage1.ipynb +1 -0
- notebooks/1.3-train-pairwise-stage2.ipynb +0 -0
- notebooks/1.4-robust-qa-model.ipynb +0 -0
- requirements.txt +7 -0
- src/app.py +26 -0
- src/features/graph_utils.py +110 -0
- src/features/text_utils.py +82 -0
- src/models/bm25_utils.py +40 -0
- src/models/pairwise_model.py +140 -0
- src/models/predict_model.py +75 -0
- src/models/qa_model.py +52 -0
- submission/answer.json +0 -0
- submission/submission.json +0 -0
- submission/test.py +10 -0
.gitignore
ADDED
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Byte-compiled / optimized / DLL files
|
2 |
+
__pycache__/
|
3 |
+
*.py[cod]
|
4 |
+
|
5 |
+
# C extensions
|
6 |
+
*.so
|
7 |
+
|
8 |
+
/models/
|
9 |
+
|
10 |
+
# Distribution / packaging
|
11 |
+
.Python
|
12 |
+
env/
|
13 |
+
build/
|
14 |
+
develop-eggs/
|
15 |
+
dist/
|
16 |
+
downloads/
|
17 |
+
eggs/
|
18 |
+
.eggs/
|
19 |
+
lib/
|
20 |
+
lib64/
|
21 |
+
parts/
|
22 |
+
sdist/
|
23 |
+
var/
|
24 |
+
*.egg-info/
|
25 |
+
.installed.cfg
|
26 |
+
*.egg
|
27 |
+
|
28 |
+
# PyInstaller
|
29 |
+
# Usually these files are written by a python script from a template
|
30 |
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
31 |
+
*.manifest
|
32 |
+
*.spec
|
33 |
+
|
34 |
+
# Installer logs
|
35 |
+
pip-log.txt
|
36 |
+
pip-delete-this-directory.txt
|
37 |
+
|
38 |
+
# Unit test / coverage reports
|
39 |
+
htmlcov/
|
40 |
+
.tox/
|
41 |
+
.coverage
|
42 |
+
.coverage.*
|
43 |
+
.cache
|
44 |
+
nosetests.xml
|
45 |
+
coverage.xml
|
46 |
+
*.cover
|
47 |
+
|
48 |
+
# Translations
|
49 |
+
*.mo
|
50 |
+
*.pot
|
51 |
+
|
52 |
+
# Django stuff:
|
53 |
+
*.log
|
54 |
+
|
55 |
+
# Sphinx documentation
|
56 |
+
docs/_build/
|
57 |
+
|
58 |
+
# PyBuilder
|
59 |
+
target/
|
60 |
+
|
61 |
+
# DotEnv configuration
|
62 |
+
.env
|
63 |
+
|
64 |
+
# Database
|
65 |
+
*.db
|
66 |
+
*.rdb
|
67 |
+
|
68 |
+
# Pycharm
|
69 |
+
.idea
|
70 |
+
|
71 |
+
# VS Code
|
72 |
+
.vscode/
|
73 |
+
|
74 |
+
# Spyder
|
75 |
+
.spyproject/
|
76 |
+
|
77 |
+
# Jupyter NB Checkpoints
|
78 |
+
.ipynb_checkpoints/
|
79 |
+
|
80 |
+
# exclude data from source control by default
|
81 |
+
/data/
|
82 |
+
|
83 |
+
# Mac OS-specific storage files
|
84 |
+
.DS_Store
|
85 |
+
|
86 |
+
# vim
|
87 |
+
*.swp
|
88 |
+
*.swo
|
89 |
+
|
90 |
+
# Mypy cache
|
91 |
+
.mypy_cache/
|
LICENSE
ADDED
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
The MIT License (MIT)
|
3 |
+
Copyright (c) 2023, foxxy
|
4 |
+
|
5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
6 |
+
|
7 |
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
8 |
+
|
9 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
10 |
+
|
notebooks/0.0-create-sliding-window.ipynb
ADDED
@@ -0,0 +1,381 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": 1,
|
6 |
+
"metadata": {},
|
7 |
+
"outputs": [],
|
8 |
+
"source": [
|
9 |
+
"# !pip install pandas \n",
|
10 |
+
"# !pip install tdqm\n",
|
11 |
+
"# !pip install pandarallel"
|
12 |
+
]
|
13 |
+
},
|
14 |
+
{
|
15 |
+
"cell_type": "code",
|
16 |
+
"execution_count": 2,
|
17 |
+
"metadata": {},
|
18 |
+
"outputs": [],
|
19 |
+
"source": [
|
20 |
+
"import re\n",
|
21 |
+
"import string\n",
|
22 |
+
"import math\n",
|
23 |
+
"import json\n",
|
24 |
+
"import pandas as pd\n",
|
25 |
+
"from tqdm.auto import tqdm\n",
|
26 |
+
"tqdm.pandas()"
|
27 |
+
]
|
28 |
+
},
|
29 |
+
{
|
30 |
+
"cell_type": "code",
|
31 |
+
"execution_count": 3,
|
32 |
+
"metadata": {},
|
33 |
+
"outputs": [],
|
34 |
+
"source": [
|
35 |
+
"_WORD_SPLIT = re.compile(\"([.,!?\\\"/':;)(])\")\n",
|
36 |
+
"_DIGIT_RE = re.compile(br\"\\d\")\n",
|
37 |
+
"STOP_WORDS = \"\\\" \\' [ ] . , ! : ; ?\".split(\" \")\n",
|
38 |
+
"\n",
|
39 |
+
"def basic_tokenizer(sentence):\n",
|
40 |
+
" words = []\n",
|
41 |
+
" for space_separated_fragment in sentence.strip().split():\n",
|
42 |
+
" words.extend(_WORD_SPLIT.split(space_separated_fragment))\n",
|
43 |
+
" return [w.lower() for w in words if w != '' and w != ' ' and w not in string.punctuation]\n",
|
44 |
+
"\n",
|
45 |
+
"def remove_appending_title(text,title):\n",
|
46 |
+
" return text.replace(f\"{title}\\n\\n{title}\",f\"{title} \")\n",
|
47 |
+
"\n",
|
48 |
+
"def create_sliding_window(text, size=256, overlap=32):\n",
|
49 |
+
" actual_size = size - overlap\n",
|
50 |
+
" windows = []\n",
|
51 |
+
" n_windows = math.ceil(len(text)/actual_size)\n",
|
52 |
+
" for i in range(n_windows):\n",
|
53 |
+
" windows.append(\" \".join(text[i*actual_size:i*actual_size + size]))\n",
|
54 |
+
" return windows"
|
55 |
+
]
|
56 |
+
},
|
57 |
+
{
|
58 |
+
"cell_type": "code",
|
59 |
+
"execution_count": 4,
|
60 |
+
"metadata": {},
|
61 |
+
"outputs": [
|
62 |
+
{
|
63 |
+
"data": {
|
64 |
+
"application/vnd.jupyter.widget-view+json": {
|
65 |
+
"model_id": "16dcb3eb371e4084be66ee507040fe18",
|
66 |
+
"version_major": 2,
|
67 |
+
"version_minor": 0
|
68 |
+
},
|
69 |
+
"text/plain": [
|
70 |
+
"0it [00:00, ?it/s]"
|
71 |
+
]
|
72 |
+
},
|
73 |
+
"metadata": {},
|
74 |
+
"output_type": "display_data"
|
75 |
+
}
|
76 |
+
],
|
77 |
+
"source": [
|
78 |
+
"all_titles = []\n",
|
79 |
+
"all_texts = []\n",
|
80 |
+
"all_bm25_texts = []\n",
|
81 |
+
"with open(\"../data/raw/wikipedia_20220620_cleaned/wikipedia_20220620_cleaned.jsonl\", encoding=\"utf-8\") as f:\n",
|
82 |
+
" for i,line in tqdm(enumerate(f)):\n",
|
83 |
+
" x = json.loads(line)\n",
|
84 |
+
" text = remove_appending_title(x[\"text\"],x[\"title\"])\n",
|
85 |
+
" text = text.split(\" \")\n",
|
86 |
+
" sliding_windows = create_sliding_window(text)\n",
|
87 |
+
" all_texts.extend(sliding_windows)\n",
|
88 |
+
" # all_bm25_texts.extend(bm25_windows)\n",
|
89 |
+
" all_titles.extend([x['title'],]*len(sliding_windows))"
|
90 |
+
]
|
91 |
+
},
|
92 |
+
{
|
93 |
+
"cell_type": "code",
|
94 |
+
"execution_count": 5,
|
95 |
+
"metadata": {},
|
96 |
+
"outputs": [
|
97 |
+
{
|
98 |
+
"data": {
|
99 |
+
"text/html": [
|
100 |
+
"<div>\n",
|
101 |
+
"<style scoped>\n",
|
102 |
+
" .dataframe tbody tr th:only-of-type {\n",
|
103 |
+
" vertical-align: middle;\n",
|
104 |
+
" }\n",
|
105 |
+
"\n",
|
106 |
+
" .dataframe tbody tr th {\n",
|
107 |
+
" vertical-align: top;\n",
|
108 |
+
" }\n",
|
109 |
+
"\n",
|
110 |
+
" .dataframe thead th {\n",
|
111 |
+
" text-align: right;\n",
|
112 |
+
" }\n",
|
113 |
+
"</style>\n",
|
114 |
+
"<table border=\"1\" class=\"dataframe\">\n",
|
115 |
+
" <thead>\n",
|
116 |
+
" <tr style=\"text-align: right;\">\n",
|
117 |
+
" <th></th>\n",
|
118 |
+
" <th>title</th>\n",
|
119 |
+
" <th>text</th>\n",
|
120 |
+
" </tr>\n",
|
121 |
+
" </thead>\n",
|
122 |
+
" <tbody>\n",
|
123 |
+
" <tr>\n",
|
124 |
+
" <th>0</th>\n",
|
125 |
+
" <td>Trang Chính</td>\n",
|
126 |
+
" <td>Trang Chính\\n\\n<templatestyles src=\"Wiki2021/s...</td>\n",
|
127 |
+
" </tr>\n",
|
128 |
+
" <tr>\n",
|
129 |
+
" <th>1</th>\n",
|
130 |
+
" <td>Internet Society</td>\n",
|
131 |
+
" <td>Internet Society hay ISOC là một tổ chức quốc...</td>\n",
|
132 |
+
" </tr>\n",
|
133 |
+
" <tr>\n",
|
134 |
+
" <th>2</th>\n",
|
135 |
+
" <td>Tiếng Việt</td>\n",
|
136 |
+
" <td>Tiếng Việt , cũng gọi là tiếng Việt Nam hay Vi...</td>\n",
|
137 |
+
" </tr>\n",
|
138 |
+
" <tr>\n",
|
139 |
+
" <th>3</th>\n",
|
140 |
+
" <td>Tiếng Việt</td>\n",
|
141 |
+
" <td>hệ thống thanh điệu phát triển cao hơn, hệ thố...</td>\n",
|
142 |
+
" </tr>\n",
|
143 |
+
" <tr>\n",
|
144 |
+
" <th>4</th>\n",
|
145 |
+
" <td>Tiếng Việt</td>\n",
|
146 |
+
" <td>tiếp xúc Hán – Việt thành 2 giai đoạn chính: \\...</td>\n",
|
147 |
+
" </tr>\n",
|
148 |
+
" <tr>\n",
|
149 |
+
" <th>...</th>\n",
|
150 |
+
" <td>...</td>\n",
|
151 |
+
" <td>...</td>\n",
|
152 |
+
" </tr>\n",
|
153 |
+
" <tr>\n",
|
154 |
+
" <th>1944401</th>\n",
|
155 |
+
" <td>VNOI</td>\n",
|
156 |
+
" <td>chuyên viên của các tập đoàn công nghệ lớn như...</td>\n",
|
157 |
+
" </tr>\n",
|
158 |
+
" <tr>\n",
|
159 |
+
" <th>1944402</th>\n",
|
160 |
+
" <td>Vòng hoa</td>\n",
|
161 |
+
" <td>Vòng hoa (; IPA: ) là một loại hoa, lá, quả, ...</td>\n",
|
162 |
+
" </tr>\n",
|
163 |
+
" <tr>\n",
|
164 |
+
" <th>1944403</th>\n",
|
165 |
+
" <td>Vòng hoa</td>\n",
|
166 |
+
" <td>vật trong thần thoại La Mã và Hy Lạp được miêu...</td>\n",
|
167 |
+
" </tr>\n",
|
168 |
+
" <tr>\n",
|
169 |
+
" <th>1944404</th>\n",
|
170 |
+
" <td>Vòng hoa</td>\n",
|
171 |
+
" <td>một vai trò nổi bật, tương tự như ở Anh.\\n\\n==...</td>\n",
|
172 |
+
" </tr>\n",
|
173 |
+
" <tr>\n",
|
174 |
+
" <th>1944405</th>\n",
|
175 |
+
" <td>Vòng hoa</td>\n",
|
176 |
+
" <td>trên giá đỡ vòng hoa thắp sáng những ngọn nến ...</td>\n",
|
177 |
+
" </tr>\n",
|
178 |
+
" </tbody>\n",
|
179 |
+
"</table>\n",
|
180 |
+
"<p>1944406 rows × 2 columns</p>\n",
|
181 |
+
"</div>"
|
182 |
+
],
|
183 |
+
"text/plain": [
|
184 |
+
" title text\n",
|
185 |
+
"0 Trang Chính Trang Chính\\n\\n<templatestyles src=\"Wiki2021/s...\n",
|
186 |
+
"1 Internet Society Internet Society hay ISOC là một tổ chức quốc...\n",
|
187 |
+
"2 Tiếng Việt Tiếng Việt , cũng gọi là tiếng Việt Nam hay Vi...\n",
|
188 |
+
"3 Tiếng Việt hệ thống thanh điệu phát triển cao hơn, hệ thố...\n",
|
189 |
+
"4 Tiếng Việt tiếp xúc Hán – Việt thành 2 giai đoạn chính: \\...\n",
|
190 |
+
"... ... ...\n",
|
191 |
+
"1944401 VNOI chuyên viên của các tập đoàn công nghệ lớn như...\n",
|
192 |
+
"1944402 Vòng hoa Vòng hoa (; IPA: ) là một loại hoa, lá, quả, ...\n",
|
193 |
+
"1944403 Vòng hoa vật trong thần thoại La Mã và Hy Lạp được miêu...\n",
|
194 |
+
"1944404 Vòng hoa một vai trò nổi bật, tương tự như ở Anh.\\n\\n==...\n",
|
195 |
+
"1944405 Vòng hoa trên giá đỡ vòng hoa thắp sáng những ngọn nến ...\n",
|
196 |
+
"\n",
|
197 |
+
"[1944406 rows x 2 columns]"
|
198 |
+
]
|
199 |
+
},
|
200 |
+
"execution_count": 5,
|
201 |
+
"metadata": {},
|
202 |
+
"output_type": "execute_result"
|
203 |
+
}
|
204 |
+
],
|
205 |
+
"source": [
|
206 |
+
"df = pd.DataFrame()\n",
|
207 |
+
"df[\"title\"] = all_titles\n",
|
208 |
+
"df[\"text\"] = all_texts\n",
|
209 |
+
"df"
|
210 |
+
]
|
211 |
+
},
|
212 |
+
{
|
213 |
+
"cell_type": "code",
|
214 |
+
"execution_count": null,
|
215 |
+
"metadata": {},
|
216 |
+
"outputs": [],
|
217 |
+
"source": [
|
218 |
+
"from pandarallel import pandarallel\n",
|
219 |
+
"\n",
|
220 |
+
"pandarallel.initialize(progress_bar=True, use_memory_fs=False, nb_workers=6) \n",
|
221 |
+
"\n",
|
222 |
+
"def apply_tokenizer(df, num_chunks):\n",
|
223 |
+
" chunk_sr = pd.Series()\n",
|
224 |
+
" i = 0\n",
|
225 |
+
" end = df.shape[0]\n",
|
226 |
+
" chunk_size = math.floor(end/num_chunks)\n",
|
227 |
+
" while i != end:\n",
|
228 |
+
" if end - i < chunk_size:\n",
|
229 |
+
" chunk_size = end - i\n",
|
230 |
+
"# print((i,i+chunk_size))\n",
|
231 |
+
" temp_df = df[i:i+chunk_size].copy()\n",
|
232 |
+
" chunk_sr = pd.concat([chunk_sr, temp_df[\"text\"].parallel_apply(lambda x: \" \".join(basic_tokenizer(x)))], ignore_index=True)\n",
|
233 |
+
" i+=chunk_size\n",
|
234 |
+
" return chunk_sr\n",
|
235 |
+
"\n",
|
236 |
+
"df[\"bm25_text\"] = apply_tokenizer(df, 5)"
|
237 |
+
]
|
238 |
+
},
|
239 |
+
{
|
240 |
+
"cell_type": "code",
|
241 |
+
"execution_count": 7,
|
242 |
+
"metadata": {},
|
243 |
+
"outputs": [
|
244 |
+
{
|
245 |
+
"data": {
|
246 |
+
"text/html": [
|
247 |
+
"<div>\n",
|
248 |
+
"<style scoped>\n",
|
249 |
+
" .dataframe tbody tr th:only-of-type {\n",
|
250 |
+
" vertical-align: middle;\n",
|
251 |
+
" }\n",
|
252 |
+
"\n",
|
253 |
+
" .dataframe tbody tr th {\n",
|
254 |
+
" vertical-align: top;\n",
|
255 |
+
" }\n",
|
256 |
+
"\n",
|
257 |
+
" .dataframe thead th {\n",
|
258 |
+
" text-align: right;\n",
|
259 |
+
" }\n",
|
260 |
+
"</style>\n",
|
261 |
+
"<table border=\"1\" class=\"dataframe\">\n",
|
262 |
+
" <thead>\n",
|
263 |
+
" <tr style=\"text-align: right;\">\n",
|
264 |
+
" <th></th>\n",
|
265 |
+
" <th>title</th>\n",
|
266 |
+
" <th>text</th>\n",
|
267 |
+
" <th>bm25_text</th>\n",
|
268 |
+
" </tr>\n",
|
269 |
+
" </thead>\n",
|
270 |
+
" <tbody>\n",
|
271 |
+
" <tr>\n",
|
272 |
+
" <th>0</th>\n",
|
273 |
+
" <td>Trang Chính</td>\n",
|
274 |
+
" <td>Trang Chính\\n\\n<templatestyles src=\"Wiki2021/s...</td>\n",
|
275 |
+
" <td>trang chính <templatestyles src= wiki2021 styl...</td>\n",
|
276 |
+
" </tr>\n",
|
277 |
+
" <tr>\n",
|
278 |
+
" <th>1</th>\n",
|
279 |
+
" <td>Internet Society</td>\n",
|
280 |
+
" <td>Internet Society hay ISOC là một tổ chức quốc...</td>\n",
|
281 |
+
" <td>internet society hay isoc là một tổ chức quốc ...</td>\n",
|
282 |
+
" </tr>\n",
|
283 |
+
" <tr>\n",
|
284 |
+
" <th>2</th>\n",
|
285 |
+
" <td>Tiếng Việt</td>\n",
|
286 |
+
" <td>Tiếng Việt , cũng gọi là tiếng Việt Nam hay Vi...</td>\n",
|
287 |
+
" <td>tiếng việt cũng gọi là tiếng việt nam hay việt...</td>\n",
|
288 |
+
" </tr>\n",
|
289 |
+
" <tr>\n",
|
290 |
+
" <th>3</th>\n",
|
291 |
+
" <td>Tiếng Việt</td>\n",
|
292 |
+
" <td>hệ thống thanh điệu phát triển cao hơn, hệ thố...</td>\n",
|
293 |
+
" <td>hệ thống thanh điệu phát triển cao hơn hệ thốn...</td>\n",
|
294 |
+
" </tr>\n",
|
295 |
+
" <tr>\n",
|
296 |
+
" <th>4</th>\n",
|
297 |
+
" <td>Tiếng Việt</td>\n",
|
298 |
+
" <td>tiếp xúc Hán – Việt thành 2 giai đoạn chính: \\...</td>\n",
|
299 |
+
" <td>tiếp xúc hán – việt thành 2 giai đoạn chính bu...</td>\n",
|
300 |
+
" </tr>\n",
|
301 |
+
" </tbody>\n",
|
302 |
+
"</table>\n",
|
303 |
+
"</div>"
|
304 |
+
],
|
305 |
+
"text/plain": [
|
306 |
+
" title text \\\n",
|
307 |
+
"0 Trang Chính Trang Chính\\n\\n<templatestyles src=\"Wiki2021/s... \n",
|
308 |
+
"1 Internet Society Internet Society hay ISOC là một tổ chức quốc... \n",
|
309 |
+
"2 Tiếng Việt Tiếng Việt , cũng gọi là tiếng Việt Nam hay Vi... \n",
|
310 |
+
"3 Tiếng Việt hệ thống thanh điệu phát triển cao hơn, hệ thố... \n",
|
311 |
+
"4 Tiếng Việt tiếp xúc Hán – Việt thành 2 giai đoạn chính: \\... \n",
|
312 |
+
"\n",
|
313 |
+
" bm25_text \n",
|
314 |
+
"0 trang chính <templatestyles src= wiki2021 styl... \n",
|
315 |
+
"1 internet society hay isoc là một tổ chức quốc ... \n",
|
316 |
+
"2 tiếng việt cũng gọi là tiếng việt nam hay việt... \n",
|
317 |
+
"3 hệ thống thanh điệu phát triển cao hơn hệ thốn... \n",
|
318 |
+
"4 tiếp xúc hán – việt thành 2 giai đoạn chính bu... "
|
319 |
+
]
|
320 |
+
},
|
321 |
+
"execution_count": 7,
|
322 |
+
"metadata": {},
|
323 |
+
"output_type": "execute_result"
|
324 |
+
}
|
325 |
+
],
|
326 |
+
"source": [
|
327 |
+
"df.head()"
|
328 |
+
]
|
329 |
+
},
|
330 |
+
{
|
331 |
+
"cell_type": "code",
|
332 |
+
"execution_count": 10,
|
333 |
+
"metadata": {},
|
334 |
+
"outputs": [
|
335 |
+
{
|
336 |
+
"data": {
|
337 |
+
"text/plain": [
|
338 |
+
"(1944406, 3)"
|
339 |
+
]
|
340 |
+
},
|
341 |
+
"execution_count": 10,
|
342 |
+
"metadata": {},
|
343 |
+
"output_type": "execute_result"
|
344 |
+
}
|
345 |
+
],
|
346 |
+
"source": [
|
347 |
+
"df.shape"
|
348 |
+
]
|
349 |
+
},
|
350 |
+
{
|
351 |
+
"cell_type": "code",
|
352 |
+
"execution_count": 9,
|
353 |
+
"metadata": {},
|
354 |
+
"outputs": [],
|
355 |
+
"source": [
|
356 |
+
"df.to_csv(\"../data/processed/wikipedia_20220620_cleaned_v2.csv\",index=False)"
|
357 |
+
]
|
358 |
+
}
|
359 |
+
],
|
360 |
+
"metadata": {
|
361 |
+
"kernelspec": {
|
362 |
+
"display_name": "Python 3 (ipykernel)",
|
363 |
+
"language": "python",
|
364 |
+
"name": "python3"
|
365 |
+
},
|
366 |
+
"language_info": {
|
367 |
+
"codemirror_mode": {
|
368 |
+
"name": "ipython",
|
369 |
+
"version": 3
|
370 |
+
},
|
371 |
+
"file_extension": ".py",
|
372 |
+
"mimetype": "text/x-python",
|
373 |
+
"name": "python",
|
374 |
+
"nbconvert_exporter": "python",
|
375 |
+
"pygments_lexer": "ipython3",
|
376 |
+
"version": "3.8.10"
|
377 |
+
}
|
378 |
+
},
|
379 |
+
"nbformat": 4,
|
380 |
+
"nbformat_minor": 2
|
381 |
+
}
|
notebooks/0.1-find-dirty-data.ipynb
ADDED
@@ -0,0 +1,2071 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": 1,
|
6 |
+
"metadata": {},
|
7 |
+
"outputs": [],
|
8 |
+
"source": [
|
9 |
+
"import json\n",
|
10 |
+
"import pandas as pd\n",
|
11 |
+
"from tqdm.auto import tqdm\n",
|
12 |
+
"tqdm.pandas()\n",
|
13 |
+
"import numpy as np\n",
|
14 |
+
"from glob import glob \n",
|
15 |
+
"import re \n",
|
16 |
+
"from nltk import word_tokenize as lib_tokenizer \n",
|
17 |
+
"import math"
|
18 |
+
]
|
19 |
+
},
|
20 |
+
{
|
21 |
+
"cell_type": "code",
|
22 |
+
"execution_count": 2,
|
23 |
+
"metadata": {},
|
24 |
+
"outputs": [],
|
25 |
+
"source": [
|
26 |
+
"df = pd.read_csv(\"../data/processed/wikipedia_20220620_cleaned_v2.csv\")\n",
|
27 |
+
"train = json.load(open(\"../data/raw/e2eqa-train+public_test-v1/zac2022_train_merged_final.json\"))"
|
28 |
+
]
|
29 |
+
},
|
30 |
+
{
|
31 |
+
"cell_type": "code",
|
32 |
+
"execution_count": 3,
|
33 |
+
"metadata": {},
|
34 |
+
"outputs": [],
|
35 |
+
"source": [
|
36 |
+
"for x in train['data']:\n",
|
37 |
+
" x['dirty_text'] = None"
|
38 |
+
]
|
39 |
+
},
|
40 |
+
{
|
41 |
+
"cell_type": "code",
|
42 |
+
"execution_count": 4,
|
43 |
+
"metadata": {},
|
44 |
+
"outputs": [
|
45 |
+
{
|
46 |
+
"data": {
|
47 |
+
"text/plain": [
|
48 |
+
"{'Trang Chính': True,\n",
|
49 |
+
" 'Internet Society': True,\n",
|
50 |
+
" 'Tiếng Việt': True,\n",
|
51 |
+
" 'Ohio': True,\n",
|
52 |
+
" 'California': True,\n",
|
53 |
+
" 'Thụy Điển': True,\n",
|
54 |
+
" 'Thành phố Hồ Chí Minh': True,\n",
|
55 |
+
" 'Lào Cai': True,\n",
|
56 |
+
" 'W3C': True,\n",
|
57 |
+
" 'Bộ Kế hoạch và Đầu tư (Việt Nam)': True,\n",
|
58 |
+
" 'Lào': True,\n",
|
59 |
+
" 'Hoa Kỳ': True,\n",
|
60 |
+
" 'Hà Giang': True,\n",
|
61 |
+
" 'Cao Bằng': True,\n",
|
62 |
+
" 'Iraq': True,\n",
|
63 |
+
" 'Hà Nội': True,\n",
|
64 |
+
" 'Campuchia': True,\n",
|
65 |
+
" 'VIQR': True,\n",
|
66 |
+
" 'Việt Nam Cộng hòa': True,\n",
|
67 |
+
" 'Sacramento, California': True,\n",
|
68 |
+
" 'Los Angeles': True,\n",
|
69 |
+
" 'San Francisco': True,\n",
|
70 |
+
" 'San Diego': True,\n",
|
71 |
+
" 'Người Mỹ gốc Việt': True,\n",
|
72 |
+
" 'Giấy phép Tài liệu Tự do GNU': True,\n",
|
73 |
+
" 'Lý Thường Kiệt': True,\n",
|
74 |
+
" 'Quang Trung': True,\n",
|
75 |
+
" 'Hồ Biểu Chánh': True,\n",
|
76 |
+
" 'Bắc Kạn': True,\n",
|
77 |
+
" 'Lạng Sơn': True,\n",
|
78 |
+
" 'A': True,\n",
|
79 |
+
" 'B': True,\n",
|
80 |
+
" 'C': True,\n",
|
81 |
+
" 'D': True,\n",
|
82 |
+
" 'E': True,\n",
|
83 |
+
" 'F': True,\n",
|
84 |
+
" 'G': True,\n",
|
85 |
+
" 'H': True,\n",
|
86 |
+
" 'I': True,\n",
|
87 |
+
" 'J': True,\n",
|
88 |
+
" 'K': True,\n",
|
89 |
+
" 'L': True,\n",
|
90 |
+
" 'M': True,\n",
|
91 |
+
" 'N': True,\n",
|
92 |
+
" 'O': True,\n",
|
93 |
+
" 'P': True,\n",
|
94 |
+
" 'Q': True,\n",
|
95 |
+
" 'R': True,\n",
|
96 |
+
" 'S': True,\n",
|
97 |
+
" 'T': True,\n",
|
98 |
+
" 'U': True,\n",
|
99 |
+
" 'V': True,\n",
|
100 |
+
" 'W': True,\n",
|
101 |
+
" 'X': True,\n",
|
102 |
+
" 'Y': True,\n",
|
103 |
+
" 'Z': True,\n",
|
104 |
+
" 'Tuyên Quang': True,\n",
|
105 |
+
" 'Unicode': True,\n",
|
106 |
+
" '2003': True,\n",
|
107 |
+
" 'Thăng Long': True,\n",
|
108 |
+
" 'Lý Thái Tổ': True,\n",
|
109 |
+
" 'Tiến quân ca': True,\n",
|
110 |
+
" 'Đức': True,\n",
|
111 |
+
" 'Liên Hợp Quốc': True,\n",
|
112 |
+
" 'Trần Hưng Đạo': True,\n",
|
113 |
+
" 'Hamid Karzai': True,\n",
|
114 |
+
" 'Hoa (định hướng)': True,\n",
|
115 |
+
" 'Tiếng Thụy Điển': True,\n",
|
116 |
+
" 'Chiến tranh Việt Nam': True,\n",
|
117 |
+
" 'New Orleans': True,\n",
|
118 |
+
" 'Ngọc Lân': True,\n",
|
119 |
+
" 'Ngọc Lan (định hướng)': True,\n",
|
120 |
+
" '26 tháng 1': True,\n",
|
121 |
+
" 'Tiếng Anh': True,\n",
|
122 |
+
" 'Canada': True,\n",
|
123 |
+
" 'Đài Tiếng nói Hoa Kỳ': True,\n",
|
124 |
+
" 'Tháng 1 năm 2004': True,\n",
|
125 |
+
" '1954': True,\n",
|
126 |
+
" 'Đ': True,\n",
|
127 |
+
" 'Trần Đức Lương': True,\n",
|
128 |
+
" 'Québec': True,\n",
|
129 |
+
" 'Saskatchewan': True,\n",
|
130 |
+
" 'Đảo Hoàng tử Edward': True,\n",
|
131 |
+
" 'Ontario': True,\n",
|
132 |
+
" 'Manitoba': True,\n",
|
133 |
+
" 'Newfoundland và Labrador': True,\n",
|
134 |
+
" 'New Brunswick': True,\n",
|
135 |
+
" 'British Columbia': True,\n",
|
136 |
+
" 'Vancouver': True,\n",
|
137 |
+
" 'Alberta': True,\n",
|
138 |
+
" 'Nova Scotia': True,\n",
|
139 |
+
" 'Anh': True,\n",
|
140 |
+
" 'Ottawa': True,\n",
|
141 |
+
" 'Bắc Mỹ': True,\n",
|
142 |
+
" 'Nga': True,\n",
|
143 |
+
" 'Labrador': True,\n",
|
144 |
+
" 'Linux': True,\n",
|
145 |
+
" 'Huế': True,\n",
|
146 |
+
" 'Võ Nguyên Giáp': True,\n",
|
147 |
+
" 'Chữ Nôm': True,\n",
|
148 |
+
" 'Tháng 2 năm 2004': True,\n",
|
149 |
+
" '19 tháng 3': True,\n",
|
150 |
+
" '20 tháng 3': True,\n",
|
151 |
+
" '21 tháng 3': True,\n",
|
152 |
+
" '22 tháng 3': True,\n",
|
153 |
+
" 'Tháng ba': True,\n",
|
154 |
+
" '23 tháng 3': True,\n",
|
155 |
+
" '24 tháng 3': True,\n",
|
156 |
+
" 'Vương quốc Anh (1707–1800)': True,\n",
|
157 |
+
" '25 tháng 3': True,\n",
|
158 |
+
" '26 tháng 3': True,\n",
|
159 |
+
" '27 tháng 3': True,\n",
|
160 |
+
" '28 tháng 3': True,\n",
|
161 |
+
" '29 tháng 3': True,\n",
|
162 |
+
" 'Chủ nhật': True,\n",
|
163 |
+
" 'Lá cờ Ohio': True,\n",
|
164 |
+
" 'Tháng tư': True,\n",
|
165 |
+
" '3 tháng 4': True,\n",
|
166 |
+
" '4 tháng 4': True,\n",
|
167 |
+
" '5 tháng 4': True,\n",
|
168 |
+
" 'Tháng 3 năm 2004': True,\n",
|
169 |
+
" 'VN': True,\n",
|
170 |
+
" 'Bách khoa toàn thư': True,\n",
|
171 |
+
" '9 tháng 4': True,\n",
|
172 |
+
" '10 tháng 4': True,\n",
|
173 |
+
" '11 tháng 4': True,\n",
|
174 |
+
" '12 tháng 4': True,\n",
|
175 |
+
" '13 tháng 4': True,\n",
|
176 |
+
" '14 tháng 4': True,\n",
|
177 |
+
" '15 tháng 4': True,\n",
|
178 |
+
" 'Hóa học': True,\n",
|
179 |
+
" '16 tháng 4': True,\n",
|
180 |
+
" 'Ngô Đình Diệm': True,\n",
|
181 |
+
" 'Máy tính': True,\n",
|
182 |
+
" 'Yên Bái': True,\n",
|
183 |
+
" '20 tháng 4': True,\n",
|
184 |
+
" 'Đà Nẵng': True,\n",
|
185 |
+
" '21 tháng 4': True,\n",
|
186 |
+
" '22 tháng 4': True,\n",
|
187 |
+
" '23 tháng 4': True,\n",
|
188 |
+
" 'Firefox': True,\n",
|
189 |
+
" 'Nguyễn Du': True,\n",
|
190 |
+
" 'CJKV': True,\n",
|
191 |
+
" 'VISCII': True,\n",
|
192 |
+
" '29 tháng 4': True,\n",
|
193 |
+
" 'Cần Thơ': True,\n",
|
194 |
+
" 'GNU': True,\n",
|
195 |
+
" 'Tam giác': True,\n",
|
196 |
+
" 'Internet': True,\n",
|
197 |
+
" 'Hello world': True,\n",
|
198 |
+
" 'Heli': True,\n",
|
199 |
+
" 'Từ viết tắt từ chữ đầu': True,\n",
|
200 |
+
" 'Berkeley Software Distribution': True,\n",
|
201 |
+
" 'FreeBSD': True,\n",
|
202 |
+
" 'Tháng 4 năm 2004': True,\n",
|
203 |
+
" 'Khoa học Trái Đất': True,\n",
|
204 |
+
" 'Việt ngữ (định hướng)': True,\n",
|
205 |
+
" 'PHP': True,\n",
|
206 |
+
" 'Wiki': True,\n",
|
207 |
+
" 'Tiêu chuẩn quốc gia (Việt Nam)': True,\n",
|
208 |
+
" 'Java (công nghệ)': True,\n",
|
209 |
+
" 'Tòa án Công lý Quốc tế': True,\n",
|
210 |
+
" 'Sun Microsystems': True,\n",
|
211 |
+
" 'OpenOffice.org': True,\n",
|
212 |
+
" 'Chương trình Phát triển của Liên Hợp Quốc': True,\n",
|
213 |
+
" '22 tháng 1': True,\n",
|
214 |
+
" 'Việt Minh': True,\n",
|
215 |
+
" 'Thuyết Truman': True,\n",
|
216 |
+
" 'Advanced Micro Devices': True,\n",
|
217 |
+
" 'Pin sạc': True,\n",
|
218 |
+
" 'Edmonton': True,\n",
|
219 |
+
" 'Luxeon': True,\n",
|
220 |
+
" 'Philips Lumileds Lighting': True,\n",
|
221 |
+
" 'Winamp': True,\n",
|
222 |
+
" 'Xích lô': True,\n",
|
223 |
+
" 'Hamasaki Ayumi': True,\n",
|
224 |
+
" 'Amuro Namie': True,\n",
|
225 |
+
" 'Java Platform, Standard Edition': True,\n",
|
226 |
+
" 'Lập trình viên': True,\n",
|
227 |
+
" 'Hạt nhân Linux': True,\n",
|
228 |
+
" 'UniKey': True,\n",
|
229 |
+
" 'Văn Tiến Dũng': True,\n",
|
230 |
+
" 'Đồng Nai': True,\n",
|
231 |
+
" 'Tiếng Nga': True,\n",
|
232 |
+
" 'Quân đội nhân dân Việt Nam': True,\n",
|
233 |
+
" 'Chiến tranh Đông Dương': True,\n",
|
234 |
+
" 'Chiến tranh Vùng Vịnh': True,\n",
|
235 |
+
" 'Phạm Văn Đồng': True,\n",
|
236 |
+
" 'Liên bang Đông Dương': True,\n",
|
237 |
+
" 'World Wide Web': True,\n",
|
238 |
+
" 'Giê-su': True,\n",
|
239 |
+
" 'Quảng Nam': True,\n",
|
240 |
+
" 'Giang Trạch Dân': True,\n",
|
241 |
+
" 'Wikipedia': True,\n",
|
242 |
+
" 'Bỉ': True,\n",
|
243 |
+
" 'Toán học': True,\n",
|
244 |
+
" 'Khoa học tự nhiên': True,\n",
|
245 |
+
" 'Hình học': True,\n",
|
246 |
+
" 'Quốc gia': True,\n",
|
247 |
+
" 'Địa lý': True,\n",
|
248 |
+
" 'Cơ học cổ điển': True,\n",
|
249 |
+
" 'Hóa hữu cơ': True,\n",
|
250 |
+
" 'Nguyễn Văn Thiệu': True,\n",
|
251 |
+
" 'George W. Bush': True,\n",
|
252 |
+
" 'Nội chiến Congo thứ hai': True,\n",
|
253 |
+
" 'Thống kê': True,\n",
|
254 |
+
" 'Chiến tranh thời cổ đại': True,\n",
|
255 |
+
" 'Sinh thái học': True,\n",
|
256 |
+
" 'Ngô Quyền': True,\n",
|
257 |
+
" 'Gangnihessou': True,\n",
|
258 |
+
" 'HTML': True,\n",
|
259 |
+
" 'XHTML': True,\n",
|
260 |
+
" 'Phong trào Chữ thập đỏ và Trăng lưỡi liềm đỏ quốc tế': True,\n",
|
261 |
+
" 'Vật lý học': True,\n",
|
262 |
+
" 'Quần đảo Trường Sa': True,\n",
|
263 |
+
" 'Quần đảo Hoàng Sa': True,\n",
|
264 |
+
" 'Thiên văn học': True,\n",
|
265 |
+
" 'Vovinam': True,\n",
|
266 |
+
" 'Cornhole': True,\n",
|
267 |
+
" 'Nhắn tin tức thời': True,\n",
|
268 |
+
" 'Tam Quốc (Triều Tiên)': True,\n",
|
269 |
+
" 'Nguyên tố': True,\n",
|
270 |
+
" 'Phan Văn Khải': True,\n",
|
271 |
+
" 'Lợn biển': True,\n",
|
272 |
+
" 'Hành tinh': True,\n",
|
273 |
+
" 'Montréal': True,\n",
|
274 |
+
" 'Hình vuông': True,\n",
|
275 |
+
" 'Kính viễn vọng không gian Hubble': True,\n",
|
276 |
+
" 'Nha Trang': True,\n",
|
277 |
+
" 'Klaipėda': True,\n",
|
278 |
+
" 'Trung Quốc': True,\n",
|
279 |
+
" 'Mạng riêng ảo': True,\n",
|
280 |
+
" 'Mạng máy tính': True,\n",
|
281 |
+
" 'Hệ quản trị nội dung': True,\n",
|
282 |
+
" 'Sinh học tế bào': True,\n",
|
283 |
+
" 'Nguyễn Trãi': True,\n",
|
284 |
+
" 'Thực vật học': True,\n",
|
285 |
+
" 'Phân loại học': True,\n",
|
286 |
+
" 'Công nghệ': True,\n",
|
287 |
+
" 'Chia cắt Ấn Độ': True,\n",
|
288 |
+
" 'Sao Kim': True,\n",
|
289 |
+
" 'Sao Hỏa': True,\n",
|
290 |
+
" 'Nam quốc sơn hà': True,\n",
|
291 |
+
" 'Red Deer, Alberta': True,\n",
|
292 |
+
" 'Hệ Mặt Trời': True,\n",
|
293 |
+
" 'Oradea': True,\n",
|
294 |
+
" 'Trái Đất': True,\n",
|
295 |
+
" 'Sao Mộc': True,\n",
|
296 |
+
" 'C�� học': True,\n",
|
297 |
+
" 'Khí tượng học': True,\n",
|
298 |
+
" 'Kế toán': True,\n",
|
299 |
+
" 'Sao Thổ': True,\n",
|
300 |
+
" 'Hoàng đế': True,\n",
|
301 |
+
" 'Moresnet': True,\n",
|
302 |
+
" 'KDE': True,\n",
|
303 |
+
" 'Người Tày': True,\n",
|
304 |
+
" 'Sinh học': True,\n",
|
305 |
+
" 'Tế bào': True,\n",
|
306 |
+
" 'Hóa phân tích': True,\n",
|
307 |
+
" 'Hóa vô cơ': True,\n",
|
308 |
+
" 'Hóa dầu': True,\n",
|
309 |
+
" 'Cân bằng nội môi': True,\n",
|
310 |
+
" 'Cây phát sinh chủng loại': True,\n",
|
311 |
+
" 'Sinh học phân tử': True,\n",
|
312 |
+
" 'Di truyền học': True,\n",
|
313 |
+
" 'Lĩnh Nam': True,\n",
|
314 |
+
" 'Hydrocarbon': True,\n",
|
315 |
+
" 'Phản ứng trùng ngưng': True,\n",
|
316 |
+
" 'Alcohol': True,\n",
|
317 |
+
" 'Nhân Chứng Giê-hô-va': True,\n",
|
318 |
+
" 'Ngôn ngữ lập trình': True,\n",
|
319 |
+
" 'Tổng sản lượng quốc gia': True,\n",
|
320 |
+
" 'GDP (định hướng)': True,\n",
|
321 |
+
" 'Tiệp': True,\n",
|
322 |
+
" 'Hà Lan': True,\n",
|
323 |
+
" 'Frankfurt am Main': True,\n",
|
324 |
+
" 'Sinh lý học': True,\n",
|
325 |
+
" 'Giải phẫu học': True,\n",
|
326 |
+
" 'Tập tính học': True,\n",
|
327 |
+
" 'Truyện Kiều': True,\n",
|
328 |
+
" 'Tản Đà': True,\n",
|
329 |
+
" 'Tết Nguyên Đán': True,\n",
|
330 |
+
" 'Lịch sử Việt Nam': True,\n",
|
331 |
+
" 'Người Việt': True,\n",
|
332 |
+
" 'Dầu mỏ': True,\n",
|
333 |
+
" 'Việt': True,\n",
|
334 |
+
" 'Kim Vân Kiều': True,\n",
|
335 |
+
" 'Kinh': True,\n",
|
336 |
+
" 'Tổ chức các nước xuất khẩu dầu lửa': True,\n",
|
337 |
+
" 'Quận Cam, California': True,\n",
|
338 |
+
" '30 tháng 4': True,\n",
|
339 |
+
" 'Trương Vĩnh Ký': True,\n",
|
340 |
+
" 'Hải Dương': True,\n",
|
341 |
+
" '8 tháng 3': True,\n",
|
342 |
+
" 'Tháng 9 năm 2004': True,\n",
|
343 |
+
" 'Amin': True,\n",
|
344 |
+
" 'Sao Thiên Vương': True,\n",
|
345 |
+
" 'Kỹ thuật': True,\n",
|
346 |
+
" 'Chăm Pa': True,\n",
|
347 |
+
" 'Nguyễn Hoàng': True,\n",
|
348 |
+
" 'Phù Nam': True,\n",
|
349 |
+
" 'Pin nhiên liệu': True,\n",
|
350 |
+
" 'Chiêm Thành': True,\n",
|
351 |
+
" 'Carbon': True,\n",
|
352 |
+
" 'Nguyễn Công Trứ': True,\n",
|
353 |
+
" 'Tế bào nhiên liệu kiềm': True,\n",
|
354 |
+
" 'AFC': True,\n",
|
355 |
+
" 'Hydro': True,\n",
|
356 |
+
" 'Đoạn mồi': True,\n",
|
357 |
+
" 'Probe': True,\n",
|
358 |
+
" 'DNA microarray': True,\n",
|
359 |
+
" 'Lạm phát': True,\n",
|
360 |
+
" 'Sông Hậu': True,\n",
|
361 |
+
" 'Ngũ hành': True,\n",
|
362 |
+
" 'PEMFC': True,\n",
|
363 |
+
" 'Phản ứng chuỗi polymerase': True,\n",
|
364 |
+
" 'Trần Ngọc Liên': True,\n",
|
365 |
+
" 'CPU': True,\n",
|
366 |
+
" 'Nguyên tố hóa học': True,\n",
|
367 |
+
" 'Tổng sản phẩm nội địa': True,\n",
|
368 |
+
" 'Electron': True,\n",
|
369 |
+
" 'Phần mềm doanh nghiệp': True,\n",
|
370 |
+
" 'Berlin': True,\n",
|
371 |
+
" 'Oxy': True,\n",
|
372 |
+
" 'Ozon': True,\n",
|
373 |
+
" 'Tích hợp ứng dụng doanh nghiệp': True,\n",
|
374 |
+
" 'Harry Potter': True,\n",
|
375 |
+
" 'Dương Văn Minh': True,\n",
|
376 |
+
" 'Bạch cầu': True,\n",
|
377 |
+
" 'Tầng bình lưu': True,\n",
|
378 |
+
" 'Chiến tranh thế giới thứ hai': True,\n",
|
379 |
+
" 'Touchdown PCR': True,\n",
|
380 |
+
" 'Telex (kiểu gõ)': True,\n",
|
381 |
+
" 'Hiệu ứng nhà kính': True,\n",
|
382 |
+
" 'Khí quyển Trái Đất': True,\n",
|
383 |
+
" 'Tăng áp (định hướng)': True,\n",
|
384 |
+
" 'Khí hậu học': True,\n",
|
385 |
+
" 'Nước': True,\n",
|
386 |
+
" 'Albert Einstein': True,\n",
|
387 |
+
" 'Isaac Newton': True,\n",
|
388 |
+
" 'Hoạch định tài nguyên doanh nghiệp': True,\n",
|
389 |
+
" 'Nhà vật lý': True,\n",
|
390 |
+
" 'Danh sách nhà vật lý': True,\n",
|
391 |
+
" 'Chúa': True,\n",
|
392 |
+
" '2004': True,\n",
|
393 |
+
" 'HIV/AIDS': True,\n",
|
394 |
+
" 'SIDA': True,\n",
|
395 |
+
" 'Giải Nobel': True,\n",
|
396 |
+
" 'Danh sách người đoạt giải Nobel': True,\n",
|
397 |
+
" 'Vật chất': True,\n",
|
398 |
+
" 'Tiên đề': True,\n",
|
399 |
+
" 'Ánh sáng': True,\n",
|
400 |
+
" 'Tương tác hấp dẫn': True,\n",
|
401 |
+
" 'Khối lượng': True,\n",
|
402 |
+
" 'Thể tích': True,\n",
|
403 |
+
" 'Tích phân': True,\n",
|
404 |
+
" 'Tân Bình (phủ cũ Gia Định)': True,\n",
|
405 |
+
" 'Kim Dung': True,\n",
|
406 |
+
" 'Đại Việt sử ký toàn thư': True,\n",
|
407 |
+
" 'SAP': True,\n",
|
408 |
+
" 'Lập xuân': True,\n",
|
409 |
+
" 'Tiết khí': True,\n",
|
410 |
+
" 'Phương trình': True,\n",
|
411 |
+
" 'Không điểm của hàm số': True,\n",
|
412 |
+
" 'Mét': True,\n",
|
413 |
+
" 'Thời gian': True,\n",
|
414 |
+
" 'Rượu (định hướng)': True,\n",
|
415 |
+
" 'Giây': True,\n",
|
416 |
+
" 'Giờ': True,\n",
|
417 |
+
" 'Phút': True,\n",
|
418 |
+
" 'Tốc độ ánh sáng': True,\n",
|
419 |
+
" 'Xuân phân': True,\n",
|
420 |
+
" 'Ba Lê (định hướng)': True,\n",
|
421 |
+
" 'Moskva': True,\n",
|
422 |
+
" 'Paris': True,\n",
|
423 |
+
" 'Cholesterol': True,\n",
|
424 |
+
" 'Kali': True,\n",
|
425 |
+
" 'CeBIT': True,\n",
|
426 |
+
" 'Hằng số Planck': True,\n",
|
427 |
+
" 'Năng lượng': True,\n",
|
428 |
+
" 'Kilôgam': True,\n",
|
429 |
+
" 'Tiền tố SI': True,\n",
|
430 |
+
" 'Yôta': True,\n",
|
431 |
+
" 'Zêta': True,\n",
|
432 |
+
" 'Êxa': True,\n",
|
433 |
+
" 'Pêta': True,\n",
|
434 |
+
" 'Têra': True,\n",
|
435 |
+
" 'Giga': True,\n",
|
436 |
+
" 'Mêga': True,\n",
|
437 |
+
" 'Kilô': True,\n",
|
438 |
+
" 'Héctô': True,\n",
|
439 |
+
" 'Đêca': True,\n",
|
440 |
+
" 'Đêxi': True,\n",
|
441 |
+
" 'Xăngti': True,\n",
|
442 |
+
" 'Mili': True,\n",
|
443 |
+
" 'Micrô': True,\n",
|
444 |
+
" 'Nanô': True,\n",
|
445 |
+
" 'Pico-': True,\n",
|
446 |
+
" 'Femto-': True,\n",
|
447 |
+
" 'Atto-': True,\n",
|
448 |
+
" 'Zepto-': True,\n",
|
449 |
+
" 'Yocto-': True,\n",
|
450 |
+
" 'Chiều dài': True,\n",
|
451 |
+
" 'Khoảng cách': True,\n",
|
452 |
+
" 'Việt kiều': True,\n",
|
453 |
+
" 'Centimet': True,\n",
|
454 |
+
" 'Gam': True,\n",
|
455 |
+
" 'Milimét': True,\n",
|
456 |
+
" 'Micrômét': True,\n",
|
457 |
+
" 'Nanômét': True,\n",
|
458 |
+
" 'Phạm Hồng Sơn (nhân vật bất đồng chính kiến)': True,\n",
|
459 |
+
" 'Rừng của người đã mất': True,\n",
|
460 |
+
" 'Đại số': True,\n",
|
461 |
+
" 'Kinh Thánh': True,\n",
|
462 |
+
" 'Quang học': True,\n",
|
463 |
+
" 'Người Hoa (Việt Nam)': True,\n",
|
464 |
+
" 'Người Trung Quốc': True,\n",
|
465 |
+
" 'Đông chí': True,\n",
|
466 |
+
" 'Thu phân': True,\n",
|
467 |
+
" 'Thức uống có cồn': True,\n",
|
468 |
+
" 'Vốn điều lệ': True,\n",
|
469 |
+
" 'Vốn pháp định': True,\n",
|
470 |
+
" 'Tiếng Pháp': True,\n",
|
471 |
+
" 'Thành Cát Tư Hãn': True,\n",
|
472 |
+
" 'Dòng Tên': True,\n",
|
473 |
+
" 'Nồng độ': True,\n",
|
474 |
+
" 'Nguyễn Đan Quế': True,\n",
|
475 |
+
" 'Khánh Hòa': True,\n",
|
476 |
+
" 'TeX': True,\n",
|
477 |
+
" 'Sao Hải Vương': True,\n",
|
478 |
+
" 'Sếu đầu đỏ': True,\n",
|
479 |
+
" 'Tây Hạ': True,\n",
|
480 |
+
" 'Đông Bắc Bộ': True,\n",
|
481 |
+
" 'Thuyết tương đối': True,\n",
|
482 |
+
" 'Nhà Kim': True,\n",
|
483 |
+
" 'Ngân Xuyên': True,\n",
|
484 |
+
" 'NATO': True,\n",
|
485 |
+
" 'Hoàng Hà': True,\n",
|
486 |
+
" 'Bệnh tả': True,\n",
|
487 |
+
" 'Trường Giang (định hướng)': True,\n",
|
488 |
+
" 'Tam Quốc (định hướng)': True,\n",
|
489 |
+
" 'Tam quốc': True,\n",
|
490 |
+
" 'Áo': True,\n",
|
491 |
+
" 'Tiếng Đức': True,\n",
|
492 |
+
" 'Cân': True,\n",
|
493 |
+
" 'Lạng': True,\n",
|
494 |
+
" 'Úc': True,\n",
|
495 |
+
" 'Trực khuẩn': True,\n",
|
496 |
+
" 'Escherichia coli': True,\n",
|
497 |
+
" 'The Star-Spangled Banner': True,\n",
|
498 |
+
" 'Pháp': True,\n",
|
499 |
+
" 'Pháp (định hướng)': True,\n",
|
500 |
+
" 'Đại số tuyến tính': True,\n",
|
501 |
+
" 'Ma trận (định hướng)': True,\n",
|
502 |
+
" 'Ma trận (toán học)': True,\n",
|
503 |
+
" 'Hình chữ nhật': True,\n",
|
504 |
+
" 'Hệ đo lường cổ Việt Nam': True,\n",
|
505 |
+
" 'Cải lương': True,\n",
|
506 |
+
" 'Lượng (kim hoàn)': True,\n",
|
507 |
+
" 'Lịch sử Nhật Bản': True,\n",
|
508 |
+
" 'Địa lý Nhật Bản': True,\n",
|
509 |
+
" 'Văn hóa Nhật Bản': True,\n",
|
510 |
+
" 'Các chính đảng ở Nhật Bản': True,\n",
|
511 |
+
" 'Kinh tế Nhật Bản': True,\n",
|
512 |
+
" 'Vi khuẩn': True,\n",
|
513 |
+
" 'Lịch sử Hoa Kỳ': True,\n",
|
514 |
+
" 'Vi trùng': True,\n",
|
515 |
+
" 'Kinh Dịch': True,\n",
|
516 |
+
" 'Sức mua tương đương': True,\n",
|
517 |
+
" 'ASCII': True,\n",
|
518 |
+
" 'Phương trình đại số': True,\n",
|
519 |
+
" 'Phương trình tuyến tính': True,\n",
|
520 |
+
" 'Biến số': True,\n",
|
521 |
+
" 'Chúa tể những chiếc nhẫn': True,\n",
|
522 |
+
" 'Bộ Sếu': True,\n",
|
523 |
+
" 'Nguyễn': True,\n",
|
524 |
+
" 'Johann Sebastian Bach': True,\n",
|
525 |
+
" 'Hệ phương trình tuyến tính': True,\n",
|
526 |
+
" 'Planctomycetes': True,\n",
|
527 |
+
" 'Murein': True,\n",
|
528 |
+
" 'PPP': True,\n",
|
529 |
+
" 'Trường Sa': True,\n",
|
530 |
+
" 'Lịch sử': True,\n",
|
531 |
+
" 'Khoa học ứng dụng': True,\n",
|
532 |
+
" 'Phát thanh quốc tế': True,\n",
|
533 |
+
" 'Truyền thông đại chúng': True,\n",
|
534 |
+
" 'Chỉ (đơn vị đo)': True,\n",
|
535 |
+
" 'Tạ': True,\n",
|
536 |
+
" 'Yến (đo lường)': True,\n",
|
537 |
+
" 'Tấn': True,\n",
|
538 |
+
" 'Vật lý thực nghiệm': True,\n",
|
539 |
+
" 'Điện từ học': True,\n",
|
540 |
+
" 'Bức xạ điện từ': True,\n",
|
541 |
+
" 'Tổ chức Thương mại Thế giới': True,\n",
|
542 |
+
" 'Vàng (định hướng)': True,\n",
|
543 |
+
" 'Vàng': True,\n",
|
544 |
+
" 'Thuần Càn': True,\n",
|
545 |
+
" 'Thuần Khôn': True,\n",
|
546 |
+
" 'Thủy Lôi Truân': True,\n",
|
547 |
+
" 'Sơn Thủy Mông': True,\n",
|
548 |
+
" 'Thủy Thiên Nhu': True,\n",
|
549 |
+
" 'Thiên Thủy Tụng': True,\n",
|
550 |
+
" 'Địa Thủy Sư': True,\n",
|
551 |
+
" '26 tháng 4': True,\n",
|
552 |
+
" 'Đảo Phục Sinh': True,\n",
|
553 |
+
" 'Thái tử': True,\n",
|
554 |
+
" 'Texas': True,\n",
|
555 |
+
" 'Ngân Hà': True,\n",
|
556 |
+
" 'Alaska': True,\n",
|
557 |
+
" 'Tán xạ': True,\n",
|
558 |
+
" 'Kinh tế Đức': True,\n",
|
559 |
+
" 'Thủy Địa Tỷ': True,\n",
|
560 |
+
" 'Phong Thiên Tiểu Súc': True,\n",
|
561 |
+
" 'Thiên Trạch Lý': True,\n",
|
562 |
+
" 'Địa Thiên Thái': True,\n",
|
563 |
+
" 'Thiên Địa Bĩ': True,\n",
|
564 |
+
" 'Thiên Hỏa Đồng Nhân': True,\n",
|
565 |
+
" 'Hỏa Thiên Đại Hữu': True,\n",
|
566 |
+
" 'Địa Sơn Khiêm': True,\n",
|
567 |
+
" 'Lôi Địa Dự': True,\n",
|
568 |
+
" 'Trạch Lôi Tùy': True,\n",
|
569 |
+
" 'Sơn Phong Cổ': True,\n",
|
570 |
+
" 'Địa Trạch Lâm': True,\n",
|
571 |
+
" 'Phong Địa Quan': True,\n",
|
572 |
+
" 'Sơn Hỏa Bí': True,\n",
|
573 |
+
" 'Sơn Địa Bác': True,\n",
|
574 |
+
" 'Địa Lôi Phục': True,\n",
|
575 |
+
" 'Thiên Lôi Vô Vọng': True,\n",
|
576 |
+
" 'Sơn Thiên Đại Súc': True,\n",
|
577 |
+
" 'Sơn Lôi Di': True,\n",
|
578 |
+
" 'Trạch Phong Đại Quá': True,\n",
|
579 |
+
" 'Thuần Khảm': True,\n",
|
580 |
+
" 'Thuần Ly': True,\n",
|
581 |
+
" 'Trạch Sơn Hàm': True,\n",
|
582 |
+
" 'Lôi Phong Hằng': True,\n",
|
583 |
+
" 'Thiên Sơn Độn': True,\n",
|
584 |
+
" 'Lôi Thiên Đại Tráng': True,\n",
|
585 |
+
" 'Địa Hỏa Minh Di': True,\n",
|
586 |
+
" 'Phong Hỏa Gia Nhân': True,\n",
|
587 |
+
" 'Hỏa Trạch Khuê': True,\n",
|
588 |
+
" 'Thủy Sơn Kiển': True,\n",
|
589 |
+
" 'Lôi Thủy Giải': True,\n",
|
590 |
+
" 'Sơn Trạch Tổn': True,\n",
|
591 |
+
" 'Phong Lôi Ích': True,\n",
|
592 |
+
" 'Trạch Thiên Quải': True,\n",
|
593 |
+
" 'Thiên Phong Cấu': True,\n",
|
594 |
+
" 'Trạch Địa Tụy': True,\n",
|
595 |
+
" 'Địa Phong Thăng': True,\n",
|
596 |
+
" 'Trạch Thủy Khốn': True,\n",
|
597 |
+
" 'Thủy Phong Tỉnh': True,\n",
|
598 |
+
" 'Trạch Hỏa Cách': True,\n",
|
599 |
+
" 'Hỏa Phong Đỉnh': True,\n",
|
600 |
+
" 'Lịch sử Hoa Kỳ (1493–1776)': True,\n",
|
601 |
+
" 'Thuần Chấn': True,\n",
|
602 |
+
" 'Thuần Cấn': True,\n",
|
603 |
+
" 'Phong Sơn Tiệm': True,\n",
|
604 |
+
" 'Lôi Trạch Quy Muội': True,\n",
|
605 |
+
" 'Lôi Hỏa Phong': True,\n",
|
606 |
+
" 'Hỏa Sơn Lữ': True,\n",
|
607 |
+
" 'Thuần Tốn': True,\n",
|
608 |
+
" 'Thuần Đoài': True,\n",
|
609 |
+
" 'Phong Thủy Hoán': True,\n",
|
610 |
+
" 'Thủy Trạch Tiết': True,\n",
|
611 |
+
" 'Lôi Sơn Tiểu Quá': True,\n",
|
612 |
+
" 'Thủy Hỏa Ký Tế': True,\n",
|
613 |
+
" 'Hỏa Thủy Vị Tế': True,\n",
|
614 |
+
" 'Lê Chí Quang': True,\n",
|
615 |
+
" 'Sao Diêm Vương': True,\n",
|
616 |
+
" 'Sông Hồng': True,\n",
|
617 |
+
" 'Đo lường': True,\n",
|
618 |
+
" 'Hồng Hà (định hướng)': True,\n",
|
619 |
+
" 'Sông Cái Nha Trang': True,\n",
|
620 |
+
" 'Nguyên Giang': True,\n",
|
621 |
+
" 'Đo lường học': True,\n",
|
622 |
+
" 'Ma trận vuông': True,\n",
|
623 |
+
" 'Hệ thống sông Thái Bình': True,\n",
|
624 |
+
" 'Sông Cầu': True,\n",
|
625 |
+
" 'Đơn vị đo': True,\n",
|
626 |
+
" 'Lễ Phục Sinh': True,\n",
|
627 |
+
" 'Sông Cửu Long': True,\n",
|
628 |
+
" 'Mê Kông': True,\n",
|
629 |
+
" 'Nguyễn Vũ Bình': True,\n",
|
630 |
+
" 'Năm nhuận': True,\n",
|
631 |
+
" 'Đơn vị đo chiều dài': True,\n",
|
632 |
+
" 'Pêtamét': True,\n",
|
633 |
+
" 'Latinh (định hướng)': True,\n",
|
634 |
+
" 'Năm ánh sáng': True,\n",
|
635 |
+
" 'Yôtamét': True,\n",
|
636 |
+
" 'Doraemon': True,\n",
|
637 |
+
" 'Nhà xuất bản Kim Đồng': True,\n",
|
638 |
+
" 'Tiếng Latinh': True,\n",
|
639 |
+
" 'Danh sách ngôn ngữ theo tổng số người sử dụng': True,\n",
|
640 |
+
" 'Thủy Tinh': True,\n",
|
641 |
+
" 'NASA': True,\n",
|
642 |
+
" 'Việt Nam Dân chủ Cộng hòa': True,\n",
|
643 |
+
" 'Năm Cam': True,\n",
|
644 |
+
" 'Năm chí tuyến': True,\n",
|
645 |
+
" 'Kitô giáo': True,\n",
|
646 |
+
" 'Thiên Chúa giáo': True,\n",
|
647 |
+
" 'Illinois': True,\n",
|
648 |
+
" 'Rhode Island': True,\n",
|
649 |
+
" 'Viên': True,\n",
|
650 |
+
" 'Nhiệt động lực học': True,\n",
|
651 |
+
" 'Thứ Hai': True,\n",
|
652 |
+
" 'Thứ Ba': True,\n",
|
653 |
+
" 'Thứ Tư': True,\n",
|
654 |
+
" 'Thứ Năm': True,\n",
|
655 |
+
" 'Thứ Sáu': True,\n",
|
656 |
+
" 'Thứ Bảy': True,\n",
|
657 |
+
" 'Giờ Phối hợp Quốc tế': True,\n",
|
658 |
+
" 'Sao Mai (định hướng)': True,\n",
|
659 |
+
" 'Tháng năm': True,\n",
|
660 |
+
" 'Tháng sáu': True,\n",
|
661 |
+
" 'Tháng bảy': True,\n",
|
662 |
+
" 'Thủy tinh': True,\n",
|
663 |
+
" 'Trịnh Công Sơn': True,\n",
|
664 |
+
" 'Kitô giáo Đông phương': True,\n",
|
665 |
+
" 'Chính thống giáo Đông phương': True,\n",
|
666 |
+
" 'Giáo hội Công giáo': True,\n",
|
667 |
+
" 'Kitô giáo Tây phương': True,\n",
|
668 |
+
" 'Kháng Cách': True,\n",
|
669 |
+
" 'Anh giáo': True,\n",
|
670 |
+
" 'Giáo hội Anh': True,\n",
|
671 |
+
" 'Tháng tám': True,\n",
|
672 |
+
" 'Tháng chín': True,\n",
|
673 |
+
" 'Phạm Duy': True,\n",
|
674 |
+
" 'Tháng mười': True,\n",
|
675 |
+
" 'Tháng mười một': True,\n",
|
676 |
+
" 'Tháng mười hai': True,\n",
|
677 |
+
" 'Tháng một': True,\n",
|
678 |
+
" 'Tháng hai': True,\n",
|
679 |
+
" 'Cơ sở dữ liệu': True,\n",
|
680 |
+
" 'Tháng giêng': True,\n",
|
681 |
+
" 'Tháng chạp': True,\n",
|
682 |
+
" 'Sóc (lịch)': True,\n",
|
683 |
+
" 'Tiếng Ý': True,\n",
|
684 |
+
" 'Nông lịch': True,\n",
|
685 |
+
" 'Tháng Tý': True,\n",
|
686 |
+
" 'Âm lịch': True,\n",
|
687 |
+
" 'Can Chi': True,\n",
|
688 |
+
" 'Công Nguyên': True,\n",
|
689 |
+
" 'CN': True,\n",
|
690 |
+
" 'Lịch sử vật lý học': True,\n",
|
691 |
+
" 'Lịch sử cơ học': True,\n",
|
692 |
+
" 'Danh sách quốc gia theo dân số': True,\n",
|
693 |
+
" 'Công giáo': True,\n",
|
694 |
+
" 'Israel': True,\n",
|
695 |
+
" 'Pakistan': True,\n",
|
696 |
+
" 'Mặt Trời': True,\n",
|
697 |
+
" 'Euro': True,\n",
|
698 |
+
" 'Land der Berge, Land am Strome': True,\n",
|
699 |
+
" 'Sankt Pölten': True,\n",
|
700 |
+
" 'Graz': True,\n",
|
701 |
+
" 'Giáo hoàng Gioan Phaolô II': True,\n",
|
702 |
+
" 'Vật lý hạt': True,\n",
|
703 |
+
" 'Thuyết tương đối hẹp': True,\n",
|
704 |
+
" 'Phục Sinh': True,\n",
|
705 |
+
" 'Lý thuyết dây': True,\n",
|
706 |
+
" 'Đức Quốc Xã': True,\n",
|
707 |
+
" 'Sao lùn trắng': True,\n",
|
708 |
+
" 'Hạt sơ cấp': True,\n",
|
709 |
+
" 'Không-thời gian': True,\n",
|
710 |
+
" 'Cơ học thống kê': True,\n",
|
711 |
+
" 'Hạt Higgs': True,\n",
|
712 |
+
" 'Lý thuyết hấp dẫn lượng tử vòng': True,\n",
|
713 |
+
" 'Chất độc da cam': True,\n",
|
714 |
+
" 'VietNamNet': True,\n",
|
715 |
+
" 'Đồng (đơn vị tiền tệ)': True,\n",
|
716 |
+
" 'Đồng (định hướng)': True,\n",
|
717 |
+
" 'Hằng số vật lý': True,\n",
|
718 |
+
" 'CH': True,\n",
|
719 |
+
" 'TP': True,\n",
|
720 |
+
" 'ĐT': True,\n",
|
721 |
+
" 'CQ': True,\n",
|
722 |
+
" 'Khí quyển (định hướng)': True,\n",
|
723 |
+
" 'TV (định hướng)': True,\n",
|
724 |
+
" 'Nhóm ngôn ngữ gốc Ý': True,\n",
|
725 |
+
" 'TN': True,\n",
|
726 |
+
" 'ĐH': True,\n",
|
727 |
+
" 'ND': True,\n",
|
728 |
+
" 'QĐ': True,\n",
|
729 |
+
" 'HQ': True,\n",
|
730 |
+
" 'BĐ': True,\n",
|
731 |
+
" 'QH': True,\n",
|
732 |
+
" 'LĐ': True,\n",
|
733 |
+
" 'ĐN': True,\n",
|
734 |
+
" 'Hỏa Lôi Phệ Hạp': True,\n",
|
735 |
+
" 'ĐC': True,\n",
|
736 |
+
" 'VH': True,\n",
|
737 |
+
" 'VV': True,\n",
|
738 |
+
" 'PT': True,\n",
|
739 |
+
" 'QL': True,\n",
|
740 |
+
" 'Tương tác cơ bản': True,\n",
|
741 |
+
" 'Giải tích thực': True,\n",
|
742 |
+
" 'Đảng Cộng sản Việt Nam': True,\n",
|
743 |
+
" 'Ngữ hệ Nam Á': True,\n",
|
744 |
+
" 'Ngữ hệ Ấn-Âu': True,\n",
|
745 |
+
" 'Ngữ tộc Môn-Khmer': True,\n",
|
746 |
+
" 'Ngữ tộc Slav': True,\n",
|
747 |
+
" 'Ngữ tộc German': True,\n",
|
748 |
+
" 'Nhóm ngôn ngữ Hy Lạp': True,\n",
|
749 |
+
" 'Giới hạn Chandrasekhar': True,\n",
|
750 |
+
" 'Phân loại sao': True,\n",
|
751 |
+
" 'Kim loại kiềm': True,\n",
|
752 |
+
" 'Au': True,\n",
|
753 |
+
" 'Kanji': True,\n",
|
754 |
+
" 'Lê (họ)': True,\n",
|
755 |
+
" 'Vàng (màu)': True,\n",
|
756 |
+
" 'Tía': True,\n",
|
757 |
+
" 'Tím': True,\n",
|
758 |
+
" 'Đỏ': True,\n",
|
759 |
+
" 'Đỏ thắm': True,\n",
|
760 |
+
" 'Đỏ tươi': True,\n",
|
761 |
+
" 'Đỏ son': True,\n",
|
762 |
+
" 'Hồng (màu)': True,\n",
|
763 |
+
" 'Du lịch Áo': True,\n",
|
764 |
+
" 'Địa khai hóa': True,\n",
|
765 |
+
" 'Alexandre Yersin': True,\n",
|
766 |
+
" 'AG': True,\n",
|
767 |
+
" 'AL': True,\n",
|
768 |
+
" 'AQ': True,\n",
|
769 |
+
" 'AN': True,\n",
|
770 |
+
" 'Màu gốc in ấn': True,\n",
|
771 |
+
" 'VI': True,\n",
|
772 |
+
" 'Vi': True,\n",
|
773 |
+
" 'AM': True,\n",
|
774 |
+
" 'Emacs': True,\n",
|
775 |
+
" 'Phối màu phát xạ': True,\n",
|
776 |
+
" 'Phối màu hấp thụ': True,\n",
|
777 |
+
" 'Mô hình màu CMYK': True,\n",
|
778 |
+
" 'Mô hình màu RGB': True,\n",
|
779 |
+
" 'Hà Nam': True,\n",
|
780 |
+
" 'Nhược trương': True,\n",
|
781 |
+
" 'Đẳng trương': True,\n",
|
782 |
+
" 'Hà Nam (định hướng)': True,\n",
|
783 |
+
" 'Mô hình Chuẩn': True,\n",
|
784 |
+
" 'Thí nghiệm Michelson-Morley': True,\n",
|
785 |
+
" 'Phú Thọ': True,\n",
|
786 |
+
" 'An Giang': True,\n",
|
787 |
+
" 'Đen': True,\n",
|
788 |
+
" 'Tổng thống Đức': True,\n",
|
789 |
+
" 'Trắng': True,\n",
|
790 |
+
" 'Das Lied der Deutschen': True,\n",
|
791 |
+
" 'Cúm gia cầm': True,\n",
|
792 |
+
" 'Danh sách màu': True,\n",
|
793 |
+
" 'Ngữ tộc Celt': True,\n",
|
794 |
+
" 'Hổ phách (màu)': True,\n",
|
795 |
+
" 'Ametit (màu)': True,\n",
|
796 |
+
" 'Tỉnh thành Việt Nam': True,\n",
|
797 |
+
" 'Xanh berin': True,\n",
|
798 |
+
" 'Xanh da trời': True,\n",
|
799 |
+
" 'Ngôn ngữ học': True,\n",
|
800 |
+
" 'Nâu sẫm': True,\n",
|
801 |
+
" 'Xanh dương': True,\n",
|
802 |
+
" 'Sinh vật biến đổi gen': True,\n",
|
803 |
+
" 'Tây Bắc Bộ': True,\n",
|
804 |
+
" 'Đồng bằng sông Hồng': True,\n",
|
805 |
+
" 'Bắc Trung Bộ': True,\n",
|
806 |
+
" 'Duyên hải Nam Trung Bộ': True,\n",
|
807 |
+
" 'Tây Nguyên': True,\n",
|
808 |
+
" 'Đông Nam Bộ': True,\n",
|
809 |
+
" 'Đồng bằng sông Cửu Long': True,\n",
|
810 |
+
" 'Bắc Bộ': True,\n",
|
811 |
+
" 'Miền Nam (Việt Nam)': True,\n",
|
812 |
+
" 'Chàm': True,\n",
|
813 |
+
" 'Chàm (bệnh)': True,\n",
|
814 |
+
" 'Yersinia pestis': True,\n",
|
815 |
+
" 'Viêm da': True,\n",
|
816 |
+
" 'Kỹ thuật di truyền': True,\n",
|
817 |
+
" 'Google': True,\n",
|
818 |
+
" 'Yahoo!': True,\n",
|
819 |
+
" 'Lịch sử Hoa Kỳ (1776–1789)': True,\n",
|
820 |
+
" 'Tháng 2 năm 2005': True,\n",
|
821 |
+
" 'Chàm (định hướng)': True,\n",
|
822 |
+
" 'Điện toán': True,\n",
|
823 |
+
" 'Văn hóa': True,\n",
|
824 |
+
" 'Màu sắc': True,\n",
|
825 |
+
" 'Giấy điện tử': True,\n",
|
826 |
+
" 'Cộng hòa Séc': True,\n",
|
827 |
+
" 'Trương Trọng Thi': True,\n",
|
828 |
+
" 'Toán học ứng dụng': True,\n",
|
829 |
+
" 'PC': True,\n",
|
830 |
+
" 'AC': True,\n",
|
831 |
+
" 'Dc': True,\n",
|
832 |
+
" 'Washington': True,\n",
|
833 |
+
" 'Màu be': True,\n",
|
834 |
+
" 'BE': True,\n",
|
835 |
+
" 'Máy tính cá nhân': True,\n",
|
836 |
+
" 'Ngôn ngữ': True,\n",
|
837 |
+
" 'Kde domov můj?': True,\n",
|
838 |
+
" 'Séc': True,\n",
|
839 |
+
" 'Y học': True,\n",
|
840 |
+
" 'Lời thề Hippocrates': True,\n",
|
841 |
+
" 'Virus': True,\n",
|
842 |
+
" 'Hồng Bàng': True,\n",
|
843 |
+
" 'An Dương Vương': True,\n",
|
844 |
+
" 'Vĩnh Phúc': True,\n",
|
845 |
+
" 'DNA': True,\n",
|
846 |
+
" 'Vụ Nổ Lớn': True,\n",
|
847 |
+
" 'Nâu': True,\n",
|
848 |
+
" 'Big Bang (định hướng)': True,\n",
|
849 |
+
" 'Tòa Thánh': True,\n",
|
850 |
+
" 'Xanh lơ': True,\n",
|
851 |
+
" 'Vi ba': True,\n",
|
852 |
+
" 'Lục bảo': True,\n",
|
853 |
+
" 'Vàng kim loại (màu)': True,\n",
|
854 |
+
" 'Xám': True,\n",
|
855 |
+
" 'Da cam': True,\n",
|
856 |
+
" 'Cam cháy': True,\n",
|
857 |
+
" 'Số Hex': True,\n",
|
858 |
+
" 'Cô ban (màu)': True,\n",
|
859 |
+
" 'Đồng (màu)': True,\n",
|
860 |
+
" 'San hô (màu)': True,\n",
|
861 |
+
" 'Kem (màu)': True,\n",
|
862 |
+
" 'Vòi voi (màu)': True,\n",
|
863 |
+
" 'Cá hồi (màu)': True,\n",
|
864 |
+
" 'Nâu đen': True,\n",
|
865 |
+
" 'Xanh chromi': True,\n",
|
866 |
+
" 'Kaki': True,\n",
|
867 |
+
" 'Ngọc thạch (màu)': True,\n",
|
868 |
+
" 'Oải hương (màu)': True,\n",
|
869 |
+
" 'Bạc (màu)': True,\n",
|
870 |
+
" 'Bước sóng': True,\n",
|
871 |
+
" 'Debian': True,\n",
|
872 |
+
" 'SI (định hướng)': True,\n",
|
873 |
+
" 'Mẫu (dạng thức)': True,\n",
|
874 |
+
" '2 tháng 9': True,\n",
|
875 |
+
" 'BCT': True,\n",
|
876 |
+
" 'Ngữ hệ Kra-Dai': True,\n",
|
877 |
+
" 'Mẫu (đơn vị đo)': True,\n",
|
878 |
+
" 'Anh đào (màu)': True,\n",
|
879 |
+
" 'Vàng chanh': True,\n",
|
880 |
+
" 'Lòng đào': True,\n",
|
881 |
+
" 'Dừa cạn (màu)': True,\n",
|
882 |
+
" 'Ngữ hệ Nhật-Lưu Cầu': True,\n",
|
883 |
+
" 'Đỏ yên chi': True,\n",
|
884 |
+
" 'Ôliu (màu)': True,\n",
|
885 |
+
" 'Lan tím': True,\n",
|
886 |
+
" 'Ngọc lam (màu)': True,\n",
|
887 |
+
" 'Mòng két (màu)': True,\n",
|
888 |
+
" 'Hoa cà (màu)': True,\n",
|
889 |
+
" 'Cẩm quỳ (màu)': True,\n",
|
890 |
+
" 'Mận (màu)': True,\n",
|
891 |
+
" 'Tần số': True,\n",
|
892 |
+
" 'Xanh nõn chuối': True,\n",
|
893 |
+
" 'Màu': True,\n",
|
894 |
+
" 'Toàn cầu hóa': True,\n",
|
895 |
+
" 'Virus (định hướng)': True,\n",
|
896 |
+
" 'Liên Xô': True,\n",
|
897 |
+
" 'Siêu dẫn': True,\n",
|
898 |
+
" 'Men ngọc (màu)': True,\n",
|
899 |
+
" 'Hạt dẻ (màu)': True,\n",
|
900 |
+
" 'Hình học giải tích': True,\n",
|
901 |
+
" 'Lam sẫm': True,\n",
|
902 |
+
" 'Nguyễn Cao': True,\n",
|
903 |
+
" 'Hồng đất': True,\n",
|
904 |
+
" 'Xanh thủy tinh': True,\n",
|
905 |
+
" 'Chu kỳ': True,\n",
|
906 |
+
" 'Nâu tanin': True,\n",
|
907 |
+
" 'Hồng y (màu)': True,\n",
|
908 |
+
" 'Ngữ chi Rôman': True,\n",
|
909 |
+
" 'Ngữ tộc Balt': True,\n",
|
910 |
+
" '17 tháng 4': True,\n",
|
911 |
+
" '18 tháng 4': True,\n",
|
912 |
+
" '19 tháng 4': True,\n",
|
913 |
+
" 'Sóng': True,\n",
|
914 |
+
" 'Tần số góc': True,\n",
|
915 |
+
" 'Thánh địa Mỹ Sơn': True,\n",
|
916 |
+
" 'Quần đảo Cát Bà': True,\n",
|
917 |
+
" 'Đồ Sơn': True,\n",
|
918 |
+
" 'Ba Bể (định hướng)': True,\n",
|
919 |
+
" 'Vịnh Hạ Long': True,\n",
|
920 |
+
" 'Hồ Ba Bể': True,\n",
|
921 |
+
" 'Sa Pa (phường)': True,\n",
|
922 |
+
" 'Đà Lạt': True,\n",
|
923 |
+
" 'Phú Quốc': True,\n",
|
924 |
+
" 'Côn Đảo': True,\n",
|
925 |
+
" 'Phố cổ Hội An': True,\n",
|
926 |
+
" 'Ao Bà Om': True,\n",
|
927 |
+
" 'Ngủ đông': True,\n",
|
928 |
+
" 'Chu trình tiềm tan': True,\n",
|
929 |
+
" 'Tiềm sinh': True,\n",
|
930 |
+
" 'Electrum': True,\n",
|
931 |
+
" 'Tia X': True,\n",
|
932 |
+
" 'KTS': True,\n",
|
933 |
+
" 'Quang tuyến': True,\n",
|
934 |
+
" 'Thanh Xuân': True,\n",
|
935 |
+
" 'Di sản thế giới': True,\n",
|
936 |
+
" 'Hạ Long (định hướng)': True,\n",
|
937 |
+
" '24 tháng 4': True,\n",
|
938 |
+
" 'Hóa sinh': True,\n",
|
939 |
+
" '25 tháng 4': True,\n",
|
940 |
+
" 'Tôn giáo': True,\n",
|
941 |
+
" 'Danh sách Thủ tướng Việt Nam': True,\n",
|
942 |
+
" 'KCS': True,\n",
|
943 |
+
" 'KCN': True,\n",
|
944 |
+
" 'Muối ăn': True,\n",
|
945 |
+
" 'Đại lượng vật lý': True,\n",
|
946 |
+
" 'Sự kiện 30 tháng 4 năm 1975': True,\n",
|
947 |
+
" 'Quy hoạch đô thị': True,\n",
|
948 |
+
" 'Danh sách nhà toán học': True,\n",
|
949 |
+
" 'Phật giáo': True,\n",
|
950 |
+
" 'Tắc đường': True,\n",
|
951 |
+
" 'Khoa học máy tính': True,\n",
|
952 |
+
" 'Hưng Yên': True,\n",
|
953 |
+
" 'Bắc Ninh': True,\n",
|
954 |
+
" 'Hà Tây (tỉnh)': True,\n",
|
955 |
+
" 'Khí quyển Sao Hỏa': True,\n",
|
956 |
+
" 'Thượng Hải': True,\n",
|
957 |
+
" 'Công nghệ thông tin': True,\n",
|
958 |
+
" 'Hồ Chí Minh (định hướng)': True,\n",
|
959 |
+
" 'Khu công nghiệp': True,\n",
|
960 |
+
" 'Tam giáo': True,\n",
|
961 |
+
" 'Thái Bình': True,\n",
|
962 |
+
" 'Nam Định': True,\n",
|
963 |
+
" 'Nhà': True,\n",
|
964 |
+
" 'Ninh Bình': True,\n",
|
965 |
+
" 'Chiếu dời đô': True,\n",
|
966 |
+
" 'Ngọc lục bảo': True,\n",
|
967 |
+
" 'Tin học': True,\n",
|
968 |
+
" 'Tự do hóa': True,\n",
|
969 |
+
" 'CSS': True,\n",
|
970 |
+
" 'Hiệp ước chung về thuế quan và mậu dịch': True,\n",
|
971 |
+
" 'Lai tạp hóa': True,\n",
|
972 |
+
" 'Mỹ hóa': True,\n",
|
973 |
+
" 'Tổ chức sở hữu trí tuệ': True,\n",
|
974 |
+
" 'Khoa học thông tin': True,\n",
|
975 |
+
" 'Thuật toán': True,\n",
|
976 |
+
" 'WEB': True,\n",
|
977 |
+
" '1 tháng 4': True,\n",
|
978 |
+
" 'Tổ chức phi chính phủ': True,\n",
|
979 |
+
" 'Đầu tư trực tiếp nước ngoài': True,\n",
|
980 |
+
" 'NGO': True,\n",
|
981 |
+
" 'Phần cứng': True,\n",
|
982 |
+
" 'Châu Âu': True,\n",
|
983 |
+
" 'Thái Lan': True,\n",
|
984 |
+
" 'Virus (máy tính)': True,\n",
|
985 |
+
" 'Phần mềm ác ý': True,\n",
|
986 |
+
" 'Linux From Scratch': True,\n",
|
987 |
+
" 'LFS': True,\n",
|
988 |
+
" 'Hà Nội (định hướng)': True,\n",
|
989 |
+
" 'Ngọc lam': True,\n",
|
990 |
+
" '2 tháng 4': True,\n",
|
991 |
+
" 'Lipid': True,\n",
|
992 |
+
" 'Toán học tổ hợp': True,\n",
|
993 |
+
" 'Toán học rời rạc': True,\n",
|
994 |
+
" 'Nara (thành phố)': True,\n",
|
995 |
+
" 'Phan Bội Châu': True,\n",
|
996 |
+
" 'Sắc ký': True,\n",
|
997 |
+
" 'Hồng ngọc': True,\n",
|
998 |
+
" 'Ribosome': True,\n",
|
999 |
+
" 'Trung tử': True,\n",
|
1000 |
+
" 'Lysosome': True,\n",
|
1001 |
+
" 'Mạng lưới nội chất': True,\n",
|
1002 |
+
" 'Peroxisome': True,\n",
|
1003 |
+
" 'Bộ máy Golgi': True,\n",
|
1004 |
+
" 'Điện tử học': True,\n",
|
1005 |
+
" 'Ty thể': True,\n",
|
1006 |
+
" 'Công nghệ nano': True,\n",
|
1007 |
+
" 'Quan Âm': True,\n",
|
1008 |
+
" 'Tháp Hà Nội (định hướng)': True,\n",
|
1009 |
+
" 'Nhà Nguyễn': True,\n",
|
1010 |
+
" 'Danh sách quốc gia có chủ quyền': True,\n",
|
1011 |
+
" 'Sông Cầu (định hướng)': True,\n",
|
1012 |
+
" 'Thiên đỉnh': True,\n",
|
1013 |
+
" 'Thiên để': True,\n",
|
1014 |
+
" 'Tạ (định hướng)': True,\n",
|
1015 |
+
" 'Tấn (định hướng)': True,\n",
|
1016 |
+
" 'Câu lệnh (khoa học máy tính)': True,\n",
|
1017 |
+
" 'Chỉ thị (máy tính)': True,\n",
|
1018 |
+
" 'Frank Sherwood Rowland': True,\n",
|
1019 |
+
" 'Cú pháp câu lệnh': True,\n",
|
1020 |
+
" 'Nhóm chức': True,\n",
|
1021 |
+
" 'Quy tắc đặt dấu thanh trong chữ quốc ngữ': True,\n",
|
1022 |
+
" 'Tán xạ Rayleigh': True,\n",
|
1023 |
+
" 'Đúng': True,\n",
|
1024 |
+
" 'Đồng': True,\n",
|
1025 |
+
" 'Đậu tương': True,\n",
|
1026 |
+
" 'Cộng đồng Wikipedia': True,\n",
|
1027 |
+
" 'Đồng tính luyến ái': True,\n",
|
1028 |
+
" 'Tam quốc diễn nghĩa': True,\n",
|
1029 |
+
" 'Vết đen Mặt Trời': True,\n",
|
1030 |
+
" 'Mô hình Markov ẩn': True,\n",
|
1031 |
+
" 'Tin sinh học': True,\n",
|
1032 |
+
" 'Vết đen': True,\n",
|
1033 |
+
" 'Tứ đại danh tác': True,\n",
|
1034 |
+
" 'Sách đỏ IUCN': True,\n",
|
1035 |
+
" 'Hệ điều hành': True,\n",
|
1036 |
+
" 'Bắt cặp trình tự': True,\n",
|
1037 |
+
" 'Tam quốc diễn nghĩa (định hướng)': True,\n",
|
1038 |
+
" 'Trình tự motif': True,\n",
|
1039 |
+
" 'Thành phố Trung Quốc': True,\n",
|
1040 |
+
" 'Thụy Sĩ': True,\n",
|
1041 |
+
" 'Kẽm': True,\n",
|
1042 |
+
" 'Dãy số thực': True,\n",
|
1043 |
+
" 'Bánh chưng': True,\n",
|
1044 |
+
" 'Lá dong': True,\n",
|
1045 |
+
" 'Bánh giầy': True,\n",
|
1046 |
+
" 'Bạc': True,\n",
|
1047 |
+
" 'Boson W': True,\n",
|
1048 |
+
" ...}"
|
1049 |
+
]
|
1050 |
+
},
|
1051 |
+
"execution_count": 4,
|
1052 |
+
"metadata": {},
|
1053 |
+
"output_type": "execute_result"
|
1054 |
+
}
|
1055 |
+
],
|
1056 |
+
"source": [
|
1057 |
+
"all_titles = dict([(x.strip(),True) for x in open(\"../data/raw/wikipedia_20220620_cleaned/wikipedia_20220620_all_titles.txt\").readlines()])\n",
|
1058 |
+
"all_titles"
|
1059 |
+
]
|
1060 |
+
},
|
1061 |
+
{
|
1062 |
+
"cell_type": "code",
|
1063 |
+
"execution_count": 5,
|
1064 |
+
"metadata": {},
|
1065 |
+
"outputs": [],
|
1066 |
+
"source": [
|
1067 |
+
"dict_map = dict({}) \n",
|
1068 |
+
" \n",
|
1069 |
+
"def word_tokenize(text): \n",
|
1070 |
+
" global dict_map \n",
|
1071 |
+
" words = text.split() \n",
|
1072 |
+
" words_norm = [] \n",
|
1073 |
+
" for w in words: \n",
|
1074 |
+
" if dict_map.get(w, None) is None: \n",
|
1075 |
+
" dict_map[w] = ' '.join(lib_tokenizer(w)).replace('``', '\"').replace(\"''\", '\"') \n",
|
1076 |
+
" words_norm.append(dict_map[w]) \n",
|
1077 |
+
" return words_norm \n",
|
1078 |
+
" \n",
|
1079 |
+
"def strip_answer_string(text): \n",
|
1080 |
+
" text = text.strip() \n",
|
1081 |
+
" while text[-1] in '.,/><;:\\'\"[]{}+=-_)(*&^!~`': \n",
|
1082 |
+
" if text[0] != '(' and text[-1] == ')' and '(' in text: \n",
|
1083 |
+
" break \n",
|
1084 |
+
" if text[-1] == '\"' and text[0] != '\"' and text.count('\"') > 1: \n",
|
1085 |
+
" break \n",
|
1086 |
+
" text = text[:-1].strip() \n",
|
1087 |
+
" while text[0] in '.,/><;:\\'\"[]{}+=-_)(*&^!~`': \n",
|
1088 |
+
" if text[0] == '\"' and text[-1] != '\"' and text.count('\"') > 1: \n",
|
1089 |
+
" break \n",
|
1090 |
+
" text = text[1:].strip() \n",
|
1091 |
+
" text = text.strip() \n",
|
1092 |
+
" return text \n",
|
1093 |
+
" \n",
|
1094 |
+
"def strip_context(text): \n",
|
1095 |
+
" text = text.replace('\\n', ' ') \n",
|
1096 |
+
" text = re.sub(r'\\s+', ' ', text) \n",
|
1097 |
+
" text = text.strip() \n",
|
1098 |
+
" return text"
|
1099 |
+
]
|
1100 |
+
},
|
1101 |
+
{
|
1102 |
+
"cell_type": "code",
|
1103 |
+
"execution_count": 6,
|
1104 |
+
"metadata": {},
|
1105 |
+
"outputs": [
|
1106 |
+
{
|
1107 |
+
"name": "stdout",
|
1108 |
+
"output_type": "stream",
|
1109 |
+
"text": [
|
1110 |
+
"INFO: Pandarallel will run on 6 workers.\n",
|
1111 |
+
"INFO: Pandarallel will use standard multiprocessing data transfer (pipe) to transfer data between the main process and workers.\n"
|
1112 |
+
]
|
1113 |
+
}
|
1114 |
+
],
|
1115 |
+
"source": [
|
1116 |
+
"from pandarallel import pandarallel\n",
|
1117 |
+
"\n",
|
1118 |
+
"pandarallel.initialize(progress_bar=True, use_memory_fs=False, nb_workers=6)"
|
1119 |
+
]
|
1120 |
+
},
|
1121 |
+
{
|
1122 |
+
"cell_type": "code",
|
1123 |
+
"execution_count": 7,
|
1124 |
+
"metadata": {},
|
1125 |
+
"outputs": [
|
1126 |
+
{
|
1127 |
+
"data": {
|
1128 |
+
"application/vnd.jupyter.widget-view+json": {
|
1129 |
+
"model_id": "9bacd2c6720d48209399c9220f4e3054",
|
1130 |
+
"version_major": 2,
|
1131 |
+
"version_minor": 0
|
1132 |
+
},
|
1133 |
+
"text/plain": [
|
1134 |
+
"VBox(children=(HBox(children=(IntProgress(value=0, description='0.00%', max=36008), Label(value='0 / 36008')))…"
|
1135 |
+
]
|
1136 |
+
},
|
1137 |
+
"metadata": {},
|
1138 |
+
"output_type": "display_data"
|
1139 |
+
},
|
1140 |
+
{
|
1141 |
+
"data": {
|
1142 |
+
"application/vnd.jupyter.widget-view+json": {
|
1143 |
+
"model_id": "140698a55ee644c79d2a54941c4beb6b",
|
1144 |
+
"version_major": 2,
|
1145 |
+
"version_minor": 0
|
1146 |
+
},
|
1147 |
+
"text/plain": [
|
1148 |
+
"VBox(children=(HBox(children=(IntProgress(value=0, description='0.00%', max=36008), Label(value='0 / 36008')))…"
|
1149 |
+
]
|
1150 |
+
},
|
1151 |
+
"metadata": {},
|
1152 |
+
"output_type": "display_data"
|
1153 |
+
},
|
1154 |
+
{
|
1155 |
+
"data": {
|
1156 |
+
"application/vnd.jupyter.widget-view+json": {
|
1157 |
+
"model_id": "8e9ae778df744c568ac4e990dd356f19",
|
1158 |
+
"version_major": 2,
|
1159 |
+
"version_minor": 0
|
1160 |
+
},
|
1161 |
+
"text/plain": [
|
1162 |
+
"VBox(children=(HBox(children=(IntProgress(value=0, description='0.00%', max=36008), Label(value='0 / 36008')))…"
|
1163 |
+
]
|
1164 |
+
},
|
1165 |
+
"metadata": {},
|
1166 |
+
"output_type": "display_data"
|
1167 |
+
},
|
1168 |
+
{
|
1169 |
+
"data": {
|
1170 |
+
"application/vnd.jupyter.widget-view+json": {
|
1171 |
+
"model_id": "b3be62a6ab8a4190974f50bc3e6eb74b",
|
1172 |
+
"version_major": 2,
|
1173 |
+
"version_minor": 0
|
1174 |
+
},
|
1175 |
+
"text/plain": [
|
1176 |
+
"VBox(children=(HBox(children=(IntProgress(value=0, description='0.00%', max=36008), Label(value='0 / 36008')))…"
|
1177 |
+
]
|
1178 |
+
},
|
1179 |
+
"metadata": {},
|
1180 |
+
"output_type": "display_data"
|
1181 |
+
},
|
1182 |
+
{
|
1183 |
+
"data": {
|
1184 |
+
"application/vnd.jupyter.widget-view+json": {
|
1185 |
+
"model_id": "c98f91a6efa94966af32ceec70eea55c",
|
1186 |
+
"version_major": 2,
|
1187 |
+
"version_minor": 0
|
1188 |
+
},
|
1189 |
+
"text/plain": [
|
1190 |
+
"VBox(children=(HBox(children=(IntProgress(value=0, description='0.00%', max=36008), Label(value='0 / 36008')))…"
|
1191 |
+
]
|
1192 |
+
},
|
1193 |
+
"metadata": {},
|
1194 |
+
"output_type": "display_data"
|
1195 |
+
},
|
1196 |
+
{
|
1197 |
+
"data": {
|
1198 |
+
"application/vnd.jupyter.widget-view+json": {
|
1199 |
+
"model_id": "ed68d16693ef4b7dadafd098e3d6bc88",
|
1200 |
+
"version_major": 2,
|
1201 |
+
"version_minor": 0
|
1202 |
+
},
|
1203 |
+
"text/plain": [
|
1204 |
+
"VBox(children=(HBox(children=(IntProgress(value=0, description='0.00%', max=36008), Label(value='0 / 36008')))…"
|
1205 |
+
]
|
1206 |
+
},
|
1207 |
+
"metadata": {},
|
1208 |
+
"output_type": "display_data"
|
1209 |
+
},
|
1210 |
+
{
|
1211 |
+
"data": {
|
1212 |
+
"application/vnd.jupyter.widget-view+json": {
|
1213 |
+
"model_id": "07f08ef339ea431ab76a84ff6b8c2e57",
|
1214 |
+
"version_major": 2,
|
1215 |
+
"version_minor": 0
|
1216 |
+
},
|
1217 |
+
"text/plain": [
|
1218 |
+
"VBox(children=(HBox(children=(IntProgress(value=0, description='0.00%', max=36008), Label(value='0 / 36008')))…"
|
1219 |
+
]
|
1220 |
+
},
|
1221 |
+
"metadata": {},
|
1222 |
+
"output_type": "display_data"
|
1223 |
+
},
|
1224 |
+
{
|
1225 |
+
"data": {
|
1226 |
+
"application/vnd.jupyter.widget-view+json": {
|
1227 |
+
"model_id": "82630b19f0164af7915195256ec63a00",
|
1228 |
+
"version_major": 2,
|
1229 |
+
"version_minor": 0
|
1230 |
+
},
|
1231 |
+
"text/plain": [
|
1232 |
+
"VBox(children=(HBox(children=(IntProgress(value=0, description='0.00%', max=36008), Label(value='0 / 36008')))…"
|
1233 |
+
]
|
1234 |
+
},
|
1235 |
+
"metadata": {},
|
1236 |
+
"output_type": "display_data"
|
1237 |
+
},
|
1238 |
+
{
|
1239 |
+
"data": {
|
1240 |
+
"application/vnd.jupyter.widget-view+json": {
|
1241 |
+
"model_id": "365cd1db011a48de884862248ecdfc84",
|
1242 |
+
"version_major": 2,
|
1243 |
+
"version_minor": 0
|
1244 |
+
},
|
1245 |
+
"text/plain": [
|
1246 |
+
"VBox(children=(HBox(children=(IntProgress(value=0, description='0.00%', max=36008), Label(value='0 / 36008')))…"
|
1247 |
+
]
|
1248 |
+
},
|
1249 |
+
"metadata": {},
|
1250 |
+
"output_type": "display_data"
|
1251 |
+
},
|
1252 |
+
{
|
1253 |
+
"data": {
|
1254 |
+
"application/vnd.jupyter.widget-view+json": {
|
1255 |
+
"model_id": "c1bb81622d9648308170dbeda422b7a5",
|
1256 |
+
"version_major": 2,
|
1257 |
+
"version_minor": 0
|
1258 |
+
},
|
1259 |
+
"text/plain": [
|
1260 |
+
"VBox(children=(HBox(children=(IntProgress(value=0, description='0.00%', max=1), Label(value='0 / 1'))),))"
|
1261 |
+
]
|
1262 |
+
},
|
1263 |
+
"metadata": {},
|
1264 |
+
"output_type": "display_data"
|
1265 |
+
},
|
1266 |
+
{
|
1267 |
+
"data": {
|
1268 |
+
"text/plain": [
|
1269 |
+
"0 Trang Chính < templatestyles src= \" Wiki2021/s...\n",
|
1270 |
+
"1 Internet Society hay ISOC là một tổ chức quốc ...\n",
|
1271 |
+
"2 Tiếng Việt , cũng gọi là tiếng Việt Nam hay Vi...\n",
|
1272 |
+
"3 hệ thống thanh điệu phát triển cao hơn , hệ th...\n",
|
1273 |
+
"4 tiếp xúc Hán – Việt thành 2 giai đoạn chính : ...\n",
|
1274 |
+
"Name: cleaned_text, dtype: object"
|
1275 |
+
]
|
1276 |
+
},
|
1277 |
+
"execution_count": 7,
|
1278 |
+
"metadata": {},
|
1279 |
+
"output_type": "execute_result"
|
1280 |
+
}
|
1281 |
+
],
|
1282 |
+
"source": [
|
1283 |
+
"def apply_tokenizer(df, num_chunks):\n",
|
1284 |
+
" chunk_sr = pd.Series()\n",
|
1285 |
+
" i = 0\n",
|
1286 |
+
" end = df.shape[0]\n",
|
1287 |
+
" chunk_size = math.floor(end/num_chunks)\n",
|
1288 |
+
" while i != end:\n",
|
1289 |
+
" if end - i < chunk_size:\n",
|
1290 |
+
" chunk_size = end - i\n",
|
1291 |
+
" temp_df = df[i:i+chunk_size].copy()\n",
|
1292 |
+
" chunk_sr = pd.concat([chunk_sr, temp_df[\"text\"].parallel_apply(lambda x: \" \".join(word_tokenize(strip_context(x))))], ignore_index=True)\n",
|
1293 |
+
" i+=chunk_size\n",
|
1294 |
+
" return chunk_sr\n",
|
1295 |
+
"\n",
|
1296 |
+
"df[\"cleaned_text\"] = apply_tokenizer(df, 9)\n",
|
1297 |
+
"df[\"cleaned_text\"].head()"
|
1298 |
+
]
|
1299 |
+
},
|
1300 |
+
{
|
1301 |
+
"cell_type": "code",
|
1302 |
+
"execution_count": 8,
|
1303 |
+
"metadata": {},
|
1304 |
+
"outputs": [],
|
1305 |
+
"source": [
|
1306 |
+
"train_titles = set([x['title'].strip() for x in train['data'] if len(x['title']) > 0])"
|
1307 |
+
]
|
1308 |
+
},
|
1309 |
+
{
|
1310 |
+
"cell_type": "code",
|
1311 |
+
"execution_count": 9,
|
1312 |
+
"metadata": {},
|
1313 |
+
"outputs": [
|
1314 |
+
{
|
1315 |
+
"data": {
|
1316 |
+
"application/vnd.jupyter.widget-view+json": {
|
1317 |
+
"model_id": "8492dc037ce24b2eb849ba28a7a64eb2",
|
1318 |
+
"version_major": 2,
|
1319 |
+
"version_minor": 0
|
1320 |
+
},
|
1321 |
+
"text/plain": [
|
1322 |
+
"VBox(children=(HBox(children=(IntProgress(value=0, description='0.00%', max=324068), Label(value='0 / 324068')…"
|
1323 |
+
]
|
1324 |
+
},
|
1325 |
+
"metadata": {},
|
1326 |
+
"output_type": "display_data"
|
1327 |
+
}
|
1328 |
+
],
|
1329 |
+
"source": [
|
1330 |
+
"df[\"valid\"] = df['title'].parallel_apply(lambda x: str(x).strip() in train_titles)"
|
1331 |
+
]
|
1332 |
+
},
|
1333 |
+
{
|
1334 |
+
"cell_type": "code",
|
1335 |
+
"execution_count": 10,
|
1336 |
+
"metadata": {},
|
1337 |
+
"outputs": [],
|
1338 |
+
"source": [
|
1339 |
+
"df = df[df['valid']]\n",
|
1340 |
+
"df.reset_index(drop=True, inplace=True)"
|
1341 |
+
]
|
1342 |
+
},
|
1343 |
+
{
|
1344 |
+
"cell_type": "code",
|
1345 |
+
"execution_count": 11,
|
1346 |
+
"metadata": {},
|
1347 |
+
"outputs": [
|
1348 |
+
{
|
1349 |
+
"data": {
|
1350 |
+
"text/plain": [
|
1351 |
+
"(8782,)"
|
1352 |
+
]
|
1353 |
+
},
|
1354 |
+
"execution_count": 11,
|
1355 |
+
"metadata": {},
|
1356 |
+
"output_type": "execute_result"
|
1357 |
+
}
|
1358 |
+
],
|
1359 |
+
"source": [
|
1360 |
+
"df.title.unique().shape"
|
1361 |
+
]
|
1362 |
+
},
|
1363 |
+
{
|
1364 |
+
"cell_type": "code",
|
1365 |
+
"execution_count": 12,
|
1366 |
+
"metadata": {},
|
1367 |
+
"outputs": [
|
1368 |
+
{
|
1369 |
+
"data": {
|
1370 |
+
"text/html": [
|
1371 |
+
"<div>\n",
|
1372 |
+
"<style scoped>\n",
|
1373 |
+
" .dataframe tbody tr th:only-of-type {\n",
|
1374 |
+
" vertical-align: middle;\n",
|
1375 |
+
" }\n",
|
1376 |
+
"\n",
|
1377 |
+
" .dataframe tbody tr th {\n",
|
1378 |
+
" vertical-align: top;\n",
|
1379 |
+
" }\n",
|
1380 |
+
"\n",
|
1381 |
+
" .dataframe thead th {\n",
|
1382 |
+
" text-align: right;\n",
|
1383 |
+
" }\n",
|
1384 |
+
"</style>\n",
|
1385 |
+
"<table border=\"1\" class=\"dataframe\">\n",
|
1386 |
+
" <thead>\n",
|
1387 |
+
" <tr style=\"text-align: right;\">\n",
|
1388 |
+
" <th></th>\n",
|
1389 |
+
" <th>title</th>\n",
|
1390 |
+
" <th>text</th>\n",
|
1391 |
+
" <th>bm25_text</th>\n",
|
1392 |
+
" <th>cleaned_text</th>\n",
|
1393 |
+
" <th>valid</th>\n",
|
1394 |
+
" </tr>\n",
|
1395 |
+
" </thead>\n",
|
1396 |
+
" <tbody>\n",
|
1397 |
+
" <tr>\n",
|
1398 |
+
" <th>0</th>\n",
|
1399 |
+
" <td>Tiếng Việt</td>\n",
|
1400 |
+
" <td>Tiếng Việt , cũng gọi là tiếng Việt Nam hay Vi...</td>\n",
|
1401 |
+
" <td>tiếng việt cũng gọi là tiếng việt nam hay việt...</td>\n",
|
1402 |
+
" <td>Tiếng Việt , cũng gọi là tiếng Việt Nam hay Vi...</td>\n",
|
1403 |
+
" <td>True</td>\n",
|
1404 |
+
" </tr>\n",
|
1405 |
+
" <tr>\n",
|
1406 |
+
" <th>1</th>\n",
|
1407 |
+
" <td>Tiếng Việt</td>\n",
|
1408 |
+
" <td>hệ thống thanh điệu phát triển cao hơn, hệ thố...</td>\n",
|
1409 |
+
" <td>hệ thống thanh điệu phát triển cao hơn hệ thốn...</td>\n",
|
1410 |
+
" <td>hệ thống thanh điệu phát triển cao hơn , hệ th...</td>\n",
|
1411 |
+
" <td>True</td>\n",
|
1412 |
+
" </tr>\n",
|
1413 |
+
" <tr>\n",
|
1414 |
+
" <th>2</th>\n",
|
1415 |
+
" <td>Tiếng Việt</td>\n",
|
1416 |
+
" <td>tiếp xúc Hán – Việt thành 2 giai đoạn chính: \\...</td>\n",
|
1417 |
+
" <td>tiếp xúc hán – việt thành 2 giai đoạn chính bu...</td>\n",
|
1418 |
+
" <td>tiếp xúc Hán – Việt thành 2 giai đoạn chính : ...</td>\n",
|
1419 |
+
" <td>True</td>\n",
|
1420 |
+
" </tr>\n",
|
1421 |
+
" <tr>\n",
|
1422 |
+
" <th>3</th>\n",
|
1423 |
+
" <td>Tiếng Việt</td>\n",
|
1424 |
+
" <td>thêm hàng loạt các yếu tố Hán–Việt. Như là \"ch...</td>\n",
|
1425 |
+
" <td>thêm hàng loạt các yếu tố hán–việt như là chủ ...</td>\n",
|
1426 |
+
" <td>thêm hàng loạt các yếu tố Hán–Việt . Như là \" ...</td>\n",
|
1427 |
+
" <td>True</td>\n",
|
1428 |
+
" </tr>\n",
|
1429 |
+
" <tr>\n",
|
1430 |
+
" <th>4</th>\n",
|
1431 |
+
" <td>Tiếng Việt</td>\n",
|
1432 |
+
" <td>tiếng Hán vẫn có ai đó chấp nhận và sử dụng tr...</td>\n",
|
1433 |
+
" <td>tiếng hán vẫn có ai đó chấp nhận và sử dụng tr...</td>\n",
|
1434 |
+
" <td>tiếng Hán vẫn có ai đó chấp nhận và sử dụng tr...</td>\n",
|
1435 |
+
" <td>True</td>\n",
|
1436 |
+
" </tr>\n",
|
1437 |
+
" </tbody>\n",
|
1438 |
+
"</table>\n",
|
1439 |
+
"</div>"
|
1440 |
+
],
|
1441 |
+
"text/plain": [
|
1442 |
+
" title text \\\n",
|
1443 |
+
"0 Tiếng Việt Tiếng Việt , cũng gọi là tiếng Việt Nam hay Vi... \n",
|
1444 |
+
"1 Tiếng Việt hệ thống thanh điệu phát triển cao hơn, hệ thố... \n",
|
1445 |
+
"2 Tiếng Việt tiếp xúc Hán – Việt thành 2 giai đoạn chính: \\... \n",
|
1446 |
+
"3 Tiếng Việt thêm hàng loạt các yếu tố Hán–Việt. Như là \"ch... \n",
|
1447 |
+
"4 Tiếng Việt tiếng Hán vẫn có ai đó chấp nhận và sử dụng tr... \n",
|
1448 |
+
"\n",
|
1449 |
+
" bm25_text \\\n",
|
1450 |
+
"0 tiếng việt cũng gọi là tiếng việt nam hay việt... \n",
|
1451 |
+
"1 hệ thống thanh điệu phát triển cao hơn hệ thốn... \n",
|
1452 |
+
"2 tiếp xúc hán – việt thành 2 giai đoạn chính bu... \n",
|
1453 |
+
"3 thêm hàng loạt các yếu tố hán–việt như là chủ ... \n",
|
1454 |
+
"4 tiếng hán vẫn có ai đó chấp nhận và sử dụng tr... \n",
|
1455 |
+
"\n",
|
1456 |
+
" cleaned_text valid \n",
|
1457 |
+
"0 Tiếng Việt , cũng gọi là tiếng Việt Nam hay Vi... True \n",
|
1458 |
+
"1 hệ thống thanh điệu phát triển cao hơn , hệ th... True \n",
|
1459 |
+
"2 tiếp xúc Hán – Việt thành 2 giai đoạn chính : ... True \n",
|
1460 |
+
"3 thêm hàng loạt các yếu tố Hán–Việt . Như là \" ... True \n",
|
1461 |
+
"4 tiếng Hán vẫn có ai đó chấp nhận và sử dụng tr... True "
|
1462 |
+
]
|
1463 |
+
},
|
1464 |
+
"execution_count": 12,
|
1465 |
+
"metadata": {},
|
1466 |
+
"output_type": "execute_result"
|
1467 |
+
}
|
1468 |
+
],
|
1469 |
+
"source": [
|
1470 |
+
"df.head()"
|
1471 |
+
]
|
1472 |
+
},
|
1473 |
+
{
|
1474 |
+
"cell_type": "code",
|
1475 |
+
"execution_count": 13,
|
1476 |
+
"metadata": {},
|
1477 |
+
"outputs": [],
|
1478 |
+
"source": [
|
1479 |
+
"train_df = pd.DataFrame()\n",
|
1480 |
+
"train_df[\"id\"] = [x['id'] for x in train['data']]\n",
|
1481 |
+
"train_df[\"title\"] = [x['title'] for x in train['data']]\n",
|
1482 |
+
"train_df[\"text\"] = [x['text'] for x in train['data']]"
|
1483 |
+
]
|
1484 |
+
},
|
1485 |
+
{
|
1486 |
+
"cell_type": "code",
|
1487 |
+
"execution_count": 16,
|
1488 |
+
"metadata": {},
|
1489 |
+
"outputs": [
|
1490 |
+
{
|
1491 |
+
"data": {
|
1492 |
+
"text/html": [
|
1493 |
+
"<div>\n",
|
1494 |
+
"<style scoped>\n",
|
1495 |
+
" .dataframe tbody tr th:only-of-type {\n",
|
1496 |
+
" vertical-align: middle;\n",
|
1497 |
+
" }\n",
|
1498 |
+
"\n",
|
1499 |
+
" .dataframe tbody tr th {\n",
|
1500 |
+
" vertical-align: top;\n",
|
1501 |
+
" }\n",
|
1502 |
+
"\n",
|
1503 |
+
" .dataframe thead th {\n",
|
1504 |
+
" text-align: right;\n",
|
1505 |
+
" }\n",
|
1506 |
+
"</style>\n",
|
1507 |
+
"<table border=\"1\" class=\"dataframe\">\n",
|
1508 |
+
" <thead>\n",
|
1509 |
+
" <tr style=\"text-align: right;\">\n",
|
1510 |
+
" <th></th>\n",
|
1511 |
+
" <th>id</th>\n",
|
1512 |
+
" <th>title</th>\n",
|
1513 |
+
" <th>text</th>\n",
|
1514 |
+
" </tr>\n",
|
1515 |
+
" </thead>\n",
|
1516 |
+
" <tbody>\n",
|
1517 |
+
" <tr>\n",
|
1518 |
+
" <th>0</th>\n",
|
1519 |
+
" <td>718d41cd997b2b44b0685ac54aa55bd8</td>\n",
|
1520 |
+
" <td>Trung Quốc</td>\n",
|
1521 |
+
" <td>Thủ tướng Trung Quốc là nhân vật lãnh đạo chín...</td>\n",
|
1522 |
+
" </tr>\n",
|
1523 |
+
" <tr>\n",
|
1524 |
+
" <th>1</th>\n",
|
1525 |
+
" <td>c926e7b0717202618a10dd907d4b4c39</td>\n",
|
1526 |
+
" <td></td>\n",
|
1527 |
+
" <td>có 23 quốc gia không có lực lượng quân đội, ba...</td>\n",
|
1528 |
+
" </tr>\n",
|
1529 |
+
" <tr>\n",
|
1530 |
+
" <th>2</th>\n",
|
1531 |
+
" <td>d38ef5bf1fb82b410026ed82c8a44cae</td>\n",
|
1532 |
+
" <td>Raymondienne</td>\n",
|
1533 |
+
" <td>Raymondienne (hay Raymonde Dien) sinh ngày 13 ...</td>\n",
|
1534 |
+
" </tr>\n",
|
1535 |
+
" <tr>\n",
|
1536 |
+
" <th>3</th>\n",
|
1537 |
+
" <td>b6b5589a98fdccd208dc752bac853993</td>\n",
|
1538 |
+
" <td>Cúp cờ vua thế giới</td>\n",
|
1539 |
+
" <td>Cúp cờ vua thế giới là tên gọi một số giải đấu...</td>\n",
|
1540 |
+
" </tr>\n",
|
1541 |
+
" <tr>\n",
|
1542 |
+
" <th>4</th>\n",
|
1543 |
+
" <td>82396a18fa9812bfec4d3ecb7ae60905</td>\n",
|
1544 |
+
" <td>Shkhara</td>\n",
|
1545 |
+
" <td>Đỉnh núi nằm ở phần trung tâm của dãy núi Đại ...</td>\n",
|
1546 |
+
" </tr>\n",
|
1547 |
+
" <tr>\n",
|
1548 |
+
" <th>...</th>\n",
|
1549 |
+
" <td>...</td>\n",
|
1550 |
+
" <td>...</td>\n",
|
1551 |
+
" <td>...</td>\n",
|
1552 |
+
" </tr>\n",
|
1553 |
+
" <tr>\n",
|
1554 |
+
" <th>20852</th>\n",
|
1555 |
+
" <td>508022f540c39fe31511f594748759bc</td>\n",
|
1556 |
+
" <td>Eros</td>\n",
|
1557 |
+
" <td>Trong thần thoại Hy Lạp , \" Eros \" là vị thần ...</td>\n",
|
1558 |
+
" </tr>\n",
|
1559 |
+
" <tr>\n",
|
1560 |
+
" <th>20853</th>\n",
|
1561 |
+
" <td>93c746695c50932ac45ac498a192a3e5</td>\n",
|
1562 |
+
" <td>Lịch sử hành chính Hà Nội</td>\n",
|
1563 |
+
" <td>Vào thời điểm hiện tại ( 2017 ) , về mặt hành ...</td>\n",
|
1564 |
+
" </tr>\n",
|
1565 |
+
" <tr>\n",
|
1566 |
+
" <th>20854</th>\n",
|
1567 |
+
" <td>c477d4b40045ee4251cf9b2a0482cfc4</td>\n",
|
1568 |
+
" <td>Nhật ký trong tù</td>\n",
|
1569 |
+
" <td>“ Nhật ký trong tù ” là một cuốn sổ tay nhỏ , ...</td>\n",
|
1570 |
+
" </tr>\n",
|
1571 |
+
" <tr>\n",
|
1572 |
+
" <th>20855</th>\n",
|
1573 |
+
" <td>278ad127825c085a54fa22116c281f92</td>\n",
|
1574 |
+
" <td>Google</td>\n",
|
1575 |
+
" <td>Tên miền www.google.com được đăng ký ngày 15 t...</td>\n",
|
1576 |
+
" </tr>\n",
|
1577 |
+
" <tr>\n",
|
1578 |
+
" <th>20856</th>\n",
|
1579 |
+
" <td>09ee53a835ea4ed2234aee8161b16d87</td>\n",
|
1580 |
+
" <td>Dãy núi Hoàng Liên Sơn</td>\n",
|
1581 |
+
" <td>Dãy núi Hoàng Liên Sơn rộng 30 km, chạy dài 18...</td>\n",
|
1582 |
+
" </tr>\n",
|
1583 |
+
" </tbody>\n",
|
1584 |
+
"</table>\n",
|
1585 |
+
"<p>20857 rows × 3 columns</p>\n",
|
1586 |
+
"</div>"
|
1587 |
+
],
|
1588 |
+
"text/plain": [
|
1589 |
+
" id title \\\n",
|
1590 |
+
"0 718d41cd997b2b44b0685ac54aa55bd8 Trung Quốc \n",
|
1591 |
+
"1 c926e7b0717202618a10dd907d4b4c39 \n",
|
1592 |
+
"2 d38ef5bf1fb82b410026ed82c8a44cae Raymondienne \n",
|
1593 |
+
"3 b6b5589a98fdccd208dc752bac853993 Cúp cờ vua thế giới \n",
|
1594 |
+
"4 82396a18fa9812bfec4d3ecb7ae60905 Shkhara \n",
|
1595 |
+
"... ... ... \n",
|
1596 |
+
"20852 508022f540c39fe31511f594748759bc Eros \n",
|
1597 |
+
"20853 93c746695c50932ac45ac498a192a3e5 Lịch sử hành chính Hà Nội \n",
|
1598 |
+
"20854 c477d4b40045ee4251cf9b2a0482cfc4 Nhật ký trong tù \n",
|
1599 |
+
"20855 278ad127825c085a54fa22116c281f92 Google \n",
|
1600 |
+
"20856 09ee53a835ea4ed2234aee8161b16d87 Dãy núi Hoàng Liên Sơn \n",
|
1601 |
+
"\n",
|
1602 |
+
" text \n",
|
1603 |
+
"0 Thủ tướng Trung Quốc là nhân vật lãnh đạo chín... \n",
|
1604 |
+
"1 có 23 quốc gia không có lực lượng quân đội, ba... \n",
|
1605 |
+
"2 Raymondienne (hay Raymonde Dien) sinh ngày 13 ... \n",
|
1606 |
+
"3 Cúp cờ vua thế giới là tên gọi một số giải đấu... \n",
|
1607 |
+
"4 Đỉnh núi nằm ở phần trung tâm của dãy núi Đại ... \n",
|
1608 |
+
"... ... \n",
|
1609 |
+
"20852 Trong thần thoại Hy Lạp , \" Eros \" là vị thần ... \n",
|
1610 |
+
"20853 Vào thời điểm hiện tại ( 2017 ) , về mặt hành ... \n",
|
1611 |
+
"20854 “ Nhật ký trong tù ” là một cuốn sổ tay nhỏ , ... \n",
|
1612 |
+
"20855 Tên miền www.google.com được đăng ký ngày 15 t... \n",
|
1613 |
+
"20856 Dãy núi Hoàng Liên Sơn rộng 30 km, chạy dài 18... \n",
|
1614 |
+
"\n",
|
1615 |
+
"[20857 rows x 3 columns]"
|
1616 |
+
]
|
1617 |
+
},
|
1618 |
+
"execution_count": 16,
|
1619 |
+
"metadata": {},
|
1620 |
+
"output_type": "execute_result"
|
1621 |
+
}
|
1622 |
+
],
|
1623 |
+
"source": [
|
1624 |
+
"train_df"
|
1625 |
+
]
|
1626 |
+
},
|
1627 |
+
{
|
1628 |
+
"cell_type": "code",
|
1629 |
+
"execution_count": 50,
|
1630 |
+
"metadata": {},
|
1631 |
+
"outputs": [
|
1632 |
+
{
|
1633 |
+
"data": {
|
1634 |
+
"text/plain": [
|
1635 |
+
"True"
|
1636 |
+
]
|
1637 |
+
},
|
1638 |
+
"execution_count": 50,
|
1639 |
+
"metadata": {},
|
1640 |
+
"output_type": "execute_result"
|
1641 |
+
}
|
1642 |
+
],
|
1643 |
+
"source": [
|
1644 |
+
"len(train_titles)\n",
|
1645 |
+
"'Bánh gai Tứ Trụ' in list(train_titles - set(df['title'].unique())) "
|
1646 |
+
]
|
1647 |
+
},
|
1648 |
+
{
|
1649 |
+
"cell_type": "markdown",
|
1650 |
+
"metadata": {},
|
1651 |
+
"source": [
|
1652 |
+
"Nếu `title` của `train_df` không nằm trong `df` thì đó là cleaned `title` (nghĩa là chỉ có một kết quả), ngược lại nếu nằm trong `df` thì là dirty (có nhiều ứng viên cho kết quả dựa vào thuật toán ranked bm25). "
|
1653 |
+
]
|
1654 |
+
},
|
1655 |
+
{
|
1656 |
+
"cell_type": "code",
|
1657 |
+
"execution_count": 51,
|
1658 |
+
"metadata": {},
|
1659 |
+
"outputs": [],
|
1660 |
+
"source": [
|
1661 |
+
"def find_dirty_text(title, text):\n",
|
1662 |
+
" text= \" \".join(word_tokenize(strip_context(text)))\n",
|
1663 |
+
" if text[-1] == \".\":\n",
|
1664 |
+
" text = text[:-1].strip()\n",
|
1665 |
+
" tmp = df[df.title == title].reset_index(drop=True)\n",
|
1666 |
+
" if len(tmp) == 0:\n",
|
1667 |
+
"# print(title)\n",
|
1668 |
+
" return None\n",
|
1669 |
+
" for candidate in tmp.cleaned_text:\n",
|
1670 |
+
" if text in candidate:\n",
|
1671 |
+
"# print(\"Found dirty\")\n",
|
1672 |
+
" return candidate\n",
|
1673 |
+
" return text"
|
1674 |
+
]
|
1675 |
+
},
|
1676 |
+
{
|
1677 |
+
"cell_type": "code",
|
1678 |
+
"execution_count": 52,
|
1679 |
+
"metadata": {},
|
1680 |
+
"outputs": [
|
1681 |
+
{
|
1682 |
+
"data": {
|
1683 |
+
"application/vnd.jupyter.widget-view+json": {
|
1684 |
+
"model_id": "cad2c798e15e47f09d4238f0280e35c9",
|
1685 |
+
"version_major": 2,
|
1686 |
+
"version_minor": 0
|
1687 |
+
},
|
1688 |
+
"text/plain": [
|
1689 |
+
"VBox(children=(HBox(children=(IntProgress(value=0, description='0.00%', max=3477), Label(value='0 / 3477'))), …"
|
1690 |
+
]
|
1691 |
+
},
|
1692 |
+
"metadata": {},
|
1693 |
+
"output_type": "display_data"
|
1694 |
+
}
|
1695 |
+
],
|
1696 |
+
"source": [
|
1697 |
+
"train_df[\"dirty_text\"] = train_df.parallel_apply(lambda row: find_dirty_text(row.title, row.text),axis=1)"
|
1698 |
+
]
|
1699 |
+
},
|
1700 |
+
{
|
1701 |
+
"cell_type": "code",
|
1702 |
+
"execution_count": 53,
|
1703 |
+
"metadata": {},
|
1704 |
+
"outputs": [
|
1705 |
+
{
|
1706 |
+
"data": {
|
1707 |
+
"text/html": [
|
1708 |
+
"<div>\n",
|
1709 |
+
"<style scoped>\n",
|
1710 |
+
" .dataframe tbody tr th:only-of-type {\n",
|
1711 |
+
" vertical-align: middle;\n",
|
1712 |
+
" }\n",
|
1713 |
+
"\n",
|
1714 |
+
" .dataframe tbody tr th {\n",
|
1715 |
+
" vertical-align: top;\n",
|
1716 |
+
" }\n",
|
1717 |
+
"\n",
|
1718 |
+
" .dataframe thead th {\n",
|
1719 |
+
" text-align: right;\n",
|
1720 |
+
" }\n",
|
1721 |
+
"</style>\n",
|
1722 |
+
"<table border=\"1\" class=\"dataframe\">\n",
|
1723 |
+
" <thead>\n",
|
1724 |
+
" <tr style=\"text-align: right;\">\n",
|
1725 |
+
" <th></th>\n",
|
1726 |
+
" <th>id</th>\n",
|
1727 |
+
" <th>title</th>\n",
|
1728 |
+
" <th>text</th>\n",
|
1729 |
+
" <th>dirty_text</th>\n",
|
1730 |
+
" </tr>\n",
|
1731 |
+
" </thead>\n",
|
1732 |
+
" <tbody>\n",
|
1733 |
+
" <tr>\n",
|
1734 |
+
" <th>0</th>\n",
|
1735 |
+
" <td>718d41cd997b2b44b0685ac54aa55bd8</td>\n",
|
1736 |
+
" <td>Trung Quốc</td>\n",
|
1737 |
+
" <td>Thủ tướng Trung Quốc là nhân vật lãnh đạo chín...</td>\n",
|
1738 |
+
" <td>Thủ tướng Trung Quốc là nhân vật lãnh đạo chín...</td>\n",
|
1739 |
+
" </tr>\n",
|
1740 |
+
" <tr>\n",
|
1741 |
+
" <th>1</th>\n",
|
1742 |
+
" <td>c926e7b0717202618a10dd907d4b4c39</td>\n",
|
1743 |
+
" <td></td>\n",
|
1744 |
+
" <td>có 23 quốc gia không có lực lượng quân đội, ba...</td>\n",
|
1745 |
+
" <td>None</td>\n",
|
1746 |
+
" </tr>\n",
|
1747 |
+
" <tr>\n",
|
1748 |
+
" <th>2</th>\n",
|
1749 |
+
" <td>d38ef5bf1fb82b410026ed82c8a44cae</td>\n",
|
1750 |
+
" <td>Raymondienne</td>\n",
|
1751 |
+
" <td>Raymondienne (hay Raymonde Dien) sinh ngày 13 ...</td>\n",
|
1752 |
+
" <td>None</td>\n",
|
1753 |
+
" </tr>\n",
|
1754 |
+
" <tr>\n",
|
1755 |
+
" <th>3</th>\n",
|
1756 |
+
" <td>b6b5589a98fdccd208dc752bac853993</td>\n",
|
1757 |
+
" <td>Cúp cờ vua thế giới</td>\n",
|
1758 |
+
" <td>Cúp cờ vua thế giới là tên gọi một số giải đấu...</td>\n",
|
1759 |
+
" <td>Cúp cờ vua thế giới là tên gọi một số giải đấu...</td>\n",
|
1760 |
+
" </tr>\n",
|
1761 |
+
" <tr>\n",
|
1762 |
+
" <th>4</th>\n",
|
1763 |
+
" <td>82396a18fa9812bfec4d3ecb7ae60905</td>\n",
|
1764 |
+
" <td>Shkhara</td>\n",
|
1765 |
+
" <td>Đỉnh núi nằm ở phần trung tâm của dãy núi Đại ...</td>\n",
|
1766 |
+
" <td>Shkhara ( ) là núi cao thứ ba trong dãy núi Ka...</td>\n",
|
1767 |
+
" </tr>\n",
|
1768 |
+
" <tr>\n",
|
1769 |
+
" <th>...</th>\n",
|
1770 |
+
" <td>...</td>\n",
|
1771 |
+
" <td>...</td>\n",
|
1772 |
+
" <td>...</td>\n",
|
1773 |
+
" <td>...</td>\n",
|
1774 |
+
" </tr>\n",
|
1775 |
+
" <tr>\n",
|
1776 |
+
" <th>20852</th>\n",
|
1777 |
+
" <td>508022f540c39fe31511f594748759bc</td>\n",
|
1778 |
+
" <td>Eros</td>\n",
|
1779 |
+
" <td>Trong thần thoại Hy Lạp , \" Eros \" là vị thần ...</td>\n",
|
1780 |
+
" <td>Eros Trong thần thoại Hy Lạp , \" Eros \" là vị ...</td>\n",
|
1781 |
+
" </tr>\n",
|
1782 |
+
" <tr>\n",
|
1783 |
+
" <th>20853</th>\n",
|
1784 |
+
" <td>93c746695c50932ac45ac498a192a3e5</td>\n",
|
1785 |
+
" <td>Lịch sử hành chính Hà Nội</td>\n",
|
1786 |
+
" <td>Vào thời điểm hiện tại ( 2017 ) , về mặt hành ...</td>\n",
|
1787 |
+
" <td>Vào thời điểm hiện tại ( 2017 ) , về mặt hành ...</td>\n",
|
1788 |
+
" </tr>\n",
|
1789 |
+
" <tr>\n",
|
1790 |
+
" <th>20854</th>\n",
|
1791 |
+
" <td>c477d4b40045ee4251cf9b2a0482cfc4</td>\n",
|
1792 |
+
" <td>Nhật ký trong tù</td>\n",
|
1793 |
+
" <td>“ Nhật ký trong tù ” là một cuốn sổ tay nhỏ , ...</td>\n",
|
1794 |
+
" <td>“ Nhật ký trong tù ” là một cuốn sổ tay nhỏ , ...</td>\n",
|
1795 |
+
" </tr>\n",
|
1796 |
+
" <tr>\n",
|
1797 |
+
" <th>20855</th>\n",
|
1798 |
+
" <td>278ad127825c085a54fa22116c281f92</td>\n",
|
1799 |
+
" <td>Google</td>\n",
|
1800 |
+
" <td>Tên miền www.google.com được đăng ký ngày 15 t...</td>\n",
|
1801 |
+
" <td>Tên miền www.google.com được đăng ký ngày 15 t...</td>\n",
|
1802 |
+
" </tr>\n",
|
1803 |
+
" <tr>\n",
|
1804 |
+
" <th>20856</th>\n",
|
1805 |
+
" <td>09ee53a835ea4ed2234aee8161b16d87</td>\n",
|
1806 |
+
" <td>Dãy núi Hoàng Liên Sơn</td>\n",
|
1807 |
+
" <td>Dãy núi Hoàng Liên Sơn rộng 30 km, chạy dài 18...</td>\n",
|
1808 |
+
" <td>Dãy núi Hoàng Liên Sơn rộng 30 km , chạy dài 1...</td>\n",
|
1809 |
+
" </tr>\n",
|
1810 |
+
" </tbody>\n",
|
1811 |
+
"</table>\n",
|
1812 |
+
"<p>20857 rows × 4 columns</p>\n",
|
1813 |
+
"</div>"
|
1814 |
+
],
|
1815 |
+
"text/plain": [
|
1816 |
+
" id title \\\n",
|
1817 |
+
"0 718d41cd997b2b44b0685ac54aa55bd8 Trung Quốc \n",
|
1818 |
+
"1 c926e7b0717202618a10dd907d4b4c39 \n",
|
1819 |
+
"2 d38ef5bf1fb82b410026ed82c8a44cae Raymondienne \n",
|
1820 |
+
"3 b6b5589a98fdccd208dc752bac853993 Cúp cờ vua thế giới \n",
|
1821 |
+
"4 82396a18fa9812bfec4d3ecb7ae60905 Shkhara \n",
|
1822 |
+
"... ... ... \n",
|
1823 |
+
"20852 508022f540c39fe31511f594748759bc Eros \n",
|
1824 |
+
"20853 93c746695c50932ac45ac498a192a3e5 Lịch sử hành chính Hà Nội \n",
|
1825 |
+
"20854 c477d4b40045ee4251cf9b2a0482cfc4 Nhật ký trong tù \n",
|
1826 |
+
"20855 278ad127825c085a54fa22116c281f92 Google \n",
|
1827 |
+
"20856 09ee53a835ea4ed2234aee8161b16d87 Dãy núi Hoàng Liên Sơn \n",
|
1828 |
+
"\n",
|
1829 |
+
" text \\\n",
|
1830 |
+
"0 Thủ tướng Trung Quốc là nhân vật lãnh đạo chín... \n",
|
1831 |
+
"1 có 23 quốc gia không có lực lượng quân đội, ba... \n",
|
1832 |
+
"2 Raymondienne (hay Raymonde Dien) sinh ngày 13 ... \n",
|
1833 |
+
"3 Cúp cờ vua thế giới là tên gọi một số giải đấu... \n",
|
1834 |
+
"4 Đỉnh núi nằm ở phần trung tâm của dãy núi Đại ... \n",
|
1835 |
+
"... ... \n",
|
1836 |
+
"20852 Trong thần thoại Hy Lạp , \" Eros \" là vị thần ... \n",
|
1837 |
+
"20853 Vào thời điểm hiện tại ( 2017 ) , về mặt hành ... \n",
|
1838 |
+
"20854 “ Nhật ký trong tù ” là một cuốn sổ tay nhỏ , ... \n",
|
1839 |
+
"20855 Tên miền www.google.com được đăng ký ngày 15 t... \n",
|
1840 |
+
"20856 Dãy núi Hoàng Liên Sơn rộng 30 km, chạy dài 18... \n",
|
1841 |
+
"\n",
|
1842 |
+
" dirty_text \n",
|
1843 |
+
"0 Thủ tướng Trung Quốc là nhân vật lãnh đạo chín... \n",
|
1844 |
+
"1 None \n",
|
1845 |
+
"2 None \n",
|
1846 |
+
"3 Cúp cờ vua thế giới là tên gọi một số giải đấu... \n",
|
1847 |
+
"4 Shkhara ( ) là núi cao thứ ba trong dãy núi Ka... \n",
|
1848 |
+
"... ... \n",
|
1849 |
+
"20852 Eros Trong thần thoại Hy Lạp , \" Eros \" là vị ... \n",
|
1850 |
+
"20853 Vào thời điểm hiện tại ( 2017 ) , về mặt hành ... \n",
|
1851 |
+
"20854 “ Nhật ký trong tù ” là một cuốn sổ tay nhỏ , ... \n",
|
1852 |
+
"20855 Tên miền www.google.com được đăng ký ngày 15 t... \n",
|
1853 |
+
"20856 Dãy núi Hoàng Liên Sơn rộng 30 km , chạy dài 1... \n",
|
1854 |
+
"\n",
|
1855 |
+
"[20857 rows x 4 columns]"
|
1856 |
+
]
|
1857 |
+
},
|
1858 |
+
"execution_count": 53,
|
1859 |
+
"metadata": {},
|
1860 |
+
"output_type": "execute_result"
|
1861 |
+
}
|
1862 |
+
],
|
1863 |
+
"source": [
|
1864 |
+
"train_df"
|
1865 |
+
]
|
1866 |
+
},
|
1867 |
+
{
|
1868 |
+
"cell_type": "code",
|
1869 |
+
"execution_count": 54,
|
1870 |
+
"metadata": {},
|
1871 |
+
"outputs": [
|
1872 |
+
{
|
1873 |
+
"data": {
|
1874 |
+
"text/html": [
|
1875 |
+
"<div>\n",
|
1876 |
+
"<style scoped>\n",
|
1877 |
+
" .dataframe tbody tr th:only-of-type {\n",
|
1878 |
+
" vertical-align: middle;\n",
|
1879 |
+
" }\n",
|
1880 |
+
"\n",
|
1881 |
+
" .dataframe tbody tr th {\n",
|
1882 |
+
" vertical-align: top;\n",
|
1883 |
+
" }\n",
|
1884 |
+
"\n",
|
1885 |
+
" .dataframe thead th {\n",
|
1886 |
+
" text-align: right;\n",
|
1887 |
+
" }\n",
|
1888 |
+
"</style>\n",
|
1889 |
+
"<table border=\"1\" class=\"dataframe\">\n",
|
1890 |
+
" <thead>\n",
|
1891 |
+
" <tr style=\"text-align: right;\">\n",
|
1892 |
+
" <th></th>\n",
|
1893 |
+
" <th>id</th>\n",
|
1894 |
+
" <th>title</th>\n",
|
1895 |
+
" <th>text</th>\n",
|
1896 |
+
" <th>dirty_text</th>\n",
|
1897 |
+
" </tr>\n",
|
1898 |
+
" </thead>\n",
|
1899 |
+
" <tbody>\n",
|
1900 |
+
" <tr>\n",
|
1901 |
+
" <th>1</th>\n",
|
1902 |
+
" <td>c926e7b0717202618a10dd907d4b4c39</td>\n",
|
1903 |
+
" <td></td>\n",
|
1904 |
+
" <td>có 23 quốc gia không có lực lượng quân đội, ba...</td>\n",
|
1905 |
+
" <td>None</td>\n",
|
1906 |
+
" </tr>\n",
|
1907 |
+
" <tr>\n",
|
1908 |
+
" <th>2</th>\n",
|
1909 |
+
" <td>d38ef5bf1fb82b410026ed82c8a44cae</td>\n",
|
1910 |
+
" <td>Raymondienne</td>\n",
|
1911 |
+
" <td>Raymondienne (hay Raymonde Dien) sinh ngày 13 ...</td>\n",
|
1912 |
+
" <td>None</td>\n",
|
1913 |
+
" </tr>\n",
|
1914 |
+
" <tr>\n",
|
1915 |
+
" <th>14</th>\n",
|
1916 |
+
" <td>361a30769c1a5dca2a7b8f5c7f601982</td>\n",
|
1917 |
+
" <td>Bánh gai Tứ Trụ</td>\n",
|
1918 |
+
" <td>Làng Mía thuộc hữu ngạn sông Chu, cách thị trấ...</td>\n",
|
1919 |
+
" <td>None</td>\n",
|
1920 |
+
" </tr>\n",
|
1921 |
+
" <tr>\n",
|
1922 |
+
" <th>18</th>\n",
|
1923 |
+
" <td>5d7d3b0d5cd7b2917a2081c3b4d7c8a8</td>\n",
|
1924 |
+
" <td>Nhà nước Hồi giáo ( chính thể )</td>\n",
|
1925 |
+
" <td>Khái niệm về nhà nước Hồi giáo hiện đại đã đượ...</td>\n",
|
1926 |
+
" <td>None</td>\n",
|
1927 |
+
" </tr>\n",
|
1928 |
+
" <tr>\n",
|
1929 |
+
" <th>20</th>\n",
|
1930 |
+
" <td>d7000d411d3f04dee7fa327ef11e3db0</td>\n",
|
1931 |
+
" <td>Quan hệ Israel – Liban</td>\n",
|
1932 |
+
" <td>Thủ tướng Liban Fouad Siniora cho biết vào thá...</td>\n",
|
1933 |
+
" <td>None</td>\n",
|
1934 |
+
" </tr>\n",
|
1935 |
+
" <tr>\n",
|
1936 |
+
" <th>...</th>\n",
|
1937 |
+
" <td>...</td>\n",
|
1938 |
+
" <td>...</td>\n",
|
1939 |
+
" <td>...</td>\n",
|
1940 |
+
" <td>...</td>\n",
|
1941 |
+
" </tr>\n",
|
1942 |
+
" <tr>\n",
|
1943 |
+
" <th>20804</th>\n",
|
1944 |
+
" <td>cb4d3b162a56b52a4927ab29b739c7a2</td>\n",
|
1945 |
+
" <td>Thủy điện An Khê - Kanak</td>\n",
|
1946 |
+
" <td>Nhà máy được khởi công xây dựng vào ngày 14 th...</td>\n",
|
1947 |
+
" <td>None</td>\n",
|
1948 |
+
" </tr>\n",
|
1949 |
+
" <tr>\n",
|
1950 |
+
" <th>20834</th>\n",
|
1951 |
+
" <td>d701dfcba59420604c66e803c9556754</td>\n",
|
1952 |
+
" <td>Sao Hoả</td>\n",
|
1953 |
+
" <td>Sao Hoả còn gọi là : Hoả Tinh , ( Tiếng Anh : ...</td>\n",
|
1954 |
+
" <td>None</td>\n",
|
1955 |
+
" </tr>\n",
|
1956 |
+
" <tr>\n",
|
1957 |
+
" <th>20836</th>\n",
|
1958 |
+
" <td>5769cee0487a9674306d271854244b39</td>\n",
|
1959 |
+
" <td></td>\n",
|
1960 |
+
" <td>Máy quay phim: Phát minh kỳ diệu của anh em Lu...</td>\n",
|
1961 |
+
" <td>None</td>\n",
|
1962 |
+
" </tr>\n",
|
1963 |
+
" <tr>\n",
|
1964 |
+
" <th>20843</th>\n",
|
1965 |
+
" <td>5f420b6d68436b684f33dcded61d5a3c</td>\n",
|
1966 |
+
" <td>Egil Kapstad</td>\n",
|
1967 |
+
" <td>Ông sinh ra tại Oslo, thủ đô của Na Uy và thàn...</td>\n",
|
1968 |
+
" <td>None</td>\n",
|
1969 |
+
" </tr>\n",
|
1970 |
+
" <tr>\n",
|
1971 |
+
" <th>20846</th>\n",
|
1972 |
+
" <td>323218bcf129df929716884a1a89e2e3</td>\n",
|
1973 |
+
" <td></td>\n",
|
1974 |
+
" <td>Vật lý học (tiếng Anh: Physics, từ tiếng Hy Lạ...</td>\n",
|
1975 |
+
" <td>None</td>\n",
|
1976 |
+
" </tr>\n",
|
1977 |
+
" </tbody>\n",
|
1978 |
+
"</table>\n",
|
1979 |
+
"<p>3498 rows × 4 columns</p>\n",
|
1980 |
+
"</div>"
|
1981 |
+
],
|
1982 |
+
"text/plain": [
|
1983 |
+
" id title \\\n",
|
1984 |
+
"1 c926e7b0717202618a10dd907d4b4c39 \n",
|
1985 |
+
"2 d38ef5bf1fb82b410026ed82c8a44cae Raymondienne \n",
|
1986 |
+
"14 361a30769c1a5dca2a7b8f5c7f601982 Bánh gai Tứ Trụ \n",
|
1987 |
+
"18 5d7d3b0d5cd7b2917a2081c3b4d7c8a8 Nhà nước Hồi giáo ( chính thể ) \n",
|
1988 |
+
"20 d7000d411d3f04dee7fa327ef11e3db0 Quan hệ Israel – Liban \n",
|
1989 |
+
"... ... ... \n",
|
1990 |
+
"20804 cb4d3b162a56b52a4927ab29b739c7a2 Thủy điện An Khê - Kanak \n",
|
1991 |
+
"20834 d701dfcba59420604c66e803c9556754 Sao Hoả \n",
|
1992 |
+
"20836 5769cee0487a9674306d271854244b39 \n",
|
1993 |
+
"20843 5f420b6d68436b684f33dcded61d5a3c Egil Kapstad \n",
|
1994 |
+
"20846 323218bcf129df929716884a1a89e2e3 \n",
|
1995 |
+
"\n",
|
1996 |
+
" text dirty_text \n",
|
1997 |
+
"1 có 23 quốc gia không có lực lượng quân đội, ba... None \n",
|
1998 |
+
"2 Raymondienne (hay Raymonde Dien) sinh ngày 13 ... None \n",
|
1999 |
+
"14 Làng Mía thuộc hữu ngạn sông Chu, cách thị trấ... None \n",
|
2000 |
+
"18 Khái niệm về nhà nước Hồi giáo hiện đại đã đượ... None \n",
|
2001 |
+
"20 Thủ tướng Liban Fouad Siniora cho biết vào thá... None \n",
|
2002 |
+
"... ... ... \n",
|
2003 |
+
"20804 Nhà máy được khởi công xây dựng vào ngày 14 th... None \n",
|
2004 |
+
"20834 Sao Hoả còn gọi là : Hoả Tinh , ( Tiếng Anh : ... None \n",
|
2005 |
+
"20836 Máy quay phim: Phát minh kỳ diệu của anh em Lu... None \n",
|
2006 |
+
"20843 Ông sinh ra tại Oslo, thủ đô của Na Uy và thàn... None \n",
|
2007 |
+
"20846 Vật lý học (tiếng Anh: Physics, từ tiếng Hy Lạ... None \n",
|
2008 |
+
"\n",
|
2009 |
+
"[3498 rows x 4 columns]"
|
2010 |
+
]
|
2011 |
+
},
|
2012 |
+
"execution_count": 54,
|
2013 |
+
"metadata": {},
|
2014 |
+
"output_type": "execute_result"
|
2015 |
+
}
|
2016 |
+
],
|
2017 |
+
"source": [
|
2018 |
+
"train_df[train_df.dirty_text.isna()]"
|
2019 |
+
]
|
2020 |
+
},
|
2021 |
+
{
|
2022 |
+
"cell_type": "code",
|
2023 |
+
"execution_count": 55,
|
2024 |
+
"metadata": {},
|
2025 |
+
"outputs": [],
|
2026 |
+
"source": [
|
2027 |
+
"dirty_text_dict = dict([x,y] for x,y in zip(train_df.id, train_df.dirty_text))"
|
2028 |
+
]
|
2029 |
+
},
|
2030 |
+
{
|
2031 |
+
"cell_type": "code",
|
2032 |
+
"execution_count": 56,
|
2033 |
+
"metadata": {},
|
2034 |
+
"outputs": [],
|
2035 |
+
"source": [
|
2036 |
+
"for x in train['data']:\n",
|
2037 |
+
" x['dirty_text'] = dirty_text_dict.get(x['id'],x['text'])"
|
2038 |
+
]
|
2039 |
+
},
|
2040 |
+
{
|
2041 |
+
"cell_type": "code",
|
2042 |
+
"execution_count": 57,
|
2043 |
+
"metadata": {},
|
2044 |
+
"outputs": [],
|
2045 |
+
"source": [
|
2046 |
+
"json.dump(train,open(\"../data/processed/zac2022_train_merged_final.json\",\"wt\"))"
|
2047 |
+
]
|
2048 |
+
}
|
2049 |
+
],
|
2050 |
+
"metadata": {
|
2051 |
+
"kernelspec": {
|
2052 |
+
"display_name": "Python 3 (ipykernel)",
|
2053 |
+
"language": "python",
|
2054 |
+
"name": "python3"
|
2055 |
+
},
|
2056 |
+
"language_info": {
|
2057 |
+
"codemirror_mode": {
|
2058 |
+
"name": "ipython",
|
2059 |
+
"version": 3
|
2060 |
+
},
|
2061 |
+
"file_extension": ".py",
|
2062 |
+
"mimetype": "text/x-python",
|
2063 |
+
"name": "python",
|
2064 |
+
"nbconvert_exporter": "python",
|
2065 |
+
"pygments_lexer": "ipython3",
|
2066 |
+
"version": "3.8.10"
|
2067 |
+
}
|
2068 |
+
},
|
2069 |
+
"nbformat": 4,
|
2070 |
+
"nbformat_minor": 2
|
2071 |
+
}
|
notebooks/0.2-create-stage1-ranking.ipynb
ADDED
The diff for this file is too large to render.
See raw diff
|
|
notebooks/0.3-create-stage2-ranking.ipynb
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"cells":[{"attachments":{},"cell_type":"markdown","id":"770bfcdb","metadata":{},"source":["### Kaggle link: https://www.kaggle.com/code/noobhocai/0-3-create-stage2-ranking"]},{"cell_type":"code","execution_count":2,"id":"646a64db","metadata":{"execution":{"iopub.execute_input":"2023-06-19T04:45:51.815046Z","iopub.status.busy":"2023-06-19T04:45:51.814713Z","iopub.status.idle":"2023-06-19T04:47:17.791641Z","shell.execute_reply":"2023-06-19T04:47:17.790706Z","shell.execute_reply.started":"2023-06-19T04:45:51.815020Z"},"trusted":true},"outputs":[{"name":"stdout","output_type":"stream","text":["Collecting pyspark\n"," Downloading pyspark-3.4.0.tar.gz (310.8 MB)\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m310.8/310.8 MB\u001b[0m \u001b[31m4.5 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m00:01\u001b[0m00:01\u001b[0m\n","\u001b[?25h Preparing metadata (setup.py) ... \u001b[?25ldone\n","\u001b[?25hRequirement already satisfied: py4j==0.10.9.7 in /opt/conda/lib/python3.10/site-packages (from pyspark) (0.10.9.7)\n","Building wheels for collected packages: pyspark\n"," Building wheel for pyspark (setup.py) ... \u001b[?25ldone\n","\u001b[?25h Created wheel for pyspark: filename=pyspark-3.4.0-py2.py3-none-any.whl size=311317146 sha256=932384efffaa19a196f9bb66e53de64eb278df10f2ddf3186116516b1fff67b5\n"," Stored in directory: /root/.cache/pip/wheels/7b/1b/4b/3363a1d04368e7ff0d408e57ff57966fcdf00583774e761327\n","Successfully built pyspark\n","Installing collected packages: pyspark\n","Successfully installed pyspark-3.4.0\n","\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n","\u001b[0mRequirement already satisfied: pyarrow in /opt/conda/lib/python3.10/site-packages (9.0.0)\n","Requirement already satisfied: numpy>=1.16.6 in /opt/conda/lib/python3.10/site-packages (from pyarrow) (1.23.5)\n","\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n","\u001b[0mRequirement already satisfied: nltk in /opt/conda/lib/python3.10/site-packages (3.2.4)\n","Requirement already satisfied: six in /opt/conda/lib/python3.10/site-packages (from nltk) (1.16.0)\n","\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n","\u001b[0mCollecting tdqm\n"," Downloading tdqm-0.0.1.tar.gz (1.4 kB)\n"," Preparing metadata (setup.py) ... \u001b[?25ldone\n","\u001b[?25hRequirement already satisfied: tqdm in /opt/conda/lib/python3.10/site-packages (from tdqm) (4.64.1)\n","Building wheels for collected packages: tdqm\n"," Building wheel for tdqm (setup.py) ... \u001b[?25ldone\n","\u001b[?25h Created wheel for tdqm: filename=tdqm-0.0.1-py3-none-any.whl size=1322 sha256=98dae54af0bf0a85639c88412f77b6a49d485bbc930a83a31edfb2dbc709a9ff\n"," Stored in directory: /root/.cache/pip/wheels/37/31/b8/7b711038035720ba0df14376af06e5e76b9bd61759c861ad92\n","Successfully built tdqm\n","Installing collected packages: tdqm\n","Successfully installed tdqm-0.0.1\n","\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n","\u001b[0mCollecting rank_bm25\n"," Downloading rank_bm25-0.2.2-py3-none-any.whl (8.6 kB)\n","Requirement already satisfied: numpy in /opt/conda/lib/python3.10/site-packages (from rank_bm25) (1.23.5)\n","Installing collected packages: rank_bm25\n","Successfully installed rank_bm25-0.2.2\n","\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n","\u001b[0mCollecting pyvi\n"," Downloading pyvi-0.1.1-py2.py3-none-any.whl (8.5 MB)\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m8.5/8.5 MB\u001b[0m \u001b[31m57.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m00:01\u001b[0m00:01\u001b[0m\n","\u001b[?25hRequirement already satisfied: scikit-learn in /opt/conda/lib/python3.10/site-packages (from pyvi) (1.2.2)\n","Collecting sklearn-crfsuite (from pyvi)\n"," Downloading sklearn_crfsuite-0.3.6-py2.py3-none-any.whl (12 kB)\n","Requirement already satisfied: numpy>=1.17.3 in /opt/conda/lib/python3.10/site-packages (from scikit-learn->pyvi) (1.23.5)\n","Requirement already satisfied: scipy>=1.3.2 in /opt/conda/lib/python3.10/site-packages (from scikit-learn->pyvi) (1.10.1)\n","Requirement already satisfied: joblib>=1.1.1 in /opt/conda/lib/python3.10/site-packages (from scikit-learn->pyvi) (1.2.0)\n","Requirement already satisfied: threadpoolctl>=2.0.0 in /opt/conda/lib/python3.10/site-packages (from scikit-learn->pyvi) (3.1.0)\n","Collecting python-crfsuite>=0.8.3 (from sklearn-crfsuite->pyvi)\n"," Downloading python_crfsuite-0.9.9-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (993 kB)\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m993.5/993.5 kB\u001b[0m \u001b[31m55.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[?25hRequirement already satisfied: six in /opt/conda/lib/python3.10/site-packages (from sklearn-crfsuite->pyvi) (1.16.0)\n","Requirement already satisfied: tabulate in /opt/conda/lib/python3.10/site-packages (from sklearn-crfsuite->pyvi) (0.9.0)\n","Requirement already satisfied: tqdm>=2.0 in /opt/conda/lib/python3.10/site-packages (from sklearn-crfsuite->pyvi) (4.64.1)\n","Installing collected packages: python-crfsuite, sklearn-crfsuite, pyvi\n","Successfully installed python-crfsuite-0.9.9 pyvi-0.1.1 sklearn-crfsuite-0.3.6\n","\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n","\u001b[0m"]}],"source":["!pip install pyspark\n","!pip install pyarrow\n","!pip install nltk\n","!pip install tdqm\n","!pip install rank_bm25\n","# !pip install pandarallel\n","!pip install pyvi"]},{"cell_type":"code","execution_count":3,"metadata":{"execution":{"iopub.execute_input":"2023-06-19T04:47:17.794768Z","iopub.status.busy":"2023-06-19T04:47:17.794437Z","iopub.status.idle":"2023-06-19T04:47:17.869550Z","shell.execute_reply":"2023-06-19T04:47:17.868392Z","shell.execute_reply.started":"2023-06-19T04:47:17.794729Z"},"trusted":true},"outputs":[{"name":"stdout","output_type":"stream","text":["3.4.0\n"]}],"source":["import pyspark\n","print(pyspark.__version__)"]},{"cell_type":"code","execution_count":4,"metadata":{"execution":{"iopub.execute_input":"2023-06-19T04:47:17.873676Z","iopub.status.busy":"2023-06-19T04:47:17.873324Z","iopub.status.idle":"2023-06-19T04:47:25.790613Z","shell.execute_reply":"2023-06-19T04:47:25.789712Z","shell.execute_reply.started":"2023-06-19T04:47:17.873647Z"},"trusted":true},"outputs":[{"name":"stderr","output_type":"stream","text":["/opt/conda/lib/python3.10/site-packages/pyspark/pandas/__init__.py:50: UserWarning: 'PYARROW_IGNORE_TIMEZONE' environment variable was not set. It is required to set this environment variable to '1' in both driver and executor sides if you use pyarrow>=2.0.0. pandas-on-Spark will set it for you but it does not work if there is a Spark context already launched.\n"," warnings.warn(\n"]},{"name":"stdout","output_type":"stream","text":["[nltk_data] Downloading package punkt to /usr/share/nltk_data...\n","[nltk_data] Package punkt is already up-to-date!\n"]},{"name":"stderr","output_type":"stream","text":["Setting default log level to \"WARN\".\n","To adjust logging level use sc.setLogLevel(newLevel). For SparkR, use setLogLevel(newLevel).\n","23/06/19 04:47:23 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable\n"]},{"data":{"text/html":["\n"," <div>\n"," <p><b>SparkSession - in-memory</b></p>\n"," \n"," <div>\n"," <p><b>SparkContext</b></p>\n","\n"," <p><a href=\"http://e65557ad95ad:4040\">Spark UI</a></p>\n","\n"," <dl>\n"," <dt>Version</dt>\n"," <dd><code>v3.4.0</code></dd>\n"," <dt>Master</dt>\n"," <dd><code>local[*]</code></dd>\n"," <dt>AppName</dt>\n"," <dd><code>Pyspark</code></dd>\n"," </dl>\n"," </div>\n"," \n"," </div>\n"," "],"text/plain":["<pyspark.sql.session.SparkSession at 0x7e77e1486620>"]},"execution_count":4,"metadata":{},"output_type":"execute_result"}],"source":["import json\n","import numpy as np\n","import pandas as pd\n","from tqdm.auto import tqdm\n","tqdm.pandas()\n","import pyspark.pandas as ps\n","import re\n","import nltk\n","nltk.download('punkt')\n","from nltk import word_tokenize as lib_tokenizer \n","from pyvi.ViTokenizer import tokenize\n","import string\n","from rank_bm25 import BM25Okapi\n","# from pandarallel import pandarallel\n","\n","import os\n","os.environ[\"PYARROW_IGNORE_TIMEZONE\"] = \"1\"\n","import pyspark as pyspark\n","from pyspark.sql import SparkSession\n","from pyspark.sql.functions import udf, col, lit, lower\n","from pyspark.sql.types import ArrayType, StringType, FloatType, IntegerType\n","MAX_MEMORY = '15G'\n","# Initialize a spark session.\n","# spark.stop()\n","conf = pyspark.SparkConf().setMaster(\"local[*]\") \\\n"," .set('spark.executor.heartbeatInterval', 10000) \\\n"," .set('spark.network.timeout', 10000) \\\n"," .set(\"spark.core.connection.ack.wait.timeout\", \"3600\") \\\n"," .set(\"spark.executor.memory\", MAX_MEMORY) \\\n"," .set(\"spark.driver.memory\", MAX_MEMORY) \\\n"," .set(\"spark.driver.maxResultSize\", \"4g\") \\\n"," .set(\"spark.sql.execution.arrow.pyspark.enabled\", \"true\")\n","spark = SparkSession.builder.appName(\"Pyspark\").config(conf=conf).getOrCreate()\n","spark"]},{"cell_type":"code","execution_count":5,"metadata":{"execution":{"iopub.execute_input":"2023-06-19T04:47:25.792027Z","iopub.status.busy":"2023-06-19T04:47:25.791731Z","iopub.status.idle":"2023-06-19T04:47:25.799813Z","shell.execute_reply":"2023-06-19T04:47:25.796610Z","shell.execute_reply.started":"2023-06-19T04:47:25.791998Z"},"trusted":true},"outputs":[],"source":["# pandarallel.initialize(progress_bar=True, use_memory_fs=False)"]},{"cell_type":"code","execution_count":6,"metadata":{"execution":{"iopub.execute_input":"2023-06-19T04:47:25.803740Z","iopub.status.busy":"2023-06-19T04:47:25.802887Z","iopub.status.idle":"2023-06-19T04:47:26.433056Z","shell.execute_reply":"2023-06-19T04:47:26.431337Z","shell.execute_reply.started":"2023-06-19T04:47:25.803711Z"},"trusted":true},"outputs":[],"source":["data = json.load(open(\"/kaggle/input/e2eqa-wiki-zalo-ai/e2eqa-trainpublic_test-v1/e2eqa-train+public_test-v1/zac2022_train_merged_final.json\"))\n","data = [x for x in data['data'] if x[\"category\"] == \"FULL_ANNOTATION\" and \"wiki/\" in x[\"answer\"]]"]},{"cell_type":"code","execution_count":7,"metadata":{"execution":{"iopub.execute_input":"2023-06-19T04:47:26.435414Z","iopub.status.busy":"2023-06-19T04:47:26.435040Z","iopub.status.idle":"2023-06-19T04:47:39.021537Z","shell.execute_reply":"2023-06-19T04:47:39.020732Z","shell.execute_reply.started":"2023-06-19T04:47:26.435385Z"},"trusted":true},"outputs":[{"name":"stderr","output_type":"stream","text":[" \r"]},{"data":{"text/plain":["pyspark.sql.dataframe.DataFrame"]},"execution_count":7,"metadata":{},"output_type":"execute_result"}],"source":["df_wiki = spark.read.json(path = \"/kaggle/input/e2eqa-wiki-zalo-ai/wikipedia_20220620_cleaned/wikipedia_20220620_cleaned.jsonl\")\n","# df_wiki = df_wiki.cache().pandas_api()\n","type(df_wiki)"]},{"cell_type":"code","execution_count":8,"metadata":{"execution":{"iopub.execute_input":"2023-06-19T04:47:39.022723Z","iopub.status.busy":"2023-06-19T04:47:39.022452Z","iopub.status.idle":"2023-06-19T04:47:39.454049Z","shell.execute_reply":"2023-06-19T04:47:39.453277Z","shell.execute_reply.started":"2023-06-19T04:47:39.022697Z"},"trusted":true},"outputs":[{"name":"stdout","output_type":"stream","text":["+---+--------+--------------------+--------------------+----------------+--------------------+\n","| id| revid| text| timestamp| title| url|\n","+---+--------+--------------------+--------------------+----------------+--------------------+\n","| 2|68591979|Trang Chính\\n\\n<t...|2022-05-12T12:46:53Z| Trang Chính|https://vi.wikipe...|\n","| 4|67988747|Internet Society\\...|2022-01-20T07:59:10Z|Internet Society|https://vi.wikipe...|\n","| 13|68660631|Tiếng Việt\\n\\nTiế...|2022-05-29T03:42:42Z| Tiếng Việt|https://vi.wikipe...|\n","| 24|68482118|Ohio\\n\\nOhio (viế...|2022-04-17T08:15:22Z| Ohio|https://vi.wikipe...|\n","| 26|68738039|California\\n\\nCal...|2022-06-16T15:27:07Z| California|https://vi.wikipe...|\n","+---+--------+--------------------+--------------------+----------------+--------------------+\n","only showing top 5 rows\n","\n"]}],"source":["df_wiki.show(5)"]},{"cell_type":"code","execution_count":9,"metadata":{"execution":{"iopub.execute_input":"2023-06-19T04:47:39.455216Z","iopub.status.busy":"2023-06-19T04:47:39.454950Z","iopub.status.idle":"2023-06-19T04:47:40.096642Z","shell.execute_reply":"2023-06-19T04:47:40.095084Z","shell.execute_reply.started":"2023-06-19T04:47:39.455192Z"},"trusted":true},"outputs":[{"data":{"text/plain":["[Table(name='df_wiki_temp', catalog=None, namespace=[], description=None, tableType='TEMPORARY', isTemporary=True)]"]},"execution_count":9,"metadata":{},"output_type":"execute_result"}],"source":["df_wiki.createOrReplaceTempView('df_wiki_temp')\n","spark.catalog.listTables()"]},{"cell_type":"code","execution_count":10,"metadata":{"execution":{"iopub.execute_input":"2023-06-19T04:47:40.097915Z","iopub.status.busy":"2023-06-19T04:47:40.097624Z","iopub.status.idle":"2023-06-19T04:47:40.130812Z","shell.execute_reply":"2023-06-19T04:47:40.129860Z","shell.execute_reply.started":"2023-06-19T04:47:40.097890Z"},"trusted":true},"outputs":[],"source":["def get_topk(query, topk=100):\n"," tokenized_query = query.split()\n"," tfidf_query = dictionary.doc2bow(tokenized_query)\n"," scores = bm25_index[tfidf_query]\n"," top_n = np.argsort(scores)[::-1][:topk]\n"," titles = [df_wiki.filter(col(\"id\") == i).select(\"title\").collect()[0][0] for i in top_n]\n"," texts = [df_wiki.filter(col(\"id\") == i).select(\"text\").collect()[0][0] for i in top_n]\n"," scores = [scores[i] for i in top_n]\n"," result = \"\\n\".join([f\"{title}\\t{text}\\t{score}\" for title, text, score in zip(titles, texts, scores)])\n"," return result\n","\n","get_topk_udf = udf(get_topk, StringType())\n","\n","dict_map = {}\n","\n","def word_tokenize(text): \n"," global dict_map\n"," words = text.split() \n"," words_norm = [] \n"," for w in words: \n"," if w not in dict_map: \n"," dict_map[w] = ' '.join(lib_tokenizer(w)).replace('``', '\"').replace(\"''\", '\"') \n"," words_norm.append(dict_map[w]) \n"," return words_norm \n","\n","word_tokenize_udf = udf(word_tokenize, ArrayType(StringType()))\n","\n","def strip_answer_string(text):\n"," text = text.strip() \n"," while text[-1] in '.,/><;:\\'\"[]{}+=-_)(*&^!~`': \n"," if text[0] != '(' and text[-1] == ')' and '(' in text: \n"," break \n"," if text[-1] == '\"' and text[0] != '\"' and text.count('\"') > 1: \n"," break \n"," text = text[:-1].strip() \n"," while text[0] in '.,/><;:\\'\"[]{}+=-_)(*&^!~`': \n"," if text[0] == '\"' and text[-1] != '\"' and text.count('\"') > 1: \n"," break \n"," text = text[1:].strip() \n"," text = text.strip() \n"," return text \n","\n","strip_answer_string_udf = udf(strip_answer_string, StringType())\n","\n","def strip_context(text):\n"," text = text.replace('\\n', ' ') # thay kí tự kết thúc bằng khoảng trắng\n"," text = re.sub(r'\\s+', ' ', text) # thay khoảng trắng lớn hơn 1 kí tự thành khoảng trắng 1 kí tự\n"," text = text.strip() # xoá khoảng trắng ở đầu và cuối \n"," return text \n","\n","strip_context_udf = udf(strip_context, StringType())\n","\n","def post_process(x):\n"," x = x.lower()\n"," x = \" \".join(word_tokenize(strip_context(x))).strip()\n"," x = x.replace(\"\\n\",\" \")\n"," x = \"\".join([i for i in x if i not in string.punctuation])\n"," x = \" \".join(x.split()[:128])\n"," return x \n","\n","post_process_udf = udf(post_process, StringType())"]},{"cell_type":"code","execution_count":11,"metadata":{"execution":{"iopub.execute_input":"2023-06-19T04:47:40.137361Z","iopub.status.busy":"2023-06-19T04:47:40.134954Z","iopub.status.idle":"2023-06-19T04:47:42.638078Z","shell.execute_reply":"2023-06-19T04:47:42.637255Z","shell.execute_reply.started":"2023-06-19T04:47:40.137321Z"},"trusted":true},"outputs":[{"name":"stderr","output_type":"stream","text":["[Stage 4:> (0 + 1) / 1]\r"]},{"name":"stdout","output_type":"stream","text":["+---+--------+--------------------+--------------------+----------------+--------------------+----------------+--------------------+\n","| id| revid| text| timestamp| title| url| title_lower| text_lower|\n","+---+--------+--------------------+--------------------+----------------+--------------------+----------------+--------------------+\n","| 2|68591979|Trang Chính\\n\\n<t...|2022-05-12T12:46:53Z| Trang Chính|https://vi.wikipe...| trang chính|trang chính templ...|\n","| 4|67988747|Internet Society\\...|2022-01-20T07:59:10Z|Internet Society|https://vi.wikipe...|internet society|internet society ...|\n","| 13|68660631|Tiếng Việt\\n\\nTiế...|2022-05-29T03:42:42Z| Tiếng Việt|https://vi.wikipe...| tiếng việt|tiếng việt tiếng ...|\n","| 24|68482118|Ohio\\n\\nOhio (viế...|2022-04-17T08:15:22Z| Ohio|https://vi.wikipe...| ohio|ohio ohio viết tắ...|\n","| 26|68738039|California\\n\\nCal...|2022-06-16T15:27:07Z| California|https://vi.wikipe...| california|california califo...|\n","+---+--------+--------------------+--------------------+----------------+--------------------+----------------+--------------------+\n","only showing top 5 rows\n","\n"]},{"name":"stderr","output_type":"stream","text":[" \r"]}],"source":["df_wiki = df_wiki.withColumn(\"title_lower\", post_process_udf(col(\"title\")))\n","df_wiki = df_wiki.withColumn(\"text_lower\", post_process_udf(col(\"text\")))\n","df_wiki.show(5)"]},{"cell_type":"code","execution_count":12,"metadata":{"execution":{"iopub.execute_input":"2023-06-19T04:47:42.639237Z","iopub.status.busy":"2023-06-19T04:47:42.638940Z","iopub.status.idle":"2023-06-19T04:47:42.674851Z","shell.execute_reply":"2023-06-19T04:47:42.674065Z","shell.execute_reply.started":"2023-06-19T04:47:42.639213Z"},"trusted":true},"outputs":[{"name":"stdout","output_type":"stream","text":["== Physical Plan ==\n","*(1) Project [id#8, revid#9, text#10, timestamp#11, title#12, url#13, pythonUDF0#144 AS title_lower#85, pythonUDF1#145 AS text_lower#94]\n","+- BatchEvalPython [post_process(title#12)#84, post_process(text#10)#93], [pythonUDF0#144, pythonUDF1#145]\n"," +- FileScan json [id#8,revid#9,text#10,timestamp#11,title#12,url#13] Batched: false, DataFilters: [], Format: JSON, Location: InMemoryFileIndex(1 paths)[file:/kaggle/input/e2eqa-wiki-zalo-ai/wikipedia_20220620_cleaned/wikip..., PartitionFilters: [], PushedFilters: [], ReadSchema: struct<id:string,revid:string,text:string,timestamp:string,title:string,url:string>\n","\n","\n"]}],"source":["df_wiki.explain()"]},{"cell_type":"markdown","metadata":{},"source":["### Đọc file __stopwords__"]},{"cell_type":"code","execution_count":13,"metadata":{"execution":{"iopub.execute_input":"2023-06-19T04:47:42.675987Z","iopub.status.busy":"2023-06-19T04:47:42.675714Z","iopub.status.idle":"2023-06-19T04:47:42.710651Z","shell.execute_reply":"2023-06-19T04:47:42.709880Z","shell.execute_reply.started":"2023-06-19T04:47:42.675963Z"},"trusted":true},"outputs":[{"data":{"text/plain":["0 mà_thôi\n","1 tuy_có\n","2 đâu_như\n","3 quay_bước\n","4 hỏi_lại\n"," ... \n","1937 cái_họ\n","1938 hết\n","1939 lại\n","1940 thế_thế\n","1941 dần_dần\n","Name: stopwords, Length: 1942, dtype: object"]},"execution_count":13,"metadata":{},"output_type":"execute_result"}],"source":["filename = '/kaggle/input/e2eqa-wiki-zalo-ai/external/stopwords.csv'\n","stop = pd.read_csv(filename, sep=\"\\t\", encoding='utf-8')\n","list_stopwords = stop['stopwords']\n","list_stopwords"]},{"cell_type":"markdown","metadata":{},"source":["---\n","---"]},{"cell_type":"code","execution_count":14,"metadata":{"_kg_hide-output":true,"execution":{"iopub.execute_input":"2023-06-19T04:47:42.712418Z","iopub.status.busy":"2023-06-19T04:47:42.711650Z","iopub.status.idle":"2023-06-19T04:47:44.373278Z","shell.execute_reply":"2023-06-19T04:47:44.372435Z","shell.execute_reply.started":"2023-06-19T04:47:42.712390Z"},"trusted":true},"outputs":[{"name":"stderr","output_type":"stream","text":["[Stage 5:> (0 + 1) / 1]\r"]},{"name":"stdout","output_type":"stream","text":["+--------------------+\n","| words|\n","+--------------------+\n","|[trang, chính, te...|\n","|[internet, societ...|\n","|[tiếng, việt, tiế...|\n","|[ohio, ohio, viết...|\n","|[california, cali...|\n","+--------------------+\n","only showing top 5 rows\n","\n"]},{"name":"stderr","output_type":"stream","text":[" \r"]}],"source":["# Tokenize text into words\n","def tokenizer(text):\n"," tokens = [word for word in tokenize(text).split() if word not in list_stopwords]\n"," return tokens\n","\n","tokenize_udf = udf(tokenizer, ArrayType(StringType()))\n","df_wiki = df_wiki.withColumn(\"words\", tokenize_udf(col(\"text_lower\")))\n","df_wiki.select(\"words\").show(5)"]},{"cell_type":"markdown","metadata":{},"source":["### Tần suất các từ trong texts"]},{"cell_type":"code","execution_count":15,"metadata":{"_kg_hide-input":false,"_kg_hide-output":false,"execution":{"iopub.execute_input":"2023-06-19T04:47:44.379705Z","iopub.status.busy":"2023-06-19T04:47:44.378439Z","iopub.status.idle":"2023-06-19T05:06:28.712339Z","shell.execute_reply":"2023-06-19T05:06:28.710514Z","shell.execute_reply.started":"2023-06-19T04:47:44.379637Z"},"trusted":true},"outputs":[{"name":"stderr","output_type":"stream","text":["[Stage 8:> (0 + 4) / 4]\r"]},{"name":"stdout","output_type":"stream","text":["+--------+-------+\n","| word| count|\n","+--------+-------+\n","| là|1858454|\n","| loài|1385128|\n","| một|1365013|\n","| trong|1046730|\n","| năm|1034325|\n","| được| 923562|\n","| họ| 846094|\n","| này| 726077|\n","| bullet| 671970|\n","| của| 656976|\n","| có| 602435|\n","| và| 578809|\n","|khoa_học| 484960|\n","|đầu_tiên| 381971|\n","| ở| 373949|\n","| hoa| 352879|\n","| thuộc| 339118|\n","| người| 321510|\n","| các| 308467|\n","|thực_vật| 287653|\n","+--------+-------+\n","only showing top 20 rows\n","\n"]},{"name":"stderr","output_type":"stream","text":[" \r"]}],"source":["from pyspark.sql import functions as F\n","# Increase the number of partitions\n","# df_wiki = df_wiki.repartition(100)\n","\n","# Cache the DataFrame in memory\n","df_wiki.cache()\n","\n","# Perform the computation\n","result = (\n"," df_wiki\n"," .select(F.explode(\"words\").alias(\"word\"))\n"," .groupBy(\"word\")\n"," .count()\n"," .orderBy(F.desc(\"count\"))\n",")\n","\n","# Show the results\n","result.show()"]},{"cell_type":"markdown","metadata":{},"source":["---\n","---"]},{"cell_type":"markdown","metadata":{},"source":["#### Map title with answer"]},{"cell_type":"code","execution_count":16,"metadata":{"execution":{"iopub.execute_input":"2023-06-19T05:06:28.718426Z","iopub.status.busy":"2023-06-19T05:06:28.717581Z","iopub.status.idle":"2023-06-19T05:07:05.169160Z","shell.execute_reply":"2023-06-19T05:07:05.168170Z","shell.execute_reply.started":"2023-06-19T05:06:28.718393Z"},"trusted":true},"outputs":[{"name":"stderr","output_type":"stream","text":[" \r"]}],"source":["from pyspark.sql import Window\n","# add index column\n","df_wiki = df_wiki.rdd.zipWithIndex().toDF([\"data\", \"index\"]).select(\"data.*\", \"index\")"]},{"cell_type":"code","execution_count":17,"metadata":{"execution":{"iopub.execute_input":"2023-06-19T05:07:05.170729Z","iopub.status.busy":"2023-06-19T05:07:05.170405Z","iopub.status.idle":"2023-06-19T05:08:02.748141Z","shell.execute_reply":"2023-06-19T05:08:02.746532Z","shell.execute_reply.started":"2023-06-19T05:07:05.170695Z"},"trusted":true},"outputs":[{"name":"stderr","output_type":"stream","text":[" \r"]},{"name":"stdout","output_type":"stream","text":["Cù Lao Chàm\n","nhà Hán\n","bán đảo Ả Rập\n"]}],"source":["from pyspark.sql.functions import trim, lower, regexp_replace\n","\n","# Create a dictionary mapping titles to indices\n","title2idx = (\n"," df_wiki\n"," .select(trim(\"title\").alias(\"title\"), \"index\")\n"," .groupBy(\"title\")\n"," .agg({\"index\": \"first\"})\n"," .rdd\n"," .collectAsMap()\n",")\n","\n","# Loop over data and check if answer is in the dictionary\n","for x in data:\n"," answer = x['answer'].replace(\"wiki/\", \"\").replace(\"_\", \" \")\n"," # Check if the cleaned up title is in the dictionary\n"," if answer not in title2idx.keys():\n"," print(answer)\n"," for key, val in title2idx.items():\n"," if answer.lower() == key.lower():\n"," x['answer'] = \"wiki/\" + key.replace(\" \", \"_\")\n"," "]},{"cell_type":"code","execution_count":18,"metadata":{"execution":{"iopub.execute_input":"2023-06-19T05:08:02.753058Z","iopub.status.busy":"2023-06-19T05:08:02.752193Z","iopub.status.idle":"2023-06-19T05:08:02.764393Z","shell.execute_reply":"2023-06-19T05:08:02.763347Z","shell.execute_reply.started":"2023-06-19T05:08:02.753016Z"},"trusted":true},"outputs":[{"data":{"text/plain":["(1849, 4608)"]},"execution_count":18,"metadata":{},"output_type":"execute_result"}],"source":["l = []\n","for x in data:\n"," l.append(x['answer'])\n","len(set(l)), len(l)"]},{"cell_type":"markdown","metadata":{},"source":["#### Lọc các stopwords ra khỏi answer"]},{"cell_type":"code","execution_count":19,"metadata":{"execution":{"iopub.execute_input":"2023-06-19T05:08:02.767039Z","iopub.status.busy":"2023-06-19T05:08:02.766644Z","iopub.status.idle":"2023-06-19T05:08:02.780001Z","shell.execute_reply":"2023-06-19T05:08:02.778564Z","shell.execute_reply.started":"2023-06-19T05:08:02.767009Z"},"trusted":true},"outputs":[],"source":["# from pyspark.ml.feature import StopWordsRemover\n","# # Tokenize and remove stop words\n","# remover = StopWordsRemover(inputCol=\"title_lower\", outputCol=\"tokens\")\n","# tokenized_df = remover.transform(df_wiki.select(\"title_lower\"))\n","\n","# # Convert tokens to a list of strings\n","# to_list = udf(lambda x: x, ArrayType(StringType()))\n","# tokenized_df = tokenized_df.withColumn(\"token_list\", to_list(\"tokens\"))\n","\n","# # Compute TF-IDF vectors\n","# cv = CountVectorizer(inputCol=\"token_list\", outputCol=\"raw_features\")\n","# cv_model = cv.fit(tokenized_df)\n","# featurized_df = cv_model.transform(tokenized_df)\n","# idf = IDF(inputCol=\"raw_features\", outputCol=\"features\")\n","# idf_model = idf.fit(featurized_df)\n","# rescaled_df = idf_model.transform(featurized_df)\n","\n","# # Convert features column to VectorUDT\n","# to_vector = udf(lambda x: x, VectorUDT())\n","# rescaled_df = rescaled_df.withColumn(\"features\", to_vector(\"features\"))\n","\n","# # Compute BM25Okapi score\n","# bm25 = BM25Okapi(rescaled_df.select(\"features\").rdd.flatMap(lambda x: x))\n","# bm25"]},{"cell_type":"code","execution_count":20,"metadata":{"execution":{"iopub.execute_input":"2023-06-19T05:08:02.781992Z","iopub.status.busy":"2023-06-19T05:08:02.781655Z","iopub.status.idle":"2023-06-19T05:09:00.711662Z","shell.execute_reply":"2023-06-19T05:09:00.710057Z","shell.execute_reply.started":"2023-06-19T05:08:02.781961Z"},"trusted":true},"outputs":[{"name":"stderr","output_type":"stream","text":[" \r"]}],"source":["docs = df_wiki.select('title_lower').toPandas()\n","tokenized_corpus = [[word for word in doc.lower().split() if word not in list_stopwords]\n"," for doc in docs['title_lower']\n"," ] #simple tokenier\n","bm25_title = BM25Okapi(tokenized_corpus)"]},{"cell_type":"code","execution_count":21,"metadata":{"execution":{"iopub.execute_input":"2023-06-19T05:09:00.713615Z","iopub.status.busy":"2023-06-19T05:09:00.713197Z","iopub.status.idle":"2023-06-19T05:09:01.135969Z","shell.execute_reply":"2023-06-19T05:09:01.135282Z","shell.execute_reply.started":"2023-06-19T05:09:00.713580Z"},"scrolled":true,"trusted":true},"outputs":[{"name":"stdout","output_type":"stream","text":["+--------------------+\n","| query|\n","+--------------------+\n","|[costa, rica, ice...|\n","| [núi, elbrus]|\n","| [alexandria]|\n","| [lê, chân]|\n","| [ý]|\n","+--------------------+\n","only showing top 5 rows\n","\n"]}],"source":["df = pd.DataFrame({\n"," \"query\": [post_process(x[\"short_candidate\"]).lower().split() for x in data]\n","})\n","df = spark.createDataFrame(df)\n","df.show(5)"]},{"cell_type":"code","execution_count":22,"metadata":{"execution":{"iopub.execute_input":"2023-06-19T05:09:01.136929Z","iopub.status.busy":"2023-06-19T05:09:01.136703Z","iopub.status.idle":"2023-06-19T05:09:01.198467Z","shell.execute_reply":"2023-06-19T05:09:01.197404Z","shell.execute_reply.started":"2023-06-19T05:09:01.136901Z"},"trusted":true},"outputs":[{"name":"stdout","output_type":"stream","text":["+--------------------+\n","| query|\n","+--------------------+\n","|[costa, rica, ice...|\n","| [núi, elbrus]|\n","| [alexandria]|\n","| [lê, chân]|\n","| [ý]|\n","| [phan, thiết]|\n","| [xã, nhơn, lý]|\n","| [google]|\n","| [tỉnh, gia, lai]|\n","| [tỉnh, quảng, nam]|\n","| [vua, khải, định]|\n","|[theo, thể, lục, ...|\n","| [trần, duy, hưng]|\n","| [suối, tranh]|\n","|[chùa, làng, vũ, ...|\n","|[nguyễn, phú, trọng]|\n","| [pháp]|\n","| [tỉnh, an, giang]|\n","| [tỉnh, bắc, kạn]|\n","| [nguyễn, văn, tý]|\n","+--------------------+\n","only showing top 20 rows\n","\n"]}],"source":["df.select('query').show()"]},{"cell_type":"code","execution_count":23,"metadata":{"execution":{"iopub.execute_input":"2023-06-19T05:09:01.199811Z","iopub.status.busy":"2023-06-19T05:09:01.199500Z","iopub.status.idle":"2023-06-19T05:09:08.924690Z","shell.execute_reply":"2023-06-19T05:09:08.923664Z","shell.execute_reply.started":"2023-06-19T05:09:01.199782Z"},"trusted":true},"outputs":[{"name":"stderr","output_type":"stream","text":["[Stage 15:> (0 + 1) / 1]\r"]},{"name":"stdout","output_type":"stream","text":["+--------------------+--------------------+\n","| query| top_n|\n","+--------------------+--------------------+\n","|[costa, rica, ice...|[6771, 25055, 585...|\n","| [núi, elbrus]|[11092, 1268687, ...|\n","| [alexandria]|[54875, 223778, 5...|\n","| [lê, chân]|[25316, 17081, 39...|\n","| [ý]|[4452, 46524, 114...|\n","+--------------------+--------------------+\n","only showing top 5 rows\n","\n"]},{"name":"stderr","output_type":"stream","text":[" \r"]}],"source":["# Define UDF to compute topk titles for a query\n","def get_topk(query, topk=10):\n"," scores = bm25_title.get_scores(query)\n"," top_titles = list(map(int, np.argsort(scores)[::-1][:topk]))\n"," return top_titles\n","\n","get_topk_udf = udf(get_topk, ArrayType(IntegerType()))\n","\n","# Add topk titles column to DataFrame\n","df = df.withColumn(\"top_n\", get_topk_udf(df[\"query\"]))\n","df.show(5)"]},{"cell_type":"code","execution_count":24,"metadata":{"execution":{"iopub.execute_input":"2023-06-19T05:09:08.926215Z","iopub.status.busy":"2023-06-19T05:09:08.925833Z","iopub.status.idle":"2023-06-19T05:30:40.685470Z","shell.execute_reply":"2023-06-19T05:30:40.683455Z","shell.execute_reply.started":"2023-06-19T05:09:08.926182Z"},"trusted":true},"outputs":[{"name":"stderr","output_type":"stream","text":[" \r"]}],"source":["candidate_ids = []\n","true_ids = []\n","top_n_df = df.select(\"top_n\").toPandas()\n","for i, x in enumerate(data):\n"," true_title = x[\"answer\"].replace(\"_\",\" \").replace(\"wiki/\",\"\").strip()\n"," top_n = top_n_df.loc[i, \"top_n\"].tolist() \n"," true_idx = title2idx[true_title]\n"," true_ids.append(true_idx)\n"," candidate_ids.append(top_n)"]},{"cell_type":"code","execution_count":25,"metadata":{"execution":{"iopub.execute_input":"2023-06-19T05:30:40.688025Z","iopub.status.busy":"2023-06-19T05:30:40.687599Z","iopub.status.idle":"2023-06-19T05:30:40.696966Z","shell.execute_reply":"2023-06-19T05:30:40.695478Z","shell.execute_reply.started":"2023-06-19T05:30:40.687990Z"},"trusted":true},"outputs":[],"source":["for x, y in zip(candidate_ids, true_ids):\n"," if y not in x:\n"," x[-1] = y"]},{"cell_type":"code","execution_count":26,"metadata":{"execution":{"iopub.execute_input":"2023-06-19T05:30:40.700316Z","iopub.status.busy":"2023-06-19T05:30:40.699499Z","iopub.status.idle":"2023-06-19T05:32:48.695056Z","shell.execute_reply":"2023-06-19T05:32:48.693738Z","shell.execute_reply.started":"2023-06-19T05:30:40.700278Z"},"trusted":true},"outputs":[{"name":"stderr","output_type":"stream","text":[" \r"]}],"source":["# Change to list of row\n","rows = df_wiki.collect()"]},{"cell_type":"code","execution_count":27,"metadata":{"execution":{"iopub.execute_input":"2023-06-19T05:32:48.697279Z","iopub.status.busy":"2023-06-19T05:32:48.696520Z","iopub.status.idle":"2023-06-19T05:32:55.538212Z","shell.execute_reply":"2023-06-19T05:32:55.537131Z","shell.execute_reply.started":"2023-06-19T05:32:48.697248Z"},"trusted":true},"outputs":[],"source":["df = pd.DataFrame()\n","questions = []\n","answers = []\n","titles = []\n","candidates = []\n","labels = []\n","groups = []\n","for idx, (sample, true_idx, candidate_idxs) in enumerate(zip(data, true_ids, candidate_ids)):\n"," assert true_idx in candidate_idxs\n"," question = sample['question']\n"," answer = sample['short_candidate']\n"," title = [rows[i]['title'] for i in candidate_idxs]\n"," candidate = [rows[i]['text'] for i in candidate_idxs]\n"," label = [1 if x == true_idx else 0 for x in candidate_idxs]\n"," \n"," questions.extend([question,]*len(candidate_idxs))\n"," answers.extend([answer,]*len(candidate_idxs))\n"," groups.extend([idx,]*len(candidate_idxs))\n"," titles.extend(title)\n"," candidates.extend(candidate)\n"," labels.extend(label)\n"," \n","df[\"question\"] = questions \n","df[\"answer\"] = answers \n","df[\"title\"] = titles \n","df[\"candidate\"] = candidates \n","df[\"label\"] = labels \n","df[\"group\"] = groups \n","df.candidate = df.candidate.apply(lambda x: \" \".join(x.strip().split()))"]},{"cell_type":"code","execution_count":28,"metadata":{"execution":{"iopub.execute_input":"2023-06-19T05:32:55.539819Z","iopub.status.busy":"2023-06-19T05:32:55.539519Z","iopub.status.idle":"2023-06-19T05:32:55.577719Z","shell.execute_reply":"2023-06-19T05:32:55.576585Z","shell.execute_reply.started":"2023-06-19T05:32:55.539794Z"},"trusted":true},"outputs":[{"data":{"text/html":["<div>\n","<style scoped>\n"," .dataframe tbody tr th:only-of-type {\n"," vertical-align: middle;\n"," }\n","\n"," .dataframe tbody tr th {\n"," vertical-align: top;\n"," }\n","\n"," .dataframe thead th {\n"," text-align: right;\n"," }\n","</style>\n","<table border=\"1\" class=\"dataframe\">\n"," <thead>\n"," <tr style=\"text-align: right;\">\n"," <th></th>\n"," <th>question</th>\n"," <th>answer</th>\n"," <th>title</th>\n"," <th>candidate</th>\n"," <th>label</th>\n"," <th>group</th>\n"," </tr>\n"," </thead>\n"," <tbody>\n"," <tr>\n"," <th>0</th>\n"," <td>Đất nước nào không có quân đội</td>\n"," <td>Costa Rica, Iceland, Panama, Micronesia, Quần ...</td>\n"," <td>Costa Rica</td>\n"," <td>Costa Rica Costa Rica (Phiên âm: Cô-xta Ri-ca)...</td>\n"," <td>0</td>\n"," <td>0</td>\n"," </tr>\n"," <tr>\n"," <th>1</th>\n"," <td>Đất nước nào không có quân đội</td>\n"," <td>Costa Rica, Iceland, Panama, Micronesia, Quần ...</td>\n"," <td>Quần đảo Marshall</td>\n"," <td>Quần đảo Marshall Quần đảo Marshall, tên chính...</td>\n"," <td>0</td>\n"," <td>0</td>\n"," </tr>\n"," <tr>\n"," <th>2</th>\n"," <td>Đất nước nào không có quân đội</td>\n"," <td>Costa Rica, Iceland, Panama, Micronesia, Quần ...</td>\n"," <td>Montezuma, Costa Rica</td>\n"," <td>Montezuma, Costa Rica Montezuma là một thị xã ...</td>\n"," <td>0</td>\n"," <td>0</td>\n"," </tr>\n"," <tr>\n"," <th>3</th>\n"," <td>Đất nước nào không có quân đội</td>\n"," <td>Costa Rica, Iceland, Panama, Micronesia, Quần ...</td>\n"," <td>Tamarindo, Costa Rica</td>\n"," <td>Tamarindo, Costa Rica Tamarindo là một thị xã ...</td>\n"," <td>0</td>\n"," <td>0</td>\n"," </tr>\n"," <tr>\n"," <th>4</th>\n"," <td>Đất nước nào không có quân đội</td>\n"," <td>Costa Rica, Iceland, Panama, Micronesia, Quần ...</td>\n"," <td>Micronesia</td>\n"," <td>Micronesia Micronesia (, ), còn gọi là Tiểu Đả...</td>\n"," <td>0</td>\n"," <td>0</td>\n"," </tr>\n"," </tbody>\n","</table>\n","</div>"],"text/plain":[" question \\\n","0 Đất nước nào không có quân đội \n","1 Đất nước nào không có quân đội \n","2 Đất nước nào không có quân đội \n","3 Đất nước nào không có quân đội \n","4 Đất nước nào không có quân đội \n","\n"," answer title \\\n","0 Costa Rica, Iceland, Panama, Micronesia, Quần ... Costa Rica \n","1 Costa Rica, Iceland, Panama, Micronesia, Quần ... Quần đảo Marshall \n","2 Costa Rica, Iceland, Panama, Micronesia, Quần ... Montezuma, Costa Rica \n","3 Costa Rica, Iceland, Panama, Micronesia, Quần ... Tamarindo, Costa Rica \n","4 Costa Rica, Iceland, Panama, Micronesia, Quần ... Micronesia \n","\n"," candidate label group \n","0 Costa Rica Costa Rica (Phiên âm: Cô-xta Ri-ca)... 0 0 \n","1 Quần đảo Marshall Quần đảo Marshall, tên chính... 0 0 \n","2 Montezuma, Costa Rica Montezuma là một thị xã ... 0 0 \n","3 Tamarindo, Costa Rica Tamarindo là một thị xã ... 0 0 \n","4 Micronesia Micronesia (, ), còn gọi là Tiểu Đả... 0 0 "]},"execution_count":28,"metadata":{},"output_type":"execute_result"}],"source":["df.head()"]},{"cell_type":"code","execution_count":30,"metadata":{"execution":{"iopub.execute_input":"2023-06-19T05:33:45.138800Z","iopub.status.busy":"2023-06-19T05:33:45.138413Z","iopub.status.idle":"2023-06-19T05:33:51.569429Z","shell.execute_reply":"2023-06-19T05:33:51.568261Z","shell.execute_reply.started":"2023-06-19T05:33:45.138771Z"},"trusted":true},"outputs":[],"source":["df.to_csv(\"/kaggle/working/train_stage2_ranking.csv\",index=False)"]},{"cell_type":"markdown","metadata":{},"source":["<a href=\"/kaggle/working/train_stage2_ranking.csv\"> Download File </a>"]},{"cell_type":"code","execution_count":33,"metadata":{"execution":{"iopub.execute_input":"2023-06-19T05:38:13.126543Z","iopub.status.busy":"2023-06-19T05:38:13.126055Z","iopub.status.idle":"2023-06-19T05:38:47.848000Z","shell.execute_reply":"2023-06-19T05:38:47.845517Z","shell.execute_reply.started":"2023-06-19T05:38:13.126496Z"},"trusted":true},"outputs":[{"name":"stdout","output_type":"stream","text":[" adding: kaggle/working/train_stage2_ranking.csv (deflated 70%)\n"]}],"source":["!zip -r file.zip /kaggle/working/train_stage2_ranking.csv"]},{"cell_type":"code","execution_count":36,"metadata":{"execution":{"iopub.execute_input":"2023-06-19T05:41:56.345417Z","iopub.status.busy":"2023-06-19T05:41:56.344395Z","iopub.status.idle":"2023-06-19T05:41:56.821886Z","shell.execute_reply":"2023-06-19T05:41:56.820592Z","shell.execute_reply.started":"2023-06-19T05:41:56.345344Z"},"trusted":true},"outputs":[{"name":"stdout","output_type":"stream","text":["total 507M\n","drwxr-xr-x 4 root root 4.0K Jun 19 05:38 .\n","-rw-r--r-- 1 root root 118M Jun 19 05:38 file.zip\n","-rw-r--r-- 1 root root 390M Jun 19 05:33 train_stage2_ranking.csv\n","drwxr-xr-x 2 root root 4.0K Jun 19 04:47 spark-warehouse\n","drwxr-xr-x 2 root root 4.0K Jun 19 04:45 .virtual_documents\n","drwxr-xr-x 5 root root 4.0K Jun 19 04:45 ..\n","---------- 1 root root 263 Jun 19 04:45 __notebook_source__.ipynb\n"]}],"source":["!cd /kaggle && ls -halt working"]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.10.10"}},"nbformat":4,"nbformat_minor":5}
|
notebooks/0.4-find-redirects.ipynb
ADDED
The diff for this file is too large to render.
See raw diff
|
|
notebooks/1.0-train-bm25-stage1.ipynb
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"cells":[{"attachments":{},"cell_type":"markdown","metadata":{},"source":["### Kaggle link: https://www.kaggle.com/code/noobhocai/train-stage-1"]},{"cell_type":"code","execution_count":1,"metadata":{"execution":{"iopub.execute_input":"2023-06-26T15:46:04.681825Z","iopub.status.busy":"2023-06-26T15:46:04.681521Z","iopub.status.idle":"2023-06-26T15:46:20.131828Z","shell.execute_reply":"2023-06-26T15:46:20.130853Z","shell.execute_reply.started":"2023-06-26T15:46:04.681800Z"},"trusted":true},"outputs":[{"name":"stdout","output_type":"stream","text":["\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n","\u001b[0m"]}],"source":["!pip install pyvi rank_bm25 pandarallel gensim --q"]},{"cell_type":"code","execution_count":2,"metadata":{"execution":{"iopub.execute_input":"2023-06-26T15:46:20.133869Z","iopub.status.busy":"2023-06-26T15:46:20.133505Z","iopub.status.idle":"2023-06-26T15:46:21.705024Z","shell.execute_reply":"2023-06-26T15:46:21.703777Z","shell.execute_reply.started":"2023-06-26T15:46:20.133832Z"},"trusted":true},"outputs":[{"name":"stdout","output_type":"stream","text":["INFO: Pandarallel will run on 10 workers.\n","INFO: Pandarallel will use Memory file system to transfer data between the main process and workers.\n"]}],"source":["import os\n","import re\n","from tqdm.auto import tqdm\n","tqdm.pandas()\n","import math\n","import pandas as pd\n","import string\n","from pyvi.ViTokenizer import tokenize\n","import numpy as np\n","import json, pickle\n","from rank_bm25 import BM25Okapi\n","import argparse\n","import gc\n","\n","from glob import glob \n","from nltk import word_tokenize as lib_tokenizer \n","\n","from pandarallel import pandarallel\n","from gensim.corpora import Dictionary\n","from gensim.corpora import MmCorpus\n","from gensim.models import TfidfModel, OkapiBM25Model\n","from gensim.similarities import SparseMatrixSimilarity\n","pandarallel.initialize(progress_bar=True, nb_workers=10)"]},{"cell_type":"code","execution_count":3,"metadata":{"execution":{"iopub.execute_input":"2023-06-26T15:12:52.194411Z","iopub.status.busy":"2023-06-26T15:12:52.193733Z","iopub.status.idle":"2023-06-26T15:12:52.208121Z","shell.execute_reply":"2023-06-26T15:12:52.206564Z","shell.execute_reply.started":"2023-06-26T15:12:52.194376Z"},"trusted":true},"outputs":[],"source":["def get_topk(query, topk = 100):\n"," tokenized_query = query.split()\n"," tfidf_query = tfidf_model[dictionary.doc2bow(tokenized_query)]\n"," scores = bm25_index[tfidf_query]\n"," top_n = np.argsort(scores)[::-1][:topk]\n"," titles = [df_wiki.title.values[i] for i in top_n]\n"," texts = [df_wiki.text.values[i] for i in top_n]\n"," # print(titles)\n"," # print(tfidf_query, scores)\n"," return titles, texts, scores[top_n]\n","\n","def post_process(x):\n"," x = \" \".join(word_tokenize(strip_context(x))).strip()\n"," x = x.replace(\"\\n\",\" \")\n"," x = \"\".join([i for i in x if i not in string.punctuation])\n"," return x\n","\n","dict_map = dict({}) \n","def word_tokenize(text): \n"," global dict_map \n"," words = text.split() \n"," words_norm = [] \n"," for w in words: \n"," if dict_map.get(w, None) is None: \n"," dict_map[w] = ' '.join(lib_tokenizer(w)).replace('``', '\"').replace(\"''\", '\"') \n"," words_norm.append(dict_map[w]) \n"," return words_norm \n"," \n","def strip_context(text): \n"," text = text.replace('\\n', ' ') \n"," text = re.sub(r'\\s+', ' ', text) \n"," text = text.strip() \n"," return text"]},{"cell_type":"code","execution_count":4,"metadata":{"execution":{"iopub.execute_input":"2023-06-26T15:12:52.210996Z","iopub.status.busy":"2023-06-26T15:12:52.210623Z","iopub.status.idle":"2023-06-26T15:12:52.227767Z","shell.execute_reply":"2023-06-26T15:12:52.226604Z","shell.execute_reply.started":"2023-06-26T15:12:52.210948Z"},"trusted":true},"outputs":[],"source":["wiki_cleaned_path = \"/kaggle/input/e2eqa-wiki-zalo-ai/processed/wikipedia_20220620_cleaned_v2.csv\"\n","test_data_path = \"/kaggle/input/e2eqa-wiki-zalo-ai/e2eqa-trainpublic_test-v1/e2eqa-train+public_test-v1/zac2022_testa_sample_submission.json\"\n","topk = 300"]},{"cell_type":"code","execution_count":5,"metadata":{"execution":{"iopub.execute_input":"2023-06-26T15:12:52.230234Z","iopub.status.busy":"2023-06-26T15:12:52.229690Z","iopub.status.idle":"2023-06-26T15:14:32.740956Z","shell.execute_reply":"2023-06-26T15:14:32.739621Z","shell.execute_reply.started":"2023-06-26T15:12:52.230185Z"},"trusted":true},"outputs":[],"source":["df_wiki = pd.read_csv(wiki_cleaned_path)"]},{"cell_type":"code","execution_count":6,"metadata":{"execution":{"iopub.execute_input":"2023-06-26T15:14:32.743587Z","iopub.status.busy":"2023-06-26T15:14:32.743104Z","iopub.status.idle":"2023-06-26T15:14:35.140539Z","shell.execute_reply":"2023-06-26T15:14:35.139511Z","shell.execute_reply.started":"2023-06-26T15:14:32.743544Z"},"trusted":true},"outputs":[],"source":["df_wiki = df_wiki.fillna(\"NaN\")\n","if \"title\" not in df_wiki.columns:\n"," df_wiki[\"title\"] = df_wiki[\"titles=\"].fillna(\"\")"]},{"cell_type":"code","execution_count":7,"metadata":{"execution":{"iopub.execute_input":"2023-06-26T15:14:35.143448Z","iopub.status.busy":"2023-06-26T15:14:35.142192Z","iopub.status.idle":"2023-06-26T15:14:35.178049Z","shell.execute_reply":"2023-06-26T15:14:35.176844Z","shell.execute_reply.started":"2023-06-26T15:14:35.143403Z"},"trusted":true},"outputs":[{"data":{"text/html":["<div>\n","<style scoped>\n"," .dataframe tbody tr th:only-of-type {\n"," vertical-align: middle;\n"," }\n","\n"," .dataframe tbody tr th {\n"," vertical-align: top;\n"," }\n","\n"," .dataframe thead th {\n"," text-align: right;\n"," }\n","</style>\n","<table border=\"1\" class=\"dataframe\">\n"," <thead>\n"," <tr style=\"text-align: right;\">\n"," <th></th>\n"," <th>title</th>\n"," <th>text</th>\n"," <th>bm25_text</th>\n"," </tr>\n"," </thead>\n"," <tbody>\n"," <tr>\n"," <th>0</th>\n"," <td>Trang Chính</td>\n"," <td>Trang Chính\\n\\n<templatestyles src=\"Wiki2021/s...</td>\n"," <td>trang chính <templatestyles src= wiki2021 styl...</td>\n"," </tr>\n"," <tr>\n"," <th>1</th>\n"," <td>Internet Society</td>\n"," <td>Internet Society hay ISOC là một tổ chức quốc...</td>\n"," <td>internet society hay isoc là một tổ chức quốc ...</td>\n"," </tr>\n"," <tr>\n"," <th>2</th>\n"," <td>Tiếng Việt</td>\n"," <td>Tiếng Việt , cũng gọi là tiếng Việt Nam hay Vi...</td>\n"," <td>tiếng việt cũng gọi là tiếng việt nam hay việt...</td>\n"," </tr>\n"," <tr>\n"," <th>3</th>\n"," <td>Tiếng Việt</td>\n"," <td>hệ thống thanh điệu phát triển cao hơn, hệ thố...</td>\n"," <td>hệ thống thanh điệu phát triển cao hơn hệ thốn...</td>\n"," </tr>\n"," <tr>\n"," <th>4</th>\n"," <td>Tiếng Việt</td>\n"," <td>tiếp xúc Hán – Việt thành 2 giai đoạn chính: \\...</td>\n"," <td>tiếp xúc hán – việt thành 2 giai đoạn chính bu...</td>\n"," </tr>\n"," </tbody>\n","</table>\n","</div>"],"text/plain":[" title text \\\n","0 Trang Chính Trang Chính\\n\\n<templatestyles src=\"Wiki2021/s... \n","1 Internet Society Internet Society hay ISOC là một tổ chức quốc... \n","2 Tiếng Việt Tiếng Việt , cũng gọi là tiếng Việt Nam hay Vi... \n","3 Tiếng Việt hệ thống thanh điệu phát triển cao hơn, hệ thố... \n","4 Tiếng Việt tiếp xúc Hán – Việt thành 2 giai đoạn chính: \\... \n","\n"," bm25_text \n","0 trang chính <templatestyles src= wiki2021 styl... \n","1 internet society hay isoc là một tổ chức quốc ... \n","2 tiếng việt cũng gọi là tiếng việt nam hay việt... \n","3 hệ thống thanh điệu phát triển cao hơn hệ thốn... \n","4 tiếp xúc hán – việt thành 2 giai đoạn chính bu... "]},"execution_count":7,"metadata":{},"output_type":"execute_result"}],"source":["df_wiki.head()"]},{"cell_type":"code","execution_count":8,"metadata":{"execution":{"iopub.execute_input":"2023-06-26T15:14:35.180010Z","iopub.status.busy":"2023-06-26T15:14:35.179628Z","iopub.status.idle":"2023-06-26T15:21:28.016391Z","shell.execute_reply":"2023-06-26T15:21:28.014113Z","shell.execute_reply.started":"2023-06-26T15:14:35.179950Z"},"trusted":true},"outputs":[{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"8492baeb724e46bd80570a9450bdc18c","version_major":2,"version_minor":0},"text/plain":["VBox(children=(HBox(children=(IntProgress(value=0, description='0.00%', max=194441), Label(value='0 / 194441')…"]},"metadata":{},"output_type":"display_data"}],"source":["df_wiki['bm25_text'] = df_wiki['bm25_text'].parallel_apply(post_process)\n","# corpus = [x.split() for x in df_wiki['bm25_text'].values]"]},{"cell_type":"code","execution_count":10,"metadata":{"execution":{"iopub.execute_input":"2023-06-26T15:22:23.179076Z","iopub.status.busy":"2023-06-26T15:22:23.178506Z","iopub.status.idle":"2023-06-26T15:31:22.030632Z","shell.execute_reply":"2023-06-26T15:31:22.028624Z","shell.execute_reply.started":"2023-06-26T15:22:23.179027Z"},"trusted":true},"outputs":[{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"01c5f715c22d4ec682dc0c7b4812ec30","version_major":2,"version_minor":0},"text/plain":[" 0%| | 0/1944406 [00:00<?, ?it/s]"]},"metadata":{},"output_type":"display_data"}],"source":["# Convert the column to a numpy array \n","texts = df_wiki['bm25_text'].to_numpy()\n","# Create an empty dictionary \n","dictionary = Dictionary()\n","# Update the dictionary with each batch of texts \n","for text in tqdm(texts): \n"," dictionary.add_documents([text.split()])"]},{"cell_type":"code","execution_count":null,"metadata":{"execution":{"iopub.execute_input":"2023-06-26T14:30:00.288679Z","iopub.status.busy":"2023-06-26T14:30:00.288263Z"},"trusted":true},"outputs":[],"source":["# dictionary = Dictionary(corpus)"]},{"cell_type":"code","execution_count":14,"metadata":{"execution":{"iopub.execute_input":"2023-06-26T15:35:34.130599Z","iopub.status.busy":"2023-06-26T15:35:34.130050Z","iopub.status.idle":"2023-06-26T15:36:52.503096Z","shell.execute_reply":"2023-06-26T15:36:52.501050Z","shell.execute_reply.started":"2023-06-26T15:35:34.130560Z"},"trusted":true},"outputs":[],"source":["try:\n"," corpus = [text.split() for text in texts]\n","except:\n"," print(\"nope\")"]},{"cell_type":"code","execution_count":17,"metadata":{"execution":{"iopub.execute_input":"2023-06-26T15:37:34.690339Z","iopub.status.busy":"2023-06-26T15:37:34.689872Z","iopub.status.idle":"2023-06-26T15:37:36.745760Z","shell.execute_reply":"2023-06-26T15:37:36.743959Z","shell.execute_reply.started":"2023-06-26T15:37:34.690307Z"},"trusted":true},"outputs":[],"source":["!mkdir /kaggle/working/bm25_stage1"]},{"cell_type":"markdown","metadata":{},"source":["Save dictionary và corpus vào bộ nhớ"]},{"cell_type":"code","execution_count":19,"metadata":{"execution":{"iopub.execute_input":"2023-06-26T15:39:40.089532Z","iopub.status.busy":"2023-06-26T15:39:40.089024Z","iopub.status.idle":"2023-06-26T15:39:55.080856Z","shell.execute_reply":"2023-06-26T15:39:55.079008Z","shell.execute_reply.started":"2023-06-26T15:39:40.089498Z"},"trusted":true},"outputs":[],"source":["# open a file for writing\n","with open('/kaggle/working/bm25_stage1/corpus.txt', 'w') as f:\n"," # use a loop to write each inner list to a line in the file\n"," for text in texts:\n"," line = text + '\\n'\n"," f.write(line)"]},{"cell_type":"code","execution_count":18,"metadata":{"execution":{"iopub.execute_input":"2023-06-26T15:37:38.871933Z","iopub.status.busy":"2023-06-26T15:37:38.870377Z","iopub.status.idle":"2023-06-26T15:37:48.653312Z","shell.execute_reply":"2023-06-26T15:37:48.651908Z","shell.execute_reply.started":"2023-06-26T15:37:38.871878Z"},"trusted":true},"outputs":[],"source":["tfidf_model = TfidfModel(dictionary=dictionary, smartirs='bnn') # Enforce binary weighting of queries\n","dictionary.save(\"/kaggle/working/bm25_stage1/dict\")\n","tfidf_model.save(\"/kaggle/working/bm25_stage1/tfidf\")"]},{"cell_type":"markdown","metadata":{},"source":["---"]},{"cell_type":"markdown","metadata":{},"source":["Dừng session và tiếp tục chạy"]},{"cell_type":"code","execution_count":9,"metadata":{"execution":{"iopub.execute_input":"2023-06-26T15:51:00.031211Z","iopub.status.busy":"2023-06-26T15:51:00.030816Z","iopub.status.idle":"2023-06-26T15:51:00.036153Z","shell.execute_reply":"2023-06-26T15:51:00.034981Z","shell.execute_reply.started":"2023-06-26T15:51:00.031173Z"},"trusted":true},"outputs":[],"source":["from gensim.models.word2vec import LineSentence"]},{"cell_type":"code","execution_count":10,"metadata":{"execution":{"iopub.execute_input":"2023-06-26T15:51:04.581262Z","iopub.status.busy":"2023-06-26T15:51:04.580512Z","iopub.status.idle":"2023-06-26T15:51:07.005096Z","shell.execute_reply":"2023-06-26T15:51:07.004157Z","shell.execute_reply.started":"2023-06-26T15:51:04.581221Z"},"trusted":true},"outputs":[],"source":["# Create a dictionary and a LineSentence object\n","dictionary = Dictionary.load(\"/kaggle/working/bm25_stage1/dict\")\n","corpus = LineSentence(\"/kaggle/working/bm25_stage1/corpus.txt\")"]},{"cell_type":"code","execution_count":13,"metadata":{"execution":{"iopub.execute_input":"2023-06-26T15:59:04.442336Z","iopub.status.busy":"2023-06-26T15:59:04.441363Z","iopub.status.idle":"2023-06-26T16:06:21.971493Z","shell.execute_reply":"2023-06-26T16:06:21.969936Z","shell.execute_reply.started":"2023-06-26T15:59:04.442296Z"},"trusted":true},"outputs":[],"source":["# # Get an iterator over the corpus\n","# corpus_iterator = corpus.getstream()\n","# Create a BM25 model\n","bm25_model = OkapiBM25Model(dictionary=dictionary)\n","# Create a BM25 corpus by applying doc2bow to each document in the iterator\n","bm25_corpus = bm25_model[list(map(dictionary.doc2bow, corpus))]\n","# Get the number of documents in the corpus from the dictionary or by counting them manually \n","num_docs = dictionary.num_docs\n","# Create a BM25 index\n","bm25_index = SparseMatrixSimilarity(bm25_corpus, num_docs=num_docs,\n"," num_terms=len(dictionary),normalize_queries=False, normalize_documents=False)\n","# Save the BM25 index to a file\n","bm25_index.save(\"/kaggle/working/bm25_stage1/bm25_index\")"]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.10.10"}},"nbformat":4,"nbformat_minor":4}
|
notebooks/1.1-train-bm25-stage2.ipynb
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"cells":[{"attachments":{},"cell_type":"markdown","metadata":{},"source":["### Kaggle link: https://www.kaggle.com/code/noobhocai/train-stage-2"]},{"cell_type":"code","execution_count":1,"metadata":{"execution":{"iopub.execute_input":"2023-06-26T16:15:26.396463Z","iopub.status.busy":"2023-06-26T16:15:26.396153Z","iopub.status.idle":"2023-06-26T16:15:44.091436Z","shell.execute_reply":"2023-06-26T16:15:44.090085Z","shell.execute_reply.started":"2023-06-26T16:15:26.396437Z"},"trusted":true},"outputs":[{"name":"stdout","output_type":"stream","text":["\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n","\u001b[0m"]}],"source":["!pip install rank_bm25 pandarallel gensim --q"]},{"cell_type":"code","execution_count":2,"metadata":{"execution":{"iopub.execute_input":"2023-06-26T16:15:46.131348Z","iopub.status.busy":"2023-06-26T16:15:46.130925Z","iopub.status.idle":"2023-06-26T16:15:47.760579Z","shell.execute_reply":"2023-06-26T16:15:47.759408Z","shell.execute_reply.started":"2023-06-26T16:15:46.131315Z"},"trusted":true},"outputs":[],"source":["import os\n","import json\n","import pandas as pd\n","import numpy as np\n","import json, pickle\n","from rank_bm25 import BM25Okapi\n","import argparse\n","import gc\n","from tqdm.auto import tqdm\n","tqdm.pandas()\n","from glob import glob \n","import re \n","from nltk import word_tokenize as lib_tokenizer \n","import string\n","from gensim.corpora import Dictionary\n","from gensim.models import TfidfModel, OkapiBM25Model\n","from gensim.similarities import SparseMatrixSimilarity"]},{"cell_type":"code","execution_count":4,"metadata":{"execution":{"iopub.execute_input":"2023-06-26T16:16:45.111948Z","iopub.status.busy":"2023-06-26T16:16:45.111271Z","iopub.status.idle":"2023-06-26T16:16:45.117881Z","shell.execute_reply":"2023-06-26T16:16:45.116573Z","shell.execute_reply.started":"2023-06-26T16:16:45.111915Z"},"trusted":true},"outputs":[{"name":"stdout","output_type":"stream","text":["INFO: Pandarallel will run on 10 workers.\n","INFO: Pandarallel will use Memory file system to transfer data between the main process and workers.\n"]}],"source":["from pandarallel import pandarallel\n","\n","pandarallel.initialize(progress_bar=True, nb_workers=10)"]},{"cell_type":"code","execution_count":5,"metadata":{"execution":{"iopub.execute_input":"2023-06-26T16:16:47.210933Z","iopub.status.busy":"2023-06-26T16:16:47.210499Z","iopub.status.idle":"2023-06-26T16:17:49.317252Z","shell.execute_reply":"2023-06-26T16:17:49.316132Z","shell.execute_reply.started":"2023-06-26T16:16:47.210900Z"},"trusted":true},"outputs":[],"source":["df_wiki = pd.read_json(\"/kaggle/input/e2eqa-wiki-zalo-ai/wikipedia_20220620_cleaned/wikipedia_20220620_cleaned.jsonl\", lines=True)"]},{"cell_type":"code","execution_count":6,"metadata":{"execution":{"iopub.execute_input":"2023-06-26T16:18:42.926014Z","iopub.status.busy":"2023-06-26T16:18:42.925307Z","iopub.status.idle":"2023-06-26T16:18:42.961174Z","shell.execute_reply":"2023-06-26T16:18:42.959896Z","shell.execute_reply.started":"2023-06-26T16:18:42.925974Z"},"trusted":true},"outputs":[{"data":{"text/html":["<div>\n","<style scoped>\n"," .dataframe tbody tr th:only-of-type {\n"," vertical-align: middle;\n"," }\n","\n"," .dataframe tbody tr th {\n"," vertical-align: top;\n"," }\n","\n"," .dataframe thead th {\n"," text-align: right;\n"," }\n","</style>\n","<table border=\"1\" class=\"dataframe\">\n"," <thead>\n"," <tr style=\"text-align: right;\">\n"," <th></th>\n"," <th>id</th>\n"," <th>url</th>\n"," <th>title</th>\n"," <th>text</th>\n"," <th>timestamp</th>\n"," <th>revid</th>\n"," </tr>\n"," </thead>\n"," <tbody>\n"," <tr>\n"," <th>0</th>\n"," <td>2</td>\n"," <td>https://vi.wikipedia.org/wiki?curid=2</td>\n"," <td>Trang Chính</td>\n"," <td>Trang Chính\\n\\n<templatestyles src=\"Wiki2021/s...</td>\n"," <td>2022-05-12 12:46:53+00:00</td>\n"," <td>68591979</td>\n"," </tr>\n"," <tr>\n"," <th>1</th>\n"," <td>4</td>\n"," <td>https://vi.wikipedia.org/wiki?curid=4</td>\n"," <td>Internet Society</td>\n"," <td>Internet Society\\n\\nInternet Society hay ISOC ...</td>\n"," <td>2022-01-20 07:59:10+00:00</td>\n"," <td>67988747</td>\n"," </tr>\n"," <tr>\n"," <th>2</th>\n"," <td>13</td>\n"," <td>https://vi.wikipedia.org/wiki?curid=13</td>\n"," <td>Tiếng Việt</td>\n"," <td>Tiếng Việt\\n\\nTiếng Việt, cũng gọi là tiếng Vi...</td>\n"," <td>2022-05-29 03:42:42+00:00</td>\n"," <td>68660631</td>\n"," </tr>\n"," <tr>\n"," <th>3</th>\n"," <td>24</td>\n"," <td>https://vi.wikipedia.org/wiki?curid=24</td>\n"," <td>Ohio</td>\n"," <td>Ohio\\n\\nOhio (viết tắt là OH, viết tắt cũ là O...</td>\n"," <td>2022-04-17 08:15:22+00:00</td>\n"," <td>68482118</td>\n"," </tr>\n"," <tr>\n"," <th>4</th>\n"," <td>26</td>\n"," <td>https://vi.wikipedia.org/wiki?curid=26</td>\n"," <td>California</td>\n"," <td>California\\n\\nCalifornia (phát âm như \"Ca-li-p...</td>\n"," <td>2022-06-16 15:27:07+00:00</td>\n"," <td>68738039</td>\n"," </tr>\n"," </tbody>\n","</table>\n","</div>"],"text/plain":[" id url title \\\n","0 2 https://vi.wikipedia.org/wiki?curid=2 Trang Chính \n","1 4 https://vi.wikipedia.org/wiki?curid=4 Internet Society \n","2 13 https://vi.wikipedia.org/wiki?curid=13 Tiếng Việt \n","3 24 https://vi.wikipedia.org/wiki?curid=24 Ohio \n","4 26 https://vi.wikipedia.org/wiki?curid=26 California \n","\n"," text \\\n","0 Trang Chính\\n\\n<templatestyles src=\"Wiki2021/s... \n","1 Internet Society\\n\\nInternet Society hay ISOC ... \n","2 Tiếng Việt\\n\\nTiếng Việt, cũng gọi là tiếng Vi... \n","3 Ohio\\n\\nOhio (viết tắt là OH, viết tắt cũ là O... \n","4 California\\n\\nCalifornia (phát âm như \"Ca-li-p... \n","\n"," timestamp revid \n","0 2022-05-12 12:46:53+00:00 68591979 \n","1 2022-01-20 07:59:10+00:00 67988747 \n","2 2022-05-29 03:42:42+00:00 68660631 \n","3 2022-04-17 08:15:22+00:00 68482118 \n","4 2022-06-16 15:27:07+00:00 68738039 "]},"execution_count":6,"metadata":{},"output_type":"execute_result"}],"source":["df_wiki.head()"]},{"cell_type":"code","execution_count":7,"metadata":{"execution":{"iopub.execute_input":"2023-06-26T16:20:14.921978Z","iopub.status.busy":"2023-06-26T16:20:14.921498Z","iopub.status.idle":"2023-06-26T16:20:14.943942Z","shell.execute_reply":"2023-06-26T16:20:14.942444Z","shell.execute_reply.started":"2023-06-26T16:20:14.921945Z"},"trusted":true},"outputs":[],"source":["def post_process(x):\n"," x = \" \".join(word_tokenize(strip_context(x))).strip()\n"," x = x.replace(\"\\n\",\" \")\n"," x = \"\".join([i for i in x if i not in string.punctuation])\n"," x = \" \".join(x.split()[:128])\n"," return x\n","\n","dict_map = dict({}) \n","def word_tokenize(text): \n"," global dict_map \n"," words = text.split() \n"," words_norm = [] \n"," for w in words: \n"," if dict_map.get(w, None) is None: \n"," dict_map[w] = ' '.join(lib_tokenizer(w)).replace('``', '\"').replace(\"''\", '\"') \n"," words_norm.append(dict_map[w]) \n"," return words_norm \n"," \n","def strip_answer_string(text): \n"," text = text.strip() \n"," while text[-1] in '.,/><;:\\'\"[]{}+=-_)(*&^!~`': \n"," if text[0] != '(' and text[-1] == ')' and '(' in text: \n"," break \n"," if text[-1] == '\"' and text[0] != '\"' and text.count('\"') > 1: \n"," break \n"," text = text[:-1].strip() \n"," while text[0] in '.,/><;:\\'\"[]{}+=-_)(*&^!~`': \n"," if text[0] == '\"' and text[-1] != '\"' and text.count('\"') > 1: \n"," break \n"," text = text[1:].strip() \n"," text = text.strip() \n"," return text \n"," \n","def strip_context(text): \n"," text = text.replace('\\n', ' ') \n"," text = re.sub(r'\\s+', ' ', text) \n"," text = text.strip() \n"," return text\n","\n","def check_(x):\n"," x = str(x).lower()\n"," return (x.isnumeric() or \"ngày\" in x or \"tháng\" in x or \"năm\" in x)\n","\n","def find_candidate_ids(x, raw_answer=None, already_added=[], topk=50):\n"," x = str(x)\n"," query = post_process(x).lower().split()\n"," tfidf_query = tfidf_model[dictionary.doc2bow(query)]\n"," scores = bm25_index[tfidf_query]\n"," top_n = list(np.argsort(scores)[::-1][:topk])\n"," top_n = [i for i in top_n if i not in already_added]\n"," # scores = list(scores[top_n])\n"," if raw_answer is not None:\n"," raw_answer = raw_answer.strip()\n"," if raw_answer in entity_dict:\n"," title = entity_dict[raw_answer].replace(\"wiki/\",\"\").replace(\"_\",\" \")\n"," extra_id = title2idx.get(title, -1)\n"," # print((raw_answer,title,extra_id, extra_id not in top_n))\n"," if extra_id != -1 and extra_id not in top_n:\n"," print(f\"Add extra id {extra_id} for {raw_answer}\")\n"," top_n.append(extra_id)\n"," top_n = list(set(top_n))\n"," scores = scores[top_n]\n"," return list(top_n), np.array(scores)"]},{"cell_type":"code","execution_count":8,"metadata":{"execution":{"iopub.execute_input":"2023-06-26T16:20:18.394704Z","iopub.status.busy":"2023-06-26T16:20:18.394284Z","iopub.status.idle":"2023-06-26T16:30:31.484998Z","shell.execute_reply":"2023-06-26T16:30:31.483810Z","shell.execute_reply.started":"2023-06-26T16:20:18.394671Z"},"trusted":true},"outputs":[{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"8cd018dfcf7e4ccc85f93f8bb319f26c","version_major":2,"version_minor":0},"text/plain":["VBox(children=(HBox(children=(IntProgress(value=0, description='0.00%', max=127347), Label(value='0 / 127347')…"]},"metadata":{},"output_type":"display_data"},{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"a13f08c5d7974e1087d598ca8b488840","version_major":2,"version_minor":0},"text/plain":["VBox(children=(HBox(children=(IntProgress(value=0, description='0.00%', max=127347), Label(value='0 / 127347')…"]},"metadata":{},"output_type":"display_data"}],"source":["df_wiki['title_lower'] = df_wiki['title'].apply(lambda x: x.lower()).parallel_apply(post_process)\n","df_wiki['text_lower'] = df_wiki['text'].apply(lambda x: x.lower()).parallel_apply(post_process)"]},{"cell_type":"code","execution_count":9,"metadata":{"execution":{"iopub.execute_input":"2023-06-26T16:33:42.344050Z","iopub.status.busy":"2023-06-26T16:33:42.342811Z","iopub.status.idle":"2023-06-26T16:33:42.362074Z","shell.execute_reply":"2023-06-26T16:33:42.360662Z","shell.execute_reply.started":"2023-06-26T16:33:42.344003Z"},"trusted":true},"outputs":[{"data":{"text/html":["<div>\n","<style scoped>\n"," .dataframe tbody tr th:only-of-type {\n"," vertical-align: middle;\n"," }\n","\n"," .dataframe tbody tr th {\n"," vertical-align: top;\n"," }\n","\n"," .dataframe thead th {\n"," text-align: right;\n"," }\n","</style>\n","<table border=\"1\" class=\"dataframe\">\n"," <thead>\n"," <tr style=\"text-align: right;\">\n"," <th></th>\n"," <th>id</th>\n"," <th>url</th>\n"," <th>title</th>\n"," <th>text</th>\n"," <th>timestamp</th>\n"," <th>revid</th>\n"," <th>title_lower</th>\n"," <th>text_lower</th>\n"," </tr>\n"," </thead>\n"," <tbody>\n"," <tr>\n"," <th>0</th>\n"," <td>2</td>\n"," <td>https://vi.wikipedia.org/wiki?curid=2</td>\n"," <td>Trang Chính</td>\n"," <td>Trang Chính\\n\\n<templatestyles src=\"Wiki2021/s...</td>\n"," <td>2022-05-12 12:46:53+00:00</td>\n"," <td>68591979</td>\n"," <td>trang chính</td>\n"," <td>trang chính templatestyles src wiki2021stylesc...</td>\n"," </tr>\n"," <tr>\n"," <th>1</th>\n"," <td>4</td>\n"," <td>https://vi.wikipedia.org/wiki?curid=4</td>\n"," <td>Internet Society</td>\n"," <td>Internet Society\\n\\nInternet Society hay ISOC ...</td>\n"," <td>2022-01-20 07:59:10+00:00</td>\n"," <td>67988747</td>\n"," <td>internet society</td>\n"," <td>internet society internet society hay isoc là ...</td>\n"," </tr>\n"," <tr>\n"," <th>2</th>\n"," <td>13</td>\n"," <td>https://vi.wikipedia.org/wiki?curid=13</td>\n"," <td>Tiếng Việt</td>\n"," <td>Tiếng Việt\\n\\nTiếng Việt, cũng gọi là tiếng Vi...</td>\n"," <td>2022-05-29 03:42:42+00:00</td>\n"," <td>68660631</td>\n"," <td>tiếng việt</td>\n"," <td>tiếng việt tiếng việt cũng gọi là tiếng việt n...</td>\n"," </tr>\n"," <tr>\n"," <th>3</th>\n"," <td>24</td>\n"," <td>https://vi.wikipedia.org/wiki?curid=24</td>\n"," <td>Ohio</td>\n"," <td>Ohio\\n\\nOhio (viết tắt là OH, viết tắt cũ là O...</td>\n"," <td>2022-04-17 08:15:22+00:00</td>\n"," <td>68482118</td>\n"," <td>ohio</td>\n"," <td>ohio ohio viết tắt là oh viết tắt cũ là o là m...</td>\n"," </tr>\n"," <tr>\n"," <th>4</th>\n"," <td>26</td>\n"," <td>https://vi.wikipedia.org/wiki?curid=26</td>\n"," <td>California</td>\n"," <td>California\\n\\nCalifornia (phát âm như \"Ca-li-p...</td>\n"," <td>2022-06-16 15:27:07+00:00</td>\n"," <td>68738039</td>\n"," <td>california</td>\n"," <td>california california phát âm như caliphótnia ...</td>\n"," </tr>\n"," </tbody>\n","</table>\n","</div>"],"text/plain":[" id url title \\\n","0 2 https://vi.wikipedia.org/wiki?curid=2 Trang Chính \n","1 4 https://vi.wikipedia.org/wiki?curid=4 Internet Society \n","2 13 https://vi.wikipedia.org/wiki?curid=13 Tiếng Việt \n","3 24 https://vi.wikipedia.org/wiki?curid=24 Ohio \n","4 26 https://vi.wikipedia.org/wiki?curid=26 California \n","\n"," text \\\n","0 Trang Chính\\n\\n<templatestyles src=\"Wiki2021/s... \n","1 Internet Society\\n\\nInternet Society hay ISOC ... \n","2 Tiếng Việt\\n\\nTiếng Việt, cũng gọi là tiếng Vi... \n","3 Ohio\\n\\nOhio (viết tắt là OH, viết tắt cũ là O... \n","4 California\\n\\nCalifornia (phát âm như \"Ca-li-p... \n","\n"," timestamp revid title_lower \\\n","0 2022-05-12 12:46:53+00:00 68591979 trang chính \n","1 2022-01-20 07:59:10+00:00 67988747 internet society \n","2 2022-05-29 03:42:42+00:00 68660631 tiếng việt \n","3 2022-04-17 08:15:22+00:00 68482118 ohio \n","4 2022-06-16 15:27:07+00:00 68738039 california \n","\n"," text_lower \n","0 trang chính templatestyles src wiki2021stylesc... \n","1 internet society internet society hay isoc là ... \n","2 tiếng việt tiếng việt cũng gọi là tiếng việt n... \n","3 ohio ohio viết tắt là oh viết tắt cũ là o là m... \n","4 california california phát âm như caliphótnia ... "]},"execution_count":9,"metadata":{},"output_type":"execute_result"}],"source":["df_wiki.head()"]},{"cell_type":"code","execution_count":10,"metadata":{"execution":{"iopub.execute_input":"2023-06-26T16:46:35.539444Z","iopub.status.busy":"2023-06-26T16:46:35.538142Z","iopub.status.idle":"2023-06-26T16:46:38.074928Z","shell.execute_reply":"2023-06-26T16:46:38.073705Z","shell.execute_reply.started":"2023-06-26T16:46:35.539390Z"},"trusted":true},"outputs":[],"source":["title2idx = dict([(x.strip(),y) for x,y in zip(df_wiki.title, df_wiki.index.values)])\n","train = json.load(open(\"/kaggle/input/e2eqa-wiki-zalo-ai/processed/zac2022_train_merged_final.json\"))\n","entity_dict = json.load(open(\"/kaggle/input/e2eqa-wiki-zalo-ai/processed/entities.json\"))"]},{"cell_type":"code","execution_count":19,"metadata":{"execution":{"iopub.execute_input":"2023-06-26T16:55:20.687579Z","iopub.status.busy":"2023-06-26T16:55:20.686344Z","iopub.status.idle":"2023-06-26T16:55:25.068585Z","shell.execute_reply":"2023-06-26T16:55:25.067193Z","shell.execute_reply.started":"2023-06-26T16:55:20.687529Z"},"trusted":true},"outputs":[{"name":"stdout","output_type":"stream","text":["mkdir: cannot create directory ‘/kaggle/working/bm25_stage2’: File exists\n","mkdir: cannot create directory ‘/kaggle/working/bm25_stage2/full_text’: File exists\n"]}],"source":["!mkdir /kaggle/working/bm25_stage2\n","!mkdir /kaggle/working/bm25_stage2/full_text\n","!mkdir /kaggle/working/bm25_stage2/title"]},{"cell_type":"code","execution_count":18,"metadata":{"execution":{"iopub.execute_input":"2023-06-26T16:54:49.241998Z","iopub.status.busy":"2023-06-26T16:54:49.240748Z","iopub.status.idle":"2023-06-26T16:54:52.346235Z","shell.execute_reply":"2023-06-26T16:54:52.345380Z","shell.execute_reply.started":"2023-06-26T16:54:49.241950Z"},"trusted":true},"outputs":[],"source":["corpus = [doc.split() for doc in df_wiki['text_lower']] #simple tokenier\n","dictionary = Dictionary(corpus)\n","bm25_model = OkapiBM25Model(dictionary=dictionary)\n","bm25_corpus = bm25_model[list(map(dictionary.doc2bow, corpus))]\n","bm25_index = SparseMatrixSimilarity(bm25_corpus, num_docs=len(corpus), num_terms=len(dictionary),normalize_queries=False, normalize_documents=False)\n","tfidf_model = TfidfModel(dictionary=dictionary, smartirs='bnn') # Enforce binary weighting of queries\n","dictionary.save(\"/kaggle/working/bm25_stage2/full_text/dict\")\n","tfidf_model.save(\"/kaggle/working/bm25_stage2/full_text/tfidf\")\n","bm25_index.save(\"/kaggle/working/bm25_stage2/full_text/bm25_index\")"]},{"cell_type":"code","execution_count":22,"metadata":{"execution":{"iopub.execute_input":"2023-06-26T16:58:58.741331Z","iopub.status.busy":"2023-06-26T16:58:58.740930Z","iopub.status.idle":"2023-06-26T16:58:59.918024Z","shell.execute_reply":"2023-06-26T16:58:59.916804Z","shell.execute_reply.started":"2023-06-26T16:58:58.741301Z"},"trusted":true},"outputs":[],"source":["corpus = [doc.split() for doc in df_wiki['title_lower']] #simple tokenier\n","dictionary = Dictionary(corpus)\n","bm25_model = OkapiBM25Model(dictionary=dictionary)\n","bm25_corpus = bm25_model[list(map(dictionary.doc2bow, corpus))]\n","bm25_index = SparseMatrixSimilarity(bm25_corpus, num_docs=len(corpus), num_terms=len(dictionary),normalize_queries=False, normalize_documents=False)\n","tfidf_model = TfidfModel(dictionary=dictionary, smartirs='bnn') # Enforce binary weighting of queries\n","dictionary.save(\"/kaggle/working/bm25_stage2/title/dict\")\n","tfidf_model.save(\"/kaggle/working/bm25_stage2/title/tfidf\")\n","bm25_index.save(\"/kaggle/working/bm25_stage2/title/bm25_index\")"]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.10.10"}},"nbformat":4,"nbformat_minor":4}
|
notebooks/1.2-train-pairwise-stage1.ipynb
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"cells":[{"attachments":{},"cell_type":"markdown","metadata":{},"source":["### Kaggle link: https://www.kaggle.com/noobhocai/train-pairwise-stage1"]},{"cell_type":"code","execution_count":1,"metadata":{"execution":{"iopub.execute_input":"2023-06-28T02:52:30.450145Z","iopub.status.busy":"2023-06-28T02:52:30.449601Z","iopub.status.idle":"2023-06-28T02:52:48.306606Z","shell.execute_reply":"2023-06-28T02:52:48.305298Z","shell.execute_reply.started":"2023-06-28T02:52:30.450111Z"},"trusted":true},"outputs":[{"name":"stdout","output_type":"stream","text":["\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n","\u001b[0m"]}],"source":["!pip install sentence_transformers pyvi -q"]},{"cell_type":"code","execution_count":2,"metadata":{"execution":{"iopub.execute_input":"2023-06-28T02:52:48.310777Z","iopub.status.busy":"2023-06-28T02:52:48.309711Z","iopub.status.idle":"2023-06-28T02:53:01.669646Z","shell.execute_reply":"2023-06-28T02:53:01.668372Z","shell.execute_reply.started":"2023-06-28T02:52:48.310744Z"},"trusted":true},"outputs":[{"name":"stdout","output_type":"stream","text":["Collecting tensorflow-io==0.32.0\n"," Downloading tensorflow_io-0.32.0-cp310-cp310-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (28.0 MB)\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m28.0/28.0 MB\u001b[0m \u001b[31m40.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m00:01\u001b[0m00:01\u001b[0m\n","\u001b[?25hCollecting tensorflow-io-gcs-filesystem==0.32.0 (from tensorflow-io==0.32.0)\n"," Downloading tensorflow_io_gcs_filesystem-0.32.0-cp310-cp310-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (2.4 MB)\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m2.4/2.4 MB\u001b[0m \u001b[31m58.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m:00:01\u001b[0m\n","\u001b[?25hInstalling collected packages: tensorflow-io-gcs-filesystem, tensorflow-io\n"," Attempting uninstall: tensorflow-io-gcs-filesystem\n"," Found existing installation: tensorflow-io-gcs-filesystem 0.31.0\n"," Uninstalling tensorflow-io-gcs-filesystem-0.31.0:\n"," Successfully uninstalled tensorflow-io-gcs-filesystem-0.31.0\n"," Attempting uninstall: tensorflow-io\n"," Found existing installation: tensorflow-io 0.31.0\n"," Uninstalling tensorflow-io-0.31.0:\n"," Successfully uninstalled tensorflow-io-0.31.0\n","Successfully installed tensorflow-io-0.32.0 tensorflow-io-gcs-filesystem-0.32.0\n","\u001b[33mWARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv\u001b[0m\u001b[33m\n","\u001b[0m"]}],"source":["!pip install --upgrade tensorflow-io==0.32.0"]},{"cell_type":"code","execution_count":3,"metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","execution":{"iopub.execute_input":"2023-06-28T02:53:01.672246Z","iopub.status.busy":"2023-06-28T02:53:01.671610Z","iopub.status.idle":"2023-06-28T02:53:15.771561Z","shell.execute_reply":"2023-06-28T02:53:15.770593Z","shell.execute_reply.started":"2023-06-28T02:53:01.672210Z"},"trusted":true},"outputs":[],"source":["import os\n","import pandas as pd\n","import json\n","from tqdm.auto import tqdm\n","tqdm.pandas()\n","from transformers import AutoModel, AutoTokenizer\n","import torch\n","from torch.utils.data import DataLoader\n","import pandas as pd\n","from sklearn.metrics.pairwise import cosine_similarity\n","import numpy as np\n","from sentence_transformers import SentenceTransformer\n","from pyvi.ViTokenizer import tokenize\n","from transformers import AutoTokenizer, AdamW, get_linear_schedule_with_warmup\n","from transformers import DataCollatorWithPadding\n","from scipy.stats import pearsonr, spearmanr\n","import math\n","from sklearn.metrics import *"]},{"cell_type":"code","execution_count":4,"metadata":{"execution":{"iopub.execute_input":"2023-06-28T02:53:15.775041Z","iopub.status.busy":"2023-06-28T02:53:15.774278Z","iopub.status.idle":"2023-06-28T02:53:15.780313Z","shell.execute_reply":"2023-06-28T02:53:15.778919Z","shell.execute_reply.started":"2023-06-28T02:53:15.774985Z"},"trusted":true},"outputs":[],"source":["AUTH_TOKEN = \"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\""]},{"cell_type":"code","execution_count":5,"metadata":{"execution":{"iopub.execute_input":"2023-06-28T02:53:15.782302Z","iopub.status.busy":"2023-06-28T02:53:15.781713Z","iopub.status.idle":"2023-06-28T02:53:18.884084Z","shell.execute_reply":"2023-06-28T02:53:18.882908Z","shell.execute_reply.started":"2023-06-28T02:53:15.782268Z"},"trusted":true},"outputs":[{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"6118765cb5854ac7b8f4c68eb0c654a2","version_major":2,"version_minor":0},"text/plain":["Downloading (…)okenizer_config.json: 0%| | 0.00/398 [00:00<?, ?B/s]"]},"metadata":{},"output_type":"display_data"},{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"9d4cfe6e1330443eb6775a558657bbfb","version_major":2,"version_minor":0},"text/plain":["Downloading (…)/main/tokenizer.json: 0%| | 0.00/9.08M [00:00<?, ?B/s]"]},"metadata":{},"output_type":"display_data"},{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"cf5607811ef54e528e24d6a66eceb758","version_major":2,"version_minor":0},"text/plain":["Downloading (…)cial_tokens_map.json: 0%| | 0.00/239 [00:00<?, ?B/s]"]},"metadata":{},"output_type":"display_data"},{"name":"stdout","output_type":"stream","text":["<s> sinh viên đại học khoa học tự nhiên</s>\n"]}],"source":["tokenizer = AutoTokenizer.from_pretrained('nguyenvulebinh/vi-mrc-base', use_auth_token=AUTH_TOKEN)\n","print(tokenizer.decode(tokenizer.encode(\"sinh viên đại học khoa học tự nhiên\")))"]},{"cell_type":"code","execution_count":6,"metadata":{"execution":{"iopub.execute_input":"2023-06-28T02:53:18.886122Z","iopub.status.busy":"2023-06-28T02:53:18.885497Z","iopub.status.idle":"2023-06-28T02:53:18.897285Z","shell.execute_reply":"2023-06-28T02:53:18.896274Z","shell.execute_reply.started":"2023-06-28T02:53:18.886088Z"},"trusted":true},"outputs":[],"source":["import json \n","from glob import glob \n","import re \n","from nltk import word_tokenize as lib_tokenizer \n"," \n","dict_map = dict({}) \n"," \n","def word_tokenize(text): \n"," global dict_map \n"," words = text.split() \n"," words_norm = [] \n"," for w in words: \n"," if dict_map.get(w, None) is None: \n"," dict_map[w] = ' '.join(lib_tokenizer(w)).replace('``', '\"').replace(\"''\", '\"') \n"," words_norm.append(dict_map[w]) \n"," return words_norm \n"," \n","def strip_answer_string(text): \n"," text = text.strip() \n"," while text[-1] in '.,/><;:\\'\"[]{}+=-_)(*&^!~`': \n"," if text[0] != '(' and text[-1] == ')' and '(' in text: \n"," break \n"," if text[-1] == '\"' and text[0] != '\"' and text.count('\"') > 1: \n"," break \n"," text = text[:-1].strip() \n"," while text[0] in '.,/><;:\\'\"[]{}+=-_)(*&^!~`': \n"," if text[0] == '\"' and text[-1] != '\"' and text.count('\"') > 1: \n"," break \n"," text = text[1:].strip() \n"," text = text.strip() \n"," return text \n"," \n","def strip_context(text): \n"," text = text.replace('\\n', ' ') \n"," text = re.sub(r'\\s+', ' ', text) \n"," text = text.strip() \n"," return text"]},{"cell_type":"code","execution_count":7,"metadata":{"execution":{"iopub.execute_input":"2023-06-28T02:53:18.899048Z","iopub.status.busy":"2023-06-28T02:53:18.898414Z","iopub.status.idle":"2023-06-28T02:53:28.963083Z","shell.execute_reply":"2023-06-28T02:53:28.962126Z","shell.execute_reply.started":"2023-06-28T02:53:18.899002Z"},"trusted":true},"outputs":[],"source":["train1 = pd.read_csv(\"/kaggle/input/e2eqa-wiki-zalo-ai/processed/train_stage1_ranking.csv\")\n","train1['text'] = train1['text'].apply(lambda x: \" \".join(word_tokenize(strip_context(x))))\n","train1['question'] = train1['question'].apply(lambda x: \" \".join(word_tokenize(strip_context(x))))\n","df = train1"]},{"cell_type":"code","execution_count":8,"metadata":{"execution":{"iopub.execute_input":"2023-06-28T02:53:28.965037Z","iopub.status.busy":"2023-06-28T02:53:28.964656Z","iopub.status.idle":"2023-06-28T02:53:28.976243Z","shell.execute_reply":"2023-06-28T02:53:28.974943Z","shell.execute_reply.started":"2023-06-28T02:53:28.964989Z"},"trusted":true},"outputs":[],"source":["import torch.nn as nn\n","from transformers import AutoModel, AutoConfig\n","\n","class MeanPooling(nn.Module):\n"," def __init__(self):\n"," super(MeanPooling, self).__init__()\n","\n"," def forward(self, last_hidden_state, attention_mask):\n"," input_mask_expanded = attention_mask.unsqueeze(-1).expand(last_hidden_state.size()).float()\n"," sum_embeddings = torch.sum(last_hidden_state * input_mask_expanded, 1)\n"," sum_mask = input_mask_expanded.sum(1)\n"," sum_mask = torch.clamp(sum_mask, min=1e-9)\n"," mean_embeddings = sum_embeddings / sum_mask\n"," return mean_embeddings\n","\n","class PairwiseModel(nn.Module):\n"," def __init__(self, model_name):\n"," super(PairwiseModel, self).__init__()\n"," self.model = AutoModel.from_pretrained(model_name, use_auth_token=AUTH_TOKEN)\n"," self.config = AutoConfig.from_pretrained(model_name, use_auth_token=AUTH_TOKEN)\n"," self.drop = nn.Dropout(p=0.2)\n"," self.fc = nn.Linear(768, 1)\n"," \n"," def forward(self, ids, masks):\n"," out = self.model(input_ids=ids,\n"," attention_mask=masks,\n"," output_hidden_states=False).last_hidden_state\n"," out = out[:,0]\n"," outputs = self.fc(out)\n"," return outputs"]},{"cell_type":"code","execution_count":9,"metadata":{"execution":{"iopub.execute_input":"2023-06-28T02:53:28.978164Z","iopub.status.busy":"2023-06-28T02:53:28.977797Z","iopub.status.idle":"2023-06-28T02:53:28.990859Z","shell.execute_reply":"2023-06-28T02:53:28.989964Z","shell.execute_reply.started":"2023-06-28T02:53:28.978133Z"},"trusted":true},"outputs":[],"source":["from torch.utils.data import Dataset\n","\n","class SiameseDataset(Dataset):\n","\n"," def __init__(self, df, tokenizer, max_length):\n"," self.df = df\n"," self.max_length = max_length\n"," self.tokenizer = tokenizer\n"," self.content1 = tokenizer.batch_encode_plus(list(df.question.apply(lambda x: x.replace(\"_\",\" \")).values), max_length=max_length, truncation=True)[\"input_ids\"]\n"," self.content2 = tokenizer.batch_encode_plus(list(df.text.apply(lambda x: x.replace(\"_\",\" \")).values), max_length=max_length, truncation=True)[\"input_ids\"]\n"," self.targets = self.df.label\n"," \n"," def __len__(self):\n"," return len(self.df)\n","\n"," def __getitem__(self, index):\n"," return {\n"," 'ids1': torch.tensor(self.content1[index], dtype=torch.long),\n"," 'ids2': torch.tensor(self.content2[index][1:], dtype=torch.long),\n"," 'target': torch.tensor(self.targets[index], dtype=torch.float)\n"," }"]},{"cell_type":"code","execution_count":10,"metadata":{"execution":{"iopub.execute_input":"2023-06-28T02:53:28.995179Z","iopub.status.busy":"2023-06-28T02:53:28.994892Z","iopub.status.idle":"2023-06-28T02:53:29.004203Z","shell.execute_reply":"2023-06-28T02:53:29.003189Z","shell.execute_reply.started":"2023-06-28T02:53:28.995156Z"},"trusted":true},"outputs":[],"source":["pad_token_id = tokenizer.pad_token_id\n","def collate_fn(batch):\n"," ids = [torch.cat([x[\"ids1\"], x[\"ids2\"]]) for x in batch]\n"," targets = [x[\"target\"] for x in batch]\n"," max_len = np.max([len(x) for x in ids])\n"," masks = []\n"," for i in range(len(ids)):\n"," if len(ids[i]) < max_len:\n"," ids[i]= torch.cat((ids[i], torch.tensor([pad_token_id,]*(max_len - len(ids[i])),dtype=torch.long)))\n"," masks.append(ids[i] != pad_token_id)\n"," # print(tokenizer.decode(ids[0]))\n"," outputs = {\n"," \"ids\": torch.vstack(ids),\n"," \"masks\": torch.vstack(masks),\n"," \"target\": torch.vstack(targets).view(-1)\n"," }\n"," return outputs"]},{"cell_type":"code","execution_count":11,"metadata":{"execution":{"iopub.execute_input":"2023-06-28T02:53:29.006085Z","iopub.status.busy":"2023-06-28T02:53:29.005583Z","iopub.status.idle":"2023-06-28T02:53:29.013002Z","shell.execute_reply":"2023-06-28T02:53:29.011919Z","shell.execute_reply.started":"2023-06-28T02:53:29.006052Z"},"trusted":true},"outputs":[],"source":["from sklearn.model_selection import GroupKFold, KFold"]},{"cell_type":"code","execution_count":12,"metadata":{"execution":{"iopub.execute_input":"2023-06-28T02:53:29.014999Z","iopub.status.busy":"2023-06-28T02:53:29.014493Z","iopub.status.idle":"2023-06-28T02:53:29.023324Z","shell.execute_reply":"2023-06-28T02:53:29.022211Z","shell.execute_reply.started":"2023-06-28T02:53:29.014969Z"},"trusted":true},"outputs":[],"source":["def optimizer_scheduler(model, num_train_steps):\n"," param_optimizer = list(model.named_parameters())\n"," no_decay = [\"bias\", \"LayerNorm.weight\"]\n"," optimizer_parameters = [\n"," {\n"," \"params\": [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)],\n"," \"weight_decay\": 0.001,\n"," },\n"," {\n"," \"params\": [p for n, p in param_optimizer if any(nd in n for nd in no_decay)],\n"," \"weight_decay\": 0.0,\n"," },\n"," ]\n","\n"," opt = AdamW(optimizer_parameters, lr=3e-5)\n"," sch = get_linear_schedule_with_warmup(\n"," opt,\n"," num_warmup_steps=int(0.05*num_train_steps),\n"," num_training_steps=num_train_steps,\n"," last_epoch=-1,\n"," )\n"," return opt, sch"]},{"cell_type":"code","execution_count":13,"metadata":{"execution":{"iopub.execute_input":"2023-06-28T02:53:29.025531Z","iopub.status.busy":"2023-06-28T02:53:29.025091Z","iopub.status.idle":"2023-06-28T02:53:29.036112Z","shell.execute_reply":"2023-06-28T02:53:29.034921Z","shell.execute_reply.started":"2023-06-28T02:53:29.025496Z"},"trusted":true},"outputs":[],"source":["from sklearn.model_selection import KFold\n","kfold = KFold(n_splits=5, shuffle=True, random_state=42)"]},{"cell_type":"code","execution_count":14,"metadata":{"execution":{"iopub.execute_input":"2023-06-28T02:53:29.038723Z","iopub.status.busy":"2023-06-28T02:53:29.037722Z","iopub.status.idle":"2023-06-28T04:54:29.777596Z","shell.execute_reply":"2023-06-28T04:54:29.776341Z","shell.execute_reply.started":"2023-06-28T02:53:29.038691Z"},"trusted":true},"outputs":[{"name":"stdout","output_type":"stream","text":["[ 3 6 17 ... 20845 20850 20855]\n"]},{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"f0f58e6b09914620903bd80dae3eca59","version_major":2,"version_minor":0},"text/plain":["Downloading (…)lve/main/config.json: 0%| | 0.00/688 [00:00<?, ?B/s]"]},"metadata":{},"output_type":"display_data"},{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"2b7bfe1d5b504e8f8ec03f19cd7bfba5","version_major":2,"version_minor":0},"text/plain":["Downloading pytorch_model.bin: 0%| | 0.00/1.11G [00:00<?, ?B/s]"]},"metadata":{},"output_type":"display_data"},{"name":"stderr","output_type":"stream","text":["Some weights of the model checkpoint at nguyenvulebinh/vi-mrc-base were not used when initializing RobertaModel: ['qa_outputs.weight', 'qa_outputs.bias']\n","- This IS expected if you are initializing RobertaModel from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForSequenceClassification model from a BertForPreTraining model).\n","- This IS NOT expected if you are initializing RobertaModel from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model).\n","Some weights of RobertaModel were not initialized from the model checkpoint at nguyenvulebinh/vi-mrc-base and are newly initialized: ['roberta.pooler.dense.weight', 'roberta.pooler.dense.bias']\n","You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.\n","/opt/conda/lib/python3.10/site-packages/transformers/optimization.py:411: FutureWarning: This implementation of AdamW is deprecated and will be removed in a future version. Use the PyTorch implementation torch.optim.AdamW instead, or set `no_deprecation_warning=True` to disable this warning\n"," warnings.warn(\n"]},{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"3a999992c57e44838063b744088409f8","version_major":2,"version_minor":0},"text/plain":[" 0%| | 0/5 [00:00<?, ?it/s]"]},"metadata":{},"output_type":"display_data"},{"name":"stdout","output_type":"stream","text":["huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...\n","To disable this warning, you can either:\n","\t- Avoid using `tokenizers` before the fork if possible\n","\t- Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)\n","huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...\n","To disable this warning, you can either:\n","\t- Avoid using `tokenizers` before the fork if possible\n","\t- Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)\n"]},{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"","version_major":2,"version_minor":0},"text/plain":[" 0%| | 0/5214 [00:00<?, ?it/s]"]},"metadata":{},"output_type":"display_data"},{"name":"stdout","output_type":"stream","text":["huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...\n","To disable this warning, you can either:\n","\t- Avoid using `tokenizers` before the fork if possible\n","\t- Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)\n","huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...\n","To disable this warning, you can either:\n","\t- Avoid using `tokenizers` before the fork if possible\n","\t- Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)\n"]},{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"","version_major":2,"version_minor":0},"text/plain":[" 0%| | 0/131 [00:00<?, ?it/s]"]},"metadata":{},"output_type":"display_data"},{"name":"stdout","output_type":"stream","text":["F1 0.9280047017337644\n","huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...\n","To disable this warning, you can either:\n","\t- Avoid using `tokenizers` before the fork if possible\n","\t- Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)\n","huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...\n","To disable this warning, you can either:\n","\t- Avoid using `tokenizers` before the fork if possible\n","\t- Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)\n"]},{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"","version_major":2,"version_minor":0},"text/plain":[" 0%| | 0/5214 [00:00<?, ?it/s]"]},"metadata":{},"output_type":"display_data"},{"name":"stdout","output_type":"stream","text":["huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...\n","To disable this warning, you can either:\n","\t- Avoid using `tokenizers` before the fork if possible\n","\t- Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)\n","huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...\n","To disable this warning, you can either:\n","\t- Avoid using `tokenizers` before the fork if possible\n","\t- Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)\n"]},{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"","version_major":2,"version_minor":0},"text/plain":[" 0%| | 0/131 [00:00<?, ?it/s]"]},"metadata":{},"output_type":"display_data"},{"name":"stdout","output_type":"stream","text":["F1 0.9665513264129183\n","huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...\n","To disable this warning, you can either:\n","\t- Avoid using `tokenizers` before the fork if possible\n","\t- Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)\n","huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...\n","To disable this warning, you can either:\n","\t- Avoid using `tokenizers` before the fork if possible\n","\t- Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)\n"]},{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"","version_major":2,"version_minor":0},"text/plain":[" 0%| | 0/5214 [00:00<?, ?it/s]"]},"metadata":{},"output_type":"display_data"},{"name":"stdout","output_type":"stream","text":["huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...\n","To disable this warning, you can either:\n","\t- Avoid using `tokenizers` before the fork if possible\n","\t- Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)\n","huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...\n","To disable this warning, you can either:\n","\t- Avoid using `tokenizers` before the fork if possible\n","\t- Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)\n"]},{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"","version_major":2,"version_minor":0},"text/plain":[" 0%| | 0/131 [00:00<?, ?it/s]"]},"metadata":{},"output_type":"display_data"},{"name":"stdout","output_type":"stream","text":["F1 0.9868613138686132\n","huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...\n","To disable this warning, you can either:\n","\t- Avoid using `tokenizers` before the fork if possible\n","\t- Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)\n","huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...\n","To disable this warning, you can either:\n","\t- Avoid using `tokenizers` before the fork if possible\n","\t- Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)\n"]},{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"","version_major":2,"version_minor":0},"text/plain":[" 0%| | 0/5214 [00:00<?, ?it/s]"]},"metadata":{},"output_type":"display_data"},{"name":"stdout","output_type":"stream","text":["huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...\n","To disable this warning, you can either:\n","\t- Avoid using `tokenizers` before the fork if possible\n","\t- Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)\n","huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...\n","To disable this warning, you can either:\n","\t- Avoid using `tokenizers` before the fork if possible\n","\t- Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)\n"]},{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"","version_major":2,"version_minor":0},"text/plain":[" 0%| | 0/131 [00:00<?, ?it/s]"]},"metadata":{},"output_type":"display_data"},{"name":"stdout","output_type":"stream","text":["F1 0.9889341875364007\n","huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...\n","To disable this warning, you can either:\n","\t- Avoid using `tokenizers` before the fork if possible\n","\t- Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)\n","huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...\n","To disable this warning, you can either:\n","\t- Avoid using `tokenizers` before the fork if possible\n","\t- Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)\n"]},{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"","version_major":2,"version_minor":0},"text/plain":[" 0%| | 0/5214 [00:00<?, ?it/s]"]},"metadata":{},"output_type":"display_data"},{"name":"stdout","output_type":"stream","text":["To disable this warning, you can either:\n","\t- Avoid using `tokenizers` before the fork if possible\n","\t- Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)\n","huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...\n","To disable this warning, you can either:\n","\t- Avoid using `tokenizers` before the fork if possible\n","\t- Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)\n","huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...\n","To disable this warning, you can either:\n","\t- Avoid using `tokenizers` before the fork if possible\n","\t- Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)\n"]},{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"","version_major":2,"version_minor":0},"text/plain":[" 0%| | 0/131 [00:00<?, ?it/s]"]},"metadata":{},"output_type":"display_data"},{"name":"stdout","output_type":"stream","text":["F1 0.9926921952645424\n"]}],"source":["from tqdm.auto import tqdm\n","loss_fn = nn.BCEWithLogitsLoss()\n","epochs = 5\n","accumulation_steps = 8\n","scaler = torch.cuda.amp.GradScaler()\n","error_ids = None\n","for fold, (train_index, test_index) in enumerate(kfold.split(df, df.label)):\n"," if fold != 0:\n"," break\n"," print(test_index)\n"," model = PairwiseModel('nguyenvulebinh/vi-mrc-base')\n"," # model.load_state_dict(torch.load(f\"./outputs/pairwise_v2.bin\"))\n"," model.cuda()\n"," train_df = df\n"," # train_df = df.iloc[train_index].reset_index(drop=True)\n"," val_df = df.iloc[test_index].reset_index(drop=True)\n"," \n"," train_dataset = SiameseDataset(train_df, tokenizer, 384)\n"," valid_dataset = SiameseDataset(val_df, tokenizer, 384)\n"," train_loader = DataLoader(train_dataset, batch_size=4, collate_fn=collate_fn,\n"," num_workers=2, shuffle=True, pin_memory=True, drop_last=True)\n"," valid_loader = DataLoader(valid_dataset, batch_size=32, collate_fn=collate_fn,\n"," num_workers=2, shuffle=False, pin_memory=True)\n"," \n"," num_train_steps = len(train_loader) * epochs // accumulation_steps\n"," optimizer, scheduler = optimizer_scheduler(model, num_train_steps)\n"," \n"," for epoch in tqdm(range(epochs)):\n"," model.train()\n"," bar = tqdm(enumerate(train_loader), total=len(train_loader), leave=False)\n"," for step, data in bar:\n"," ids = data[\"ids\"].cuda()\n"," # for x in ids:\n"," # print(tokenizer.decode(x))\n"," masks = data[\"masks\"].cuda()\n"," target = data[\"target\"].cuda()\n"," # with torch.cuda.amp.autocast():\n"," preds = model(ids, masks)\n"," # print(preds.view(-1))\n"," loss = loss_fn(preds.view(-1), target.view(-1))\n"," loss /= accumulation_steps\n"," loss.backward()\n"," if (step + 1) % accumulation_steps == 0:\n"," optimizer.step()\n"," # scaler.update()\n"," optimizer.zero_grad()\n"," scheduler.step()\n"," bar.set_postfix(loss=loss.item())\n","\n"," model.eval()\n"," with torch.no_grad():\n"," bar = tqdm(enumerate(valid_loader), total=len(valid_loader), leave=False)\n"," targets = []\n"," all_preds = []\n"," for step, data in bar:\n"," ids = data[\"ids\"].cuda()\n"," masks = data[\"masks\"].cuda()\n"," target = data[\"target\"].cuda()\n"," preds = torch.sigmoid(model(ids, masks))\n"," all_preds.extend(preds.cpu().view(-1).numpy())\n"," targets.extend(target.cpu().view(-1).numpy())\n"," all_preds = np.array(all_preds)\n"," targets = np.array(targets)\n"," print(f\"F1 {f1_score(targets, all_preds > 0.5)}\")"]},{"cell_type":"code","execution_count":15,"metadata":{"execution":{"iopub.execute_input":"2023-06-28T04:54:29.780731Z","iopub.status.busy":"2023-06-28T04:54:29.779924Z","iopub.status.idle":"2023-06-28T04:54:29.791869Z","shell.execute_reply":"2023-06-28T04:54:29.790613Z","shell.execute_reply.started":"2023-06-28T04:54:29.780691Z"},"trusted":true},"outputs":[{"name":"stdout","output_type":"stream","text":["F1 0.9953106682297772\n"]}],"source":["print(f\"F1 {recall_score(np.array(targets), np.array(all_preds) > 0.5)}\")"]},{"cell_type":"code","execution_count":16,"metadata":{"execution":{"iopub.execute_input":"2023-06-28T04:54:29.796171Z","iopub.status.busy":"2023-06-28T04:54:29.795752Z","iopub.status.idle":"2023-06-28T04:54:31.811461Z","shell.execute_reply":"2023-06-28T04:54:31.810427Z","shell.execute_reply.started":"2023-06-28T04:54:29.796143Z"},"trusted":true},"outputs":[],"source":["torch.save(model.state_dict(), f\"/kaggle/working/pairwise_v2.bin\")\n"]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.10.10"}},"nbformat":4,"nbformat_minor":4}
|
notebooks/1.3-train-pairwise-stage2.ipynb
ADDED
The diff for this file is too large to render.
See raw diff
|
|
notebooks/1.4-robust-qa-model.ipynb
ADDED
The diff for this file is too large to render.
See raw diff
|
|
requirements.txt
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# local package
|
2 |
+
-e .
|
3 |
+
|
4 |
+
# external requirements
|
5 |
+
streamlit==1.24.0
|
6 |
+
transformers==4.24.0
|
7 |
+
git+https://github.com/witiko/gensim.git@feature/bm25
|
src/app.py
ADDED
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
from models.predict_model import *
|
3 |
+
|
4 |
+
with st.sidebar:
|
5 |
+
st.write("# 🤖 Language Models")
|
6 |
+
"[](https://github.com/Foxxy-HCMUS/e2eqa)"
|
7 |
+
|
8 |
+
st.title("💬 Question-Answering System")
|
9 |
+
if "messages" not in st.session_state:
|
10 |
+
st.session_state["messages"] = [{"role": "assistant", "content": "How can I help you?"}]
|
11 |
+
|
12 |
+
for msg in st.session_state.messages:
|
13 |
+
st.chat_message(msg["role"]).write(msg["content"])
|
14 |
+
|
15 |
+
if prompt := st.chat_input():
|
16 |
+
|
17 |
+
st.session_state.messages.append({"role": "user", "content": prompt})
|
18 |
+
st.chat_message("user").write(prompt)
|
19 |
+
msg = {
|
20 |
+
"role": "assistant",
|
21 |
+
"content": get_answer_e2e(prompt)
|
22 |
+
}
|
23 |
+
st.session_state.messages.append(msg)
|
24 |
+
st.chat_message("assistant").write(msg["content"])
|
25 |
+
|
26 |
+
|
src/features/graph_utils.py
ADDED
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import networkx as nx
|
2 |
+
import numpy as np
|
3 |
+
from cdlib import algorithms
|
4 |
+
|
5 |
+
|
6 |
+
# these functions are heavily influenced by the HF squad_metrics.py script
|
7 |
+
def normalize_text(s):
|
8 |
+
"""Removing articles and punctuation, and standardizing whitespace are all typical text processing steps."""
|
9 |
+
import string, re
|
10 |
+
|
11 |
+
def remove_articles(text):
|
12 |
+
regex = re.compile(r"\b(a|an|the)\b", re.UNICODE)
|
13 |
+
return re.sub(regex, " ", text)
|
14 |
+
|
15 |
+
def white_space_fix(text):
|
16 |
+
return " ".join(text.split())
|
17 |
+
|
18 |
+
def remove_punc(text):
|
19 |
+
exclude = set(string.punctuation)
|
20 |
+
return "".join(ch for ch in text if ch not in exclude)
|
21 |
+
|
22 |
+
def lower(text):
|
23 |
+
return text.lower()
|
24 |
+
|
25 |
+
return white_space_fix(remove_articles(remove_punc(lower(s))))
|
26 |
+
|
27 |
+
|
28 |
+
def compute_exact_match(prediction, truth):
|
29 |
+
return int(normalize_text(prediction) == normalize_text(truth))
|
30 |
+
|
31 |
+
|
32 |
+
def compute_f1(prediction, truth):
|
33 |
+
pred_tokens = normalize_text(prediction).split()
|
34 |
+
truth_tokens = normalize_text(truth).split()
|
35 |
+
|
36 |
+
# if either the prediction or the truth is no-answer then f1 = 1 if they agree, 0 otherwise
|
37 |
+
if len(pred_tokens) == 0 or len(truth_tokens) == 0:
|
38 |
+
return int(pred_tokens == truth_tokens)
|
39 |
+
|
40 |
+
common_tokens = set(pred_tokens) & set(truth_tokens)
|
41 |
+
|
42 |
+
# if there are no common tokens then f1 = 0
|
43 |
+
if len(common_tokens) == 0:
|
44 |
+
return 0
|
45 |
+
|
46 |
+
prec = len(common_tokens) / len(pred_tokens)
|
47 |
+
rec = len(common_tokens) / len(truth_tokens)
|
48 |
+
|
49 |
+
return 2 * (prec * rec) / (prec + rec)
|
50 |
+
|
51 |
+
|
52 |
+
def is_date_or_num(answer):
|
53 |
+
answer = answer.lower().split()
|
54 |
+
for w in answer:
|
55 |
+
w = w.strip()
|
56 |
+
if w.isnumeric() or w in ["ngày", "tháng", "năm"]:
|
57 |
+
return True
|
58 |
+
return False
|
59 |
+
|
60 |
+
|
61 |
+
def find_best_cluster(answers, best_answer, thr=0.79):
|
62 |
+
if len(answers) == 0: # or best_answer not in answers:
|
63 |
+
return best_answer
|
64 |
+
elif len(answers) == 1:
|
65 |
+
return answers[0]
|
66 |
+
dists = np.zeros((len(answers), len(answers)))
|
67 |
+
for i in range(len(answers) - 1):
|
68 |
+
for j in range(i + 1, len(answers)):
|
69 |
+
a1 = answers[i].lower().strip()
|
70 |
+
a2 = answers[j].lower().strip()
|
71 |
+
if is_date_or_num(a1) or is_date_or_num(a2):
|
72 |
+
# print(a1, a2)
|
73 |
+
if a1 == a2 or ("tháng" in a1 and a1 in a2) or ("tháng" in a2 and a2 in a1):
|
74 |
+
dists[i, j] = 1
|
75 |
+
dists[j, i] = 1
|
76 |
+
# continue
|
77 |
+
elif a1 == a2 or (a1 in a2) or (a2 in a1) or compute_f1(a1.lower(), a2.lower()) >= thr:
|
78 |
+
dists[i, j] = 1
|
79 |
+
dists[j, i] = 1
|
80 |
+
# print(dists)
|
81 |
+
try:
|
82 |
+
thr = 1
|
83 |
+
dups = np.where(dists >= thr)
|
84 |
+
dup_strs = []
|
85 |
+
edges = []
|
86 |
+
for i, j in zip(dups[0], dups[1]):
|
87 |
+
if i != j:
|
88 |
+
edges.append((i, j))
|
89 |
+
G = nx.Graph()
|
90 |
+
for i, answer in enumerate(answers):
|
91 |
+
G.add_node(i, content=answer)
|
92 |
+
G.add_edges_from(edges)
|
93 |
+
partition = algorithms.louvain(G)
|
94 |
+
max_len_comm = np.max([len(x) for x in partition.communities])
|
95 |
+
best_comms = []
|
96 |
+
for comm in partition.communities:
|
97 |
+
# print([answers[i] for i in comm])
|
98 |
+
if len(comm) == max_len_comm:
|
99 |
+
best_comms.append([answers[i] for i in comm])
|
100 |
+
# if len(best_comms) > 1:
|
101 |
+
# return best_answer
|
102 |
+
for comm in best_comms:
|
103 |
+
if best_answer in comm:
|
104 |
+
return best_answer
|
105 |
+
mid = len(best_comms[0]) // 2
|
106 |
+
# print(mid, sorted(best_comms[0], key = len))
|
107 |
+
return sorted(best_comms[0], key=len)[mid]
|
108 |
+
except Exception as e:
|
109 |
+
print(e, "Disconnected graph")
|
110 |
+
return best_answer
|
src/features/text_utils.py
ADDED
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
from glob import glob
|
3 |
+
import re
|
4 |
+
from nltk import word_tokenize as lib_tokenizer
|
5 |
+
import string
|
6 |
+
|
7 |
+
|
8 |
+
def preprocess(x, max_length=-1, remove_puncts=False):
|
9 |
+
x = nltk_tokenize(x)
|
10 |
+
x = x.replace("\n", " ")
|
11 |
+
if remove_puncts:
|
12 |
+
x = "".join([i for i in x if i not in string.punctuation])
|
13 |
+
if max_length > 0:
|
14 |
+
x = " ".join(x.split()[:max_length])
|
15 |
+
return x
|
16 |
+
|
17 |
+
|
18 |
+
def nltk_tokenize(x):
|
19 |
+
return " ".join(word_tokenize(strip_context(x))).strip()
|
20 |
+
|
21 |
+
|
22 |
+
def post_process_answer(x, entity_dict):
|
23 |
+
if type(x) is not str:
|
24 |
+
return x
|
25 |
+
try:
|
26 |
+
x = strip_answer_string(x)
|
27 |
+
except:
|
28 |
+
return "NaN"
|
29 |
+
x = "".join([c for c in x if c not in string.punctuation])
|
30 |
+
x = " ".join(x.split())
|
31 |
+
y = x.lower()
|
32 |
+
if len(y) > 1 and y.split()[0].isnumeric() and ("tháng" not in x):
|
33 |
+
return y.split()[0]
|
34 |
+
if not (x.isnumeric() or "ngày" in x or "tháng" in x or "năm" in x):
|
35 |
+
if len(x.split()) <= 2:
|
36 |
+
return entity_dict.get(x.lower(), x)
|
37 |
+
else:
|
38 |
+
return x
|
39 |
+
else:
|
40 |
+
return y
|
41 |
+
|
42 |
+
|
43 |
+
dict_map = dict({})
|
44 |
+
|
45 |
+
|
46 |
+
def word_tokenize(text):
|
47 |
+
global dict_map
|
48 |
+
words = text.split()
|
49 |
+
words_norm = []
|
50 |
+
for w in words:
|
51 |
+
if dict_map.get(w, None) is None:
|
52 |
+
dict_map[w] = ' '.join(lib_tokenizer(w)).replace('``', '"').replace("''", '"')
|
53 |
+
words_norm.append(dict_map[w])
|
54 |
+
return words_norm
|
55 |
+
|
56 |
+
|
57 |
+
def strip_answer_string(text):
|
58 |
+
text = text.strip()
|
59 |
+
while text[-1] in '.,/><;:\'"[]{}+=-_)(*&^!~`':
|
60 |
+
if text[0] != '(' and text[-1] == ')' and '(' in text:
|
61 |
+
break
|
62 |
+
if text[-1] == '"' and text[0] != '"' and text.count('"') > 1:
|
63 |
+
break
|
64 |
+
text = text[:-1].strip()
|
65 |
+
while text[0] in '.,/><;:\'"[]{}+=-_)(*&^!~`':
|
66 |
+
if text[0] == '"' and text[-1] != '"' and text.count('"') > 1:
|
67 |
+
break
|
68 |
+
text = text[1:].strip()
|
69 |
+
text = text.strip()
|
70 |
+
return text
|
71 |
+
|
72 |
+
|
73 |
+
def strip_context(text):
|
74 |
+
text = text.replace('\n', ' ')
|
75 |
+
text = re.sub(r'\s+', ' ', text)
|
76 |
+
text = text.strip()
|
77 |
+
return text
|
78 |
+
|
79 |
+
|
80 |
+
def check_number(x):
|
81 |
+
x = str(x).lower()
|
82 |
+
return (x.isnumeric() or "ngày" in x or "tháng" in x or "năm" in x)
|
src/models/bm25_utils.py
ADDED
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
from tqdm.auto import tqdm
|
3 |
+
|
4 |
+
tqdm.pandas()
|
5 |
+
from gensim.corpora import Dictionary
|
6 |
+
from gensim.models import TfidfModel
|
7 |
+
from gensim.similarities import SparseMatrixSimilarity
|
8 |
+
from features.text_utils import preprocess
|
9 |
+
|
10 |
+
|
11 |
+
class BM25Gensim:
|
12 |
+
def __init__(self, checkpoint_path, entity_dict, title2idx):
|
13 |
+
self.dictionary = Dictionary.load(checkpoint_path + "/dict")
|
14 |
+
self.tfidf_model = SparseMatrixSimilarity.load(checkpoint_path + "/tfidf")
|
15 |
+
self.bm25_index = TfidfModel.load(checkpoint_path + "/bm25_index")
|
16 |
+
self.title2idx = title2idx
|
17 |
+
self.entity_dict = entity_dict
|
18 |
+
|
19 |
+
def get_topk_stage1(self, query, topk=100):
|
20 |
+
tokenized_query = query.split()
|
21 |
+
tfidf_query = self.tfidf_model[self.dictionary.doc2bow(tokenized_query)]
|
22 |
+
scores = self.bm25_index[tfidf_query]
|
23 |
+
top_n = np.argsort(scores)[::-1][:topk]
|
24 |
+
return top_n, scores[top_n]
|
25 |
+
|
26 |
+
def get_topk_stage2(self, x, raw_answer=None, topk=50):
|
27 |
+
x = str(x)
|
28 |
+
query = preprocess(x, max_length=128).lower().split()
|
29 |
+
tfidf_query = self.tfidf_model[self.dictionary.doc2bow(query)]
|
30 |
+
scores = self.bm25_index[tfidf_query]
|
31 |
+
top_n = list(np.argsort(scores)[::-1][:topk])
|
32 |
+
if raw_answer is not None:
|
33 |
+
raw_answer = raw_answer.strip()
|
34 |
+
if raw_answer in self.entity_dict:
|
35 |
+
title = self.entity_dict[raw_answer].replace("wiki/", "").replace("_", " ")
|
36 |
+
extra_id = self.title2idx.get(title, -1)
|
37 |
+
if extra_id != -1 and extra_id not in top_n:
|
38 |
+
top_n.append(extra_id)
|
39 |
+
scores = scores[top_n]
|
40 |
+
return np.array(top_n), np.array(scores)
|
src/models/pairwise_model.py
ADDED
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import torch
|
3 |
+
import torch.nn as nn
|
4 |
+
from torch.utils.data import Dataset, DataLoader
|
5 |
+
from transformers import AutoModel, AutoConfig
|
6 |
+
from transformers import AutoTokenizer
|
7 |
+
import pandas as pd
|
8 |
+
|
9 |
+
AUTH_TOKEN = "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"
|
10 |
+
|
11 |
+
tokenizer = AutoTokenizer.from_pretrained('nguyenvulebinh/vi-mrc-base',
|
12 |
+
use_auth_token=AUTH_TOKEN)
|
13 |
+
pad_token_id = tokenizer.pad_token_id
|
14 |
+
|
15 |
+
|
16 |
+
class PairwiseModel(nn.Module):
|
17 |
+
def __init__(self, model_name, max_length=384, batch_size=16, device="cuda:0"):
|
18 |
+
super(PairwiseModel, self).__init__()
|
19 |
+
self.max_length = max_length
|
20 |
+
self.batch_size = batch_size
|
21 |
+
self.device = device
|
22 |
+
self.model = AutoModel.from_pretrained(model_name, use_auth_token=AUTH_TOKEN)
|
23 |
+
self.model.to(self.device)
|
24 |
+
self.model.eval()
|
25 |
+
self.config = AutoConfig.from_pretrained(model_name, use_auth_token=AUTH_TOKEN)
|
26 |
+
self.fc = nn.Linear(768, 1).to(self.device)
|
27 |
+
|
28 |
+
def forward(self, ids, masks):
|
29 |
+
out = self.model(input_ids=ids,
|
30 |
+
attention_mask=masks,
|
31 |
+
output_hidden_states=False).last_hidden_state
|
32 |
+
out = out[:, 0]
|
33 |
+
outputs = self.fc(out)
|
34 |
+
return outputs
|
35 |
+
|
36 |
+
def stage1_ranking(self, question, texts):
|
37 |
+
tmp = pd.DataFrame()
|
38 |
+
tmp["text"] = [" ".join(x.split()) for x in texts]
|
39 |
+
tmp["question"] = question
|
40 |
+
valid_dataset = SiameseDatasetStage1(tmp, tokenizer, self.max_length, is_test=True)
|
41 |
+
valid_loader = DataLoader(valid_dataset, batch_size=self.batch_size, collate_fn=collate_fn,
|
42 |
+
num_workers=0, shuffle=False, pin_memory=True)
|
43 |
+
preds = []
|
44 |
+
with torch.no_grad():
|
45 |
+
bar = enumerate(valid_loader)
|
46 |
+
for step, data in bar:
|
47 |
+
ids = data["ids"].to(self.device)
|
48 |
+
masks = data["masks"].to(self.device)
|
49 |
+
preds.append(torch.sigmoid(self(ids, masks)).view(-1))
|
50 |
+
preds = torch.concat(preds)
|
51 |
+
return preds.cpu().numpy()
|
52 |
+
|
53 |
+
def stage2_ranking(self, question, answer, titles, texts):
|
54 |
+
tmp = pd.DataFrame()
|
55 |
+
tmp["candidate"] = texts
|
56 |
+
tmp["question"] = question
|
57 |
+
tmp["answer"] = answer
|
58 |
+
tmp["title"] = titles
|
59 |
+
valid_dataset = SiameseDatasetStage2(tmp, tokenizer, self.max_length, is_test=True)
|
60 |
+
valid_loader = DataLoader(valid_dataset, batch_size=self.batch_size, collate_fn=collate_fn,
|
61 |
+
num_workers=0, shuffle=False, pin_memory=True)
|
62 |
+
preds = []
|
63 |
+
with torch.no_grad():
|
64 |
+
bar = enumerate(valid_loader)
|
65 |
+
for step, data in bar:
|
66 |
+
ids = data["ids"].to(self.device)
|
67 |
+
masks = data["masks"].to(self.device)
|
68 |
+
preds.append(torch.sigmoid(self(ids, masks)).view(-1))
|
69 |
+
preds = torch.concat(preds)
|
70 |
+
return preds.cpu().numpy()
|
71 |
+
|
72 |
+
|
73 |
+
class SiameseDatasetStage1(Dataset):
|
74 |
+
|
75 |
+
def __init__(self, df, tokenizer, max_length, is_test=False):
|
76 |
+
self.df = df
|
77 |
+
self.max_length = max_length
|
78 |
+
self.tokenizer = tokenizer
|
79 |
+
self.is_test = is_test
|
80 |
+
self.content1 = tokenizer.batch_encode_plus(list(df.question.values), max_length=max_length, truncation=True)[
|
81 |
+
"input_ids"]
|
82 |
+
self.content2 = tokenizer.batch_encode_plus(list(df.text.values), max_length=max_length, truncation=True)[
|
83 |
+
"input_ids"]
|
84 |
+
if not self.is_test:
|
85 |
+
self.targets = self.df.label
|
86 |
+
|
87 |
+
def __len__(self):
|
88 |
+
return len(self.df)
|
89 |
+
|
90 |
+
def __getitem__(self, index):
|
91 |
+
return {
|
92 |
+
'ids1': torch.tensor(self.content1[index], dtype=torch.long),
|
93 |
+
'ids2': torch.tensor(self.content2[index][1:], dtype=torch.long),
|
94 |
+
'target': torch.tensor(0) if self.is_test else torch.tensor(self.targets[index], dtype=torch.float)
|
95 |
+
}
|
96 |
+
|
97 |
+
|
98 |
+
class SiameseDatasetStage2(Dataset):
|
99 |
+
|
100 |
+
def __init__(self, df, tokenizer, max_length, is_test=False):
|
101 |
+
self.df = df
|
102 |
+
self.max_length = max_length
|
103 |
+
self.tokenizer = tokenizer
|
104 |
+
self.is_test = is_test
|
105 |
+
self.df["content1"] = self.df.apply(lambda row: row.question + f" {tokenizer.sep_token} " + row.answer, axis=1)
|
106 |
+
self.df["content2"] = self.df.apply(lambda row: row.title + f" {tokenizer.sep_token} " + row.candidate, axis=1)
|
107 |
+
self.content1 = tokenizer.batch_encode_plus(list(df.content1.values), max_length=max_length, truncation=True)[
|
108 |
+
"input_ids"]
|
109 |
+
self.content2 = tokenizer.batch_encode_plus(list(df.content2.values), max_length=max_length, truncation=True)[
|
110 |
+
"input_ids"]
|
111 |
+
if not self.is_test:
|
112 |
+
self.targets = self.df.label
|
113 |
+
|
114 |
+
def __len__(self):
|
115 |
+
return len(self.df)
|
116 |
+
|
117 |
+
def __getitem__(self, index):
|
118 |
+
return {
|
119 |
+
'ids1': torch.tensor(self.content1[index], dtype=torch.long),
|
120 |
+
'ids2': torch.tensor(self.content2[index][1:], dtype=torch.long),
|
121 |
+
'target': torch.tensor(0) if self.is_test else torch.tensor(self.targets[index], dtype=torch.float)
|
122 |
+
}
|
123 |
+
|
124 |
+
|
125 |
+
def collate_fn(batch):
|
126 |
+
ids = [torch.cat([x["ids1"], x["ids2"]]) for x in batch]
|
127 |
+
targets = [x["target"] for x in batch]
|
128 |
+
max_len = np.max([len(x) for x in ids])
|
129 |
+
masks = []
|
130 |
+
for i in range(len(ids)):
|
131 |
+
if len(ids[i]) < max_len:
|
132 |
+
ids[i] = torch.cat((ids[i], torch.tensor([pad_token_id, ] * (max_len - len(ids[i])), dtype=torch.long)))
|
133 |
+
masks.append(ids[i] != pad_token_id)
|
134 |
+
# print(tokenizer.decode(ids[0]))
|
135 |
+
outputs = {
|
136 |
+
"ids": torch.vstack(ids),
|
137 |
+
"masks": torch.vstack(masks),
|
138 |
+
"target": torch.vstack(targets).view(-1)
|
139 |
+
}
|
140 |
+
return outputs
|
src/models/predict_model.py
ADDED
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from models.pairwise_model import *
|
2 |
+
from features.text_utils import *
|
3 |
+
import regex as re
|
4 |
+
from models.bm25_utils import BM25Gensim
|
5 |
+
from models.qa_model import *
|
6 |
+
from tqdm.auto import tqdm
|
7 |
+
tqdm.pandas()
|
8 |
+
|
9 |
+
df_wiki_windows = pd.read_csv("../data/processed/wikipedia_20220620_cleaned_v2.csv")
|
10 |
+
df_wiki = pd.read_csv("../data/wikipedia_20220620_short.csv")
|
11 |
+
df_wiki.title = df_wiki.title.apply(str)
|
12 |
+
|
13 |
+
entity_dict = json.load(open("../data/processed/entities.json"))
|
14 |
+
new_dict = dict()
|
15 |
+
for key, val in entity_dict.items():
|
16 |
+
val = val.replace("wiki/", "").replace("_", " ")
|
17 |
+
entity_dict[key] = val
|
18 |
+
key = preprocess(key)
|
19 |
+
new_dict[key.lower()] = val
|
20 |
+
entity_dict.update(new_dict)
|
21 |
+
title2idx = dict([(x.strip(), y) for x, y in zip(df_wiki.title, df_wiki.index.values)])
|
22 |
+
|
23 |
+
qa_model = QAEnsembleModel("nguyenvulebinh/vi-mrc-large", ["../models/qa_model_robust.bin"], entity_dict)
|
24 |
+
pairwise_model_stage1 = PairwiseModel("nguyenvulebinh/vi-mrc-base").half()
|
25 |
+
pairwise_model_stage1.load_state_dict(torch.load("../models/pairwise_v2.bin"))
|
26 |
+
pairwise_model_stage1.eval()
|
27 |
+
|
28 |
+
pairwise_model_stage2 = PairwiseModel("nguyenvulebinh/vi-mrc-base").half()
|
29 |
+
pairwise_model_stage2.load_state_dict(torch.load("../models/pairwise_stage2_seed0.bin"))
|
30 |
+
|
31 |
+
bm25_model_stage1 = BM25Gensim("../models/bm25_stage1/", entity_dict, title2idx)
|
32 |
+
bm25_model_stage2_full = BM25Gensim("../models/bm25_stage2/full_text/", entity_dict, title2idx)
|
33 |
+
bm25_model_stage2_title = BM25Gensim("../models/bm25_stage2/title/", entity_dict, title2idx)
|
34 |
+
|
35 |
+
def get_answer_e2e(question):
|
36 |
+
#Bm25 retrieval for top200 candidates
|
37 |
+
query = preprocess(question).lower()
|
38 |
+
top_n, bm25_scores = bm25_model_stage1.get_topk_stage1(query, topk=200)
|
39 |
+
titles = [preprocess(df_wiki_windows.title.values[i]) for i in top_n]
|
40 |
+
texts = [preprocess(df_wiki_windows.text.values[i]) for i in top_n]
|
41 |
+
|
42 |
+
#Reranking with pairwise model for top10
|
43 |
+
question = preprocess(question)
|
44 |
+
ranking_preds = pairwise_model_stage1.stage1_ranking(question, texts)
|
45 |
+
ranking_scores = ranking_preds * bm25_scores
|
46 |
+
|
47 |
+
#Question answering
|
48 |
+
best_idxs = np.argsort(ranking_scores)[-10:]
|
49 |
+
ranking_scores = np.array(ranking_scores)[best_idxs]
|
50 |
+
texts = np.array(texts)[best_idxs]
|
51 |
+
best_answer = qa_model(question, texts, ranking_scores)
|
52 |
+
if best_answer is None:
|
53 |
+
return "Chịu"
|
54 |
+
bm25_answer = preprocess(str(best_answer).lower(), max_length=128, remove_puncts=True)
|
55 |
+
|
56 |
+
#Entity mapping
|
57 |
+
if not check_number(bm25_answer):
|
58 |
+
bm25_question = preprocess(str(question).lower(), max_length=128, remove_puncts=True)
|
59 |
+
bm25_question_answer = bm25_question + " " + bm25_answer
|
60 |
+
candidates, scores = bm25_model_stage2_title.get_topk_stage2(bm25_answer, raw_answer=best_answer)
|
61 |
+
titles = [df_wiki.title.values[i] for i in candidates]
|
62 |
+
texts = [df_wiki.text.values[i] for i in candidates]
|
63 |
+
ranking_preds = pairwise_model_stage2.stage2_ranking(question, best_answer, titles, texts)
|
64 |
+
if ranking_preds.max() >= 0.1:
|
65 |
+
final_answer = titles[ranking_preds.argmax()]
|
66 |
+
else:
|
67 |
+
candidates, scores = bm25_model_stage2_full.get_topk_stage2(bm25_question_answer)
|
68 |
+
titles = [df_wiki.title.values[i] for i in candidates] + titles
|
69 |
+
texts = [df_wiki.text.values[i] for i in candidates] + texts
|
70 |
+
ranking_preds = np.concatenate(
|
71 |
+
[pairwise_model_stage2.stage2_ranking(question, best_answer, titles, texts), ranking_preds])
|
72 |
+
final_answer = "wiki/"+titles[ranking_preds.argmax()].replace(" ","_")
|
73 |
+
else:
|
74 |
+
final_answer = bm25_answer.lower()
|
75 |
+
return final_answer
|
src/models/qa_model.py
ADDED
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import torch
|
3 |
+
import torch.nn as nn
|
4 |
+
from transformers import AutoModelForQuestionAnswering, pipeline
|
5 |
+
from features.text_utils import post_process_answer
|
6 |
+
from features.graph_utils import find_best_cluster
|
7 |
+
|
8 |
+
|
9 |
+
class QAEnsembleModel(nn.Module):
|
10 |
+
|
11 |
+
def __init__(self, model_name, model_checkpoints, entity_dict,
|
12 |
+
thr=0.1, device="cuda:0"):
|
13 |
+
super(QAEnsembleModel, self).__init__()
|
14 |
+
self.nlps = []
|
15 |
+
for model_checkpoint in model_checkpoints:
|
16 |
+
model = AutoModelForQuestionAnswering.from_pretrained(model_name).half()
|
17 |
+
model.load_state_dict(torch.load(model_checkpoint), strict=False)
|
18 |
+
nlp = pipeline('question-answering', model=model,
|
19 |
+
tokenizer=model_name, device=int(device.split(":")[-1]))
|
20 |
+
self.nlps.append(nlp)
|
21 |
+
self.entity_dict = entity_dict
|
22 |
+
self.thr = thr
|
23 |
+
|
24 |
+
def forward(self, question, texts, ranking_scores=None):
|
25 |
+
if ranking_scores is None:
|
26 |
+
ranking_scores = np.ones((len(texts),))
|
27 |
+
|
28 |
+
curr_answers = []
|
29 |
+
curr_scores = []
|
30 |
+
best_score = 0
|
31 |
+
for i, nlp in enumerate(self.nlps):
|
32 |
+
for text, score in zip(texts, ranking_scores):
|
33 |
+
QA_input = {
|
34 |
+
'question': question,
|
35 |
+
'context': text
|
36 |
+
}
|
37 |
+
res = nlp(QA_input)
|
38 |
+
# print(res)
|
39 |
+
if res["score"] > self.thr:
|
40 |
+
curr_answers.append(res["answer"])
|
41 |
+
curr_scores.append(res["score"])
|
42 |
+
res["score"] = res["score"] * score
|
43 |
+
if i == 0:
|
44 |
+
if res["score"] > best_score:
|
45 |
+
answer = res["answer"]
|
46 |
+
best_score = res["score"]
|
47 |
+
if len(curr_answers) == 0:
|
48 |
+
return None
|
49 |
+
curr_answers = [post_process_answer(x, self.entity_dict) for x in curr_answers]
|
50 |
+
answer = post_process_answer(answer, self.entity_dict)
|
51 |
+
new_best_answer = post_process_answer(find_best_cluster(curr_answers, answer), self.entity_dict)
|
52 |
+
return new_best_answer
|
submission/answer.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
submission/submission.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
submission/test.py
ADDED
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
data = json.load(open("answer.json", encoding="utf8"))
|
3 |
+
for i in data:
|
4 |
+
if i['answer'] == "Khong biet":
|
5 |
+
i['answer'] = None
|
6 |
+
|
7 |
+
obj = {
|
8 |
+
"data": data
|
9 |
+
}
|
10 |
+
json.dump(obj, open("submission.json", "w", encoding="utf8"), ensure_ascii=False, indent=4)
|