{"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":"code","source":"%matplotlib inline\nimport warnings\nwarnings.filterwarnings('ignore')\n\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nfrom subprocess import check_output\n\n%matplotlib inline\nimport plotly.offline as py\npy.init_notebook_mode(connected=True)\nimport plotly.graph_objs as go\nimport plotly.tools as tls\n\nimport os\nimport gc\nimport csv\nimport re\nimport string\n\nfrom tqdm import tqdm\nfrom collections import Counter\nfrom wordcloud import WordCloud, STOPWORDS\nfrom scipy.sparse import hstack\nfrom IPython.display import Image\nfrom tqdm import tqdm_notebook\ntqdm_notebook().pandas()\n\nfrom nltk.corpus import stopwords\nfrom nltk.stem import PorterStemmer, SnowballStemmer, WordNetLemmatizer\nfrom nltk.stem.lancaster import LancasterStemmer\nfrom nltk.util import ngrams","metadata":{"execution":{"iopub.status.busy":"2021-05-23T14:57:39.743313Z","iopub.execute_input":"2021-05-23T14:57:39.743722Z","iopub.status.idle":"2021-05-23T14:57:40.545420Z","shell.execute_reply.started":"2021-05-23T14:57:39.743638Z","shell.execute_reply":"2021-05-23T14:57:40.544665Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import nltk\nnltk.download('wordnet')\nnltk.download('punkt')\nnltk.download('stopwords')","metadata":{"execution":{"iopub.status.busy":"2021-05-23T14:57:40.546950Z","iopub.execute_input":"2021-05-23T14:57:40.547541Z","iopub.status.idle":"2021-05-23T14:58:40.647087Z","shell.execute_reply.started":"2021-05-23T14:57:40.547496Z","shell.execute_reply":"2021-05-23T14:58:40.646035Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Đọc dữ liệu và các số liệu thống kê cơ bản","metadata":{}},{"cell_type":"code","source":"#Đọc dữ liệu từ file data\ntrain = pd.read_csv(\"../input/quora-insincere-questions-classification/train.csv\")\n#Đọc dữ liệu từ file test \ntest=pd.read_csv(\"../input/quora-insincere-questions-classification/test.csv\")\nprint(\"Number of train data points:\",train.shape[0])\nprint(\"Number of test data points:\",test.shape[0])\nprint(\"Shape of Train Data:\", train.shape)\nprint(\"Shape of Test Data:\", test.shape)","metadata":{"execution":{"iopub.status.busy":"2021-05-23T14:58:40.649553Z","iopub.execute_input":"2021-05-23T14:58:40.650306Z","iopub.status.idle":"2021-05-23T14:58:44.442504Z","shell.execute_reply.started":"2021-05-23T14:58:40.650261Z","shell.execute_reply":"2021-05-23T14:58:44.441474Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"* Nhận xét :\n* Tập dữ liệu train bao gồm 1.3 triệu dòng và 3 cột\n* Tập dữ liệu test hơn 300 nghìn dòng và 2 cột ","metadata":{}},{"cell_type":"code","source":"train.head()","metadata":{"execution":{"iopub.status.busy":"2021-05-23T14:58:44.444544Z","iopub.execute_input":"2021-05-23T14:58:44.445300Z","iopub.status.idle":"2021-05-23T14:58:44.461123Z","shell.execute_reply.started":"2021-05-23T14:58:44.445251Z","shell.execute_reply":"2021-05-23T14:58:44.459667Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"* Có 3 trường dữ liệu :\n* qid: mã định danh câu hỏi \n* question_text : Các câu hỏi trên quora \n* target : một câu hỏi có nhãn \"toxic\" có giá trị là 1 , nếu không là 0","metadata":{}},{"cell_type":"code","source":"train.info()","metadata":{"execution":{"iopub.status.busy":"2021-05-23T14:58:44.462631Z","iopub.execute_input":"2021-05-23T14:58:44.463111Z","iopub.status.idle":"2021-05-23T14:58:44.718851Z","shell.execute_reply.started":"2021-05-23T14:58:44.463081Z","shell.execute_reply":"2021-05-23T14:58:44.717834Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Tỉ lệ dữ liệu giữa câu hỏi toxic và câu hỏi không toxic :","metadata":{}},{"cell_type":"code","source":"train.groupby(\"target\")['qid'].count().plot.bar()","metadata":{"execution":{"iopub.status.busy":"2021-05-23T14:58:44.720077Z","iopub.execute_input":"2021-05-23T14:58:44.720363Z","iopub.status.idle":"2021-05-23T14:58:45.011486Z","shell.execute_reply.started":"2021-05-23T14:58:44.720336Z","shell.execute_reply":"2021-05-23T14:58:45.010303Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('~> Percentage of Sincere Questions (is_duplicate = 0):\\n   {}%'.format(100 - round(train['target'].mean()*100, 2)))\nprint('\\n~> Percentage of Insincere Questions (is_duplicate = 1):\\n   {}%'.format(round(train['target'].mean()*100, 2)))","metadata":{"execution":{"iopub.status.busy":"2021-05-23T14:58:45.013236Z","iopub.execute_input":"2021-05-23T14:58:45.013532Z","iopub.status.idle":"2021-05-23T14:58:45.025114Z","shell.execute_reply.started":"2021-05-23T14:58:45.013504Z","shell.execute_reply":"2021-05-23T14:58:45.023882Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"* Nhận xét\n* Dữ liệu về câu hỏi toxic chiếm 93.81% trong khi đó dữ liệu về câu hỏi không toxic chỉ chiếm 6.19%\n* Dữ liệu rất mất cân bằng và có rất ít câu hỏi được đánh dấu là toxic trong tập dữ liệu\n* Hướng giải quyết \n* Chia lại tập dữ liệu sao cho câu hỏi toxic và không toxic trở nên cân bằng hơn ","metadata":{}},{"cell_type":"code","source":"#Chia lại tập dữ liệu theo tỉ lệ 3:1\nfrom sklearn.utils import resample\n\nsincere = train[train.target == 0]\ninsincere = train[train.target == 1]\nx = pd.concat([resample(sincere,replace = True,n_samples = len(insincere)*3), insincere])\nx","metadata":{"execution":{"iopub.status.busy":"2021-05-23T14:58:45.029017Z","iopub.execute_input":"2021-05-23T14:58:45.029943Z","iopub.status.idle":"2021-05-23T14:58:45.306706Z","shell.execute_reply.started":"2021-05-23T14:58:45.029893Z","shell.execute_reply":"2021-05-23T14:58:45.305672Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Phân tích dữ liệu trước khi xử lí","metadata":{}},{"cell_type":"markdown","source":"Dữ liệu thô không xem được nên cần thêm 1 số nhãn để phân tích rõ dữ liệu\n* freq_id : tần suất xuất hiện của id\n* q_len : độ dài của các câu hỏi \n* n_words : số từ trong câu hỏi\n* numeric_words : số lượng các chữ số trong câu \n* sp_char_words : số lượng các kí tự đặc biệt trong câu\n* char_words : số lượng các kí tự trong câu \n* unique_words : số lượng các từ duy nhất trong câu ","metadata":{}},{"cell_type":"code","source":"    train['freq_qid'] = train.groupby('qid')['qid'].transform('count') \n    train['qlen'] = train['question_text'].str.len() \n    train['n_words'] = train['question_text'].apply(lambda row: len(row.split(\" \")))\n    train['numeric_words'] = train['question_text'].apply(lambda row: sum(c.isdigit() for c in row))\n    train['sp_char_words'] = train['question_text'].str.findall(r'[^a-zA-Z0-9 ]').str.len()\n    train['char_words'] = train['question_text'].apply(lambda row: len(str(row)))\n    train['unique_words'] = train['question_text'].apply(lambda row: len(set(str(row).split())))\n    \ntrain.head()","metadata":{"execution":{"iopub.status.busy":"2021-05-23T14:58:45.308744Z","iopub.execute_input":"2021-05-23T14:58:45.309051Z","iopub.status.idle":"2021-05-23T14:59:09.123948Z","shell.execute_reply.started":"2021-05-23T14:58:45.309020Z","shell.execute_reply":"2021-05-23T14:59:09.117861Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Độ dài bé nhất của câu hỏi \nprint (\"Minimum length of the questions: \" , min(train['n_words']))\n# Độ dài lớn nhất của câu hỏi\nprint (\"Maximum length of the questions: \" , max(train['n_words']))\n# Độ dài trung bình của câu hỏi\nprint (\"Number of Questions with minimum length:\", train[train['n_words']== 1].shape[0])","metadata":{"execution":{"iopub.status.busy":"2021-05-23T14:59:09.128115Z","iopub.execute_input":"2021-05-23T14:59:09.128819Z","iopub.status.idle":"2021-05-23T14:59:09.589434Z","shell.execute_reply.started":"2021-05-23T14:59:09.128768Z","shell.execute_reply":"2021-05-23T14:59:09.588322Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Biểu đồ phân bố về nhãn 'n_word'**","metadata":{}},{"cell_type":"code","source":"plt.figure(figsize=(8, 8))\nsns.violinplot(x = 'target', y = 'n_words', data = train[0:])\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2021-05-23T14:59:09.590774Z","iopub.execute_input":"2021-05-23T14:59:09.591224Z","iopub.status.idle":"2021-05-23T14:59:12.727840Z","shell.execute_reply.started":"2021-05-23T14:59:09.591192Z","shell.execute_reply":"2021-05-23T14:59:12.726847Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"* Nhận xét \n* Hầu hết các câu hỏi có độ dài chủ yếu từ 12-20\n* Những câu hỏi toxic có độ dài không quá 80 và độ dài trung bình ngắn hơn so với câu hỏi không toxic ","metadata":{}},{"cell_type":"markdown","source":"**Biểu đồ phân bố về nhãn 'numeric_word'**","metadata":{}},{"cell_type":"code","source":"plt.figure(figsize=(8, 8))\nsns.violinplot(x = 'target', y = 'numeric_words', data = train[0:])\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2021-05-23T14:59:12.729135Z","iopub.execute_input":"2021-05-23T14:59:12.729495Z","iopub.status.idle":"2021-05-23T14:59:16.133252Z","shell.execute_reply.started":"2021-05-23T14:59:12.729458Z","shell.execute_reply":"2021-05-23T14:59:16.132164Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"* Nhận xét\n* Các từ là số trong câu hỏi không toxic dao động từ 0 đến hơn 200\n* Các từ là số trong câu hỏi toxic dao động từ 0 đến gần 100 ","metadata":{}},{"cell_type":"markdown","source":"**Biểu đồ phân bố về nhãn 'sp_char_words'**","metadata":{}},{"cell_type":"code","source":"plt.figure(figsize=(4, 4))\nsns.violinplot(x = 'target', y = 'sp_char_words', data = train[0:])\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2021-05-23T14:59:16.135161Z","iopub.execute_input":"2021-05-23T14:59:16.135813Z","iopub.status.idle":"2021-05-23T14:59:19.598649Z","shell.execute_reply.started":"2021-05-23T14:59:16.135763Z","shell.execute_reply":"2021-05-23T14:59:19.597691Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"* Nhận xét\n* Ở câu hỏi toxic số kí tự đặc biệt nhiều hơn gấp đôi so với câu hỏi không toxic\n* Câu hỏi không toxic có số lượng kí tự đặc biệt dao động từ 0 đến 150 và thường chỉ đa số chỉ có từ 0-1 kí tự đặc biệt\ntrong câu\n* Câu hỏi toxic có số lượng kí tự đặc biệt dao động từ 0-400 và đa số có từ 1-3 kí tự đặc biệt trong câu\n","metadata":{}},{"cell_type":"markdown","source":"**Biểu đồ phân bố về nhãn 'unique_words'**\n","metadata":{}},{"cell_type":"code","source":"plt.figure(figsize=(8, 8))\nsns.violinplot(x = 'target', y = 'unique_words', data = train[0:])\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2021-05-23T14:59:19.600181Z","iopub.execute_input":"2021-05-23T14:59:19.600881Z","iopub.status.idle":"2021-05-23T14:59:23.444751Z","shell.execute_reply.started":"2021-05-23T14:59:19.600840Z","shell.execute_reply":"2021-05-23T14:59:23.443753Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Biểu đồ phân bố về nhãn 'char_words'**\n","metadata":{}},{"cell_type":"code","source":"plt.figure(figsize=(4, 4))\nsns.violinplot(x = 'target', y = 'char_words', data = train[0:])\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2021-05-23T14:59:23.446072Z","iopub.execute_input":"2021-05-23T14:59:23.446381Z","iopub.status.idle":"2021-05-23T14:59:26.417380Z","shell.execute_reply.started":"2021-05-23T14:59:23.446350Z","shell.execute_reply":"2021-05-23T14:59:26.416350Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Nhận xét :\nSố lượng kí tự ở câu hỏi toxic từ 0 đến 1000 và tập trung trong đoạn 0-200\nSố lượng kí tự ở câu hỏi không toxic từ 0-gần 700 và tập trung trong đoạn 0-150","metadata":{}},{"cell_type":"markdown","source":"# Xử lí dữ liệu","metadata":{}},{"cell_type":"markdown","source":"*** Qua phân tích dữ liệu ở trên ta thấy dữ liệu có có những tác nhân gây nhiễu hoặc không cần thiết , dư thừa để xác nhận xem câu hỏi có phải toxic hay không . Qua đó chúng ta sẽ tìm cách loại bỏ nó :**\n* Loại bỏ những kí tự đặc biệt có trong câu\n* Loại bỏ dấu câu \n* Loại bỏ chữ số \n* Thay thế những từ sai chính tả\n* Thay thế các từ viết tắt \n* Loại bỏ những từ là stop word ( ví dụ \"a\" , \"an\", \"the\" ,...)\n* Biến đổi 1 từ về dạng gốc (được gọi là stem hoặc root form) bằng cách loại bỏ 1 số ký tự nằm ở cuối từ mà nó nghĩ rằng là biến thể của từ\n* giống như trên nhưng xử lý bằng cách loại bỏ các ký tự cuối từ theo thuật toán heuristic (lemmatization)","metadata":{}},{"cell_type":"code","source":"puncts=[',', '.', '\"', ':', ')', '(', '-', '!', '?', '|', ';', \"'\", '$', '&', '/', '[', ']', '>', '%', '=', '#', '*', '+', '\\\\', \n        '•', '~', '@', '£', '·', '_', '{', '}', '©', '^', '®', '`', '<', '→', '°', '€', '™', '›', '♥', '←', '×', '§', '″', '′', \n        '█', '…', '“', '★', '”', '–', '●', '►', '−', '¢', '¬', '░', '¡', '¶', '↑', '±', '¿', '▾', '═', '¦', '║', '―', '¥', '▓', \n        '—', '‹', '─', '▒', '：', '⊕', '▼', '▪', '†', '■', '’', '▀', '¨', '▄', '♫', '☆', '¯', '♦', '¤', '▲', '¸', '⋅', '‘', '∞', \n        '∙', '）', '↓', '、', '│', '（', '»', '，', '♪', '╩', '╚', '・', '╦', '╣', '╔', '╗', '▬', '❤', '≤', '‡', '√', '◄', '━', \n        '⇒', '▶', '≥', '╝', '♡', '◊', '。', '✈', '≡', '☺', '✔', '↵', '≈', '✓', '♣', '☎', '℃', '◦', '└', '‟', '～', '！', '○', \n        '◆', '№', '♠', '▌', '✿', '▸', '⁄', '□', '❖', '✦', '．', '÷', '｜', '┃', '／', '￥', '╠', '↩', '✭', '▐', '☼', '☻', '┐', \n        '├', '«', '∼', '┌', '℉', '☮', '฿', '≦', '♬', '✧', '〉', '－', '⌂', '✖', '･', '◕', '※', '‖', '◀', '‰', '\\x97', '↺', \n        '∆', '┘', '┬', '╬', '،', '⌘', '⊂', '＞', '〈', '⎙', '？', '☠', '⇐', '▫', '∗', '∈', '≠', '♀', '♔', '˚', '℗', '┗', '＊', \n        '┼', '❀', '＆', '∩', '♂', '‿', '∑', '‣', '➜', '┛', '⇓', '☯', '⊖', '☀', '┳', '；', '∇', '⇑', '✰', '◇', '♯', '☞', '´', \n        '↔', '┏', '｡', '◘', '∂', '✌', '♭', '┣', '┴', '┓', '✨', '\\xa0', '˜', '❥', '┫', '℠', '✒', '［', '∫', '\\x93', '≧', '］', \n        '\\x94', '∀', '♛', '\\x96', '∨', '◎', '↻', '⇩', '＜', '≫', '✩', '✪', '♕', '؟', '₤', '☛', '╮', '␊', '＋', '┈', '％', \n        '╋', '▽', '⇨', '┻', '⊗', '￡', '।', '▂', '✯', '▇', '＿', '➤', '✞', '＝', '▷', '△', '◙', '▅', '✝', '∧', '␉', '☭', \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        '⇣', '｛', '̄', '↝', '⎟', '▍', '❗', '״', '΄', '▞', '◁', '⛄', '⇝', '⎪', '♁', '⇠', '☇', '✊', 'ி', '｝', '⭕', '➘', \n        '⁀', '☙', '❛', '❓', '⟲', '⇀', '≲', 'ⓕ', '⎥', '\\u06dd', 'ͤ', '₋', '̱', '̎', '♝', '≳', '▙', '➭', '܀', 'ⓖ', '⇛', '▊', \n        '⇗', '̷', '⇱', '℅', 'ⓧ', '⚛', '̐', '̕', '⇌', '␀', '≌', 'ⓦ', '⊤', '̓', '☦', 'ⓕ', '▜', '➙', 'ⓨ', '⌨', '◮', '☷', \n        '◍', 'ⓚ', '≔', '⏩', '⍳', '℞', '┋', '˻', '▚', '≺', 'ْ', '▟', '➻', '̪', '⏪', '̉', '⎞', '┇', '⍟', '⇪', '▎', '⇦', '␝', \n        '⤷', '≖', '⟶', '♗', '̴', '♄', 'ͨ', '̈', '❜', '̡', '▛', '✁', '➩', 'ா', '˂', '↥', '⏎', '⎷', '̲', '➖', '↲', '⩵', '̗', '❢', \n        '≎', '⚔', '⇇', '̑', '⊿', '̖', '☍', '➹', '⥊', '⁁', '✢']","metadata":{"execution":{"iopub.status.busy":"2021-05-23T14:59:26.419109Z","iopub.execute_input":"2021-05-23T14:59:26.419427Z","iopub.status.idle":"2021-05-23T14:59:26.460526Z","shell.execute_reply.started":"2021-05-23T14:59:26.419396Z","shell.execute_reply":"2021-05-23T14:59:26.459195Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#loại bỏ kí tự đặc biệt\ndef clean_punct(x):\n    for punct in puncts:\n        if punct in x:\n            x = x.replace(punct, '{}' .format(punct))\n    return x","metadata":{"execution":{"iopub.status.busy":"2021-05-23T14:59:26.462265Z","iopub.execute_input":"2021-05-23T14:59:26.462719Z","iopub.status.idle":"2021-05-23T14:59:26.480991Z","shell.execute_reply.started":"2021-05-23T14:59:26.462674Z","shell.execute_reply":"2021-05-23T14:59:26.479674Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#loại bỏ chữ số \ndef clean_numbers(x):\n    if bool(re.search(r'\\d', 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-05-23T14:59:26.482670Z","iopub.execute_input":"2021-05-23T14:59:26.483093Z","iopub.status.idle":"2021-05-23T14:59:26.496536Z","shell.execute_reply.started":"2021-05-23T14:59:26.483051Z","shell.execute_reply":"2021-05-23T14:59:26.495316Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"mispell_dict = {'colour': 'color', 'centre': 'center', 'favourite': 'favorite', 'travelling': 'traveling', 'counselling': 'counseling', 'theatre': 'theater', 'cancelled': 'canceled', 'labour': 'labor', 'organisation': 'organization', 'wwii': 'world war 2', 'citicise': 'criticize', 'youtu ': 'youtube ', 'Qoura': 'Quora', 'sallary': 'salary', 'Whta': 'What', 'narcisist': 'narcissist', 'howdo': 'how do', 'whatare': 'what are', 'howcan': 'how can', 'howmuch': 'how much', 'howmany': 'how many', 'whydo': 'why do', 'doI': 'do I', 'theBest': 'the best', 'howdoes': 'how does', 'mastrubation': 'masturbation', 'mastrubate': 'masturbate', \"mastrubating\": 'masturbating', 'pennis': 'penis', 'Etherium': 'bitcoin', 'narcissit': 'narcissist', 'bigdata': 'big data', '2k17': '2017', '2k18': '2018', 'qouta': 'quota', 'exboyfriend': 'ex boyfriend', 'airhostess': 'air hostess', \"whst\": 'what', 'watsapp': 'whatsapp', 'demonitisation': 'demonetization', 'demonitization': 'demonetization', 'demonetisation': 'demonetization', \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                'iiest':'institute','dceu':'comics','pessat':'exam','uceed':'college','bhakts':'devotee','boruto':'anime',\n                'cryptocoin':'bitcoin','blockchains':'blockchain','fiancee':'fiance','redmi':'smartphone','oneplus':'smartphone','qoura':'quora','deepmind':'framework','ryzen':'cpu','whattsapp':'whatsapp',\n                'undertale':'adventure','zenfone':'smartphone','cryptocurencies':'cryptocurrencies','koinex':'bitcoin','zebpay':'bitcoin','binance':'bitcoin','whtsapp':'whatsapp',\n                'reactjs':'framework','bittrex':'bitcoin','bitconnect':'bitcoin','bitfinex':'bitcoin','yourquote':'your quote','whyis':'why is','jiophone':'smartphone',\n                'dogecoin':'bitcoin','onecoin':'bitcoin','poloniex':'bitcoin','7700k':'cpu','angular2':'framework','segwit2x':'bitcoin','hashflare':'bitcoin','940mx':'gpu',\n                'openai':'framework','hashflare':'bitcoin','1050ti':'gpu','nearbuy':'near buy','freebitco':'bitcoin','antminer':'bitcoin','filecoin':'bitcoin','whatapp':'whatsapp',\n                'empowr':'empower','1080ti':'gpu','crytocurrency':'cryptocurrency','8700k':'cpu','whatsaap':'whatsapp','g4560':'cpu','payymoney':'pay money',\n                'fuckboys':'fuck boys','intenship':'internship','zcash':'bitcoin','demonatisation':'demonetization','narcicist':'narcissist','mastuburation':'masturbation',\n                'trignometric':'trigonometric','cryptocurreny':'cryptocurrency','howdid':'how did','crytocurrencies':'cryptocurrencies','phycopath':'psychopath',\n                'bytecoin':'bitcoin','possesiveness':'possessiveness','scollege':'college','humanties':'humanities','altacoin':'bitcoin','demonitised':'demonetized',\n                'brasília':'brazilia','accolite':'accolyte','econimics':'economics','varrier':'warrier','quroa':'quora','statergy':'strategy','langague':'language',\n                'splatoon':'game','7600k':'cpu','gate2018':'gate 2018','in2018':'in 2018','narcassist':'narcissist','jiocoin':'bitcoin','hnlu':'hulu','7300hq':'cpu',\n                'weatern':'western','interledger':'blockchain','deplation':'deflation', 'cryptocurrencies':'cryptocurrency', 'bitcoin':'blockchain cryptocurrency',}","metadata":{"execution":{"iopub.status.busy":"2021-05-23T14:59:26.498361Z","iopub.execute_input":"2021-05-23T14:59:26.498756Z","iopub.status.idle":"2021-05-23T14:59:26.517297Z","shell.execute_reply.started":"2021-05-23T14:59:26.498668Z","shell.execute_reply":"2021-05-23T14:59:26.515979Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Thay thế các từ sai chính tả\ndef _get_mispell(mispell_dict):\n    mispell_re = re.compile('(%s)' % '|'.join(mispell_dict.keys()))\n    return mispell_dict, mispell_re\n\nmispellings, mispellings_re = _get_mispell(mispell_dict)\ndef replace_typical_misspell(text):\n    def replace(match):\n        return mispellings[match.group(0)]\n    return mispellings_re.sub(replace, text)","metadata":{"execution":{"iopub.status.busy":"2021-05-23T14:59:26.519134Z","iopub.execute_input":"2021-05-23T14:59:26.519456Z","iopub.status.idle":"2021-05-23T14:59:26.541261Z","shell.execute_reply.started":"2021-05-23T14:59:26.519424Z","shell.execute_reply":"2021-05-23T14:59:26.540441Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"contraction_dict = {\"ain't\": \"is not\", \"aren't\": \"are not\",\"can't\": \"cannot\", \"'cause\": \"because\", \"could've\": \"could have\", \"couldn't\": \"could not\", \"didn't\": \"did not\",  \"doesn't\": \"does not\", \"don't\": \"do not\", \"hadn't\": \"had not\", \"hasn't\": \"has not\", \"haven't\": \"have not\", \"he'd\": \"he would\",\"he'll\": \"he will\", \"he's\": \"he is\", \"how'd\": \"how did\", \"how'd'y\": \"how do you\", \"how'll\": \"how will\", \"how's\": \"how is\",  \"I'd\": \"I would\", \"I'd've\": \"I would have\", \"I'll\": \"I will\", \"I'll've\": \"I will have\",\"I'm\": \"I am\", \"I've\": \"I have\", \"i'd\": \"i would\", \"i'd've\": \"i would have\", \"i'll\": \"i will\",  \"i'll've\": \"i will have\",\"i'm\": \"i am\", \"i've\": \"i have\", \"isn't\": \"is not\", \"it'd\": \"it would\", \"it'd've\": \"it would have\", \"it'll\": \"it will\", \"it'll've\": \"it will have\",\"it's\": \"it is\", \"let's\": \"let us\", \"ma'am\": \"madam\", \"mayn't\": \"may not\", \"might've\": \"might have\",\"mightn't\": \"might not\",\"mightn't've\": \"might not have\", \"must've\": \"must have\", \"mustn't\": \"must not\", \"mustn't've\": \"must not have\", \"needn't\": \"need not\", \"needn't've\": \"need not have\",\"o'clock\": \"of the clock\", \"oughtn't\": \"ought not\", \"oughtn't've\": \"ought not have\", \"shan't\": \"shall not\", \"sha'n't\": \"shall not\", \"shan't've\": \"shall not have\", \"she'd\": \"she would\", \"she'd've\": \"she would have\", \"she'll\": \"she will\", \"she'll've\": \"she will have\", \"she's\": \"she is\", \"should've\": \"should have\", \"shouldn't\": \"should not\", \"shouldn't've\": \"should not have\", \"so've\": \"so have\",\"so's\": \"so as\", \"this's\": \"this is\",\"that'd\": \"that would\", \"that'd've\": \"that would have\", \"that's\": \"that is\", \"there'd\": \"there would\", \"there'd've\": \"there would have\", \"there's\": \"there is\", \"here's\": \"here is\",\"they'd\": \"they would\", \"they'd've\": \"they would have\", \"they'll\": \"they will\", \"they'll've\": \"they will have\", \"they're\": \"they are\", \"they've\": \"they have\", \"to've\": \"to have\", \"wasn't\": \"was not\", \"we'd\": \"we would\", \"we'd've\": \"we would have\", \"we'll\": \"we will\", \"we'll've\": \"we will have\", \"we're\": \"we are\", \"we've\": \"we have\", \"weren't\": \"were not\", \"what'll\": \"what will\", \"what'll've\": \"what will have\", \"what're\": \"what are\",  \"what's\": \"what is\", \"what've\": \"what have\", \"when's\": \"when is\", \"when've\": \"when have\", \"where'd\": \"where did\", \"where's\": \"where is\", \"where've\": \"where have\", \"who'll\": \"who will\", \"who'll've\": \"who will have\", \"who's\": \"who is\", \"who've\": \"who have\", \"why's\": \"why is\", \"why've\": \"why have\", \"will've\": \"will have\", \"won't\": \"will not\", \"won't've\": \"will not have\", \"would've\": \"would have\", \"wouldn't\": \"would not\", \"wouldn't've\": \"would not have\", \"y'all\": \"you all\", \"y'all'd\": \"you all would\",\"y'all'd've\": \"you all would have\",\"y'all're\": \"you all are\",\"y'all've\": \"you all have\",\"you'd\": \"you would\", \"you'd've\": \"you would have\", \"you'll\": \"you will\", \"you'll've\": \"you will have\", \"you're\": \"you are\", \"you've\": \"you have\"}","metadata":{"execution":{"iopub.status.busy":"2021-05-23T14:59:26.542726Z","iopub.execute_input":"2021-05-23T14:59:26.543017Z","iopub.status.idle":"2021-05-23T14:59:26.558880Z","shell.execute_reply.started":"2021-05-23T14:59:26.542989Z","shell.execute_reply":"2021-05-23T14:59:26.557992Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Thay thế các từ viết tắt\ndef _get_contractions(contraction_dict):\n    contraction_re = re.compile('(%s)' % '|'.join(contraction_dict.keys()))\n    return contraction_dict, contraction_re\n\ncontractions, contractions_re = _get_contractions(contraction_dict)\n\ndef replace_contractions(text):\n    def replace(match):\n        return contractions[match.group(0)]\n    return contractions_re.sub(replace, text)","metadata":{"execution":{"iopub.status.busy":"2021-05-23T14:59:26.560113Z","iopub.execute_input":"2021-05-23T14:59:26.560686Z","iopub.status.idle":"2021-05-23T14:59:26.580542Z","shell.execute_reply.started":"2021-05-23T14:59:26.560642Z","shell.execute_reply":"2021-05-23T14:59:26.579581Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#loại bỏ các từ trong stopword\nstopword_list = nltk.corpus.stopwords.words('english')\ndef remove_stopwords(text, is_lower_case=True):\n    tokenizer = ToktokTokenizer()\n    tokens = tokenizer.tokenize(text)\n    tokens = [token.strip() for token in tokens]\n    if is_lower_case:\n        filtered_tokens = [token for token in tokens if token not in stopword_list]\n    else:\n        filtered_tokens = [token for token in tokens if token.lower() not in stopword_list]\n    filtered_text = ' '.join(filtered_tokens)\n    return filtered_text","metadata":{"execution":{"iopub.status.busy":"2021-05-23T14:59:26.584007Z","iopub.execute_input":"2021-05-23T14:59:26.584370Z","iopub.status.idle":"2021-05-23T14:59:26.597434Z","shell.execute_reply.started":"2021-05-23T14:59:26.584332Z","shell.execute_reply":"2021-05-23T14:59:26.596274Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Stemming\nfrom nltk.stem import  SnowballStemmer\nfrom nltk.tokenize.toktok import ToktokTokenizer\ndef stem_text(text):\n    tokenizer = ToktokTokenizer()\n    stemmer = SnowballStemmer('english')\n    tokens = tokenizer.tokenize(text)\n    tokens = [token.strip() for token in tokens]\n    tokens = [stemmer.stem(token) for token in tokens]\n    return ' '.join(tokens)","metadata":{"execution":{"iopub.status.busy":"2021-05-23T14:59:26.599281Z","iopub.execute_input":"2021-05-23T14:59:26.599650Z","iopub.status.idle":"2021-05-23T14:59:26.613184Z","shell.execute_reply.started":"2021-05-23T14:59:26.599612Z","shell.execute_reply":"2021-05-23T14:59:26.612314Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Lemmatization\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.tokenize.toktok import ToktokTokenizer\nwordnet_lemmatizer = WordNetLemmatizer()\ndef lemma_text(text):\n    tokenizer = ToktokTokenizer()\n    tokens = tokenizer.tokenize(text)\n    tokens = [token.strip() for token in tokens]\n    tokens = [wordnet_lemmatizer.lemmatize(token) for token in tokens]\n    return ' '.join(tokens)","metadata":{"execution":{"iopub.status.busy":"2021-05-23T14:59:26.614378Z","iopub.execute_input":"2021-05-23T14:59:26.614917Z","iopub.status.idle":"2021-05-23T14:59:26.628981Z","shell.execute_reply.started":"2021-05-23T14:59:26.614885Z","shell.execute_reply":"2021-05-23T14:59:26.628158Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def clean_sentence(x):\n    x = x.lower()\n    x = clean_punct(x)\n    x = clean_numbers(x)\n    x = replace_typical_misspell(x)\n    x = remove_stopwords(x)\n    x = replace_contractions(x)\n    x = stem_text(x)\n    x = lemma_text(x)\n    x = x.replace(\"'\",\"\")\n    return x","metadata":{"execution":{"iopub.status.busy":"2021-05-23T14:59:26.630166Z","iopub.execute_input":"2021-05-23T14:59:26.630679Z","iopub.status.idle":"2021-05-23T14:59:26.641648Z","shell.execute_reply.started":"2021-05-23T14:59:26.630647Z","shell.execute_reply":"2021-05-23T14:59:26.640574Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Xử lí dữ liệu trên cả tập train và tập test \nx['question_text'] = x['question_text'].apply(lambda x: clean_sentence(x))\ntest['question_text'] = test['question_text'].apply(lambda x: clean_sentence(x))","metadata":{"execution":{"iopub.status.busy":"2021-05-23T14:59:26.642896Z","iopub.execute_input":"2021-05-23T14:59:26.643235Z","iopub.status.idle":"2021-05-23T15:05:37.497091Z","shell.execute_reply.started":"2021-05-23T14:59:26.643205Z","shell.execute_reply":"2021-05-23T15:05:37.495972Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Phân tích các nhãn được trích xuất bằng word cloud\n* Tạo word cloud để thấy được các từ xuất hiện thường xuyên nhất trong những câu hỏi toxic hay không toxic\n* Các từ có kích thước càng lớn thì tần suất xuất hiện càng nhiều","metadata":{}},{"cell_type":"code","source":"\ndef cloud(text, title, size = (10,7)):\n    # Processing Text\n    words_list = text.unique().tolist()\n    words = ' '.join(words_list)\n    \n    wordcloud = WordCloud(width=800, height=400,\n                          collocations=False\n                         ).generate(words)\n    \n    # Output Visualization\n    fig = plt.figure(figsize=size, dpi=80, facecolor='k',edgecolor='k')\n    plt.imshow(wordcloud,interpolation='bilinear')\n    plt.axis('off')\n    plt.title(title, fontsize=25,color='w')\n    plt.tight_layout(pad=0)\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2021-05-23T15:05:37.498447Z","iopub.execute_input":"2021-05-23T15:05:37.498768Z","iopub.status.idle":"2021-05-23T15:05:37.506379Z","shell.execute_reply.started":"2021-05-23T15:05:37.498738Z","shell.execute_reply":"2021-05-23T15:05:37.505067Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cloud(train[train['target']==0]['question_text'], 'Sincere Questions On Question_text')","metadata":{"execution":{"iopub.status.busy":"2021-05-23T15:05:37.507602Z","iopub.execute_input":"2021-05-23T15:05:37.507883Z","iopub.status.idle":"2021-05-23T15:06:01.723674Z","shell.execute_reply.started":"2021-05-23T15:05:37.507857Z","shell.execute_reply":"2021-05-23T15:06:01.722625Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cloud(x[x['target']==0]['question_text'], 'Sincere Questions On Question_text')","metadata":{"execution":{"iopub.status.busy":"2021-05-23T15:06:01.724992Z","iopub.execute_input":"2021-05-23T15:06:01.725286Z","iopub.status.idle":"2021-05-23T15:06:05.596674Z","shell.execute_reply.started":"2021-05-23T15:06:01.725258Z","shell.execute_reply":"2021-05-23T15:06:05.595387Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Nhận xét :\n* Trước khi xử lí dữ liệu , stopword có tần suất xuất hiện nhiều","metadata":{}},{"cell_type":"code","source":"cloud(train[train['target']==1]['question_text'], 'Insincere Questions On question_text')","metadata":{"execution":{"iopub.status.busy":"2021-05-23T15:06:05.598081Z","iopub.execute_input":"2021-05-23T15:06:05.598385Z","iopub.status.idle":"2021-05-23T15:06:08.807653Z","shell.execute_reply.started":"2021-05-23T15:06:05.598357Z","shell.execute_reply":"2021-05-23T15:06:08.806603Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cloud(x[x['target']==1]['question_text'], 'Insincere Questions On question_text')","metadata":{"execution":{"iopub.status.busy":"2021-05-23T15:06:08.809178Z","iopub.execute_input":"2021-05-23T15:06:08.809578Z","iopub.status.idle":"2021-05-23T15:06:11.233203Z","shell.execute_reply.started":"2021-05-23T15:06:08.809527Z","shell.execute_reply":"2021-05-23T15:06:11.232458Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Xử lí ngôn ngữ và xây dựng model","metadata":{}},{"cell_type":"code","source":"from sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import accuracy_score, log_loss\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import GridSearchCV\nimport math\nfrom sklearn.metrics import normalized_mutual_info_score\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn import model_selection\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import precision_recall_curve, auc, roc_curve\nfrom sklearn.metrics import f1_score","metadata":{"execution":{"iopub.status.busy":"2021-05-23T15:06:11.234293Z","iopub.execute_input":"2021-05-23T15:06:11.234772Z","iopub.status.idle":"2021-05-23T15:06:11.239796Z","shell.execute_reply.started":"2021-05-23T15:06:11.234738Z","shell.execute_reply":"2021-05-23T15:06:11.239103Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"* Chia tập dữ liệu train , test với test_size = 0.2","metadata":{}},{"cell_type":"code","source":"train_x, test_x,train_y, test_y = train_test_split(x['question_text'], x['target'], test_size=0.2, random_state=0)\nprint('x_train: ', train_x.shape, train_y.shape)\nprint('x_test: ',test_x.shape, test_y.shape)","metadata":{"execution":{"iopub.status.busy":"2021-05-23T15:06:11.240837Z","iopub.execute_input":"2021-05-23T15:06:11.241274Z","iopub.status.idle":"2021-05-23T15:06:11.314866Z","shell.execute_reply.started":"2021-05-23T15:06:11.241245Z","shell.execute_reply":"2021-05-23T15:06:11.313014Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Hướng tiếp cận : CountVectorizer**\n* Các giải thuật Machine Learning chỉ làm việc được với số, nên sẽ convert text về định dạng số :\n* chúng ta chia câu hỏi thành các từ. Trong mã hóa thì từ là đơn vị cơ sở. Chúng ta cần một bộ tokenizer có kích thước bằng toàn bộ các từ xuất hiện trong văn bản hoặc bằng toàn bộ các từ có trong từ điển. Một câu văn sẽ được biểu diễn bằng một sparse vector mà mỗi một phần tử đại diện cho một từ, giá trị của nó bằng 0 hoặc 1 tương ứng với từ không xuất hiện hoặc có xuất hiện.\n* Chúng ta sử dụng các túi từ (bags of words) để tạo ra một vector có độ dài bằng độ dài của tokenizer và mỗi phần tử của túi từ sẽ đếm số lần xuất hiện của một từ trong câu và sắp xếp chúng theo một vị trí phù hợp trong vector\n* Học trên tập từ vựng của toàn bộ tập train và test, vector đếm có thể phải mã hoá những từ có ở tập test và tập train\n* Hạn chế : Các biểu diễn theo túi từ có hạn chế đó là không phân biệt được 2 câu văn có cùng các từ bởi túi từ không phân biệt thứ tự trước sau của các từ trong một câu. ví dụ như ‘you have no dog’ và ‘no, you have dog’ là 2 câu văn có biểu diễn giống nhau mặc dù có ý nghĩa trái ngược nhau","metadata":{}},{"cell_type":"code","source":"vectorizer = CountVectorizer()\nvectorizer2 = CountVectorizer(min_df=0.0001, max_df=0.999, max_features=5000, ngram_range=(1,2,)) \nbow_train = vectorizer.fit_transform(train_x) \nbow_train2 = vectorizer2.fit_transform(train_x) \nprint(bow_train.shape)\nprint(bow_train2.shape)\nbow_test = vectorizer.transform(test_x)\nbow_test2 = vectorizer2.transform(test_x)\nprint(\"Done creating Bag-of-Words\")","metadata":{"execution":{"iopub.status.busy":"2021-05-23T15:06:11.316041Z","iopub.execute_input":"2021-05-23T15:06:11.316551Z","iopub.status.idle":"2021-05-23T15:06:28.670111Z","shell.execute_reply.started":"2021-05-23T15:06:11.316519Z","shell.execute_reply":"2021-05-23T15:06:28.669043Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Mô hình sử dụng : logictics regression","metadata":{}},{"cell_type":"code","source":"print(f\"Results of logistic regression on full bag-of-words\")\nlogistic = LogisticRegression(penalty=\"l2\", C=1) \nlogistic.fit(bow_train, train_y) \ntrain_predictions = logistic.predict(bow_train)\ntrain_acc = accuracy_score(train_y, train_predictions)  \ntrain_f1 = f1_score(train_y, train_predictions) \nprint(f\"Training accuracy: {train_acc:.2%}, F1: {train_f1:.4f}\") \ntest_predictions = logistic.predict(bow_test)\ntest_acc = accuracy_score(test_y, test_predictions) \ntest_f1 = f1_score(test_y, test_predictions) \nprint(f\"Testing accuracy:  {test_acc:.2%}, F1: {test_f1:.4f}\")","metadata":{"execution":{"iopub.status.busy":"2021-05-23T15:06:28.671436Z","iopub.execute_input":"2021-05-23T15:06:28.671764Z","iopub.status.idle":"2021-05-23T15:06:40.086795Z","shell.execute_reply.started":"2021-05-23T15:06:28.671731Z","shell.execute_reply":"2021-05-23T15:06:40.085594Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"* Nhận xét:\n* Tỉ lệ accuracy cao\n* Sau khi chia lại dữ liệu ta thấy kết quả tốt hơn dự đoán câu hỏi insincere tăng \n* f1-score tăng lên đáng kể sau khi chia lại dữ liệu","metadata":{}},{"cell_type":"markdown","source":"# Submission","metadata":{}},{"cell_type":"code","source":"x_val = vectorizer.transform(test['question_text'])\nvalidation_predictions = logistic.predict(x_val)\nsubmission = pd.DataFrame({'qid':test['qid'], 'prediction':validation_predictions })\nsubmission.to_csv('submission.csv', index=False)\nsubmission.groupby(\"prediction\")['qid'].count().plot.bar()","metadata":{"execution":{"iopub.status.busy":"2021-05-23T15:06:40.088365Z","iopub.execute_input":"2021-05-23T15:06:40.088813Z","iopub.status.idle":"2021-05-23T15:06:45.773010Z","shell.execute_reply.started":"2021-05-23T15:06:40.088767Z","shell.execute_reply":"2021-05-23T15:06:45.772041Z"},"trusted":true},"execution_count":null,"outputs":[]}]}