{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"* **Họ và tên:** Nguyễn Thị Quyên\n* **MSSV:** 18021063\n* **Topic:** Quora Insincere Questions Classification","metadata":{}},{"cell_type":"markdown","source":"# GIỚI THIỆU VỀ BÀI TOÁN\n* Quora là một nền tảng để mọi người học hỏi với nhau. Mọi người có thể đăng những câu hỏi và người khác vào chia sẻ, trả lời những thắc mắc đó. Mục đích của bài toán này là để chỉ ra câu hỏi có chân thành hay không. Những câu hỏi không chân thành thường là những câu đưa ra tuyên bố quan điểm của mình hơn là để tìm những câu trả lời có ích: không trung lập, khiêu khích hoặc chê bai, không có căn cứ thực tế và nội dung khiêu dâm.\n* Câu hỏi chân thành hay không sẽ được gán nhãn bằng 0 hoặc 1","metadata":{}},{"cell_type":"markdown","source":"# EDA","metadata":{"execution":{"iopub.status.busy":"2021-06-10T21:40:09.905212Z","iopub.execute_input":"2021-06-10T21:40:09.905764Z","iopub.status.idle":"2021-06-10T21:40:09.911588Z","shell.execute_reply.started":"2021-06-10T21:40:09.905646Z","shell.execute_reply":"2021-06-10T21:40:09.910253Z"}}},{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session\nimport matplotlib.pyplot as plt\nimport seaborn as sb\nimport nltk\nimport string\nfrom nltk.tokenize import word_tokenize\nfrom nltk.corpus import stopwords\nfrom nltk.stem import WordNetLemmatizer\nnltk.download('stopwords')\nnltk_stopwords = stopwords.words('english')\nfrom keras.preprocessing.sequence import pad_sequences\nfrom sklearn import *","metadata":{"execution":{"iopub.status.busy":"2021-06-11T06:58:49.056580Z","iopub.execute_input":"2021-06-11T06:58:49.056887Z","iopub.status.idle":"2021-06-11T06:58:49.068396Z","shell.execute_reply.started":"2021-06-11T06:58:49.056859Z","shell.execute_reply":"2021-06-11T06:58:49.067261Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data = pd.read_csv('/kaggle/input/quora-insincere-questions-classification/train.csv')\ntest_data = pd.read_csv('/kaggle/input/quora-insincere-questions-classification/test.csv')","metadata":{"execution":{"iopub.status.busy":"2021-06-11T06:58:50.116436Z","iopub.execute_input":"2021-06-11T06:58:50.116752Z","iopub.status.idle":"2021-06-11T06:58:54.633892Z","shell.execute_reply.started":"2021-06-11T06:58:50.116723Z","shell.execute_reply":"2021-06-11T06:58:54.632957Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Train shape :\", train_data.shape)\nprint(\"Test shape :\", test_data.shape)","metadata":{"execution":{"iopub.status.busy":"2021-06-11T06:58:54.635445Z","iopub.execute_input":"2021-06-11T06:58:54.635806Z","iopub.status.idle":"2021-06-11T06:58:54.642604Z","shell.execute_reply.started":"2021-06-11T06:58:54.635769Z","shell.execute_reply":"2021-06-11T06:58:54.641351Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data.info()","metadata":{"execution":{"iopub.status.busy":"2021-06-11T06:58:54.644449Z","iopub.execute_input":"2021-06-11T06:58:54.644810Z","iopub.status.idle":"2021-06-11T06:58:54.869033Z","shell.execute_reply.started":"2021-06-11T06:58:54.644775Z","shell.execute_reply":"2021-06-11T06:58:54.868009Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Nhận xét:** Tập dữ liệu train có 1306122 câu hỏi và tập test chứa 375806 câu hỏi để đánh giá hiệu năng mô hình. Trong đó, không có giá trị null nào và có 3 trường dữ liệu: qid, question_text, target.\n- qid : id của câu hỏi, mỗi câu hỏi có 1 id riêng phân biệt\n- question_text : nội dung câu hỏi ở dạng text\n- target: gồm 2 nhãn 0 và 1. Nhãn 0 là sincere là câu hỏi chân thành, nhãn 1 là insincere là câu hỏi không chân thành","metadata":{}},{"cell_type":"markdown","source":"**Biểu đồ biểu diễn sự phân bố của dữ liệu**","metadata":{}},{"cell_type":"code","source":"sb.countplot(train_data['target'])","metadata":{"execution":{"iopub.status.busy":"2021-06-11T06:58:55.844603Z","iopub.execute_input":"2021-06-11T06:58:55.844920Z","iopub.status.idle":"2021-06-11T06:58:56.029533Z","shell.execute_reply.started":"2021-06-11T06:58:55.844890Z","shell.execute_reply":"2021-06-11T06:58:56.028470Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"val_counts = train_data['target'].value_counts()\nval_counts","metadata":{"execution":{"iopub.status.busy":"2021-06-11T06:58:56.760730Z","iopub.execute_input":"2021-06-11T06:58:56.761045Z","iopub.status.idle":"2021-06-11T06:58:56.780498Z","shell.execute_reply.started":"2021-06-11T06:58:56.761010Z","shell.execute_reply":"2021-06-11T06:58:56.779777Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":" **TARGET DISTRIBUTION**\n","metadata":{}},{"cell_type":"code","source":"sincere_percent= (val_counts[0] / val_counts.sum())* 100\ninsincere_percent= 100 - sincere_percent","metadata":{"execution":{"iopub.status.busy":"2021-06-11T06:58:58.708403Z","iopub.execute_input":"2021-06-11T06:58:58.708728Z","iopub.status.idle":"2021-06-11T06:58:58.712698Z","shell.execute_reply.started":"2021-06-11T06:58:58.708700Z","shell.execute_reply":"2021-06-11T06:58:58.711852Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(sincere_percent, insincere_percent)","metadata":{"execution":{"iopub.status.busy":"2021-06-11T06:58:59.428435Z","iopub.execute_input":"2021-06-11T06:58:59.428758Z","iopub.status.idle":"2021-06-11T06:58:59.435421Z","shell.execute_reply.started":"2021-06-11T06:58:59.428730Z","shell.execute_reply":"2021-06-11T06:58:59.434402Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"labels = 'Sincere', 'Insincere'\nsizes = [sincere_percent, insincere_percent]\nplt.pie(sizes, labels=labels,\nautopct='%1.1f%%', shadow=True, startangle=140)\nplt.axis('equal')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2021-06-11T06:59:00.364195Z","iopub.execute_input":"2021-06-11T06:59:00.364552Z","iopub.status.idle":"2021-06-11T06:59:00.469983Z","shell.execute_reply.started":"2021-06-11T06:59:00.364521Z","shell.execute_reply":"2021-06-11T06:59:00.469216Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Nhận xét:** Số lượng câu hỏi sincerce:insincere có sự chênh lệch rất lớn: Số lượng câu hỏi chân thành chiếm đến gần 94% tập dữ liệu trong khi số lượng câu hỏi không chân thành chỉ chiếm 6.2%.\n \n -> Dữ liệu này mất cân bằng rất lớn\n \n -> Cần áp dụng các phương pháp cân bằng dữ liệu\n \n -> F1-score sẽ được sử dụng để đánh giá hiệu năng của mô hình. F1 score là độ cân bằng đồng đều giữa precision và recall","metadata":{}},{"cell_type":"markdown","source":"# TIỀN XỬ LÝ","metadata":{}},{"cell_type":"markdown","source":"**Dữ liệu này ở dạng text. Ta cần chuyển sang dạng vector để mô hình có thể học được. Trước hết ta xử lý nhiễu dữ liệu.**\n\nTa sẽ loại bỏ noise của dữ liệu theo các bước sau:\n*     ***clean_punct()***: loại bỏ đi các kí tự đặc biệt có trong câu hỏi\n*     ***clean_numbers()***: xóa đi các chữ số\n*     ***clean_misspells()***: sửa các từ tiếng anh viết tắt hoặc viết sai\n*     ***clean_stopwords()***: loại bỏ các stopwords như 'a', 'the', 'does',... ","metadata":{}},{"cell_type":"code","source":"puncts = [',', '.', '\"', ':', ')', '(', '-', '!', '?', '|', ';', \"'\", '$', '&', '/', '[', ']', '>', '%', '=', '#', '*', '+', '\\\\', \n        '•', '~', '@', '£', '·', '_', '{', '}', '©', '^', '®', '`', '<', '→', '°', '€', '™', '›', '♥', '←', '×', '§', '″', '′', \n        '█', '…', '“', '★', '”', '–', '●', '►', '−', '¢', '¬', '░', '¡', '¶', '↑', '±', '¿', '▾', '═', '¦', '║', '―', '¥', '▓', \n        '—', '‹', '─', '▒', '：', '⊕', '▼', '▪', '†', '■', '’', '▀', '¨', '▄', '♫', '☆', '¯', '♦', '¤', '▲', '¸', '⋅', '‘', '∞', \n        '∙', '）', '↓', '、', '│', '（', '»', '，', '♪', '╩', '╚', '・', '╦', '╣', '╔', '╗', '▬', '❤', '≤', '‡', '√', '◄', '━', \n        '⇒', '▶', '≥', '╝', '♡', '◊', '。', '✈', '≡', '☺', '✔', '↵', '≈', '✓', '♣', '☎', '℃', '◦', '└', '‟', '～', '！', '○', \n        '◆', '№', '♠', '▌', '✿', '▸', '⁄', '□', '❖', '✦', '．', '÷', '｜', '┃', '／', '￥', '╠', '↩', '✭', '▐', '☼', '☻', '┐', \n        '├', '«', '∼', '┌', '℉', '☮', '฿', '≦', '♬', '✧', '〉', '－', '⌂', '✖', '･', '◕', '※', '‖', '◀', '‰', '\\x97', '↺', \n        '∆', '┘', '┬', '╬', '،', '⌘', '⊂', '＞', '〈', '⎙', '？', '☠', '⇐', '▫', '∗', '∈', '≠', '♀', '♔', '˚', '℗', '┗', '＊', \n        '┼', '❀', '＆', '∩', '♂', '‿', '∑', '‣', '➜', '┛', '⇓', '☯', '⊖', '☀', '┳', '；', '∇', '⇑', '✰', '◇', '♯', '☞', '´', \n        '↔', '┏', '｡', '◘', '∂', '✌', '♭', '┣', '┴', '┓', '✨', '\\xa0', '˜', '❥', '┫', '℠', '✒', '［', '∫', '\\x93', '≧', '］', \n        '\\x94', '∀', '♛', '\\x96', '∨', '◎', '↻', '⇩', '＜', '≫', '✩', '✪', '♕', '؟', '₤', '☛', '╮', '␊', '＋', '┈', '％', \n        '╋', '▽', '⇨', '┻', '⊗', '￡', '।', '▂', '✯', '▇', '＿', '➤', '✞', '＝', '▷', '△', '◙', '▅', '✝', '∧', '␉', '☭', '┊', '╯', '☾', '➔', '∴', '\\x92', '▃', '↳', '＾', '׳', '➢', '╭', '➡', '＠', '⊙', '☢', '˝', '∏', '„', '∥', '❝', '☐', \n        '▆', '╱', '⋙', '๏', '☁', '⇔', '▔', '\\x91', '➚', '◡', '╰', '\\x85', '♢', '˙', '۞', '✘', '✮', '☑', '⋆', 'ⓘ', '❒', \n        '☣', '✉', '⌊', '➠', '∣', '❑', '◢', 'ⓒ', '\\x80', '〒', '∕', '▮', '⦿', '✫', '✚', '⋯', '♩', '☂', '❞', '‗', '܂', '☜', \n        '‾', '✜', '╲', '∘', '⟩', '＼', '⟨', '·', '✗', '♚', '∅', 'ⓔ', '◣', '͡', '‛', '❦', '◠', '✄', '❄', '∃', '␣', '≪', '｢', \n        '≅', '◯', '☽', '∎', '｣', '❧', '̅', 'ⓐ', '↘', '⚓', '▣', '˘', '∪', '⇢', '✍', '⊥', '＃', '⎯', '↠', '۩', '☰', '◥', \n        '⊆', '✽', '⚡', '↪', '❁', '☹', '◼', '☃', '◤', '❏', 'ⓢ', '⊱', '➝', '̣', '✡', '∠', '｀', '▴', '┤', '∝', '♏', 'ⓐ', \n        '✎', ';', '␤', '＇', '❣', '✂', '✤', 'ⓞ', '☪', '✴', '⌒', '˛', '♒', '＄', '✶', '▻', 'ⓔ', '◌', '◈', '❚', '❂', '￦', \n        '◉', '╜', '̃', '✱', '╖', '❉', 'ⓡ', '↗', 'ⓣ', '♻', '➽', '׀', '✲', '✬', '☉', '▉', '≒', '☥', '⌐', '♨', '✕', 'ⓝ', \n        '⊰', '❘', '＂', '⇧', '̵', '➪', '▁', '▏', '⊃', 'ⓛ', '‚', '♰', '́', '✏', '⏑', '̶', 'ⓢ', '⩾', '￠', '❍', '≃', '⋰', '♋', \n        '､', '̂', '❋', '✳', 'ⓤ', '╤', '▕', '⌣', '✸', '℮', '⁺', '▨', '╨', 'ⓥ', '♈', '❃', '☝', '✻', '⊇', '≻', '♘', '♞', \n        '◂', '✟', '⌠', '✠', '☚', '✥', '❊', 'ⓒ', '⌈', '❅', 'ⓡ', '♧', 'ⓞ', '▭', '❱', 'ⓣ', '∟', '☕', '♺', '∵', '⍝', 'ⓑ', \n        '✵', '✣', '٭', '♆', 'ⓘ', '∶', '⚜', '◞', '்', '✹', '➥', '↕', '̳', '∷', '✋', '➧', '∋', '̿', 'ͧ', '┅', '⥤', '⬆', '⋱', \n        '☄', '↖', '⋮', '۔', '♌', 'ⓛ', '╕', '♓', '❯', '♍', '▋', '✺', '⭐', '✾', '♊', '➣', '▿', 'ⓑ', '♉', '⏠', '◾', '▹', \n        '⩽', '↦', '╥', '⍵', '⌋', '։', '➨', '∮', '⇥', 'ⓗ', 'ⓓ', '⁻', '⎝', '⌥', '⌉', '◔', '◑', '✼', '♎', '♐', '╪', '⊚', '☒', '⇤', 'ⓜ', '⎠', '◐', '⚠', '╞', '◗', '⎕', 'ⓨ', '☟', 'ⓟ', '♟', '❈', '↬', 'ⓓ', '◻', '♮', '❙', '♤', '∉', '؛', \n        '⁂', 'ⓝ', '־', '♑', '╫', '╓', '╳', '⬅', '☔', '☸', '┄', '╧', '׃', '⎢', '❆', '⋄', '⚫', '̏', '☏', '➞', '͂', '␙', \n        'ⓤ', '◟', '̊', '⚐', '✙', '↙', '̾', '℘', '✷', '⍺', '❌', '⊢', '▵', '✅', 'ⓖ', '☨', '▰', '╡', 'ⓜ', '☤', '∽', '╘', \n        '˹', '↨', '♙', '⬇', '♱', '⌡', '⠀', '╛', '❕', '┉', 'ⓟ', '̀', '♖', 'ⓚ', '┆', '⎜', '◜', '⚾', '⤴', '✇', '╟', '⎛', \n        '☩', '➲', '➟', 'ⓥ', 'ⓗ', '⏝', '◃', '╢', '↯', '✆', '˃', '⍴', '❇', '⚽', '╒', '̸', '♜', '☓', '➳', '⇄', '☬', '⚑', \n        '✐', '⌃', '◅', '▢', '❐', '∊', '☈', '॥', '⎮', '▩', 'ு', '⊹', '‵', '␔', '☊', '➸', '̌', '☿', '⇉', '⊳', '╙', 'ⓦ', \n        '⇣', '｛', '̄', '↝', '⎟', '▍', '❗', '״', '΄', '▞', '◁', '⛄', '⇝', '⎪', '♁', '⇠', '☇', '✊', 'ி', '｝', '⭕', '➘', \n        '⁀', '☙', '❛', '❓', '⟲', '⇀', '≲', 'ⓕ', '⎥', '\\u06dd', 'ͤ', '₋', '̱', '̎', '♝', '≳', '▙', '➭', '܀', 'ⓖ', '⇛', '▊', \n        '⇗', '̷', '⇱', '℅', 'ⓧ', '⚛', '̐', '̕', '⇌', '␀', '≌', 'ⓦ', '⊤', '̓', '☦', 'ⓕ', '▜', '➙', 'ⓨ', '⌨', '◮', '☷', \n        '◍', 'ⓚ', '≔', '⏩', '⍳', '℞', '┋', '˻', '▚', '≺', 'ْ', '▟', '➻', '̪', '⏪', '̉', '⎞', '┇', '⍟', '⇪', '▎', '⇦', '␝', \n        '⤷', '≖', '⟶', '♗', '̴', '♄', 'ͨ', '̈', '❜', '̡', '▛', '✁', '➩', 'ா', '˂', '↥', '⏎', '⎷', '̲', '➖', '↲', '⩵', '̗', '❢', \n        '≎', '⚔', '⇇', '̑', '⊿', '̖', '☍', '➹', '⥊', '⁁', '✢']\ndef clean_punct(x):\n  x = str(x)\n  for punct in puncts:\n    if punct in x:\n      x = x.replace(punct, ' ')\n    return x","metadata":{"execution":{"iopub.status.busy":"2021-06-11T06:59:03.931170Z","iopub.execute_input":"2021-06-11T06:59:03.931514Z","iopub.status.idle":"2021-06-11T06:59:03.965990Z","shell.execute_reply.started":"2021-06-11T06:59:03.931483Z","shell.execute_reply":"2021-06-11T06:59:03.965174Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def clean_numbers(x):\n    x = x.translate(str.maketrans('', '', string.digits))\n    return x","metadata":{"execution":{"iopub.status.busy":"2021-06-11T07:21:33.383190Z","iopub.execute_input":"2021-06-11T07:21:33.383553Z","iopub.status.idle":"2021-06-11T07:21:33.387732Z","shell.execute_reply.started":"2021-06-11T07:21:33.383521Z","shell.execute_reply":"2021-06-11T07:21:33.386897Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"misspell_dict = {\"I'm\": 'I am', \"I'm'a\": 'I am about to', \"I'm'o\": 'I am going to',\n \"I've\": 'I have',\"I'll\": 'I will',\"I'll've\": 'I will have',\n \"I'd\": 'I would',\"I'd've\": 'I would have','Whatcha': 'What are you',\n \"amn't\": 'am not',\"ain't\": 'are not',\"aren't\": 'are not',\n \"'cause\": 'because',\"can't\": 'can not',\"can't've\": 'can not have',\n \"could've\": 'could have',\"couldn't\": 'could not',\"couldn't've\": 'could not have',\n \"daren't\": 'dare not',\"daresn't\": 'dare not',\"dasn't\": 'dare not',\n \"didn't\": 'did not','didn’t': 'did not',\"don't\": 'do not',\n 'don’t': 'do not',\"doesn't\": 'does not',\"e'er\": 'ever',\n \"everyone's\": 'everyone is','finna': 'fixing to','gimme': 'give me',\n \"gon't\": 'go not','gonna': 'going to','gotta': 'got to',\n \"hadn't\": 'had not',\"hadn't've\": 'had not have',\"hasn't\": 'has not',\n \"haven't\": 'have not',\"he've\": 'he have',\"he's\": 'he is',\n \"he'll\": 'he will',\"he'll've\": 'he will have',\"he'd\": 'he would',\n \"he'd've\": 'he would have',\"here's\": 'here is',\"how're\": 'how are',\n \"how'd\": 'how did',\"how'd'y\": 'how do you',\"how's\": 'how is',\n \"how'll\": 'how will',\"isn't\": 'is not',\"it's\": 'it is',\n \"'tis\": 'it is',\"'twas\": 'it was',\"it'll\": 'it will',\n \"it'll've\": 'it will have',\"it'd\": 'it would',\"it'd've\": 'it would have',\n 'kinda': 'kind of',\"let's\": 'let us','luv': 'love',\n \"ma'am\": 'madam',\"may've\": 'may have',\"mayn't\": 'may not',\n \"might've\": 'might have',\"mightn't\": 'might not',\"mightn't've\": 'might not have',\n \"must've\": 'must have',\"mustn't\": 'must not',\"mustn't've\": 'must not have',\n \"needn't\": 'need not',\"needn't've\": 'need not have',\"ne'er\": 'never',\n \"o'\": 'of',\"o'clock\": 'of the clock',\"ol'\": 'old',\n \"oughtn't\": 'ought not',\"oughtn't've\": 'ought not have',\"o'er\": 'over',\n \"shan't\": 'shall not',\"sha'n't\": 'shall not',\"shalln't\": 'shall not',\n \"shan't've\": 'shall not have',\"she's\": 'she is',\"she'll\": 'she will',\n \"she'd\": 'she would',\"she'd've\": 'she would have',\"should've\": 'should have',\n \"shouldn't\": 'should not',\"shouldn't've\": 'should not have',\"so've\": 'so have',\n \"so's\": 'so is',\"somebody's\": 'somebody is',\"someone's\": 'someone is',\n \"something's\": 'something is','sux': 'sucks',\"that're\": 'that are',\n \"that's\": 'that is',\"that'll\": 'that will',\"that'd\": 'that would',\n \"that'd've\": 'that would have','em': 'them',\"there're\": 'there are',\n \"there's\": 'there is',\"there'll\": 'there will',\"there'd\": 'there would',\n \"there'd've\": 'there would have',\"these're\": 'these are',\"they're\": 'they are',\n \"they've\": 'they have',\"they'll\": 'they will',\"they'll've\": 'they will have',\n \"they'd\": 'they would',\"they'd've\": 'they would have',\"this's\": 'this is',\n \"those're\": 'those are',\"to've\": 'to have','wanna': 'want to',\n \"wasn't\": 'was not',\"we're\": 'we are',\"we've\": 'we have',\n \"we'll\": 'we will',\"we'll've\": 'we will have',\"we'd\": 'we would',\n \"we'd've\": 'we would have',\"weren't\": 'were not',\"what're\": 'what are',\n \"what'd\": 'what did',\"what've\": 'what have',\"what's\": 'what is',\n \"what'll\": 'what will',\"what'll've\": 'what will have',\"when've\": 'when have',\n \"when's\": 'when is',\"where're\": 'where are',\"where'd\": 'where did',\n \"where've\": 'where have',\"where's\": 'where is',\"which's\": 'which is',\n \"who're\": 'who are',\"who've\": 'who have',\"who's\": 'who is',\n \"who'll\": 'who will',\"who'll've\": 'who will have',\"who'd\": 'who would',\n \"who'd've\": 'who would have',\"why're\": 'why are',\"why'd\": 'why did',\n \"why've\": 'why have',\"why's\": 'why is',\"will've\": 'will have',\n \"won't\": 'will not',\"won't've\": 'will not have',\"would've\": 'would have',\n \"wouldn't\": 'would not',\"wouldn't've\": 'would not have',\"y'all\": 'you all',\n \"y'all're\": 'you all are',\"y'all've\": 'you all have',\"y'all'd\": 'you all would',\n \"y'all'd've\": 'you all would have',\"you're\": 'you are',\"you've\": 'you have',\n \"you'll've\": 'you shall have',\"you'll\": 'you will',\"you'd\": 'you would',\n \"you'd've\": 'you would have','jan.': 'january','feb.': 'february',\n 'mar.': 'march','apr.': 'april','jun.': 'june',\n 'jul.': 'july','aug.': 'august','sep.': 'september',\n 'oct.': 'october','nov.': 'november','dec.': 'december',\n 'I’m': 'I am','I’m’a': 'I am about to','I’m’o': 'I am going to',\n 'I’ve': 'I have','I’ll': 'I will','I’ll’ve': 'I will have',\n 'I’d': 'I would','I’d’ve': 'I would have','amn’t': 'am not',\n 'ain’t': 'are not','aren’t': 'are not','’cause': 'because',\n 'can’t': 'can not','can’t’ve': 'can not have','could’ve': 'could have',\n 'couldn’t': 'could not','couldn’t’ve': 'could not have','daren’t': 'dare not',\n 'daresn’t': 'dare not','dasn’t': 'dare not','doesn’t': 'does not',\n 'e’er': 'ever','everyone’s': 'everyone is','gon’t': 'go not',\n 'hadn’t': 'had not','hadn’t’ve': 'had not have',\n 'hasn’t': 'has not','haven’t': 'have not',\n 'he’ve': 'he have','he’s': 'he is','he’ll': 'he will',\n 'he’ll’ve': 'he will have','he’d': 'he would','he’d’ve': 'he would have',\n 'here’s': 'here is','how’re': 'how are','how’d': 'how did',\n 'how’d’y': 'how do you','how’s': 'how is','how’ll': 'how will',\n 'isn’t': 'is not','it’s': 'it is','’tis': 'it is',\n '’twas': 'it was','it’ll': 'it will','it’ll’ve': 'it will have',\n 'it’d': 'it would','it’d’ve': 'it would have','let’s': 'let us',\n 'ma’am': 'madam','may’ve': 'may have','mayn’t': 'may not',\n 'might’ve': 'might have','mightn’t': 'might not','mightn’t’ve': 'might not have',\n 'must’ve': 'must have','mustn’t': 'must not','mustn’t’ve': 'must not have',\n 'needn’t': 'need not','needn’t’ve': 'need not have','ne’er': 'never',\n 'o’': 'of','o’clock': 'of the clock','ol’': 'old',\n 'oughtn’t': 'ought not','oughtn’t’ve': 'ought not have','o’er': 'over',\n 'shan’t': 'shall not','sha’n’t': 'shall not','shalln’t': 'shall not',\n 'shan’t’ve': 'shall not have','she’s': 'she is','she’ll': 'she will',\n 'she’d': 'she would','she’d’ve': 'she would have','should’ve': 'should have',\n 'shouldn’t': 'should not','shouldn’t’ve': 'should not have','so’ve': 'so have',\n 'so’s': 'so is','somebody’s': 'somebody is','someone’s': 'someone is',\n 'something’s': 'something is','that’re': 'that are','that’s': 'that is',\n 'that’ll': 'that will','that’d': 'that would','that’d’ve': 'that would have',\n 'there’re': 'there are','there’s': 'there is','there’ll': 'there will',\n 'there’d': 'there would','there’d’ve': 'there would have','these’re': 'these are',\n 'they’re': 'they are','they’ve': 'they have','they’ll': 'they will',\n 'they’ll’ve': 'they will have','they’d': 'they would','they’d’ve': 'they would have',\n 'this’s': 'this is','those’re': 'those are','to’ve': 'to have',\n 'wasn’t': 'was not','we’re': 'we are','we’ve': 'we have',\n 'we’ll': 'we will','we’ll’ve': 'we will have','we’d': 'we would',\n 'we’d’ve': 'we would have','weren’t': 'were not','what’re': 'what are',\n 'what’d': 'what did','what’ve': 'what have','what’s': 'what is',\n 'what’ll': 'what will','what’ll’ve': 'what will have','when’ve': 'when have',\n 'when’s': 'when is','where’re': 'where are','where’d': 'where did',\n 'where’ve': 'where have','where’s': 'where is','which’s': 'which is',\n 'who’re': 'who are','who’ve': 'who have','who’s': 'who is',\n 'who’ll': 'who will','who’ll’ve': 'who will have','who’d': 'who would',\n 'who’d’ve': 'who would have','why’re': 'why are','why’d': 'why did',\n 'why’ve': 'why have','why’s': 'why is','will’ve': 'will have',\n 'won’t': 'will not','won’t’ve': 'will not have','would’ve': 'would have',\n 'wouldn’t': 'would not','wouldn’t’ve': 'would not have','y’all': 'you all',\n 'y’all’re': 'you all are','y’all’ve': 'you all have','y’all’d': 'you all would',\n 'y’all’d’ve': 'you all would have','you’re': 'you are','you’ve': 'you have',\n 'you’ll’ve': 'you shall have','you’ll': 'you will','you’d': 'you would','you’d’ve': 'you would have',\n 'colour':'color','centre':'center', 'favourite':'favorite',\n 'travelling':'traveling','counselling':'counseling','theatre':'theater',\n 'cancelled':'canceled','labour':'labor','organisation':'organization',\n 'wwii':'world war 2','citicise':'criticize','instagram': 'social medium',\n 'whatsapp': 'social medium','snapchat': 'social medium', 'colour': 'color', 'centre': 'center', 'favourite': 'favorite', \n 'travelling': 'traveling', 'counselling': 'counseling', 'theatre': 'theater', 'cancelled': 'canceled', \n 'labour': 'labor', 'organisation': 'organization', 'wwii': 'world war 2', 'citicise': 'criticize',\n 'youtu ': 'youtube ', 'Qoura': 'Quora', 'sallary': 'salary', 'Whta': 'What', \n 'narcisist': 'narcissist', 'howdo': 'how do', 'whatare': 'what are', 'howcan': 'how can', 'howmuch': 'how much', 'howmany': 'how many', 'whydo': 'why do', 'doI': 'do I', \n 'theBest': 'the best', 'howdoes': 'how does', 'mastrubation': 'masturbation', 'mastrubate': 'masturbate', \"mastrubating\": 'masturbating',\n 'pennis': 'penis', 'Etherium': 'bitcoin', 'narcissit': 'narcissist', 'bigdata': 'big data', '2k17': '2017', '2k18': '2018', 'qouta': 'quota', 'exboyfriend': 'ex boyfriend',\n 'airhostess': 'air hostess', \"whst\": 'what', 'watsapp': 'whatsapp', 'demonitisation': 'demonetization', 'demonitization': 'demonetization', 'demonetisation': 'demonetization',\n 'weatern':'western','interledger':'blockchain','deplation':'deflation', 'cryptocurrencies':'cryptocurrency', 'bitcoin':'blockchain cryptocurrency',\n 'electroneum':'bitcoin','nanodegree':'degree','hotstar':'star','dream11':'dream','ftre':'fire','tensorflow':'framework','unocoin':'bitcoin',\n 'lnmiit':'limit','unacademy':'academy','altcoin':'bitcoin','altcoins':'bitcoin','litecoin':'bitcoin','coinbase':'bitcoin','cryptocurency':'cryptocurrency',\n 'simpliv':'simple','quoras':'quora','schizoids':'psychopath','remainers':'remainder','twinflame':'soulmate','quorans':'quora','brexit':'demonetized'}\n\ndef clean_misspell(word):\n    try:\n        x = misspell_dict[word]\n    except KeyError:\n        x = word\n    return x","metadata":{"execution":{"iopub.status.busy":"2021-06-11T06:59:05.399578Z","iopub.execute_input":"2021-06-11T06:59:05.399898Z","iopub.status.idle":"2021-06-11T06:59:05.434163Z","shell.execute_reply.started":"2021-06-11T06:59:05.399871Z","shell.execute_reply":"2021-06-11T06:59:05.433316Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def clean_stopwords(x):\n  x = [word for word in x.split() if word not in nltk_stopwords]\n  x = ' '.join(x)\n  return x","metadata":{"execution":{"iopub.status.busy":"2021-06-11T06:59:06.040144Z","iopub.execute_input":"2021-06-11T06:59:06.040502Z","iopub.status.idle":"2021-06-11T06:59:06.045059Z","shell.execute_reply.started":"2021-06-11T06:59:06.040471Z","shell.execute_reply":"2021-06-11T06:59:06.044060Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"***Tổng hợp hàm tiền xử lý***","metadata":{}},{"cell_type":"code","source":"def preprocessing(x):\n    x = clean_punct(x)\n    x = clean_misspell(x)\n    x = clean_numbers(x)\n    x = clean_stopwords(x)\n    return x;","metadata":{"execution":{"iopub.status.busy":"2021-06-11T07:21:37.647174Z","iopub.execute_input":"2021-06-11T07:21:37.647555Z","iopub.status.idle":"2021-06-11T07:21:37.653242Z","shell.execute_reply.started":"2021-06-11T07:21:37.647515Z","shell.execute_reply":"2021-06-11T07:21:37.651948Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"***Tiền xử lý dữ liệu train***","metadata":{}},{"cell_type":"code","source":"train_data['question_text_cleaned'] = train_data['question_text'].apply(preprocessing)","metadata":{"execution":{"iopub.status.busy":"2021-06-11T07:21:39.895282Z","iopub.execute_input":"2021-06-11T07:21:39.895681Z","iopub.status.idle":"2021-06-11T07:22:10.965776Z","shell.execute_reply.started":"2021-06-11T07:21:39.895649Z","shell.execute_reply":"2021-06-11T07:22:10.964825Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**VECTOR HÓA DỮ LIỆU BẰNG TF-IDF**","metadata":{}},{"cell_type":"markdown","source":"***Biểu diễn dữ liệu bằng TF-IDF***\n\nTF-IDF (Term Frequency – Inverse Document Frequency) là 1 kĩ thuật sử dụng trong khai phá dữ liệu văn bản. Trọng số này được sử dụng để đánh giá tầm quan trọng của một từ trong một văn bản. Giá trị cao thể hiện độ quan trọng cao và nó phụ thuộc vào số lần từ xuất hiện trong văn bản nhưng bù lại bởi tần suất của từ đó trong tập dữ liệu.\n\nTF: Term Frequency(Tần suất xuất hiện của từ) là số lần từ xuất hiện trong văn bản.Vì các văn bản có thể có độ dài ngắn khác nhau nên một số từ có thể xuất hiện nhiều lần trong một văn bản dài hơn là một văn bản ngắn. Như vậy, term frequency thường được chia cho độ dài văn bản( tổng số từ trong một văn bản).\n\nIDF: Inverse Document Frequency(Nghịch đảo tần suất của văn bản), giúp đánh giá tầm quan trọng của một từ. Khi tính toán TF , tất cả các từ được coi như có độ quan trọng bằng nhau. Nhưng một số từ như “is”, “of” và “that” thường xuất hiện rất nhiều lần nhưng độ quan trọng là không cao. Như thế chúng ta cần giảm độ quan trọng của những từ này xuống.","metadata":{}},{"cell_type":"code","source":"from sklearn.feature_extraction.text import TfidfVectorizer\nvectorizer = TfidfVectorizer()\nX = vectorizer.fit_transform(train_data['question_text_cleaned'].tolist())","metadata":{"execution":{"iopub.status.busy":"2021-06-11T08:52:07.813166Z","iopub.execute_input":"2021-06-11T08:52:07.813565Z","iopub.status.idle":"2021-06-11T08:52:24.157170Z","shell.execute_reply.started":"2021-06-11T08:52:07.813533Z","shell.execute_reply":"2021-06-11T08:52:24.156243Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Chia dữ liệu theo tỉ lẹ 80:20. 20% để kiểm tra và 80% để huấn luyện","metadata":{}},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, train_data.target, test_size=0.2, random_state=1)","metadata":{"execution":{"iopub.status.busy":"2021-06-11T08:52:31.764482Z","iopub.execute_input":"2021-06-11T08:52:31.764839Z","iopub.status.idle":"2021-06-11T08:52:31.944667Z","shell.execute_reply.started":"2021-06-11T08:52:31.764811Z","shell.execute_reply":"2021-06-11T08:52:31.943738Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# CÁC PHƯƠNG PHÁP CÂN BẰNG DỮ LIỆU","metadata":{}},{"cell_type":"markdown","source":"Do dữ liệu mất cân bằng nên ta cần **cân bằng lại dữ liệu**. Em sẽ sử dụng Oversampling và Undersampling để cân bằng dữ liệu.\n\n***Undersampling*** lấy mẫu làm cân bằng tập dữ liệu bằng cách giảm kích thước của lớp trội. Phương pháp này được sử dụng khi số lượng dữ liệu là đủ. Bằng cách giữ tất cả các mẫu trong lớp hiếm và chọn ngẫu nhiên một số trong lớp trội, một tập dữ liệu cân bằng mới có thể được lấy ra để lập mô hình tiếp theo.\n\n***Oversampling*** là kỹ thuật lấy mẫu quá mức, tức là lấy ngẫu nhiên các mẫu dữ liệu ở lớp thiểu số (trong trường hợp này là các câu hỏi nhãn 0) để bù thêm vào chính nó nhằm đạt được sự phân bố số lượng xấp xỉ với lớp đa số(câu hỏi có nhãn 1).","metadata":{}},{"cell_type":"code","source":"#OVERSAMPLING\nfrom imblearn.over_sampling import RandomOverSampler\nros = RandomOverSampler(sampling_strategy=0.6, random_state=1)\nX_resampled, y_resampled = ros.fit_resample(X_train, y_train)","metadata":{"execution":{"iopub.status.busy":"2021-06-11T08:54:37.079455Z","iopub.execute_input":"2021-06-11T08:54:37.079811Z","iopub.status.idle":"2021-06-11T08:54:37.584729Z","shell.execute_reply.started":"2021-06-11T08:54:37.079781Z","shell.execute_reply":"2021-06-11T08:54:37.583855Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import collections\ncount = collections.Counter(y_resampled)\nlist_value = list(count.values())\nratio = pd.DataFrame({\n    'Label': ['0','1'],\n\n    'Tỉ lệ': [list_value[0]/(list_value[0] + list_value[1]) * 100,\n              list_value[1]/(list_value[0] + list_value[1]) * 100]})\nratio","metadata":{"execution":{"iopub.status.busy":"2021-06-11T08:54:40.087045Z","iopub.execute_input":"2021-06-11T08:54:40.087389Z","iopub.status.idle":"2021-06-11T08:54:40.322287Z","shell.execute_reply.started":"2021-06-11T08:54:40.087356Z","shell.execute_reply":"2021-06-11T08:54:40.321391Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# UNDERSAMPLING\nfrom imblearn.under_sampling import RandomUnderSampler\nros = RandomUnderSampler(sampling_strategy=0.4, random_state=1)\nX_resampled_under, y_resampled_under = ros.fit_resample(X_train, y_train)","metadata":{"execution":{"iopub.status.busy":"2021-06-11T08:56:33.845213Z","iopub.execute_input":"2021-06-11T08:56:33.845593Z","iopub.status.idle":"2021-06-11T08:56:34.254512Z","shell.execute_reply.started":"2021-06-11T08:56:33.845561Z","shell.execute_reply":"2021-06-11T08:56:34.253636Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# ÁP DỤNG VÀO MODEL","metadata":{}},{"cell_type":"markdown","source":"**NAIVE BAYES**","metadata":{}},{"cell_type":"markdown","source":"Naive Bayes chủ yếu được sử dụng trong phân loại văn bản. Đặc trưng đầu vào ở đây chính là tần suất xuất hiện của từ trong văn bản đó.","metadata":{}},{"cell_type":"markdown","source":"**Naive Bayes trước khi resampling**","metadata":{}},{"cell_type":"code","source":"from sklearn.naive_bayes import MultinomialNB\nmodel_nb = MultinomialNB().fit(X_train, y_train)\ny_pred = model_nb.predict(X_test)\nprint(\"Accuracy: \", accuracy_score(y_test, y_pred))\nprint(\"F1-score: \",f1_score(y_test, y_pred, pos_label=1))","metadata":{"execution":{"iopub.status.busy":"2021-06-11T08:52:35.826836Z","iopub.execute_input":"2021-06-11T08:52:35.827174Z","iopub.status.idle":"2021-06-11T08:52:36.085636Z","shell.execute_reply.started":"2021-06-11T08:52:35.827143Z","shell.execute_reply":"2021-06-11T08:52:36.084690Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**NB sau khi oversampling**","metadata":{}},{"cell_type":"code","source":"model_nb = MultinomialNB().fit(X_resampled, y_resampled)\ny_resampled_pred = model_nb.predict(X_test)\nprint(\"Accuracy: \", accuracy_score(y_test, y_resampled_pred))\nprint(\"F1-score: \",f1_score(y_test, y_resampled_pred, pos_label=1))","metadata":{"execution":{"iopub.status.busy":"2021-06-11T08:54:41.798576Z","iopub.execute_input":"2021-06-11T08:54:41.798935Z","iopub.status.idle":"2021-06-11T08:54:42.173282Z","shell.execute_reply.started":"2021-06-11T08:54:41.798902Z","shell.execute_reply":"2021-06-11T08:54:42.172390Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**NB sau khi undersampling**","metadata":{}},{"cell_type":"code","source":"model_nb = MultinomialNB().fit(X_resampled_under, y_resampled_under)\ny_resampled_pred = model_nb.predict(X_test)\nprint(\"Accuracy: \", accuracy_score(y_test, y_resampled_pred))\nprint(\"F1-score: \",f1_score(y_test, y_resampled_pred, pos_label=1))","metadata":{"execution":{"iopub.status.busy":"2021-06-11T08:56:36.509784Z","iopub.execute_input":"2021-06-11T08:56:36.510108Z","iopub.status.idle":"2021-06-11T08:56:36.648228Z","shell.execute_reply.started":"2021-06-11T08:56:36.510077Z","shell.execute_reply":"2021-06-11T08:56:36.647045Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"***Nhận xét:*** Trước khi resampling thì kết quả F1 khá thấp do dữ liệu mất cân bằng. Nhưng sau đó F1 đã tăng 0.4 đối với undersampling và 0.4 với oversampling","metadata":{}},{"cell_type":"markdown","source":"**LOGISTIC REGRESSION**","metadata":{}},{"cell_type":"markdown","source":"**Logistic Regression** là một thuật toán phân loại dùng để gán đối tượng cho một tập giá trị rời rạc và được ứng dụng trong phân loại thư rác và bài toán phân loại câu hỏi insincere này khá tương đồng.","metadata":{}},{"cell_type":"markdown","source":"**LR trước khi resampling**","metadata":{}},{"cell_type":"code","source":"from sklearn.linear_model import LogisticRegression\nmodel_lr = LogisticRegression()\nmodel_lr.fit(X_train, y_train)\n\ny_pred = model_lr.predict(X_test)\nprint(\"Accuracy: \", accuracy_score(y_test, y_pred))\nprint(\"F1-score: \",f1_score(y_test, y_pred, pos_label=1))","metadata":{"execution":{"iopub.status.busy":"2021-06-11T08:57:06.039145Z","iopub.execute_input":"2021-06-11T08:57:06.039549Z","iopub.status.idle":"2021-06-11T08:57:30.342520Z","shell.execute_reply.started":"2021-06-11T08:57:06.039507Z","shell.execute_reply":"2021-06-11T08:57:30.339836Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"***Nhận xét:*** LR có kết quả khá cao mặc dù dữ liệu mất cân bằng","metadata":{}},{"cell_type":"markdown","source":"**LR sau khi oversampling**","metadata":{}},{"cell_type":"code","source":"model_lr = LogisticRegression(max_iter=300)\nmodel_lr.fit(X_resampled, y_resampled)\n\ny_resampled_pred = model_lr.predict(X_test)\nprint(\"Accuracy: \", accuracy_score(y_test, y_resampled_pred))\nprint(\"F1-score: \",f1_score(y_test, y_resampled_pred, pos_label=1))","metadata":{"execution":{"iopub.status.busy":"2021-06-11T09:01:36.561993Z","iopub.execute_input":"2021-06-11T09:01:36.562355Z","iopub.status.idle":"2021-06-11T09:03:24.062407Z","shell.execute_reply.started":"2021-06-11T09:01:36.562317Z","shell.execute_reply":"2021-06-11T09:03:24.061545Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**LR sau khi undersampling**","metadata":{}},{"cell_type":"code","source":"model_lr = LogisticRegression(max_iter=300)\nmodel_lr.fit(X_resampled_under, y_resampled_under)\n\ny_resampled_pred = model_lr.predict(X_test)\nprint(\"Accuracy: \", accuracy_score(y_test, y_resampled_pred))\nprint(\"F1-score: \",f1_score(y_test, y_resampled_pred, pos_label=1))","metadata":{"execution":{"iopub.status.busy":"2021-06-11T09:05:54.056551Z","iopub.execute_input":"2021-06-11T09:05:54.056976Z","iopub.status.idle":"2021-06-11T09:06:16.987124Z","shell.execute_reply.started":"2021-06-11T09:05:54.056939Z","shell.execute_reply":"2021-06-11T09:06:16.986255Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"***Nhận xét:*** Sau khi xử lý mất cân bằng thì độ đo F1 không thay đổi nhiều những kết quả sau khi xử lý với Undersampling vẫn cao nhất","metadata":{}},{"cell_type":"markdown","source":"# TIỀN XỬ LÝ DỮ LIỆU VỚI TẬP EMBEDDINGS","metadata":{}},{"cell_type":"markdown","source":"***Word Embedding*** là mô hình ngôn ngữ và các phương pháp học theo đặc trưng trong Xử lý ngôn ngữ tự nhiên (NLP), ở đó các từ hoặc cụm từ được ánh xạ sang các vector số. Thay vì đi thẳng vào xử lý dữ liệu tiêu chuẩn như bên trên em sẽ sử dụng file pretrained có sẵn của GoogleNews. Tập embedding có sẵn của GoogleNews là một tập chứa các từ và vector có sẵn của từ đó. ","metadata":{}},{"cell_type":"markdown","source":"Đoạn code dưới đây là để theo dõi vốn từ huấn luyện, nó sẽ đi qua tất cả các text và đếm số lần xuất hiện của các từ có trong đó. Ta sẽ xây dựng một tập từ vựng dựa trên tập có sẵn của GoogleNews","metadata":{}},{"cell_type":"code","source":"from tqdm import tqdm\ntqdm.pandas()\ndef build_vocab(sentences, verbose =  True):\n    \"\"\"\n    :param sentences: list of list of words\n    :return: dictionary of words and their count\n    \"\"\"\n    vocab = {} \n    for sentence in tqdm(sentences, disable = (not verbose)):\n        for word in sentence:\n            try:\n                vocab[word] += 1\n            except KeyError:\n                vocab[word] = 1\n    return vocab","metadata":{"execution":{"iopub.status.busy":"2021-06-11T07:28:17.029740Z","iopub.execute_input":"2021-06-11T07:28:17.030100Z","iopub.status.idle":"2021-06-11T07:28:17.036697Z","shell.execute_reply.started":"2021-06-11T07:28:17.030066Z","shell.execute_reply":"2021-06-11T07:28:17.035699Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sentences = train_data[\"question_text\"].progress_apply(lambda x: x.split()).values\nvocab = build_vocab(sentences)\nprint({k: vocab[k] for k in list(vocab)[:5]})","metadata":{"execution":{"iopub.status.busy":"2021-06-11T07:28:22.762750Z","iopub.execute_input":"2021-06-11T07:28:22.763208Z","iopub.status.idle":"2021-06-11T07:28:33.779119Z","shell.execute_reply.started":"2021-06-11T07:28:22.763167Z","shell.execute_reply":"2021-06-11T07:28:33.778101Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Unzip tập embeddings và load file embeddings**","metadata":{}},{"cell_type":"code","source":"!unzip ../input/quora-insincere-questions-classification/embeddings.zip","metadata":{"execution":{"iopub.status.busy":"2021-06-11T07:12:34.730239Z","iopub.execute_input":"2021-06-11T07:12:34.730557Z","iopub.status.idle":"2021-06-11T07:14:23.795897Z","shell.execute_reply.started":"2021-06-11T07:12:34.730518Z","shell.execute_reply":"2021-06-11T07:14:23.790100Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from gensim.models import KeyedVectors\n\nnews_path = './GoogleNews-vectors-negative300/GoogleNews-vectors-negative300.bin'\nembeddings_index = KeyedVectors.load_word2vec_format(news_path, binary=True)","metadata":{"execution":{"iopub.status.busy":"2021-06-11T07:23:35.770519Z","iopub.execute_input":"2021-06-11T07:23:35.770862Z","iopub.status.idle":"2021-06-11T07:24:17.356988Z","shell.execute_reply.started":"2021-06-11T07:23:35.770831Z","shell.execute_reply":"2021-06-11T07:24:17.355964Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Đây là hàm kiểm tra sự tương quan giữa từ vựng với embeddings, xem xem tập vocab đó bao phủ bao nhiêu phần trăm dữ liệu của mình. Output sẽ là dánh sách các từ out of vocabulary (oov) mà ta có thể sử dụng để cải thiện quá trình tiền xử lý dữ liệu\n","metadata":{}},{"cell_type":"code","source":"import operator \n\ndef check_coverage(vocab,embeddings_index):\n    a = {}\n    oov = {}\n    k = 0\n    i = 0\n    for word in tqdm(vocab):\n        try:\n            a[word] = embeddings_index[word]\n            k += vocab[word]\n        except:\n\n            oov[word] = vocab[word]\n            i += vocab[word]\n            pass\n\n    print('Found embeddings for {:.2%} of vocab'.format(len(a) / len(vocab)))\n    print('Found embeddings for  {:.2%} of all text'.format(k / (k + i)))\n    sorted_x = sorted(oov.items(), key=operator.itemgetter(1))[::-1]\n\n    return sorted_x","metadata":{"execution":{"iopub.status.busy":"2021-06-11T07:28:44.488952Z","iopub.execute_input":"2021-06-11T07:28:44.489286Z","iopub.status.idle":"2021-06-11T07:28:44.496678Z","shell.execute_reply.started":"2021-06-11T07:28:44.489253Z","shell.execute_reply":"2021-06-11T07:28:44.495764Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"oov = check_coverage(vocab,embeddings_index)","metadata":{"execution":{"iopub.status.busy":"2021-06-11T07:28:47.964383Z","iopub.execute_input":"2021-06-11T07:28:47.964762Z","iopub.status.idle":"2021-06-11T07:28:49.728759Z","shell.execute_reply.started":"2021-06-11T07:28:47.964729Z","shell.execute_reply":"2021-06-11T07:28:49.727965Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Nhận xét: Chỉ có 24.31% từ vựng có embeddings nhưng độ bao phủ khá cao 78.75%. Ta sẽ quan sát oov đứng đầu","metadata":{}},{"cell_type":"code","source":"oov[:10]","metadata":{"execution":{"iopub.status.busy":"2021-06-11T07:28:53.477263Z","iopub.execute_input":"2021-06-11T07:28:53.477636Z","iopub.status.idle":"2021-06-11T07:28:53.484640Z","shell.execute_reply.started":"2021-06-11T07:28:53.477602Z","shell.execute_reply":"2021-06-11T07:28:53.483375Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"'?' in embeddings_index","metadata":{"execution":{"iopub.status.busy":"2021-06-11T07:28:55.948459Z","iopub.execute_input":"2021-06-11T07:28:55.948804Z","iopub.status.idle":"2021-06-11T07:28:55.954149Z","shell.execute_reply.started":"2021-06-11T07:28:55.948774Z","shell.execute_reply":"2021-06-11T07:28:55.953236Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"'&' in embeddings_index","metadata":{"execution":{"iopub.status.busy":"2021-06-11T07:28:58.228552Z","iopub.execute_input":"2021-06-11T07:28:58.228888Z","iopub.status.idle":"2021-06-11T07:28:58.234586Z","shell.execute_reply.started":"2021-06-11T07:28:58.228857Z","shell.execute_reply":"2021-06-11T07:28:58.233580Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Trong khi các kí tự đặc biệt có trong Google Embeddings thì các dấu chấm câu lại không có -> ta sẽ tạo một hàm để tách các kí tự đặc biệt và xóa những kí tự còn lại","metadata":{}},{"cell_type":"code","source":"def clean_puncts(x):\n    x = str(x)\n    for punct in \"/-'\":\n        x = x.replace(punct, ' ')\n    for punct in '& \"#$%\\'()*+-/ <=>@[\\\\]^_`{|}~':\n        x = x.replace(punct, f' {punct} ')\n    for punct in '?!.,:;' '“”’':\n        x = x.replace(punct, '')\n    return x","metadata":{"execution":{"iopub.status.busy":"2021-06-11T07:29:20.313410Z","iopub.execute_input":"2021-06-11T07:29:20.313776Z","iopub.status.idle":"2021-06-11T07:29:20.318587Z","shell.execute_reply.started":"2021-06-11T07:29:20.313745Z","shell.execute_reply":"2021-06-11T07:29:20.317619Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data[\"question_text\"] = train_data[\"question_text\"].progress_apply(lambda x: clean_puncts(x))\nsentences = train_data[\"question_text\"].apply(lambda x: x.split())\nvocab = build_vocab(sentences)","metadata":{"execution":{"iopub.status.busy":"2021-06-11T07:29:52.057118Z","iopub.execute_input":"2021-06-11T07:29:52.057486Z","iopub.status.idle":"2021-06-11T07:30:23.269259Z","shell.execute_reply.started":"2021-06-11T07:29:52.057452Z","shell.execute_reply":"2021-06-11T07:30:23.268436Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"oov = check_coverage(vocab,embeddings_index)","metadata":{"execution":{"iopub.status.busy":"2021-06-11T07:30:25.882581Z","iopub.execute_input":"2021-06-11T07:30:25.882930Z","iopub.status.idle":"2021-06-11T07:30:26.907141Z","shell.execute_reply.started":"2021-06-11T07:30:25.882898Z","shell.execute_reply":"2021-06-11T07:30:26.906332Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Nhận xét:** kết quả tăng từ 24.31% đến 58.55% sau khi ta xử lý các kí tự đặc biệt","metadata":{}},{"cell_type":"code","source":"oov[:10]","metadata":{"execution":{"iopub.status.busy":"2021-06-11T07:30:36.804624Z","iopub.execute_input":"2021-06-11T07:30:36.804999Z","iopub.status.idle":"2021-06-11T07:30:36.814017Z","shell.execute_reply.started":"2021-06-11T07:30:36.804966Z","shell.execute_reply":"2021-06-11T07:30:36.812958Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Tiếp theo, ta sẽ loại bỏ những chữ số trong dữ liệu và thay những số lớn hơn 9 bằng dấu ## qua hàm ***clean_numbers()***","metadata":{}},{"cell_type":"code","source":"import re\ndef clean_number(x):\n    x = re.sub('[0-9]{5,}', '#####', x)\n    x = re.sub('[0-9]{4}', '####', x)\n    x = re.sub('[0-9]{3}', '###', x)\n    x = re.sub('[0-9]{2}', '##', x)\n    return x","metadata":{"execution":{"iopub.status.busy":"2021-06-11T07:30:47.416265Z","iopub.execute_input":"2021-06-11T07:30:47.416629Z","iopub.status.idle":"2021-06-11T07:30:47.421989Z","shell.execute_reply.started":"2021-06-11T07:30:47.416597Z","shell.execute_reply":"2021-06-11T07:30:47.420969Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data[\"question_text\"] = train_data[\"question_text\"].progress_apply(lambda x: clean_numbers(x))\nsentences = train_data[\"question_text\"].progress_apply(lambda x: x.split())\nvocab = build_vocab(sentences)","metadata":{"execution":{"iopub.status.busy":"2021-06-11T07:30:55.868950Z","iopub.execute_input":"2021-06-11T07:30:55.869388Z","iopub.status.idle":"2021-06-11T07:31:12.264039Z","shell.execute_reply.started":"2021-06-11T07:30:55.869345Z","shell.execute_reply":"2021-06-11T07:31:12.263013Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"oov = check_coverage(vocab,embeddings_index)","metadata":{"execution":{"iopub.status.busy":"2021-06-11T07:31:14.524026Z","iopub.execute_input":"2021-06-11T07:31:14.524376Z","iopub.status.idle":"2021-06-11T07:31:15.418210Z","shell.execute_reply.started":"2021-06-11T07:31:14.524342Z","shell.execute_reply":"2021-06-11T07:31:15.417193Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Nhận xét:** Kết quả tăng lên 62.29% sau khi ta xử lý chữ số. Không tăng nhiều như xử lý kí tự đặc biệt nhưng cũng có cải thiện","metadata":{}},{"cell_type":"code","source":"oov[:20]","metadata":{"execution":{"iopub.status.busy":"2021-06-11T07:31:29.812101Z","iopub.execute_input":"2021-06-11T07:31:29.812463Z","iopub.status.idle":"2021-06-11T07:31:29.822048Z","shell.execute_reply.started":"2021-06-11T07:31:29.812429Z","shell.execute_reply":"2021-06-11T07:31:29.821190Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Vấn đề tiếp theo là những từ tiếng anh thường được đánh vần nhầm như 'color' và 'colour'hay những từ viết tắt. Ta sẽ chuyển các từ này thành từ hoàn chỉnh để không làm mất ý của câu hỏi bằng hàm ***clean_misspell()***","metadata":{}},{"cell_type":"code","source":"train_data[\"question_text\"] = train_data[\"question_text\"].progress_apply(lambda x: clean_misspell(x))\nsentences = train_data[\"question_text\"].progress_apply(lambda x: x.split())\nvocab = build_vocab(sentences)","metadata":{"execution":{"iopub.status.busy":"2021-06-11T07:31:42.257028Z","iopub.execute_input":"2021-06-11T07:31:42.257379Z","iopub.status.idle":"2021-06-11T07:31:56.405514Z","shell.execute_reply.started":"2021-06-11T07:31:42.257345Z","shell.execute_reply":"2021-06-11T07:31:56.404489Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"oov = check_coverage(vocab,embeddings_index)","metadata":{"execution":{"iopub.status.busy":"2021-06-11T07:32:12.415779Z","iopub.execute_input":"2021-06-11T07:32:12.416169Z","iopub.status.idle":"2021-06-11T07:32:13.483569Z","shell.execute_reply.started":"2021-06-11T07:32:12.416125Z","shell.execute_reply":"2021-06-11T07:32:13.482402Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"oov[:10]","metadata":{"execution":{"iopub.status.busy":"2021-06-11T07:32:23.147691Z","iopub.execute_input":"2021-06-11T07:32:23.148049Z","iopub.status.idle":"2021-06-11T07:32:23.153461Z","shell.execute_reply.started":"2021-06-11T07:32:23.148005Z","shell.execute_reply":"2021-06-11T07:32:23.152566Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Ta sẽ loại bỏ các từ stopwords như 'a', 'of', and'...bằng hàm ***clean_stopwords()***","metadata":{}},{"cell_type":"code","source":"def clean_stopword(x):\n  x = [word for word in x.split() if word not in nltk_stopwords]\n  x = ' '.join(x)\n  return x","metadata":{"execution":{"iopub.status.busy":"2021-06-11T07:32:49.160002Z","iopub.execute_input":"2021-06-11T07:32:49.160490Z","iopub.status.idle":"2021-06-11T07:32:49.165220Z","shell.execute_reply.started":"2021-06-11T07:32:49.160440Z","shell.execute_reply":"2021-06-11T07:32:49.164189Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data[\"question_text\"] = train_data[\"question_text\"].progress_apply(lambda x: clean_stopwords(x))\nsentences = train_data[\"question_text\"].progress_apply(lambda x: x.split())\nvocab = build_vocab(sentences)","metadata":{"execution":{"iopub.status.busy":"2021-06-11T07:32:54.584989Z","iopub.execute_input":"2021-06-11T07:32:54.585350Z","iopub.status.idle":"2021-06-11T07:33:30.683572Z","shell.execute_reply.started":"2021-06-11T07:32:54.585308Z","shell.execute_reply":"2021-06-11T07:33:30.682661Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"oov = check_coverage(vocab,embeddings_index)","metadata":{"execution":{"iopub.status.busy":"2021-06-11T07:33:33.702587Z","iopub.execute_input":"2021-06-11T07:33:33.702926Z","iopub.status.idle":"2021-06-11T07:33:34.604659Z","shell.execute_reply.started":"2021-06-11T07:33:33.702894Z","shell.execute_reply":"2021-06-11T07:33:34.603647Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Nhận xét:** Kết quả không thay đổi sau khi ta xử lý các lỗi từ vựng và stopwords nhưng độ phủ tăng lên 96.50%\n","metadata":{}},{"cell_type":"code","source":"oov[:10]","metadata":{"execution":{"iopub.status.busy":"2021-06-11T07:33:42.386614Z","iopub.execute_input":"2021-06-11T07:33:42.386975Z","iopub.status.idle":"2021-06-11T07:33:42.392216Z","shell.execute_reply.started":"2021-06-11T07:33:42.386943Z","shell.execute_reply":"2021-06-11T07:33:42.391387Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Sau khi tiền xử lý thì những từ không xuất hiện trong embeddings bây giờ không có giá trị nên ta có thể loại bỏ chúng","metadata":{}},{"cell_type":"code","source":"def clean(x):\n    x = clean_puncts(x)\n    x = clean_misspell(x)\n    x = clean_number(x)\n    x = clean_stopword(x)\n    return x","metadata":{"execution":{"iopub.status.busy":"2021-06-11T07:33:51.879216Z","iopub.execute_input":"2021-06-11T07:33:51.879679Z","iopub.status.idle":"2021-06-11T07:33:51.886971Z","shell.execute_reply.started":"2021-06-11T07:33:51.879633Z","shell.execute_reply":"2021-06-11T07:33:51.886035Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data.head()","metadata":{"execution":{"iopub.status.busy":"2021-06-11T07:34:34.554573Z","iopub.execute_input":"2021-06-11T07:34:34.554928Z","iopub.status.idle":"2021-06-11T07:34:34.567768Z","shell.execute_reply.started":"2021-06-11T07:34:34.554896Z","shell.execute_reply":"2021-06-11T07:34:34.566794Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Build tập vocab**","metadata":{}},{"cell_type":"code","source":"train_data['processed'] = train_data['question_text'].progress_map(lambda x: clean(x))","metadata":{"execution":{"iopub.status.busy":"2021-06-11T07:37:20.853004Z","iopub.execute_input":"2021-06-11T07:37:20.853479Z","iopub.status.idle":"2021-06-11T07:38:23.950425Z","shell.execute_reply.started":"2021-06-11T07:37:20.853430Z","shell.execute_reply":"2021-06-11T07:38:23.949558Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data.head()","metadata":{"execution":{"iopub.status.busy":"2021-06-11T07:38:36.638912Z","iopub.execute_input":"2021-06-11T07:38:36.639257Z","iopub.status.idle":"2021-06-11T07:38:36.650983Z","shell.execute_reply.started":"2021-06-11T07:38:36.639225Z","shell.execute_reply":"2021-06-11T07:38:36.649990Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_data = pd.read_csv('/kaggle/input/quora-insincere-questions-classification/test.csv')","metadata":{"execution":{"iopub.status.busy":"2021-06-11T07:39:46.715705Z","iopub.execute_input":"2021-06-11T07:39:46.716048Z","iopub.status.idle":"2021-06-11T07:39:47.707762Z","shell.execute_reply.started":"2021-06-11T07:39:46.716016Z","shell.execute_reply":"2021-06-11T07:39:47.706875Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_data.head()","metadata":{"execution":{"iopub.status.busy":"2021-06-11T07:39:59.555008Z","iopub.execute_input":"2021-06-11T07:39:59.555404Z","iopub.status.idle":"2021-06-11T07:39:59.574371Z","shell.execute_reply.started":"2021-06-11T07:39:59.555367Z","shell.execute_reply":"2021-06-11T07:39:59.573389Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_data['processed'] = test_data['question_text'].progress_map(lambda x: clean(x))","metadata":{"execution":{"iopub.status.busy":"2021-06-11T07:40:12.258928Z","iopub.execute_input":"2021-06-11T07:40:12.259277Z","iopub.status.idle":"2021-06-11T07:40:35.195802Z","shell.execute_reply.started":"2021-06-11T07:40:12.259245Z","shell.execute_reply":"2021-06-11T07:40:35.194760Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"text = pd.concat([train_data.processed, test_data.processed])\nvocabulary = build_vocab(text)","metadata":{"execution":{"iopub.status.busy":"2021-06-11T07:47:12.981540Z","iopub.execute_input":"2021-06-11T07:47:12.981882Z","iopub.status.idle":"2021-06-11T07:47:21.870931Z","shell.execute_reply.started":"2021-06-11T07:47:12.981851Z","shell.execute_reply":"2021-06-11T07:47:21.869959Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"max_feat=30000\nfeat_vec=300\nmax_len=55 #toi da so tu cua cau hoi duoc dung\nvocab_size=len(vocabulary)","metadata":{"execution":{"iopub.status.busy":"2021-06-11T07:47:25.160163Z","iopub.execute_input":"2021-06-11T07:47:25.160526Z","iopub.status.idle":"2021-06-11T07:47:25.164562Z","shell.execute_reply.started":"2021-06-11T07:47:25.160494Z","shell.execute_reply":"2021-06-11T07:47:25.163575Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Sau đây, ta sẽ lấy ra index của tập từ điển để mã hóa one hot","metadata":{}},{"cell_type":"code","source":"def get_word_index(vocab): #lấy ra index của từ trong tập từ vựng\n    word_index=dict((w,i+1) for i,w in enumerate(vocab.keys()))\n    return word_index\ndef fit_one_hot(word_index,corpus): #mã hóa \n    sent=[]\n    for text in tqdm(corpus):\n        li=[]\n        for word in text.split():\n            try:\n                li.append(word_index[word])\n            except KeyError:\n                li.append(0)\n        sent.append(li)\n    return sent","metadata":{"execution":{"iopub.status.busy":"2021-06-11T07:47:30.184506Z","iopub.execute_input":"2021-06-11T07:47:30.184851Z","iopub.status.idle":"2021-06-11T07:47:30.191102Z","shell.execute_reply.started":"2021-06-11T07:47:30.184818Z","shell.execute_reply":"2021-06-11T07:47:30.189728Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Chia tập dữ liệu train thành train:validation theo tỉ lệ 4:1","metadata":{}},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\ntrain, val=train_test_split(train_data,test_size=0.2,stratify=train_data.target,random_state=123)","metadata":{"execution":{"iopub.status.busy":"2021-06-11T07:50:58.590434Z","iopub.execute_input":"2021-06-11T07:50:58.590788Z","iopub.status.idle":"2021-06-11T07:50:59.878986Z","shell.execute_reply.started":"2021-06-11T07:50:58.590757Z","shell.execute_reply":"2021-06-11T07:50:59.877978Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nword_index=get_word_index(vocabulary)\n### Chuẩn bị dữ liệu đã được xử lý\ntrain_text = train['processed']\nval_text = val['processed']\ntest_text = test_data['processed']\n\n### mã hóa câu trong tập train sang dạng onehot cho dễ xử lý\nencodes=fit_one_hot(word_index,train_text)\ntrain_padded=pad_sequences(encodes,maxlen=max_len,padding=\"post\")\n\n### mã hóa câu trong tập validation sang dạng onehot cho dễ xử lý\nencodes_=fit_one_hot(word_index,val_text)\nval_padded=pad_sequences(encodes_,maxlen=max_len,padding=\"post\")\n\n### mã hóa câu trong tập test sang dạng onehot cho dễ xử lý\nencodes__=fit_one_hot(word_index,test_text)\ntest_padded=pad_sequences(encodes__,maxlen=max_len,padding=\"post\")","metadata":{"execution":{"iopub.status.busy":"2021-06-11T08:05:02.404182Z","iopub.execute_input":"2021-06-11T08:05:02.404565Z","iopub.status.idle":"2021-06-11T08:05:22.162700Z","shell.execute_reply.started":"2021-06-11T08:05:02.404525Z","shell.execute_reply":"2021-06-11T08:05:22.161706Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"count=0\n#Khởi tạo ma trận embeddings với size của tập vocab\nembedding_mat=np.zeros((vocab_size,300))\nfor word,i in tqdm(word_index.items()):\n    try:\n        vec=embeddings_index[word]\n        embedding_mat[i]=vec\n    except KeyError:\n        count+=1\n        continue\n\nprint(\"Number of Out of Vocabulary\",count)","metadata":{"execution":{"iopub.status.busy":"2021-06-11T08:05:22.165272Z","iopub.execute_input":"2021-06-11T08:05:22.165665Z","iopub.status.idle":"2021-06-11T08:05:22.188923Z","shell.execute_reply.started":"2021-06-11T08:05:22.165626Z","shell.execute_reply":"2021-06-11T08:05:22.187677Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_padded.shape","metadata":{"execution":{"iopub.status.busy":"2021-06-11T08:05:37.199690Z","iopub.execute_input":"2021-06-11T08:05:37.200041Z","iopub.status.idle":"2021-06-11T08:05:37.205741Z","shell.execute_reply.started":"2021-06-11T08:05:37.200004Z","shell.execute_reply":"2021-06-11T08:05:37.204626Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_padded.shape","metadata":{"execution":{"iopub.status.busy":"2021-06-11T08:05:39.670798Z","iopub.execute_input":"2021-06-11T08:05:39.671263Z","iopub.status.idle":"2021-06-11T08:05:39.676866Z","shell.execute_reply.started":"2021-06-11T08:05:39.671220Z","shell.execute_reply":"2021-06-11T08:05:39.675875Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# ÁP DỤNG VÀO MÔ HÌNH LOGISTIC REGRESSION","metadata":{}},{"cell_type":"markdown","source":"Logistic Regression là một thuật toán phân loại dùng để gán đối tượng cho một tập giá trị rời rạc và được ứng dụng trong phân loại thư rác và bài toán phân loại câu hỏi insincere này khá tương đồng.","metadata":{}},{"cell_type":"code","source":"from sklearn.metrics import accuracy_score, f1_score, classification_report\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn import *","metadata":{"execution":{"iopub.status.busy":"2021-06-11T09:35:51.686798Z","iopub.execute_input":"2021-06-11T09:35:51.687144Z","iopub.status.idle":"2021-06-11T09:35:51.691063Z","shell.execute_reply.started":"2021-06-11T09:35:51.687110Z","shell.execute_reply":"2021-06-11T09:35:51.690178Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n%%time\nmodel = LogisticRegression(max_iter=300)\n## Chạy mô hình\nprint(f\"Running Logistic Regression\")\nmodel.fit(train_padded, train.target)\n\n\ny_pred = model_lr.predict(val_padded)\nprint(\"Accuracy: \", accuracy_score(val.target, y_pred))\nprint(\"F1-score: \",f1_score(val.target, y_pred, pos_label=1))","metadata":{"execution":{"iopub.status.busy":"2021-06-11T09:35:54.126427Z","iopub.execute_input":"2021-06-11T09:35:54.126775Z","iopub.status.idle":"2021-06-11T09:36:39.374709Z","shell.execute_reply.started":"2021-06-11T09:35:54.126745Z","shell.execute_reply":"2021-06-11T09:36:39.373792Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}