{"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\"))\n# Keras Imports\nimport keras\nfrom keras import backend as K\nfrom keras.models import Sequential\nfrom keras.layers import Dense, CuDNNLSTM, CuDNNGRU, Dropout, Bidirectional, Conv1D\nfrom keras.layers.embeddings import Embedding\nfrom keras.preprocessing import sequence \nfrom keras.wrappers.scikit_learn import KerasClassifier\n# Numpy\nimport numpy\nnumpy.random.seed(1331)\n# Pandas\nimport pandas as pd\n# Sklearn\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import f1_score\nfrom sklearn.model_selection import GridSearchCV, RandomizedSearchCV, StratifiedKFold, cross_val_score\n# Visualizations\nimport matplotlib.pyplot as plt\n%matplotlib inline\n# Garbage Collector\nimport gc\nimport sys\nfrom keras.optimizers import Adam\n\nimport time\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"cd3a1d611bdb8d83130ef03c283bf83338f27d45"},"cell_type":"code","source":"from tqdm import tqdm","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"3c803db591b4da6c4bea50ba467a7cee6cbb85ce"},"cell_type":"markdown","source":"# Train 1st Model -- GRU "},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"start= time.clock()\n\nq_df = pd.read_csv(\"../input/train.csv\")\ntest = pd.read_csv('../input/test.csv')\n\nX_train = q_df.question_text\ny_train = q_df.target\n\nx_test = test.question_text\n\nfrom keras.preprocessing.text import Tokenizer\n\n# create a tokenizer \ntot_uniq_words= 49681\ntoken = Tokenizer(num_words=tot_uniq_words)\ntoken.fit_on_texts(q_df['question_text'])\nword_index = token.word_index\n\n# convert text to sequence of tokens and pad them to ensure equal length vectors \nmaxlen = 134\ntrain_seq_x = sequence.pad_sequences(token.texts_to_sequences(X_train), maxlen=maxlen)\ntest_seq_x = sequence.pad_sequences(token.texts_to_sequences(x_test), maxlen=maxlen)","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"del [X_train, x_test]\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"cef8675b87fde9f5ad4041d5ba18b5e062adb653"},"cell_type":"code","source":"batches= 3152\ndrpt_amt = .2\nembed_size = 88\nepochs =2\ngru1_nrns = 47\ngru2_nrns= 49","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"0d119b5d97e65da239c2546feceb99033409371c"},"cell_type":"code","source":"\nK.clear_session()\nmodel = Sequential()\nmodel.add(Embedding(tot_uniq_words, embed_size, input_length=maxlen))\nmodel.add(Dropout(drpt_amt))\nmodel.add(Bidirectional(CuDNNGRU(gru1_nrns, return_sequences=True)))\nmodel.add(Dropout(drpt_amt))\nmodel.add(Bidirectional(CuDNNGRU(gru2_nrns)))\nmodel.add(Dropout(drpt_amt))\nmodel.add(Dense(1, activation='sigmoid'))\n\n# Compile model\nmodel.compile(loss='binary_crossentropy', optimizer=Adam(), metrics=['accuracy'])\nmodel.fit(x = train_seq_x, y = np.array(y_train), epochs= epochs, batch_size=batches)\n\n\ngru_preds= model.predict(train_seq_x)\ngru_x_test = model.predict(test_seq_x)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"b0d1fa7294c5c73c8e7b9db38a9143b2e433fb08"},"cell_type":"code","source":"del [train_seq_x, token, model]\ngc.collect() ","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"27f942886ff67720fd644c804aa74c2ec9b0d026"},"cell_type":"markdown","source":"# Train 2nd Model -- DPCNN"},{"metadata":{"trusted":true,"_uuid":"aeb225811e1357adfb780f1e5ce534097ada5ef0"},"cell_type":"code","source":"import os\nimport gc\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nimport warnings\nwarnings.filterwarnings('ignore')\n\nfrom keras import backend as K\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.model_selection import KFold\nfrom keras.models import Model\nfrom keras.layers import Input, Dense, Embedding, MaxPooling1D, Conv1D, SpatialDropout1D\nfrom keras.layers import add, Dropout, PReLU, BatchNormalization, GlobalMaxPooling1D\nfrom keras.preprocessing import text, sequence\nfrom keras.callbacks import Callback\nfrom keras import optimizers\nfrom keras import initializers, regularizers, constraints, callbacks\n\n\nfrom datetime import datetime\n\n\nfrom keras import backend as K\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.model_selection import StratifiedKFold\nfrom keras.models import Model\nfrom keras.layers import Input, Dense, Embedding, MaxPooling1D, Conv1D, SpatialDropout1D\nfrom keras.layers import add, Dropout, PReLU, BatchNormalization, GlobalMaxPooling1D\nfrom keras.preprocessing import text, sequence\nfrom keras.callbacks import Callback\nfrom keras import optimizers\nfrom keras import initializers, regularizers, constraints, callbacks\n# Any results you write to the current directory are saved as output.\n\nimport time\n\nfrom keras.models import load_model\nfrom sklearn.metrics import f1_score, roc_auc_score\nfrom keras.callbacks import ModelCheckpoint\nfrom tqdm import tqdm\n\nfrom sklearn.model_selection import StratifiedKFold","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"64fcc6ae06c00ba45964271c1717b65729f34197"},"cell_type":"code","source":"\n# DPCNN\n\ntrain_df = pd.read_csv('../input/train.csv')\ntest = pd.read_csv('../input/test.csv')\n\nX_train = train_df.question_text\ny_train = train_df.target\n\nX_test = test.question_text\n\nmax_features= 100000\nmaxlen = 134\nembed_size = 300\n\n### GETTING 3% HOLDOUT\n\n\n\ncontraction_mapping = {\"ain't\": \"is not\", \"aren't\": \"are not\",\"can't\": \"cannot\", \"'cause\": \"because\", \"could've\": \"could have\", \"couldn't\": \"could not\", \"didn't\": \"did not\",  \"doesn't\": \"does not\", \"don't\": \"do not\", \"hadn't\": \"had not\", \"hasn't\": \"has not\", \"haven't\": \"have not\", \"he'd\": \"he would\",\"he'll\": \"he will\", \"he's\": \"he is\", \"how'd\": \"how did\", \"how'd'y\": \"how do you\", \"how'll\": \"how will\", \"how's\": \"how is\",  \"I'd\": \"I would\", \"I'd've\": \"I would have\", \"I'll\": \"I will\", \"I'll've\": \"I will have\",\"I'm\": \"I am\", \"I've\": \"I have\", \"i'd\": \"i would\", \"i'd've\": \"i would have\", \"i'll\": \"i will\",  \"i'll've\": \"i will have\",\"i'm\": \"i am\", \"i've\": \"i have\", \"isn't\": \"is not\", \"it'd\": \"it would\", \"it'd've\": \"it would have\", \"it'll\": \"it will\", \"it'll've\": \"it will have\",\"it's\": \"it is\", \"let's\": \"let us\", \"ma'am\": \"madam\", \"mayn't\": \"may not\", \"might've\": \"might have\",\"mightn't\": \"might not\",\"mightn't've\": \"might not have\", \"must've\": \"must have\", \"mustn't\": \"must not\", \"mustn't've\": \"must not have\", \"needn't\": \"need not\", \"needn't've\": \"need not have\",\"o'clock\": \"of the clock\", \"oughtn't\": \"ought not\", \"oughtn't've\": \"ought not have\", \"shan't\": \"shall not\", \"sha'n't\": \"shall not\", \"shan't've\": \"shall not have\", \"she'd\": \"she would\", \"she'd've\": \"she would have\", \"she'll\": \"she will\", \"she'll've\": \"she will have\", \"she's\": \"she is\", \"should've\": \"should have\", \"shouldn't\": \"should not\", \"shouldn't've\": \"should not have\", \"so've\": \"so have\",\"so's\": \"so as\", \"this's\": \"this is\",\"that'd\": \"that would\", \"that'd've\": \"that would have\", \"that's\": \"that is\", \"there'd\": \"there would\", \"there'd've\": \"there would have\", \"there's\": \"there is\", \"here's\": \"here is\",\"they'd\": \"they would\", \"they'd've\": \"they would have\", \"they'll\": \"they will\", \"they'll've\": \"they will have\", \"they're\": \"they are\", \"they've\": \"they have\", \"to've\": \"to have\", \"wasn't\": \"was not\", \"we'd\": \"we would\", \"we'd've\": \"we would have\", \"we'll\": \"we will\", \"we'll've\": \"we will have\", \"we're\": \"we are\", \"we've\": \"we have\", \"weren't\": \"were not\", \"what'll\": \"what will\", \"what'll've\": \"what will have\", \"what're\": \"what are\",  \"what's\": \"what is\", \"what've\": \"what have\", \"when's\": \"when is\", \"when've\": \"when have\", \"where'd\": \"where did\", \"where's\": \"where is\", \"where've\": \"where have\", \"who'll\": \"who will\", \"who'll've\": \"who will have\", \"who's\": \"who is\", \"who've\": \"who have\", \"why's\": \"why is\", \"why've\": \"why have\", \"will've\": \"will have\", \"won't\": \"will not\", \"won't've\": \"will not have\", \"would've\": \"would have\", \"wouldn't\": \"would not\", \"wouldn't've\": \"would not have\", \"y'all\": \"you all\", \"y'all'd\": \"you all would\",\"y'all'd've\": \"you all would have\",\"y'all're\": \"you all are\",\"y'all've\": \"you all have\",\"you'd\": \"you would\", \"you'd've\": \"you would have\", \"you'll\": \"you will\", \"you'll've\": \"you will have\", \"you're\": \"you are\", \"you've\": \"you have\" }\n\ndef clean_contractions(text, mapping):\n    specials = [\"’\", \"‘\", \"´\", \"`\"]\n    for s in specials:\n        text = text.replace(s, \"'\")\n    text = ' '.join([mapping[t] if t in mapping else t for t in text.split(\" \")])\n    return text\n\nX_train = X_train.apply(lambda x: clean_contractions(x, contraction_mapping))\n\nX_test = X_test.apply(lambda x: clean_contractions(x, contraction_mapping))\n\n# deal with punctuations\n\npunct = \"/-'?!.,#$%\\'()*+-/:;<=>@[\\\\]^_`{|}~\" + '\"\"“”’' + '∞θ÷α•à−β∅³π‘₹´°£€\\×™√²—–&'\n\n\npunct_mapping = {\"‘\": \"'\", \"₹\": \"e\", \"´\": \"'\", \"°\": \"\", \"€\": \"e\", \"™\": \"tm\", \"√\": \" sqrt \", \"×\": \"x\", \"²\": \"2\", \"—\": \"-\", \"–\": \"-\", \"’\": \"'\", \"_\": \"-\", \"`\": \"'\", '“': '\"', '”': '\"', '“': '\"', \"£\": \"e\", '∞': 'infinity', 'θ': 'theta', '÷': '/', 'α': 'alpha', '•': '.', 'à': 'a', '−': '-', 'β': 'beta', '∅': '', '³': '3', 'π': 'pi', }\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': '', 'करना': '', 'है': ''}  # Other special characters that I have to deal with in last\n    for s in specials:\n        text = text.replace(s, specials[s])\n    \n    return text\n\nX_train = X_train.apply(lambda x: clean_special_chars(x, punct, punct_mapping))\n\nX_test = X_test.apply(lambda x: clean_special_chars(x, punct, punct_mapping))\n\n\nmispell_dict = {'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'}\n\ndef correct_spelling(x, dic):\n    for word in dic.keys():\n        x = x.replace(word, dic[word])\n    return x\n\nX_train = X_train.apply(lambda x: correct_spelling(x, mispell_dict))\n\nX_test = X_test.apply(lambda x: correct_spelling(x, mispell_dict))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"3158f873be3468796926d4711d18dfdabdd59863"},"cell_type":"code","source":"print('preprocessing start')\n\ntokenizer = Tokenizer(num_words=max_features)\ntokenizer.fit_on_texts(list(X_train)) \nX_train = tokenizer.texts_to_sequences(X_train)\nX_test = tokenizer.texts_to_sequences(X_test)\n\nx_train = sequence.pad_sequences(X_train, maxlen=maxlen)\nx_test = sequence.pad_sequences(X_test, maxlen=maxlen)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"312f595b1dd1bff9efce9c58234fe366299815b4"},"cell_type":"code","source":"EMBEDDING_FILE = '../input/embeddings/paragram_300_sl999/paragram_300_sl999.txt'\ndef get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32')\nembeddings_index = dict(get_coefs(*o.split(\" \")) for o in open(EMBEDDING_FILE, encoding=\"utf8\", errors='ignore') if len(o)>100)\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\n# word_index = tokenizer.word_index\nnb_words = len(tokenizer.word_index)+1\nembedding_matrix = np.zeros((nb_words, embed_size))\nfor word, i in tqdm(tokenizer.word_index.items()):\n#     if i >= max_features: continue\n    embedding_vector = embeddings_index.get(word)\n    if embedding_vector is not None: embedding_matrix[i] = embedding_vector\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"7771ecae8d6149ae6375ccc1eb0afc14611738ef"},"cell_type":"code","source":"epochs = 2\nbatch_size = 500\nspatial_dropout=0.11260266916085344\ndense_nr = 64\nfilter_nr=64\nfilter_size=4\nmax_pool_size= 3\ndense_dropout = 0.5365018989527698\nmax_pool_strides=2,\nconv_kern_reg= 1e-06\nconv_bias_reg=1e-05\nnb_words=nb_words\nembedding_matrix= embedding_matrix","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"6baf9f6580cc8ca5c1425e0d4e0cc4ee6e363a0d","scrolled":true},"cell_type":"code","source":"\nK.clear_session()\ncomment = Input(shape=(maxlen,))\nemb_comment = Embedding(nb_words, embed_size, weights= [embedding_matrix], trainable= False)(comment)\nemb_comment = SpatialDropout1D(spatial_dropout)(emb_comment)\n\nblock1 = Conv1D(filter_nr, kernel_size=filter_size, padding='same', activation='linear', \n            kernel_regularizer=regularizers.l2(conv_kern_reg), bias_regularizer=regularizers.l2(conv_bias_reg))(emb_comment)\nblock1 = BatchNormalization()(block1)\nblock1 = PReLU()(block1)\nblock1 = Conv1D(filter_nr, kernel_size=filter_size, padding='same', activation='linear', \n            kernel_regularizer=regularizers.l2(conv_kern_reg), bias_regularizer=regularizers.l2(conv_bias_reg))(block1)\nblock1 = BatchNormalization()(block1)\nblock1 = PReLU()(block1)\n\n#we pass embedded comment through conv1d with filter size 1 because it needs to have the same shape as block output\n#if you choose filter_nr = embed_size (300 in this case) you don't have to do this part and can add emb_comment directly to block1_output\nresize_emb = Conv1D(filter_nr, kernel_size=1, padding='same', activation='linear', \n            kernel_regularizer=regularizers.l2(conv_kern_reg), bias_regularizer=regularizers.l2(conv_bias_reg))(emb_comment)\nresize_emb = PReLU()(resize_emb)\n\nblock1_output = add([block1, resize_emb])\nblock1_output = MaxPooling1D(pool_size=max_pool_size, strides=max_pool_strides)(block1_output)\n\nblock2 = Conv1D(filter_nr, kernel_size=filter_size, padding='same', activation='linear', \n            kernel_regularizer=regularizers.l2(conv_kern_reg), bias_regularizer=regularizers.l2(conv_bias_reg))(block1_output)\nblock2 = BatchNormalization()(block2)\nblock2 = PReLU()(block2)\nblock2 = Conv1D(filter_nr, kernel_size=filter_size, padding='same', activation='linear', \n            kernel_regularizer=regularizers.l2(conv_kern_reg), bias_regularizer=regularizers.l2(conv_bias_reg))(block2)\nblock2 = BatchNormalization()(block2)\nblock2 = PReLU()(block2)\n\nblock2_output = add([block2, block1_output])\nblock2_output = MaxPooling1D(pool_size=max_pool_size, strides=max_pool_strides)(block2_output)\n\nblock3 = Conv1D(filter_nr, kernel_size=filter_size, padding='same', activation='linear', \n            kernel_regularizer=regularizers.l2(conv_kern_reg), bias_regularizer=regularizers.l2(conv_bias_reg))(block2_output)\nblock3 = BatchNormalization()(block3)\nblock3 = PReLU()(block3)\nblock3 = Conv1D(filter_nr, kernel_size=filter_size, padding='same', activation='linear', \n            kernel_regularizer=regularizers.l2(conv_kern_reg), bias_regularizer=regularizers.l2(conv_bias_reg))(block3)\nblock3 = BatchNormalization()(block3)\nblock3 = PReLU()(block3)\n\nblock3_output = add([block3, block2_output])\nblock3_output = MaxPooling1D(pool_size=max_pool_size, strides=max_pool_strides)(block3_output)\n\nblock4 = Conv1D(filter_nr, kernel_size=filter_size, padding='same', activation='linear', \n            kernel_regularizer=regularizers.l2(conv_kern_reg), bias_regularizer=regularizers.l2(conv_bias_reg))(block3_output)\nblock4 = BatchNormalization()(block4)\nblock4 = PReLU()(block4)\nblock4 = Conv1D(filter_nr, kernel_size=filter_size, padding='same', activation='linear', \n            kernel_regularizer=regularizers.l2(conv_kern_reg), bias_regularizer=regularizers.l2(conv_bias_reg))(block4)\nblock4 = BatchNormalization()(block4)\nblock4 = PReLU()(block4)\n\nblock4_output = add([block4, block3_output])\nblock4_output = MaxPooling1D(pool_size=max_pool_size, strides=max_pool_strides)(block4_output)\n\nblock5 = Conv1D(filter_nr, kernel_size=filter_size, padding='same', activation='linear', \n            kernel_regularizer=regularizers.l2(conv_kern_reg), bias_regularizer=regularizers.l2(conv_bias_reg))(block4_output)\nblock5 = BatchNormalization()(block5)\nblock5 = PReLU()(block5)\nblock5 = Conv1D(filter_nr, kernel_size=filter_size, padding='same', activation='linear', \n            kernel_regularizer=regularizers.l2(conv_kern_reg), bias_regularizer=regularizers.l2(conv_bias_reg))(block5)\nblock5 = BatchNormalization()(block5)\nblock5 = PReLU()(block5)\n\nblock5_output = add([block5, block4_output])\nblock5_output = MaxPooling1D(pool_size=max_pool_size, strides=max_pool_strides)(block5_output)\n\nblock6 = Conv1D(filter_nr, kernel_size=filter_size, padding='same', activation='linear', \n            kernel_regularizer=regularizers.l2(conv_kern_reg), bias_regularizer=regularizers.l2(conv_bias_reg))(block5_output)\nblock6 = BatchNormalization()(block6)\nblock6 = PReLU()(block6)\nblock6 = Conv1D(filter_nr, kernel_size=filter_size, padding='same', activation='linear', \n            kernel_regularizer=regularizers.l2(conv_kern_reg), bias_regularizer=regularizers.l2(conv_bias_reg))(block6)\nblock6 = BatchNormalization()(block6)\nblock6 = PReLU()(block6)\n\nblock6_output = add([block6, block5_output])\nblock6_output = MaxPooling1D(pool_size=max_pool_size, strides=max_pool_strides)(block6_output)\n\nblock7 = Conv1D(filter_nr, kernel_size=filter_size, padding='same', activation='linear', \n            kernel_regularizer=regularizers.l2(conv_kern_reg), bias_regularizer=regularizers.l2(conv_bias_reg))(block6_output)\nblock7 = BatchNormalization()(block7)\nblock7 = PReLU()(block7)\nblock7 = Conv1D(filter_nr, kernel_size=filter_size, padding='same', activation='linear', \n            kernel_regularizer=regularizers.l2(conv_kern_reg), bias_regularizer=regularizers.l2(conv_bias_reg))(block7)\nblock7 = BatchNormalization()(block7)\nblock7 = PReLU()(block7)\n\nblock7_output = add([block7, block6_output])\noutput = GlobalMaxPooling1D()(block7_output)\n\noutput = Dense(dense_nr, activation='linear')(output)\noutput = BatchNormalization()(output)\noutput = PReLU()(output)\noutput = Dropout(dense_dropout)(output)\noutput = Dense(1, activation='sigmoid')(output)\n\nmodel = Model(comment, output)\n\n\nmodel.compile(loss='binary_crossentropy', \n            optimizer=optimizers.Adam(),\n            metrics=['accuracy'])\n# Compile model\nmodel.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\nmodel.fit(x = x_train, y = np.array(y_train), epochs= epochs, batch_size=batch_size)\n\n### NOTE\n# this goes to level 1 \ndpcnn_preds = model.predict(x_train, verbose=1)\n# this goes to prediction\ndpcnn_x_test = model.predict(x_test, verbose=1)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"aea9d4293cd56bce38e63d558ef8edeb6c95ea0c"},"cell_type":"code","source":"del [x_train,  X_train, x_test, X_test, y_train, tokenizer, train_df, max_features,model,all_embs, q_df, test_seq_x, word_index]\ndel [embedding_vector, embeddings_index, embedding_matrix]\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"f2060c1ccedd744d5bb5b88b696d0b732adc41c2"},"cell_type":"code","source":"import gc","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"ff96fab43e64f90a074d80738408744ebfb8befb"},"cell_type":"code","source":"import os\nimport time\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\nfrom sklearn import metrics\nfrom sklearn.model_selection import GridSearchCV, StratifiedKFold\nfrom sklearn.metrics import f1_score, roc_auc_score\n\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.layers import Dense, Input, CuDNNLSTM, Embedding, Dropout, Activation, CuDNNGRU, Conv1D\nfrom keras.layers import Bidirectional, GlobalMaxPool1D, GlobalMaxPooling1D, GlobalAveragePooling1D\nfrom keras.layers import Input, Embedding, Dense, Conv2D, MaxPool2D, concatenate\nfrom keras.layers import Reshape, Flatten, Concatenate, Dropout, SpatialDropout1D\nfrom keras.optimizers import Adam\nfrom keras.models import Model\nfrom keras import backend as K\nfrom keras.engine.topology import Layer\nfrom keras import initializers, regularizers, constraints, optimizers, layers\nfrom keras.layers import concatenate\nfrom keras.callbacks import *\n\n\nmaxlen = 70 # max number of words in a question to use\n\ntrain_df = pd.read_csv(\"../input/train.csv\")\ntest_df = pd.read_csv(\"../input/test.csv\")\nprint(\"Train shape : \",train_df.shape)\nprint(\"Test shape : \",test_df.shape)\n\n## fill up the missing values\ntrain_X = train_df[\"question_text\"].fillna(\"_##_\").values\ntest_X = test_df[\"question_text\"].fillna(\"_##_\").values\n\n## Tokenize the sentences\ntokenizer = Tokenizer()\ntokenizer.fit_on_texts(list(train_X))\ntrain_X = tokenizer.texts_to_sequences(train_X)\ntest_X = tokenizer.texts_to_sequences(test_X)\n\n## Pad the sentences \nx_train = pad_sequences(train_X, maxlen=maxlen)\nx_test = pad_sequences(test_X, maxlen=maxlen)\n\n## Get the target values\ny_train = train_df['target'].values","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"a1be27ca8ee0f388af47ca3dcbf3b340bc4c1d14"},"cell_type":"code","source":"del[train_df, train_X ]\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"d96673f9eab49b2f99aae18413f2c28c0bd51e87"},"cell_type":"code","source":"EMBEDDING_FILE = '../input/embeddings/paragram_300_sl999/paragram_300_sl999.txt'\ndef get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32')\nembeddings_index = dict(get_coefs(*o.split(\" \")) for o in open(EMBEDDING_FILE, encoding=\"utf8\", errors='ignore') if len(o)>100)\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\n# word_index = tokenizer.word_index\nnb_words = len(tokenizer.word_index)+1\nembedding_matrix = np.zeros((nb_words, embed_size))\nfor word, i in tqdm(tokenizer.word_index.items()):\n#     if i >= max_features: continue\n    embedding_vector = embeddings_index.get(word)\n    if embedding_vector is not None: embedding_matrix[i] = embedding_vector\n\n## some config values \nembed_size = 300 # how big is each word vector\nmax_features = nb_words # how many unique words to use (i.e num rows in embedding vector)\n\n\nclass Attention(Layer):\n    def __init__(self, step_dim,\n                 W_regularizer=None, b_regularizer=None,\n                 W_constraint=None, b_constraint=None,\n                 bias=True, **kwargs):\n        self.supports_masking = True\n        self.init = initializers.get('glorot_uniform')\n\n        self.W_regularizer = regularizers.get(W_regularizer)\n        self.b_regularizer = regularizers.get(b_regularizer)\n\n        self.W_constraint = constraints.get(W_constraint)\n        self.b_constraint = constraints.get(b_constraint)\n\n        self.bias = bias\n        self.step_dim = step_dim\n        self.features_dim = 0\n        super(Attention, self).__init__(**kwargs)\n\n    def build(self, input_shape):\n        assert len(input_shape) == 3\n\n        self.W = self.add_weight((input_shape[-1],),\n                                 initializer=self.init,\n                                 name='{}_W'.format(self.name),\n                                 regularizer=self.W_regularizer,\n                                 constraint=self.W_constraint)\n        self.features_dim = input_shape[-1]\n\n        if self.bias:\n            self.b = self.add_weight((input_shape[1],),\n                                     initializer='zero',\n                                     name='{}_b'.format(self.name),\n                                     regularizer=self.b_regularizer,\n                                     constraint=self.b_constraint)\n        else:\n            self.b = None\n\n        self.built = True\n\n    def compute_mask(self, input, input_mask=None):\n        return None\n\n    def call(self, x, mask=None):\n        features_dim = self.features_dim\n        step_dim = self.step_dim\n\n        eij = K.reshape(K.dot(K.reshape(x, (-1, features_dim)),\n                        K.reshape(self.W, (features_dim, 1))), (-1, step_dim))\n\n        if self.bias:\n            eij += self.b\n\n        eij = K.tanh(eij)\n\n        a = K.exp(eij)\n\n        if mask is not None:\n            a *= K.cast(mask, K.floatx())\n\n        a /= K.cast(K.sum(a, axis=1, keepdims=True) + K.epsilon(), K.floatx())\n\n        a = K.expand_dims(a)\n        weighted_input = x * a\n        return K.sum(weighted_input, axis=1)\n\n    def compute_output_shape(self, input_shape):\n        return input_shape[0],  self.features_dim\n\n# https://www.kaggle.com/hireme/fun-api-keras-f1-metric-cyclical-learning-rate/code\n\nclass CyclicLR(Callback):\n    \"\"\"This callback implements a cyclical learning rate policy (CLR).\n    The method cycles the learning rate between two boundaries with\n    some constant frequency, as detailed in this paper (https://arxiv.org/abs/1506.01186).\n    The amplitude of the cycle can be scaled on a per-iteration or \n    per-cycle basis.\n    This class has three built-in policies, as put forth in the paper.\n    \"triangular\":\n        A basic triangular cycle w/ no amplitude scaling.\n    \"triangular2\":\n        A basic triangular cycle that scales initial amplitude by half each cycle.\n    \"exp_range\":\n        A cycle that scales initial amplitude by gamma**(cycle iterations) at each \n        cycle iteration.\n    For more detail, please see paper.\n    \n    # Example\n        ```python\n            clr = CyclicLR(base_lr=0.001, max_lr=0.006,\n                                step_size=2000., mode='triangular')\n            model.fit(X_train, Y_train, callbacks=[clr])\n        ```\n    \n    Class also supports custom scaling functions:\n        ```python\n            clr_fn = lambda x: 0.5*(1+np.sin(x*np.pi/2.))\n            clr = CyclicLR(base_lr=0.001, max_lr=0.006,\n                                step_size=2000., scale_fn=clr_fn,\n                                scale_mode='cycle')\n            model.fit(X_train, Y_train, callbacks=[clr])\n        ```    \n    # Arguments\n        base_lr: initial learning rate which is the\n            lower boundary in the cycle.\n        max_lr: upper boundary in the cycle. Functionally,\n            it defines the cycle amplitude (max_lr - base_lr).\n            The lr at any cycle is the sum of base_lr\n            and some scaling of the amplitude; therefore \n            max_lr may not actually be reached depending on\n            scaling function.\n        step_size: number of training iterations per\n            half cycle. Authors suggest setting step_size\n            2-8 x training iterations in epoch.\n        mode: one of {triangular, triangular2, exp_range}.\n            Default 'triangular'.\n            Values correspond to policies detailed above.\n            If scale_fn is not None, this argument is ignored.\n        gamma: constant in 'exp_range' scaling function:\n            gamma**(cycle iterations)\n        scale_fn: Custom scaling policy defined by a single\n            argument lambda function, where \n            0 <= scale_fn(x) <= 1 for all x >= 0.\n            mode paramater is ignored \n        scale_mode: {'cycle', 'iterations'}.\n            Defines whether scale_fn is evaluated on \n            cycle number or cycle iterations (training\n            iterations since start of cycle). Default is 'cycle'.\n    \"\"\"\n\n    def __init__(self, base_lr=0.001, max_lr=0.006, step_size=2000., mode='triangular',\n                 gamma=1., scale_fn=None, scale_mode='cycle'):\n        super(CyclicLR, self).__init__()\n\n        self.base_lr = base_lr\n        self.max_lr = max_lr\n        self.step_size = step_size\n        self.mode = mode\n        self.gamma = gamma\n        if scale_fn == None:\n            if self.mode == 'triangular':\n                self.scale_fn = lambda x: 1.\n                self.scale_mode = 'cycle'\n            elif self.mode == 'triangular2':\n                self.scale_fn = lambda x: 1/(2.**(x-1))\n                self.scale_mode = 'cycle'\n            elif self.mode == 'exp_range':\n                self.scale_fn = lambda x: gamma**(x)\n                self.scale_mode = 'iterations'\n        else:\n            self.scale_fn = scale_fn\n            self.scale_mode = scale_mode\n        self.clr_iterations = 0.\n        self.trn_iterations = 0.\n        self.history = {}\n\n        self._reset()\n\n    def _reset(self, new_base_lr=None, new_max_lr=None,\n               new_step_size=None):\n        \"\"\"Resets cycle iterations.\n        Optional boundary/step size adjustment.\n        \"\"\"\n        if new_base_lr != None:\n            self.base_lr = new_base_lr\n        if new_max_lr != None:\n            self.max_lr = new_max_lr\n        if new_step_size != None:\n            self.step_size = new_step_size\n        self.clr_iterations = 0.\n        \n    def clr(self):\n        cycle = np.floor(1+self.clr_iterations/(2*self.step_size))\n        x = np.abs(self.clr_iterations/self.step_size - 2*cycle + 1)\n        if self.scale_mode == 'cycle':\n            return self.base_lr + (self.max_lr-self.base_lr)*np.maximum(0, (1-x))*self.scale_fn(cycle)\n        else:\n            return self.base_lr + (self.max_lr-self.base_lr)*np.maximum(0, (1-x))*self.scale_fn(self.clr_iterations)\n        \n    def on_train_begin(self, logs={}):\n        logs = logs or {}\n\n        if self.clr_iterations == 0:\n            K.set_value(self.model.optimizer.lr, self.base_lr)\n        else:\n            K.set_value(self.model.optimizer.lr, self.clr())        \n            \n    def on_batch_end(self, epoch, logs=None):\n        \n        logs = logs or {}\n        self.trn_iterations += 1\n        self.clr_iterations += 1\n\n        self.history.setdefault('lr', []).append(K.get_value(self.model.optimizer.lr))\n        self.history.setdefault('iterations', []).append(self.trn_iterations)\n\n        for k, v in logs.items():\n            self.history.setdefault(k, []).append(v)\n        \n        K.set_value(self.model.optimizer.lr, self.clr())\n    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"c5c3b6495d1911f5c1abd00b88221ed19414c258"},"cell_type":"code","source":"# create model\n\nK.clear_session()\n    # Inputs\n\ninp = Input(shape=(maxlen,))\nx = Embedding(max_features, embed_size, weights=[embedding_matrix], trainable=False)(inp)\nx = SpatialDropout1D(0.1)(x)\nx = Bidirectional(CuDNNLSTM(40, return_sequences=True))(x)\ny = Bidirectional(CuDNNGRU(40, return_sequences=True))(x)\n\natten_1 = Attention(maxlen)(x) # skip connect\natten_2 = Attention(maxlen)(y)\navg_pool = GlobalAveragePooling1D()(y)\nmax_pool = GlobalMaxPooling1D()(y)\n\nconc = concatenate([atten_1, atten_2, avg_pool, max_pool])\nconc = Dense(16, activation=\"relu\")(conc)\nconc = Dropout(0.1)(conc)\noutp = Dense(1, activation=\"sigmoid\")(conc)    \n\nmodel = Model(inputs=inp, outputs=outp)\nmodel.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\n\nclr = CyclicLR(base_lr=0.001, max_lr=0.002,\n           step_size=300., mode='exp_range',\n           gamma=0.99994)\n\nmodel.fit(x_train, np.array(y_train), batch_size=512, epochs=2, callbacks = [clr], verbose=1)    \n\nattn_preds = model.predict(x_train, verbose=1)\nattn_x_test = model.predict(x_test, verbose=1)\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"52327bb5f1534b963e17790eef0a786bf4b3a929"},"cell_type":"code","source":"del model\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d6dacde3b64fad582595719a542b5dc9d2356738"},"cell_type":"markdown","source":"# Meta Learner"},{"metadata":{"trusted":true,"_uuid":"c37157e54520936ade61e9aeae15e72704d7c822"},"cell_type":"code","source":"target = np.array(y_train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"a5d7df45fdf28b74afaf3ed2680329158b11ba4c"},"cell_type":"code","source":"level_1_metalearner = pd.DataFrame(columns = ['attn', 'dpcnn', 'gru','target'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"046b151037d21baa7574e7556d742488e965c470"},"cell_type":"code","source":"level_1_metalearner['attn'] = attn_preds.ravel()\nlevel_1_metalearner['dpcnn'] = dpcnn_preds.ravel()\nlevel_1_metalearner['gru'] = gru_preds.ravel()\nlevel_1_metalearner['target'] = target.ravel()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"82c5951129fa56cb252a0604ee5da177ef15d38e"},"cell_type":"code","source":"level_1_metalearner.head()","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"0b23556da402937c178e7ecfc8c8177900cd8d7f"},"cell_type":"markdown","source":"# Level 1 table for test units\n"},{"metadata":{"trusted":true,"_uuid":"a82306150ecf89da67b885e9792f91541a5034fc"},"cell_type":"code","source":"level_1_test = pd.DataFrame(pd.DataFrame(columns = ['attn_test', 'dpcnn_test', 'gru_test']))\n\nlevel_1_test.attn_test = attn_x_test.ravel()\nlevel_1_test.dpcnn_test = dpcnn_x_test.ravel()\nlevel_1_test.gru_test = gru_x_test.ravel()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"1acbcc35d4db8f05cebb3faab927a89ca92b2d8d"},"cell_type":"code","source":"level_1_test.head()","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"c3820d50eeba8f83887eed2bc9dd9a5a154bb634"},"cell_type":"markdown","source":"# Train meta learner"},{"metadata":{"trusted":true,"_uuid":"7e252d48e54d25867415e5d1c85b52e87fa9e6ee"},"cell_type":"code","source":"x_train = level_1_metalearner.drop('target', axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"4115ec8af1cfeed0b205a5f4f9595247315f18b8"},"cell_type":"code","source":"y_train = level_1_metalearner.target","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"c72e000d7e0999fd2fed31cd9d4c7a51b9b073ba"},"cell_type":"code","source":"act1= 'relu'\nact2= 'tanh'\nact3= 'tanh'\nbatch_size= 100000\ndense_nr1= 287\ndense_nr2= 670\ndense_nr3= 140\ndropout1= 0.3383299306103077\ndropout2= 0.43369555270628113\ndropout3= 0.543347139093403\nepochs= 70","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"5bb2ca8ed07512297c9b0417468cd5440bc2c4b9"},"cell_type":"code","source":"# create model\n\nK.clear_session()\nmodel= Sequential()\nmodel.add(Dense(dense_nr1, activation=act1, input_shape=(3,)))\nmodel.add(Dropout(dropout1))\nmodel.add(Dense(dense_nr2, activation=act2))\nmodel.add(Dropout(dropout2))\nmodel.add(Dense(dense_nr3, activation=act3))\nmodel.add(Dropout(dropout3))\nmodel.add(Dense(1, activation='sigmoid'))\n\nmodel.compile(loss='binary_crossentropy', \n            optimizer='adam',\n            metrics=['accuracy'])\n\nmodel.fit(x_train, np.array(y_train), batch_size=batch_size, epochs=epochs, verbose=1)    \n\nmetalearner_x_test = model.predict(level_1_test, verbose=1)\n\n","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"3ba71d8fbaf68afa5364a402b61e1c922fd1b05c"},"cell_type":"raw","source":""},{"metadata":{"trusted":true,"_uuid":"7b251255cd6b7f6cab810e4846b15a7b848a6bff"},"cell_type":"code","source":"test_df.drop('question_text', axis=1, inplace=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"d7a48c1ccd3818073ec887d38992f7c25f7970eb"},"cell_type":"code","source":"test_df['prediction'] = metalearner_x_test.ravel()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"4bf1e611920a1f556bc08b7f01fe4bdeb996570d"},"cell_type":"code","source":"test_df.prediction = test_df.prediction.apply(lambda x: 1 if x>=.34 else 0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"91f9add90d568d4288401366821287aba1a39243"},"cell_type":"code","source":"test_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"2322f7ef6160e03e63c59d1668508269f19daad0"},"cell_type":"code","source":"print('process time in minutes: ', (time.clock()-start)/60)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"abec90cc5c8bb569ac59df8e608dbd582bb19523"},"cell_type":"code","source":"test_df.to_csv('submission.csv', index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"8c0520231f913c14d6c1a8f0a5f4d4895733e46d"},"cell_type":"code","source":"","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}