{"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":"b576cf8d4f43a0c1129401e0277bfc71f4bfc5cc","scrolled":true},"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":"6f6c6088840b9e0b41cd73c71cd7657d23ecd28d"},"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":"372ee5b31ed7beb4b67ec1098cb2cd9a13c70b06"},"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":"8f4fce9de3c11cb8fe62040e795bbfede8709ec7","scrolled":true},"cell_type":"code","source":"\nfrom 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":"0ca1abdabf67d15e10973be0a6acc71ff308a691"},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\n\ntrain_df, val_df = train_test_split(rawTrainData,test_size=0.015)\nmaxAllowedSequenceLength = 50","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"3bde3517dfdebe3dcb9a91da341fb61c6983aa7c"},"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":"f8e0e983f855df4c119ba02b3dfbd8c5c737600f"},"cell_type":"code","source":"from nltk.tokenize import word_tokenize\n#print(rawTrainData.head(10))\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)    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"1a087d13a1a8b32c846dd790973456ab41d87904"},"cell_type":"code","source":"x_val = np.array([text_to_array(text) for text in tqdm(val_df['stopWordsRemovedText'][:])])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"7fbb46bc7fb045236d2e7da7a808c28e462453e2"},"cell_type":"code","source":"y_val = np.array(val_df['target'])\nprint(np.shape(x_val))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"c5c15616d9309935c328521d936f7e3ffbb8a0ca"},"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 = 128\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            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":"fc3059514acb00c969eaab752c4f9787609c4524"},"cell_type":"code","source":"model = Sequential()\nmodel.add(Bidirectional(LSTM(10, return_sequences=True),\n                        input_shape=(50, 300)))\nmodel.add(Bidirectional(LSTM(10)))\nmodel.add(Dense(1))\nmodel.add(Activation('sigmoid'))\nmodel.compile(loss='binary_crossentropy', metrics = ['accuracy'],optimizer='rmsprop')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"2b25dfe0f2e2aaa92d45dda31a519c9abe13367b"},"cell_type":"code","source":"dataGenerator = generateBatches(batch_size)\nnumBatches = np.ceil(train_df.shape[0]/batch_size)\nfrom keras import callbacks\nes = callbacks.EarlyStopping(monitor='val_loss',\n                              min_delta=0,\n                              patience=2,\n                              verbose=0, mode='auto')\nmodel.fit_generator(dataGenerator,steps_per_epoch=1000, epochs=5,validation_data = (x_val,y_val),verbose = False,callbacks = [es])","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}