{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"../input\"))\nprint(os.listdir(\"../input/embeddings\"))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport csv\nfrom tqdm import tqdm\nfrom keras.layers import Dense,Activation,LSTM, Bidirectional\nfrom keras.models import Sequential\n\nremoveStopWords = 1","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"dafc1eb5adbe42303e922ee2bd9b6f28f64d7615"},"cell_type":"code","source":"rawTrainData = pd.read_csv('../input/train.csv')\nrawTestData = pd.read_csv('../input/test.csv')\nprint('The training data has the following: ',rawTrainData.columns)\nprint('The number of questions given in train data is: ',rawTrainData.shape[0])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"2c4a03bdc7d7841efd63c2f8b162c6cf6b7ad2df"},"cell_type":"code","source":"def read_glove_vecs(glove_file):\n    fileData = open(glove_file, 'r',encoding='utf-8')\n    with fileData as f:\n        words = set()\n        word_to_vec_map = {}\n        \n        for line in tqdm(f):\n            line = line.split(\" \")\n            curr_word = line[0]\n            words.add(curr_word)\n            word_to_vec_map[curr_word] = np.array(line[1:], dtype=np.float32)\n            \n    return words, word_to_vec_map","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"41be7e3aad7742e9d23c9765cbc162b80d9950cd"},"cell_type":"code","source":"# read glove word vectors\nwords, word_to_vec_map = read_glove_vecs('../input/embeddings/glove.840B.300d/glove.840B.300d.txt')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"c92754a92620456087e7b287059069ee8c869de9"},"cell_type":"code","source":"print(rawTrainData.head(10))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"6ed1523f68c17fbe88dfa2b294f2ba658b04e37a"},"cell_type":"code","source":"from tqdm import tqdm, tqdm_notebook\ntqdm_notebook().pandas()\nfrom nltk.corpus import stopwords\ndef removeStopWords(word_list):\n    return [word for word in word_list if word not in stopwords.words('english')]        ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"8229e49ff1e72010a3beed107c08fe31d035905f"},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\n\ntrain_df, val_df = train_test_split(rawTrainData,test_size=0.02)\nmaxAllowedSequenceLength = 40","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"36bf336e71784837422392e473919774f71850c6"},"cell_type":"code","source":"def text_to_array(textVal):\n    emptyArr = np.zeros(300)    \n    textVal = textVal[:maxAllowedSequenceLength]\n    embed_text = [word_to_vec_map.get(text,emptyArr) for text in textVal]    \n    embed_text+= [emptyArr] * (maxAllowedSequenceLength - len(embed_text))  \n    return np.array(embed_text)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"4c97bc2cf4acdd021b68177f83989c52bdade7c8"},"cell_type":"code","source":"from nltk.tokenize import word_tokenize\nval_df['tokenizedText'] = val_df.apply(lambda row: word_tokenize(row['question_text']), axis=1)\nval_df['sents_length'] = val_df.apply(lambda row: len(row['tokenizedText']), axis=1)\nval_df['stopWordsRemovedText'] = val_df.progress_apply(lambda row: removeStopWords(row['tokenizedText']), axis=1)\nx_val = np.array([text_to_array(text) for text in tqdm(val_df['stopWordsRemovedText'][:])])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"157441e62e5623de2d82dac7233751c660080fd0"},"cell_type":"code","source":"y_val = np.array(val_df['target'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"c6eec0a47259a684cecb5462b95922247e0cf9c0"},"cell_type":"code","source":"print(np.shape(x_val))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"12248847574d19897749811de832633e79ed889e"},"cell_type":"code","source":"# I tried calling the text_to_array function directly on the train_df but ran out of memory after just a few tens of thousands\n# of runs. So using generator and yield seems to be the way to go. let us see if that works.\n\nbatch_size = 256\n\ndef generateBatches(batch_size):\n    numBatches = int(np.ceil(train_df.shape[0]/batch_size))\n    while True:\n        for i in range(numBatches):\n            batchDF = train_df.iloc[i*batch_size : (i+1)*batch_size]\n            batchDF['tokenizedText'] = batchDF.apply(lambda row: word_tokenize(row['question_text']), axis=1)\n            batchDF['sents_length'] = batchDF.apply(lambda row: len(row['tokenizedText']), axis=1)            \n            batchDF['stopWordsRemovedText'] = batchDF.progress_apply(lambda row: removeStopWords(row['tokenizedText']), axis=1)\n            text_arr = np.array([text_to_array(text) for text in (batchDF['stopWordsRemovedText'])])\n            targetVal = np.array(batchDF['target'])\n            yield text_arr,targetVal                      ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"8d18739b2e792fa40fc82aee52db3bd52379fac9"},"cell_type":"code","source":"model = Sequential()\nmodel.add(Bidirectional(LSTM(10, return_sequences=True),\n                        input_shape=(40, 300)))\nmodel.add(Bidirectional(LSTM(10)))\nmodel.add(Dense(1))\nmodel.add(Activation('sigmoid'))\nmodel.compile(loss='binary_crossentropy', metrics = ['accuracy'],optimizer='adam')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"904999a0ebd06ea850623b6f4b8448a639202bf5"},"cell_type":"code","source":"dataGenerator = generateBatches(batch_size)\nnumBatches = np.ceil(train_df.shape[0]/batch_size)\nmodel.fit_generator(dataGenerator,steps_per_epoch=500, epochs=6,validation_data = (x_val,y_val),verbose = True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"5e19f28b70ed937bd06103aafa1c54dd8a3dda8b"},"cell_type":"code","source":"from sklearn.metrics import f1_score\n\npred_val_y = model.predict([x_val], batch_size=1024, verbose=1)\nfor thresh in np.arange(0.1, 0.501, 0.01):\n    thresh = np.round(thresh, 2)\n    print(\"F1 score at threshold {0} is {1}\".format(thresh, f1_score(y_val, (pred_val_y>thresh).astype(int))))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"dfb3b783450ad6ffb8d59b4dce80647c878b2d94"},"cell_type":"code","source":"rawTestData['tokenizedText'] = rawTestData.apply(lambda row: word_tokenize(row['question_text']), axis=1)\nrawTestData['sents_length'] = rawTestData.apply(lambda row: len(row['tokenizedText']), axis=1)\nrawTestData['stopWordsRemovedText'] = rawTestData.progress_apply(lambda row: removeStopWords(row['tokenizedText']), axis=1)  ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"6de323a533b5353c4a3d7c039b7fe95ada37ff0f"},"cell_type":"code","source":"def generateBatchesTest(batch_size):\n    numBatches = int(np.ceil(rawTestData.shape[0]/batch_size))\n    for i in range(numBatches):\n        batchDF = rawTestData.iloc[i*batch_size : (i+1)*batch_size]\n        text_arr = np.array([text_to_array(text) for text in (batchDF['stopWordsRemovedText'])])            \n        yield text_arr      ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"bfe9ea5cddae379f2ed7f367675b372c03718f6e"},"cell_type":"code","source":"pred_test_y = []\nfor x_test in tqdm(generateBatchesTest(batch_size)):\n    pred_test_y.extend(model.predict(x_test,verbose=1))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"b2fccfcb302831709b6f4a0c813640e60945f8df"},"cell_type":"code","source":"y_pred = (np.array(pred_test_y)>0.33).astype(int)\nsubmissionDF = pd.DataFrame({'qid':rawTestData['qid'],'prediction':y_pred.flatten()})\nsubmissionDF.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}