{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Importando Librerias"},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing.sequence import pad_sequences\n#import tensorflow as tf\nimport os\nimport numpy as np \nimport pandas as pd\nfrom tqdm import tqdm\nimport math\nfrom sklearn.model_selection import train_test_split\nfrom keras.models import Model,Sequential\nfrom keras.layers import  Dense, Bidirectional,LSTM,Dropout\nfrom keras.optimizers import Adam\ntqdm.pandas()\nfrom gensim.models import KeyedVectors\nimport operator\nimport gc\nimport matplotlib.pyplot as plt","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Imprimiendo las direcciones de la data"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Importando training y test set"},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"train=pd.read_csv(\"../input/quora-insincere-questions-classification/train.csv\")\ntest=pd.read_csv(\"../input/quora-insincere-questions-classification/test.csv\")\ntrainx=train.drop(['qid','target'],axis=1)\ntrainy=train['target']\ntestx=train.drop(['qid'],axis=1)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Funcion que crea vocabulario de las palabras en las preguntas del set"},{"metadata":{"trusted":true},"cell_type":"code","source":"def 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","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sentences = train[\"question_text\"].progress_apply(lambda x: x.split()).values\nvocab = build_vocab(sentences)\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Primeras 8 palabras encontradas en el vocabulario con la frcuencia que aparecen"},{"metadata":{"trusted":true},"cell_type":"code","source":"print({k: vocab[k] for k in list(vocab)[:8]})","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Cargando el embedding glove"},{"metadata":{"trusted":true},"cell_type":"code","source":"def load_embed(file):\n    def get_coefs(word,*arr): \n        return word, np.asarray(arr, dtype='float32')\n    \n    if file == '../input/quora-insincere-questions-classification/embeddings/wiki-news-300d-1M/wiki-news-300d-1M.vec':\n        embeddings_index = dict(get_coefs(*o.split(\" \")) for o in open(file) if len(o)>100)\n    else:\n        embeddings_index = dict(get_coefs(*o.split(\" \")) for o in open(file, encoding='latin'))\n        \n    return embeddings_index","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"embed_glove = load_embed('../input/quora-insincere-questions-classification/embeddings/glove.840B.300d/glove.840B.300d.txt')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Funcion para saber que porcentaje de palabras del vocabulario se encuentran en el embedding"},{"metadata":{"trusted":true},"cell_type":"code","source":"def check_coverage(vocab, embeddings_index):\n    known_words = {}\n    unknown_words = {}\n    nb_known_words = 0\n    nb_unknown_words = 0\n    for word in vocab.keys():\n        try:\n            known_words[word] = embeddings_index[word]\n            nb_known_words += vocab[word]\n        except:\n            unknown_words[word] = vocab[word]\n            nb_unknown_words += vocab[word]\n            pass\n\n    print('Found embeddings for {:.3%} of vocab'.format(len(known_words) / len(vocab)))\n    print('Found embeddings for  {:.3%} of all text'.format(nb_known_words / (nb_known_words + nb_unknown_words)))\n    unknown_words = sorted(unknown_words.items(), key=operator.itemgetter(1))[::-1]\n\n    return unknown_words","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"Glove : \")\noov_glove = check_coverage(vocab, embed_glove)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Palabras que no se encuentran en el embedding mas frecuentes "},{"metadata":{"trusted":true},"cell_type":"code","source":"oov_glove[:10]","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# PREPROCESAMIENTO DE DATOS"},{"metadata":{},"cell_type":"markdown","source":"Se remueven signos de las palabras del vocabulario"},{"metadata":{"trusted":true},"cell_type":"code","source":"punct = \"/-'?!.,#$%\\'()*+-/:;<=>@[\\\\]^_`{|}~\" + '\"\"“”’' + '∞θ÷α•à−β∅³π‘₹´°£€\\×™√²—–&'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def unknown_punct(embed, punct):\n    unknown = ''\n    for p in punct:\n        if p not in embed:\n            unknown += p\n            unknown += ' '\n    return unknown","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"Glove :\")\nprint(unknown_punct(embed_glove, punct))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def clean_text(x):\n\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","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train[\"question_text\"] = train[\"question_text\"].progress_apply(lambda x: clean_text(x))\nsentences = train[\"question_text\"].apply(lambda x: x.split())\nvocab = build_vocab(sentences)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Porcentaje de palabras del vocabulario en el embedding una vez se han removido los signos"},{"metadata":{"trusted":true},"cell_type":"code","source":"oov_glove = check_coverage(vocab,embed_glove)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Nuevas palabras que no se encuentran en el embedding mas frecuentes "},{"metadata":{"trusted":true},"cell_type":"code","source":"oov_glove[:50]","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Se puede observar que son palabras de nombres propios con lo cual tiene sentido que no se encuentren en el embedding"},{"metadata":{},"cell_type":"markdown","source":"Se pone en minusculas las palabras en el vocabulario y se observa una mejora de casi un 1% en las palabras que se encuentran en el embedding"},{"metadata":{"trusted":true},"cell_type":"code","source":"train['lowered_question'] = train['question_text'].apply(lambda x: x.lower())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def add_lower(embedding, vocab):\n    count = 0\n    for word in vocab:\n        if word in embedding and word.lower() not in embedding:  \n            embedding[word.lower()] = embedding[word]\n            count += 1\n    print(f\"Added {count} words to embedding\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"Glove : \")\noov_glove = check_coverage(vocab, embed_glove)\nadd_lower(embed_glove, vocab)\noov_glove = check_coverage(vocab, embed_glove)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"oov_glove = check_coverage(vocab,embed_glove)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"del embed_glove\ndel sentences\ndel vocab\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# ENTRENAMIENTO DEL MODELO"},{"metadata":{"trusted":true},"cell_type":"code","source":"embeddings_index = {}\nf = open('../input/quora-insincere-questions-classification/embeddings/glove.840B.300d/glove.840B.300d.txt')\nfor line in tqdm(f):\n    values = line.split(\" \")\n    word = values[0]\n    coefs = np.asarray(values[1:], dtype='float32')\n    embeddings_index[word] = coefs\nf.close()\n\nprint('Found %s word vectors.' % len(embeddings_index))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Se le aplica al training set los cambios del preprocesamiento "},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df,validation_df= train_test_split(train, test_size=0.1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df['treated_question'] = train_df['question_text'].apply(lambda x: x.lower())\nvalidation_df['treated_question'] = validation_df['question_text'].apply(lambda x: x.lower())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df['treated_question'] = train_df['treated_question'].apply(lambda x: clean_text(x))\nvalidation_df['treated_question'] = validation_df['treated_question'].apply(lambda x: clean_text(x))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y = train['target'].values","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def text_to_array(text):\n    empyt_emb = np.zeros(300)\n    text = text[:-1].split()[:30]\n    embeds = [embeddings_index.get(x, empyt_emb) for x in text]\n    embeds+= [empyt_emb] * (30 - len(embeds))\n    return np.array(embeds)\n\nval_vects = np.array([text_to_array(X_text) for X_text in tqdm(validation_df[\"treated_question\"][:3000])])\nval_y = np.array(validation_df[\"target\"][:3000])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"batch_size = 128\n\ndef batch_gen(train_df):\n    n_batches = math.ceil(len(train_df) / batch_size)\n    while True: \n        train_df = train_df.sample(frac=1.)  # Shuffle the data.\n        for i in range(n_batches):\n            texts = train_df.iloc[i*batch_size:(i+1)*batch_size, 1]\n            text_arr = np.array([text_to_array(text) for text in texts])\n            yield text_arr, np.array(train_df[\"target\"][i*batch_size:(i+1)*batch_size])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Modelo"},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Sequential()\nmodel.add(Bidirectional(LSTM(64, return_sequences=True),\n                        input_shape=(30, 300)))\nmodel.add(Bidirectional(LSTM(64)))\nmodel.add(Dense(1, activation=\"sigmoid\"))\n\nmodel.compile(loss='binary_crossentropy',\n              optimizer='adam',\n              metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Entrenando"},{"metadata":{"trusted":true},"cell_type":"code","source":"mg = batch_gen(train_df)\nhistory=model.fit_generator(mg, epochs=10,\n                    steps_per_epoch=1000,\n                    validation_data=(val_vects, val_y),\n                    verbose=True)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Grafica del accuracy"},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(12,8))\nplt.plot(history.history['accuracy'], label='Train Accuracy')\nplt.plot(history.history['val_accuracy'], label='Test Accuracy')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# PREDICCION"},{"metadata":{"trusted":true,"_kg_hide-output":true},"cell_type":"code","source":"batch_size = 256\ndef batch_gen(test_df):\n    n_batches = math.ceil(len(test_df) / batch_size)\n    for i in range(n_batches):\n        texts = test_df.iloc[i*batch_size:(i+1)*batch_size, 1]\n        text_arr = np.array([text_to_array(text) for text in texts])\n        yield text_arr\n\ntest_df = test\n\nall_preds = []\nfor x in tqdm(batch_gen(test_df)):\n    all_preds.extend(model.predict(x).flatten())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_te = (np.array(all_preds) > 0.5).astype(np.int)\n\nsubmit_df = pd.DataFrame({\"qid\": test_df[\"qid\"], \"prediction\": y_te})\nsubmit_df.to_csv(\"submission.csv\", index=False)","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":1}