{"cells":[{"metadata":{"_uuid":"aa10a2c56cf5959f038eaa9847cef5d76d82e28d"},"cell_type":"markdown","source":"## Quora Insincere Question Classification\n---\n>  ### Outline of the notebook\n> 1. [**Load Library**](#1)\n> 1. [**Define the sequence of words**](#2)\n> 1. [**Setup Train data**](#3)\n> 1. [**Some Question Statistics**](#4)\n> 1. [**Embedding Datasetup**](#5)\n> 1. [**Value to Embedding**](#6)\n> 1. [**Data Providers**](#7)\n> 1. [**Model Training**](#8)\n> 1. [**Inference of result**](#9)\n> 1. [**Submission**](#10)"},{"metadata":{"_uuid":"b86b39097fe0e9837dffb58fff01b1c7fb9343dc"},"cell_type":"markdown","source":"# 1. Load Library<a id=\"1\"></a>"},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"# forked from : https://www.kaggle.com/mihaskalic/lstm-is-all-you-need-well-maybe-embeddings-also\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing.sequence import pad_sequences\n\nimport os\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nfrom tqdm import tqdm\nimport math\nfrom sklearn.model_selection import train_test_split","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"917bb6222fe8211548f9eb12553c8f35a577825b"},"cell_type":"markdown","source":"# 2.Define the sequence of words<a id=\"2\"></a>"},{"metadata":{"trusted":true,"_uuid":"083d70c6848351af633b832751c75e5daa86ced1"},"cell_type":"code","source":"SEQ_LEN = 28  # magic number - length to truncate sequences of words","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"21f85dfd5b9bf3d8b27ba29149d52253e5d64049"},"cell_type":"markdown","source":"# 3.Setup Train data <a id=\"3\"></a>"},{"metadata":{"trusted":true,"_uuid":"78578eab64a477d0a5ad6b1c917ae154868a44df"},"cell_type":"code","source":"train_df = pd.read_csv(\"../input/train.csv\")\ntrain_df, val_df = train_test_split(train_df, test_size=0.07)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"a48bb4f9bd19bd2b98ec7e0aa322497779a07788"},"cell_type":"markdown","source":"# 4.Some Question Statistics <a id=\"4\"> </a>"},{"metadata":{"trusted":true,"_uuid":"05cab1c46136382e8b7ff2fa9d70fbb90063d8c2"},"cell_type":"code","source":"#minor eda: average question length (in words) is 12  , majority are under 12 words\ntrain_df.question_text.str.split().str.len().describe()","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"1c30b1f5a11c4a71641f60edd3de195ec30d2555"},"cell_type":"markdown","source":"# 5.Embedding Datasetup <a id=\"5\"> </a>"},{"metadata":{"trusted":true,"_uuid":"92ffbf2ef35d2dc5863ee27c61eadd1869ca5440","scrolled":true},"cell_type":"code","source":"### Unclear why fails to open [encoding error], format is same as for glove. Will Debug, Dan:\n### f = open('../input/embeddings/paragram_300_sl999/paragram_300_sl999.txt')\n\n# embedding setup\n# Source https://blog.keras.io/using-pre-trained-word-embeddings-in-a-keras-model.html\n# \nembeddings_index = {}\nf = open('../input/embeddings/glove.840B.300d/glove.840B.300d.txt')\n# f = open('../input/embeddings/paragram_300_sl999/paragram_300_sl999.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":{"_uuid":"df1f0bfefbc85652670e0cfcb7d670c91d01da42"},"cell_type":"markdown","source":"# 6. Value to Embedding<a id=\"6\"></a> "},{"metadata":{"trusted":true,"_uuid":"9cc8b0bcd285225ce651d024f506615d4656b9f7"},"cell_type":"code","source":"# Convert values to embeddings\ndef text_to_array(text):\n    empyt_emb = np.zeros(300)\n    text = text[:-1].split()[:SEQ_LEN]\n    embeds = [embeddings_index.get(x, empyt_emb) for x in text]\n    embeds+= [empyt_emb] * (SEQ_LEN - len(embeds))\n    return np.array(embeds)\n\n# train_vects = [text_to_array(X_text) for X_text in tqdm(train_df[\"question_text\"])]\nval_vects = np.array([text_to_array(X_text) for X_text in tqdm(val_df[\"question_text\"][:3000])])\nval_y = np.array(val_df[\"target\"][:3000])","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"26f3d445a415712d0f983ab48b235b70d7cb760c"},"cell_type":"markdown","source":"# 7.Data Providers <a id=\"7\"> </a>"},{"metadata":{"trusted":true,"_uuid":"0c950448e0717eaebb920d93cfdc6b4561e21853"},"cell_type":"code","source":"# Data providers\nbatch_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":{"_uuid":"706c0224b6112e5a8f00ad25f35e90fbb9519a5f"},"cell_type":"markdown","source":"# 8.Model Training <a id=\"8\"> </a>"},{"metadata":{"trusted":true,"_uuid":"798c303ec834fb530a60a1e590cfbd9a86f93fde"},"cell_type":"code","source":"from keras.models import Sequential\nfrom keras.layers import CuDNNLSTM, Dense, Bidirectional, CuDNNGRU\nimport matplotlib.pyplot as plt\n%matplotlib inline","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"9ad418c95b31ab5691d49b72c7c9622ef9ea42cf"},"cell_type":"code","source":"model = Sequential()\nmodel.add(Bidirectional(CuDNNLSTM(128, return_sequences=True),input_shape=(SEQ_LEN, 300)))\nmodel.add(Bidirectional(CuDNNGRU(128, return_sequences=True),input_shape=(SEQ_LEN, 300)))\nmodel.add(Bidirectional(CuDNNGRU(64)))\nmodel.add(Dense(1, activation=\"sigmoid\"))\n\nmodel.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"3f0b703ded691293450beb4ddf2d903d0e08c737"},"cell_type":"code","source":"mg = batch_gen(train_df)\nmodel.fit_generator(mg, epochs=25,\n                    steps_per_epoch=1000,\n                    validation_data=(val_vects, val_y),\n                    verbose=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"82bb58c4814da64ceafd6f682a9a9883e568ec84"},"cell_type":"code","source":"# Plot training & validation accuracy values\nplt.style.use(\"fivethirtyeight\")\nplt.figure(figsize=(12,5))\nplt.plot(model.history.history['acc'])\nplt.plot(model.history.history['val_acc'])\nplt.title('Model accuracy')\nplt.ylabel('Accuracy')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Test'], loc='upper left')\nplt.show()\n\n# Plot training & validation loss values\nplt.figure(figsize=(12,5))\nplt.plot(model.history.history['loss'])\nplt.plot(model.history.history['val_loss'])\nplt.title('Model loss')\nplt.ylabel('Loss')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Test'], loc='upper left')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d6cdda0e301be0b84e826e29f0f3a85c41aa6da9"},"cell_type":"markdown","source":"# 9.Inference of result <a id = \"9\"></a>"},{"metadata":{"trusted":true,"_uuid":"b58cd95254f41e5002a17de0c3feab54a5fc3c67"},"cell_type":"code","source":"# prediction part\nbatch_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 = pd.read_csv(\"../input/test.csv\")\n\nall_preds = []\nfor x in tqdm(batch_gen(test_df)):\n    all_preds.extend(model.predict(x).flatten())","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"3432ff401150ccef3647c42bf48a4a3636ac5c99"},"cell_type":"markdown","source":"# 10.Submission<a id=\"10\"> </a>"},{"metadata":{"trusted":true,"_uuid":"3e6ed54def110c881f401c6f8a844752baedcfbd"},"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":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}