{"cells":[{"metadata":{},"cell_type":"markdown","source":"**IMPORTACION DE LIBRERIAS**"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import re\nimport string\nimport operator\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pandas as pd\nimport numpy as np\n%matplotlib inline\n\nfrom keras import backend as K\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.layers import Dense, Input, CuDNNLSTM, Embedding, Dropout, Activation, CuDNNGRU, Conv1D, Bidirectional, Lambda, Reshape,GlobalMaxPool1D\nfrom keras.optimizers import Adam\nfrom keras.models import Model, Sequential\nfrom keras.engine.topology import Layer\nfrom keras import initializers, regularizers, constraints, optimizers, layers\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import metrics\n\nimport nltk\nfrom nltk.corpus import stopwords\n\n\n\nimport os\nprint(os.listdir(\"../input\"))\n","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"df = pd.read_csv(\"../input/train.csv\")\ntest_df = pd.read_csv(\"../input/test.csv\")\n\n\n\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Verificando valores null**\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"Train shape : \",df.shape)\nprint(\"Test shape : \",test_df.shape)\nprint(df.isnull().sum())\nprint(test_df.isnull().sum())","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Grafica de preguntas toxicas y preguntas sinceras**"},{"metadata":{"trusted":true},"cell_type":"code","source":"df['target'].value_counts().plot(kind = 'pie', labels = ['Sinceras', 'Toxicas '])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Contracciones de palabras**"},{"metadata":{"trusted":true},"cell_type":"code","source":"\nimport re\ncList = {\n  \"ain't\": \"am not\",\n  \"aren't\": \"are not\",\n  \"can't\": \"cannot\",\n  \"can't've\": \"cannot have\",\n  \"'cause\": \"because\",\n  \"could've\": \"could have\",\n  \"couldn't\": \"could not\",\n  \"couldn't've\": \"could not have\",\n  \"didn't\": \"did not\",\n  \"doesn't\": \"does not\",\n  \"don't\": \"do not\",\n  \"hadn't\": \"had not\",\n  \"hadn't've\": \"had not have\",\n  \"hasn't\": \"has not\",\n  \"haven't\": \"have not\",\n  \"he'd\": \"he would\",\n  \"he'd've\": \"he would have\",\n  \"he'll\": \"he will\",\n  \"he'll've\": \"he will have\",\n  \"he's\": \"he is\",\n  \"how'd\": \"how did\",\n  \"how'd'y\": \"how do you\",\n  \"how'll\": \"how will\",\n  \"how's\": \"how is\",\n  \"I'd\": \"I would\",\n  \"I'd've\": \"I would have\",\n  \"I'll\": \"I will\",\n  \"I'll've\": \"I will have\",\n  \"I'm\": \"I am\",\n  \"I've\": \"I have\",\n  \"isn't\": \"is not\",\n  \"it'd\": \"it had\",\n  \"it'd've\": \"it would have\",\n  \"it'll\": \"it will\",\n  \"it'll've\": \"it will have\",\n  \"it's\": \"it is\",\n  \"let's\": \"let us\",\n  \"ma'am\": \"madam\",\n  \"mayn't\": \"may not\",\n  \"might've\": \"might have\",\n  \"mightn't\": \"might not\",\n  \"mightn't've\": \"might not have\",\n  \"must've\": \"must have\",\n  \"mustn't\": \"must not\",\n  \"mustn't've\": \"must not have\",\n  \"needn't\": \"need not\",\n  \"needn't've\": \"need not have\",\n  \"o'clock\": \"of the clock\",\n  \"oughtn't\": \"ought not\",\n  \"oughtn't've\": \"ought not have\",\n  \"shan't\": \"shall not\",\n  \"sha'n't\": \"shall not\",\n  \"shan't've\": \"shall not have\",\n  \"she'd\": \"she would\",\n  \"she'd've\": \"she would have\",\n  \"she'll\": \"she will\",\n  \"she'll've\": \"she will have\",\n  \"she's\": \"she is\",\n  \"should've\": \"should have\",\n  \"shouldn't\": \"should not\",\n  \"shouldn't've\": \"should not have\",\n  \"so've\": \"so have\",\n  \"so's\": \"so is\",\n  \"that'd\": \"that would\",\n  \"that'd've\": \"that would have\",\n  \"that's\": \"that is\",\n  \"there'd\": \"there had\",\n  \"there'd've\": \"there would have\",\n  \"there's\": \"there is\",\n  \"they'd\": \"they would\",\n  \"they'd've\": \"they would have\",\n  \"they'll\": \"they will\",\n  \"they'll've\": \"they will have\",\n  \"they're\": \"they are\",\n  \"they've\": \"they have\",\n  \"to've\": \"to have\",\n  \"wasn't\": \"was not\",\n  \"we'd\": \"we had\",\n  \"we'd've\": \"we would have\",\n  \"we'll\": \"we will\",\n  \"we'll've\": \"we will have\",\n  \"we're\": \"we are\",\n  \"we've\": \"we have\",\n  \"weren't\": \"were not\",\n  \"what'll\": \"what will\",\n  \"what'll've\": \"what will have\",\n  \"what're\": \"what are\",\n  \"what's\": \"what is\",\n  \"what've\": \"what have\",\n  \"when's\": \"when is\",\n  \"when've\": \"when have\",\n  \"where'd\": \"where did\",\n  \"where's\": \"where is\",\n  \"where've\": \"where have\",\n  \"who'll\": \"who will\",\n  \"who'll've\": \"who will have\",\n  \"who's\": \"who is\",\n  \"who've\": \"who have\",\n  \"why's\": \"why is\",\n  \"why've\": \"why have\",\n  \"will've\": \"will have\",\n  \"won't\": \"will not\",\n  \"won't've\": \"will not have\",\n  \"would've\": \"would have\",\n  \"wouldn't\": \"would not\",\n  \"wouldn't've\": \"would not have\",\n  \"y'all\": \"you all\",\n  \"y'alls\": \"you alls\",\n  \"y'all'd\": \"you all would\",\n  \"y'all'd've\": \"you all would have\",\n  \"y'all're\": \"you all are\",\n  \"y'all've\": \"you all have\",\n  \"you'd\": \"you had\",\n  \"you'd've\": \"you would have\",\n  \"you'll\": \"you you will\",\n  \"you'll've\": \"you you will have\",\n  \"you're\": \"you are\",\n  \"you've\": \"you have\"\n}\n\nc_re = re.compile('(%s)' % '|'.join(cList.keys()))\n\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Aplicamos todas las modificaciones a las preguntas: Expandemos contracciones, limpiamos numeros, pasamos a letras minusculas el texto y quitamos caracteres especiales**"},{"metadata":{"trusted":true},"cell_type":"code","source":"punct_mapping = {\"‘\": \"'\", \"₹\": \"e\", \"´\": \"'\", \"°\": \"\", \"€\": \"e\", \"™\": \"tm\", \"√\": \" sqrt \", \"×\": \"x\", \"²\": \"2\", \"—\": \"-\", \"–\": \"-\", \"’\": \"'\", \"_\": \"-\", \"`\": \"'\", '“': '\"', '”': '\"', '“': '\"', \"£\": \"e\", '∞': 'infinity', 'θ': 'theta', '÷': '/', 'α': 'alpha', '•': '.', 'à': 'a', '−': '-', 'β': 'beta', '∅': '', '³': '3', 'π': 'pi', }\npunct = \"/-'?!.,#$%\\'()*+-/:;<=>@[\\\\]^_`{|}~\" + '\"\"“”’' + '∞θ÷α•à−β∅³π‘₹´°£€\\×™√²—–&'\nmispell_dict = {'advanatges': 'advantages', 'irrationaol': 'irrational' , 'defferences': 'differences','lamboghini':'lamborghini','hypothical':'hypothetical', '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': 'Ethereum', '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', 'pokémon': 'pokemon'}","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def expandContractions(text, c_re=c_re):\n    def replace(match):\n        return cList[match.group(0)]\n    return c_re.sub(replace, text)\n\n\ndef clean_numbers(x):\n    x = re.sub('[0-9]{5,}', ' number ', x)\n    x = re.sub('[0-9]{4}', ' number ', x)\n    x = re.sub('[0-9]{3}', ' number ', x)\n    x = re.sub('[0-9]{2}', ' number ', x)\n    return x\n\n\n\ndef clean_special_chars(text, punct, mapping):\n    for p in mapping:\n        text = text.replace(p, mapping[p])\n    \n    for p in punct:\n        text = text.replace(p, f' {p} ')\n    \n    specials = {'\\u200b': ' ', '…': ' ... ', '\\ufeff': '', 'करना': '', 'है': ''}  \n    for s in specials:\n        text = text.replace(s, specials[s])\n    \n    return text\n\n\n\n\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Diccionario de correcciones**"},{"metadata":{"trusted":true},"cell_type":"code","source":"def correct_spelling(x, dic):\n    for word in dic.keys():\n        x = x.replace(word, dic[word])\n    return x","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Aplicamos la transfomacion del spelling**"},{"metadata":{"trusted":true},"cell_type":"code","source":"df['question_text'] = df['question_text'].apply(lambda x: expandContractions(x))\ndf['question_text'] = df['question_text'].apply(lambda x: clean_numbers(x))\ndf['question_text'] = df['question_text'].apply(lambda x: x.lower())\ndf['question_text'] = df['question_text'].apply(lambda x: clean_special_chars(x, punct, punct_mapping))\ndf['question_text'] = df['question_text'].apply(lambda x: correct_spelling(x, mispell_dict))\ndf.head(100)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df['question_text'] = test_df['question_text'].apply(lambda x: expandContractions(x))\ntest_df['question_text'] = test_df['question_text'].apply(lambda x: clean_numbers(x))\ntest_df['question_text'] = test_df['question_text'].apply(lambda x: x.lower())\ntest_df['question_text'] = test_df['question_text'].apply(lambda x: clean_special_chars(x, punct, punct_mapping))\ntest_df['question_text'] = test_df['question_text'].apply(lambda x: correct_spelling(x, mispell_dict))\ntest_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_train, df_val = train_test_split(df, test_size=0.1, random_state=42)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# some config values \nembed_size = 500 # how big is each word vector\nmax_features = 50000 # how many unique words to use (i.e num rows in embedding vector)\nmaxlen = 200 # max number of words in a question to use\n\n# fill up the missing values\nx_train = df_train[\"question_text\"].fillna(\"_na_\").values\nx_val = df_val[\"question_text\"].fillna(\"_na_\").values\n\n# Tokenize the sentences\ntokenizer = Tokenizer(num_words=max_features)\ntokenizer.fit_on_texts(list(x_train))\nx_train = tokenizer.texts_to_sequences(x_train)\nx_val = tokenizer.texts_to_sequences(x_val)\n\n# Pad the sentences \nx_train = pad_sequences(x_train, maxlen=maxlen)\nx_val = pad_sequences(x_val, maxlen=maxlen)\n\n# Get the target values\ny_train = df_train['target'].values\ny_val = df_val['target'].values","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"EMBEDDING_FILE = '../input/embeddings/glove.840B.300d/glove.840B.300d.txt'\ndef get_coefs(word,*arr): \n    return word, np.asarray(arr, dtype='float32')\nembeddings_index = dict(get_coefs(*o.split(\" \")) for o in open(EMBEDDING_FILE))\n\nall_embs = np.stack(embeddings_index.values())\nemb_mean,emb_std = all_embs.mean(), all_embs.std()\nembed_size = all_embs.shape[1]\n\nword_index = tokenizer.word_index\nnb_words = min(max_features, len(word_index))\nembedding_matrix = np.random.normal(emb_mean, emb_std, (nb_words, embed_size))\nfor word, i in word_index.items():\n    if i >= max_features: \n        continue\n    embedding_vector = embeddings_index.get(word)\n    if embedding_vector is not None: \n        embedding_matrix[i] = embedding_vector","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Sequential()\nmodel.add(Embedding(max_features, \n                    embed_size, \n                    weights=[embedding_matrix]))\nmodel.add(Bidirectional(CuDNNGRU(64, return_sequences=True)))\nmodel.add(GlobalMaxPool1D())\nmodel.add(Dropout(0.1))\nmodel.add(Dense(16, activation='relu'))\nmodel.add(Dropout(0.1))\nmodel.add(Dense(1, activation='sigmoid'))\n\nmodel.compile(optimizer='adam',\n              loss='binary_crossentropy',\n              metrics=['acc'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit(x_train, y_train, batch_size=512, epochs=5, validation_data=(x_val, y_val))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\nx_test = test_df[\"question_text\"].fillna(\"_na_\").values\n\nx_test = tokenizer.texts_to_sequences(x_test)\n\nx_test = pad_sequences(x_test, maxlen=maxlen)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_test = model.predict([x_test], batch_size=1024, verbose=1)\ny_test = (y_test > 0.5).astype(int)\ntest_df = pd.DataFrame({\"qid\": test_df[\"qid\"].values})\ntest_df['prediction'] = y_test\ntest_df.to_csv(\"submission.csv\", index=False)","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.4","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}