{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt # librarie qui affiche les graphes\nimport seaborn as sns # Python data visualization library based on matplotlib\nimport re\nimport nltk \nfrom nltk.tokenize import word_tokenize\nfrom nltk.tokenize.toktok import ToktokTokenizer\nfrom nltk.corpus import stopwords \nfrom nltk.stem import WordNetLemmatizer\nimport string\nfrom string import punctuation\nfrom sklearn.model_selection import train_test_split\nfrom keras.models import Sequential\n\nimport sys, os, re, csv, codecs, numpy as np, pandas as pd\nfrom tqdm import tqdm\nimport math\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import metrics\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.layers import Dense, Input, LSTM, Embedding, Dropout, Activation\nfrom keras.layers import Bidirectional, GlobalMaxPool1D\nfrom keras import callbacks\nfrom keras.models import Model\nfrom keras import initializers, regularizers, constraints, optimizers, layers\n\nimport keras\nfrom keras.preprocessing.text import Tokenizer\nfrom tensorflow.python.keras.preprocessing.sequence import pad_sequences","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":" 1. Lire et visualser les données d'apprentissage‏"},{"metadata":{"trusted":true},"cell_type":"code","source":"df_train = pd.read_csv('../input/quora-insincere-questions-classification/train.csv')\ndf_test = pd.read_csv('../input/quora-insincere-questions-classification/test.csv',index_col=False) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print (df_train.shape)\nprint (df_test.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"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 '≎', '⚔', '⇇', '̑', '⊿', '̖', '☍', '➹', '⥊', '⁁', '✢']\n\ndef clean_punct(x):\n\n#     print(x)\n    for punct in puncts:\n        if punct in x:\n            x = x.replace(punct,'')\n#     print(x)\n\n    return x","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def remove_abb(data):\n        data = re.sub(r\"he's\", \"he is\", data)\n        data = re.sub(r\"there's\", \"there is\", data)\n        data = re.sub(r\"We're\", \"We are\", data)\n        data = re.sub(r\"That's\", \"That is\", data)\n        data = re.sub(r\"won't\", \"will not\", data)\n        data = re.sub(r\"they're\", \"they are\", data)\n        data = re.sub(r\"Can't\", \"Cannot\", data)\n        data = re.sub(r\"wasn't\", \"was not\", data)\n        data = re.sub(r\"don\\x89Ûªt\", \"do not\", data)\n        data = re.sub(r\"aren't\", \"are not\", data)\n        data = re.sub(r\"isn't\", \"is not\", data)\n        data = re.sub(r\"What's\", \"What is\", data)\n        data = re.sub(r\"haven't\", \"have not\", data)\n        data = re.sub(r\"hasn't\", \"has not\", data)\n        data = re.sub(r\"There's\", \"There is\", data)\n        data = re.sub(r\"He's\", \"He is\", data)\n        data = re.sub(r\"It's\", \"It is\", data)\n        data = re.sub(r\"You're\", \"You are\", data)\n        data = re.sub(r\"I'M\", \"I am\", data)\n        data = re.sub(r\"shouldn't\", \"should not\", data)\n        data = re.sub(r\"wouldn't\", \"would not\", data)\n        data = re.sub(r\"i'm\", \"I am\", data)\n        data = re.sub(r\"I\\x89Ûªm\", \"I am\", data)\n        data = re.sub(r\"I'm\", \"I am\", data)\n        data = re.sub(r\"Isn't\", \"is not\", data)\n        data = re.sub(r\"Here's\", \"Here is\", data)\n        data = re.sub(r\"you've\", \"you have\", data)\n        data = re.sub(r\"you\\x89Ûªve\", \"you have\", data)\n        data = re.sub(r\"we're\", \"we are\", data)\n        data = re.sub(r\"what's\", \"what is\", data)\n        data = re.sub(r\"couldn't\", \"could not\", data)\n        data = re.sub(r\"we've\", \"we have\", data)\n        data = re.sub(r\"it\\x89Ûªs\", \"it is\", data)\n        data = re.sub(r\"doesn\\x89Ûªt\", \"does not\", data)\n        data = re.sub(r\"It\\x89Ûªs\", \"It is\", data)\n        data = re.sub(r\"Here\\x89Ûªs\", \"Here is\", data)\n        data = re.sub(r\"who's\", \"who is\", data)\n        data = re.sub(r\"I\\x89Ûªve\", \"I have\", data)\n        data = re.sub(r\"y'all\", \"you all\", data)\n        data = re.sub(r\"can\\x89Ûªt\", \"cannot\", data)\n        data = re.sub(r\"would've\", \"would have\", data)\n        data = re.sub(r\"it'll\", \"it will\", data)\n        data = re.sub(r\"we'll\", \"we will\", data)\n        data = re.sub(r\"wouldn\\x89Ûªt\", \"would not\", data)\n        data = re.sub(r\"We've\", \"We have\", data)\n        data = re.sub(r\"he'll\", \"he will\", data)\n        data = re.sub(r\"Y'all\", \"You all\", data)\n        data = re.sub(r\"Weren't\", \"Were not\", data)\n        data = re.sub(r\"Didn't\", \"Did not\", data)\n        data = re.sub(r\"they'll\", \"they will\", data)\n        data = re.sub(r\"they'd\", \"they would\", data)\n        data = re.sub(r\"DON'T\", \"DO NOT\", data)\n        data = re.sub(r\"That\\x89Ûªs\", \"That is\", data)\n        data = re.sub(r\"they've\", \"they have\", data)\n        data = re.sub(r\"i'd\", \"I would\", data)\n        data = re.sub(r\"should've\", \"should have\", data)\n        data = re.sub(r\"You\\x89Ûªre\", \"You are\", data)\n        data = re.sub(r\"where's\", \"where is\", data)\n        data = re.sub(r\"Don\\x89Ûªt\", \"Do not\", data)\n        data = re.sub(r\"we'd\", \"we would\", data)\n        data = re.sub(r\"i'll\", \"I will\", data)\n        data = re.sub(r\"weren't\", \"were not\", data)\n        data = re.sub(r\"They're\", \"They are\", data)\n        data = re.sub(r\"Can\\x89Ûªt\", \"Cannot\", data)\n        data = re.sub(r\"you\\x89Ûªll\", \"you will\", data)\n        data = re.sub(r\"I\\x89Ûªd\", \"I would\", data)\n        data = re.sub(r\"let's\", \"let us\", data)\n        data = re.sub(r\"it's\", \"it is\", data)\n        data = re.sub(r\"can't\", \"cannot\", data)\n        data = re.sub(r\"dont\", \"do not\", data)\n        data = re.sub(r\"don't\", \"do not\", data)\n        data = re.sub(r\"you're\", \"you are\", data)\n        data = re.sub(r\"i've\", \"I have\", data)\n        data = re.sub(r\"that's\", \"that is\", data)\n        data = re.sub(r\"i'll\", \"I will\", data)\n        data = re.sub(r\"doesn't\", \"does not\",data)\n        data = re.sub(r\"i'd\", \"I would\", data)\n        data = re.sub(r\"didn't\", \"did not\", data)\n        data = re.sub(r\"ain't\", \"am not\", data)\n        data = re.sub(r\"you'll\", \"you will\", data)\n        data = re.sub(r\"I've\", \"I have\", data)\n        data = re.sub(r\"Don't\", \"do not\", data)\n        data = re.sub(r\"I'll\", \"I will\", data)\n        data = re.sub(r\"I'd\", \"I would\", data)\n        data = re.sub(r\"Let's\", \"Let us\", data)\n        data = re.sub(r\"you'd\", \"You would\", data)\n        data = re.sub(r\"It's\", \"It is\", data)\n        data = re.sub(r\"Ain't\", \"am not\", data)\n        data = re.sub(r\"Haven't\", \"Have not\", data)\n        data = re.sub(r\"Could've\", \"Could have\", data)\n        data = re.sub(r\"youve\", \"you have\", data)  \n        data = re.sub(r\"donå«t\", \"do not\", data)\n        return data","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"mispell_dict = {\"ain't\": \"is not\", \"aren't\": \"are not\",\"can't\": \"cannot\", \"'cause\": \"because\", \"could've\": \"could have\", \"couldn't\": \"could not\", \n                \"didn't\": \"did not\",  \"doesn't\": \"does not\", \"don't\": \"do not\", \"hadn't\": \"had not\", \"hasn't\": \"has not\", \"haven't\": \"have not\", \n                \"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\", \n                \"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\", \n                \"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\", \n                \"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\",\n                \"it's\": \"it is\", \"let's\": \"let us\", \"ma'am\": \"madam\", \"mayn't\": \"may not\", \"might've\": \"might have\",\"mightn't\": \"might not\",\n                \"mightn't've\": \"might not have\", \"must've\": \"must have\", \"mustn't\": \"must not\", \"mustn't've\": \"must not have\", \"needn't\": \"need not\", \n                \"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\", \n                \"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\", \n                \"she'll've\": \"she will have\", \"she's\": \"she is\", \"should've\": \"should have\", \"shouldn't\": \"should not\", \"shouldn't've\": \"should not have\", \n                \"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\", \n                \"there'd\": \"there would\", \"there'd've\": \"there would have\", \"there's\": \"there is\", \"here's\": \"here is\",\"they'd\": \"they would\", \n                \"they'd've\": \"they would have\", \"they'll\": \"they will\", \"they'll've\": \"they will have\", \"they're\": \"they are\", \"they've\": \"they have\", \n                \"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\", \n                \"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\",  \n                \"what's\": \"what is\", \"what've\": \"what have\", \"when's\": \"when is\", \"when've\": \"when have\", \"where'd\": \"where did\", \"where's\": \"where is\", \n                \"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\", \n                \"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\", \n                \"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\",\n                \"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\", \n                \"you've\": \"you have\", 'colour': 'color', 'centre': 'center', 'favourite': 'favorite', 'travelling': 'traveling', 'counselling': 'counseling', \n                'theatre': 'theater', 'cancelled': 'canceled', 'labour': 'labor', 'organisation': 'organization', 'wwii': 'world war 2', 'citicise': 'criticize', \n                'youtu ': 'youtube ', 'Qoura': 'Quora', 'sallary': 'salary', 'Whta': 'What', 'narcisist': 'narcissist', 'howdo': 'how do', 'whatare': 'what are', \n                'howcan': 'how can', 'howmuch': 'how much', 'howmany': 'how many', 'whydo': 'why do', 'doI': 'do I', 'theBest': 'the best', 'howdoes': 'how does', \n                'mastrubation': 'masturbation', 'mastrubate': 'masturbate', \"mastrubating\": 'masturbating', 'pennis': 'penis', 'Etherium': 'Ethereum', 'narcissit': 'narcissist', \n                'bigdata': 'big data', '2k17': '2017', '2k18': '2018', 'qouta': 'quota', 'exboyfriend': 'ex boyfriend', 'airhostess': 'air hostess', \"whst\": 'what', \n                'watsapp': 'whatsapp', 'demonitisation': 'demonetization', 'demonitization': 'demonetization', 'demonetisation': 'demonetization'}","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Pour une meilleure couverture d'intégration, \n# nous remplacerons les mots mal orthographiés\n# à l'aide d'un dictionnaire.\ndef correct_spell(text, dic):\n#     text = ' youtu '\n    for word in dic.keys():\n        text = text.replace(word, dic[word])\n   \n    return text","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from string import digits\n\n# supprimer les nombre qui ont dans le mot\ndef clean_numbers(x):\n    \n    remove_digits = str.maketrans('', '', digits)\n    res = x.translate(remove_digits)\n\n    return res\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# supprimer les mots qui n'ajoute aucun\n# sens à la phrase comme (an, a..... )\n\ndef remove_stopwords(x):\n\n    stop_words = set(stopwords.words('english')) \n    stop_words.remove('not')\n    word_tokens = word_tokenize(x)    \n    x = [w for w in word_tokens if not w in stop_words]  \n    x =  ' '.join(x)\n    \n    return x","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# cleaning data en utilisant les fonction précédente \nfrom nltk.tokenize import word_tokenize\nfrom nltk.stem import WordNetLemmatizer\nimport spacy \nnlp = spacy.load('en_core_web_sm')\ndef clean_sentence(x, mispell_dict):\n    \n#     print(x)\n    x = remove_abb(x)  \n    x = x.lower()\n    x = clean_punct(x)\n    x = clean_numbers(x)    \n    x = remove_stopwords(x)\n    x = correct_spell(x ,mispell_dict)\n#     print(x)\n\n    return x\n\ndf_train[\"question_text\"] = df_train['question_text'].apply(lambda s: clean_sentence(s, mispell_dict))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_test[\"question_text\"] = df_test['question_text'].apply(lambda s: clean_sentence(s, mispell_dict))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# diviser data de fichier train en 80% \n# pour traning et 20% pourr validation \ndf_train, val_df = train_test_split(df_train, test_size=0.2, random_state=42)\n\nembed_size = 300 # taille de vecteur \nmax_features = 228394 # how many unique words to use (i.e num rows in embedding vector) \n###   maxlen : maximum length of all sequences and shorter sequences are padded with zeros\nmaxlen = 55 #maximun taille pour tous les séquences  \n\n\ntrain_X =  df_train[\"question_text\"].values\nval_X = val_df[\"question_text\"].values\ntest_X = df_test[\"question_text\"].values\n\n\n\n#initialisation de constructeur\ntokenizer = Tokenizer(num_words=max_features)\n\n# remplir le dictionnaire tekenizer par list des questions \ntokenizer.fit_on_texts(list(train_X)+list(val_X))\n\n# donne pour chaque question son vecteur corresponds\ntrain_X_tokens = tokenizer.texts_to_sequences(train_X)\nval_X = tokenizer.texts_to_sequences(val_X)\ntest_X_tokens = tokenizer.texts_to_sequences(test_X)\n\n\n# pad_sequence() pour complit les séquence \n# les plus cours par 0 pour rendre les séquences  \n# au même  taille pour train validation et test\n# taille pour train validation et test\ntrain_X_pad = pad_sequences(train_X_tokens, maxlen=maxlen)\nval_X = pad_sequences(val_X, maxlen=maxlen)\ntest_X_pad = pad_sequences(test_X_tokens, maxlen=maxlen)\n\n\n\n## Obtenir les valeurs target\ntrain_y = df_train['target'].values\nval_y = val_df['target'].values\n\n# train_X_pad\n# test_X_pad\n# train_X_pad\n\n# train_y \n# val_y ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import zipfile\nfrom gensim.models import KeyedVectors\nimport io\nfrom tqdm import tqdm\nembeddings_index={}\n\nwith zipfile.ZipFile(\"../input/quora-insincere-questions-classification/embeddings.zip\") as zf:\n    with io.TextIOWrapper(zf.open(\"glove.840B.300d/glove.840B.300d.txt\"), encoding=\"utf-8\") as f:\n        for line in tqdm(f):\n            values=line.split(' ') # \".split(' ')\" only for glove-840b-300d; for all other files, \".split()\" works\n            word=values[0]\n            vectors=np.asarray(values[1:],'float32')\n            embeddings_index[word]=vectors","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#collect les vecteur dans un seul vecteur\nall_embs = np.stack(embeddings_index.values())\nemb_mean,emb_std = all_embs.mean(), all_embs.std() \n\n#récupérer mean pour moyen de vecteur et std pour ecart type\nemb_mean,emb_std\nword_index = tokenizer.word_index\nnb_words = len(word_index)\nnb_words","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# initialisation du matrice\nembedding_matrix = np.random.normal(emb_mean, emb_std, (nb_words+1, embed_size))\n\nfor word, i in word_index.items():  \n    if i >= nb_words:\n        continue        \n    embedding_vector = embeddings_index.get(word)    \n    # ajouter le vecteur du mot dans la ligne du matrice\n    if embedding_vector is not None: \n        embedding_matrix[i] = embedding_vector\n\n    # pour ajouter les mots qui ont capitaliser au matrice    \n    elif embeddings_index.get(word.capitalize()) is not None : \n        \n        embedding_matrix[i] = embeddings_index.get(word.capitalize())\n    \n    # pour ajouter les mots qui sont au majuscules    \n    elif embeddings_index.get(word.upper()) is not None : \n        embedding_matrix[i] = embeddings_index.get(word.upper())\n            \n    else:\n        pass","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Sequential()\n\nembedding_size = 300\n\n#les couche de model \nmodel.add(Embedding(nb_words+1, embedding_size , weights=[embedding_matrix], trainable=False))\nmodel.add(LSTM(128\n#             , kernel_regularizer=regularizers.l1(l1=1e-18),\n#               dropout=0.1\n\n              )) \n\nmodel.add(Dense(128,activation='relu'))\nmodel.add(Dropout(0.2)) \nmodel.add(Dense(1, activation=\"sigmoid\"\n#                 kernel_regularizer=regularizers.l1(l1=1e-5),\n#     bias_regularizer=regularizers.l2(1e-4),\n         ))\n\n\nmodel.compile(loss='binary_crossentropy', optimizer='adam' ,metrics=['accuracy'])\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"es = callbacks.EarlyStopping( patience = 5 )\nmc = callbacks.ModelCheckpoint('./w.h5', save_best_only=True, save_weights_only=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.fit(train_X_pad, train_y, batch_size=512, epochs=100, callbacks=[es, mc ], validation_data=(val_X, val_y))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# on tester notre model sur le data test\nout = model.predict(test_X_pad,batch_size=256)\nout_df = pd.DataFrame({\"qid\":df_test[\"qid\"].values})\n\n# si out>0,35 le target =1 sinon target =0\nout_pred = (out>0.35).astype(int)\n\nout_df['prediction'] = out_pred\nout_df.to_csv(\"submission.csv\", index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"out_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"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":4,"nbformat_minor":4}