{"cells":[{"metadata":{"trusted":true,"_uuid":"770d49198692019f045f0c547433f4e851bb3375"},"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\nfrom keras.engine.topology import Layer\nimport math\nimport operator \nfrom sklearn.model_selection import train_test_split\nfrom sklearn import metrics\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.layers import Dense, Input, LSTM, Embedding, Dropout, Activation, CuDNNGRU, Conv1D, TimeDistributed, CuDNNLSTM,Conv2D\nfrom keras.layers import Bidirectional, GlobalMaxPool1D, GlobalAveragePooling1D, concatenate, Flatten, Reshape, AveragePooling2D, Average\nfrom keras.models import Model\nfrom keras.layers import Wrapper\nimport keras.backend as K\nfrom keras.optimizers import Adam\nfrom keras import initializers, regularizers, constraints, optimizers, layers\ntqdm.pandas()","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"train_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)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"80386448be04b2e216c9ff0515bd0f6e92f39458"},"cell_type":"code","source":"train_df[train_df.target==1].head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"983e8fc2d71c04eac8985440a825b3f371a3ce57"},"cell_type":"code","source":"contraction_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\" }\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\ncontraction_patterns = [ (r'won\\'t', 'will not'), (r'can\\'t', 'cannot'), (r'i\\'m', 'i am'), (r'ain\\'t', 'is not'), (r'(\\w+)\\'ll', '\\g<1> will'), (r'(\\w+)n\\'t', '\\g<1> not'),\n                         (r'(\\w+)\\'ve', '\\g<1> have'), (r'(\\w+)\\'s', '\\g<1> is'), (r'(\\w+)\\'re', '\\g<1> are'), (r'(\\w+)\\'d', '\\g<1> would'), (r'&', 'and'), (r'dammit', 'damn it'), (r'dont', 'do not'), (r'wont', 'will not') ]\ndef replaceContraction(text):\n    patterns = [(re.compile(regex), repl) for (regex, repl) in contraction_patterns]\n    for (pattern, repl) in patterns:\n        (text, count) = re.subn(pattern, repl, text)\n    return text\ndef 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\nimport re\n\ndef clean_numbers(x):\n\n    x = re.sub('[0-9]{5,}', ' number ', x)\n    x = re.sub('[0-9]{4}', ' number ', x)\n    x = re.sub('[0-9]{3}', ' number ', x)\n    x = re.sub('[0-9]{2}', ' number ', x)\n    return x\n\npunct_mapping = {\"‘\": \"'\", \"₹\": \"e\", \"´\": \"'\", \"°\": \"\", \"€\": \"e\", \"™\": \"tm\", \"√\": \" sqrt \", \"×\": \"x\", \"²\": \"2\", \"—\": \"-\", \"–\": \"-\", \"’\": \"'\", \"_\": \"-\", \"`\": \"'\", '“': '\"', '”': '\"', '“': '\"', \"£\": \"e\", '∞': 'infinity', 'θ': 'theta', '÷': '/', 'α': 'alpha', '•': '.', 'à': 'a', '−': '-', 'β': 'beta', '∅': '', '³': '3', 'π': 'pi', }\npunct = \"/-'?!.,#$%\\'()*+-/:;<=>@[\\\\]^_`{|}~\" + '\"\"“”’' + '∞θ÷α•à−β∅³π‘₹´°£€\\×™√²—–&'\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\nmispell_dict = {'advanatges': 'advantages', 'irrationaol': 'irrational' , 'defferences': 'differences','lamboghini':'lamborghini','hypothical':'hypothetical', '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', 'pokémon': 'pokemon'}\ndef correct_spelling(x, dic):\n    for word in dic.keys():\n        x = x.replace(word, dic[word])\n    return x","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"c24de641eed37e2050a2f70ef16a51d97a1b6f0c"},"cell_type":"code","source":"train_df[\"question_text\"] = train_df[\"question_text\"].progress_apply(lambda x: x.lower())\ntrain_df['question_text'] = train_df['question_text'].progress_apply(lambda x: correct_spelling(x, mispell_dict))\ntrain_df[\"question_text\"] = train_df[\"question_text\"].progress_apply(lambda x: clean_numbers(x))\ntrain_df[\"question_text\"] = train_df[\"question_text\"].progress_apply(lambda x: clean_special_chars(x, punct, punct_mapping))\n\n\ntest_df[\"question_text\"] = test_df[\"question_text\"].progress_apply(lambda x: x.lower())\ntest_df['question_text'] = test_df['question_text'].progress_apply(lambda x: correct_spelling(x, mispell_dict))\ntest_df[\"question_text\"] = test_df[\"question_text\"].progress_apply(lambda x: clean_numbers(x))\ntest_df[\"question_text\"] = test_df[\"question_text\"].progress_apply(lambda x: clean_special_chars(x, punct, punct_mapping))\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"af9639c0a154449b944e44fc32e51f5bffa8fb0b"},"cell_type":"code","source":"## split to train and val\ntrain_df, val_df = train_test_split(train_df, test_size=0.1, random_state=2018)\n## some config values \nembed_size = 300 # how big is each word vector\nmax_features = 90000 # how many unique words to use (i.e num rows in embedding vector)\nmaxlen = 50 # max number of words in a question to use\n## fill up the missing values\ntrain_X = train_df[\"question_text\"].fillna(\"_na_\").values\nval_X = val_df[\"question_text\"].fillna(\"_na_\").values\ntest_X = test_df[\"question_text\"].fillna(\"_na_\").values","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"508f733fcac3a2809f0ff9e28c95be82371fbddb"},"cell_type":"code","source":"train_X[1]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"c2f617f7ab73e8c224ff20d9c09955d3c16b333f"},"cell_type":"code","source":"## Tokenize the sentences\ntokenizer = Tokenizer(num_words=max_features, char_level=False, oov_token='<OOV>')\ntokenizer.fit_on_texts(list(train_X))\n\ntrain_XT = tokenizer.texts_to_sequences(train_X)\nval_XT = tokenizer.texts_to_sequences(val_X)\ntest_XT = tokenizer.texts_to_sequences(test_X)\n## Pad the sentences \ntrain_XT = pad_sequences(train_XT, maxlen=maxlen)\nval_XT = pad_sequences(val_XT, maxlen=maxlen)\ntest_XT = pad_sequences(test_XT, maxlen=maxlen)\n## Get the target values\ntrain_y = train_df['target'].values\nval_y = val_df['target'].values","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"68913452d5663437df32962306e0909b70ef9f84"},"cell_type":"code","source":"print(train_X[1])\nprint(train_XT[1])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"24a70577d129b225d8c35d5efc4f003c7220202d"},"cell_type":"code","source":"coverage = np.zeros((max_features))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"9ef99498956918c896d9629b7bf042f3e944672f"},"cell_type":"code","source":"EMBEDDING_FILE = '../input/embeddings/glove.840B.300d/glove.840B.300d.txt'\nword_index = tokenizer.word_index\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) if o.split(\" \")[0] in word_index)\nall_embs = np.stack(embeddings_index.values())\nemb_mean,emb_std = all_embs.mean(), all_embs.std()\nembed_size = all_embs.shape[1]\nno_vocab={}\nnb_words = min(max_features, len(word_index))\nembedding_matrix = np.random.normal(emb_mean, emb_std, (nb_words, embed_size))\nfor word, i in word_index.items():\n    if i >= max_features: continue\n    embedding_vector = embeddings_index.get(word)\n    if embedding_vector is not None:\n        coverage[i] +=1\n        embedding_matrix[i] = embedding_vector\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"2994d3061a92900e89484ca1ce16f4f590d23289"},"cell_type":"code","source":"EMBEDDING_FILE = '../input/embeddings/paragram_300_sl999/paragram_300_sl999.txt'\nword_index = tokenizer.word_index\ndef get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32')\nembeddings_index2 = dict(get_coefs(*o.split(\" \")) for o in open(EMBEDDING_FILE, encoding=\"utf8\", errors='ignore') if len(o)>100 and o.split(\" \")[0] in word_index)\nall_embs = np.stack(embeddings_index2.values())\nemb_mean,emb_std = all_embs.mean(), all_embs.std()\nembed_size = all_embs.shape[1]\nno_vocab={}\nnb_words = min(max_features, len(word_index))\nembedding_matrix2 = np.random.normal(emb_mean, emb_std, (nb_words, embed_size))\nfor word, i in word_index.items():\n    if i >= max_features: continue\n    embedding_vector = embeddings_index2.get(word)\n    if embedding_vector is not None:\n        coverage[i] +=1\n        embedding_matrix2[i] = embedding_vector","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"7853b1ea251aadfe79328718a2094c0b97bee0df"},"cell_type":"code","source":"EMBEDDING_FILE = '../input/embeddings/wiki-news-300d-1M/wiki-news-300d-1M.vec'\nword_index = tokenizer.word_index\ndef get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32')\nembeddings_index3 = dict(get_coefs(*o.split(\" \")) for o in open(EMBEDDING_FILE, encoding=\"utf8\", errors='ignore') if len(o)>100 and o.split(\" \")[0] in word_index)\nall_embs = np.stack(embeddings_index3.values())\nemb_mean,emb_std = all_embs.mean(), all_embs.std()\nembed_size = all_embs.shape[1]\nno_vocab={}\nnb_words = min(max_features, len(word_index))\nembedding_matrix3 = np.random.normal(emb_mean, emb_std, (nb_words, embed_size))\nfor word, i in word_index.items():\n    if i >= max_features: continue\n    embedding_vector = embeddings_index3.get(word)\n    if embedding_vector is not None:\n        coverage[i] +=1\n        embedding_matrix3[i] = embedding_vector","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"1e87dea32643d3d8ced3e90dcdf5e017ef273a39"},"cell_type":"code","source":"from gensim.models import KeyedVectors\nnews_path = '../input/embeddings/GoogleNews-vectors-negative300/GoogleNews-vectors-negative300.bin'\nembeddings_index4 = KeyedVectors.load_word2vec_format(news_path, binary=True)\nno_vocab={}\nnb_words = min(max_features, len(word_index))\nembedding_matrix4 = np.random.normal(emb_mean, emb_std, (nb_words, embed_size))\nfor word, i in word_index.items():\n    if i >= max_features:\n        continue\n    try:\n        embedding_vector = embeddings_index4.get_vector(word)       \n    except (KeyError):\n        continue\n    \n    if embedding_vector is not None:\n        coverage[i] +=1\n        embedding_matrix4[i] = embedding_vector","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"70788bec5eaaf434226f07197b44b08f74cb9323"},"cell_type":"code","source":"unique, counts = np.unique(coverage, return_counts=True)\ndict(zip(unique, counts))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"277674dc4a23a048edf879b6e610c2b466ec9dc5"},"cell_type":"code","source":"embedding_matrix = np.mean([embedding_matrix2,embedding_matrix3,embedding_matrix, embedding_matrix4],axis=0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"244e708445b86649f52acbc2334326a9ed063f25"},"cell_type":"code","source":"embeddings_index = {**embeddings_index2,**embeddings_index3, **embeddings_index}","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"f4ba2ebb36dd22b72d0c48334aaabcda7fd4c9cf"},"cell_type":"code","source":"import operator, gc\ndef 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 {:.2%} of vocab'.format(len(known_words) / len(vocab)))\n    print('Found embeddings for  {:.2%} 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,"_uuid":"39af542352de867f06697d7933caa6c0e36237fb"},"cell_type":"code","source":"no = check_coverage(tokenizer.word_index ,embeddings_index)\nno = check_coverage(tokenizer.word_index ,embeddings_index4)\ndel embeddings_index, embeddings_index2\ndel embeddings_index3, embeddings_index4\ngc.collect()   ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"3d450f26d7847cb40e222e6368d0f4c4d81f4f2b"},"cell_type":"code","source":"no[0:10]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"7318b53509eaa2a41469453d7cecbd03ff72c5a3"},"cell_type":"code","source":"class 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","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"527f127a547478dea3b391c93089003de17685d5"},"cell_type":"code","source":"class DropConnect(Wrapper):\n    def __init__(self, layer, prob=1., **kwargs):\n        self.prob = prob\n        self.layer = layer\n        super(DropConnect, self).__init__(layer, **kwargs)\n        if 0. < self.prob < 1.:\n            self.uses_learning_phase = True\n\n    def build(self, input_shape):\n        if not self.layer.built:\n            self.layer.build(input_shape)\n            self.layer.built = True\n        super(DropConnect, self).build()\n\n    def compute_output_shape(self, input_shape):\n        return self.layer.compute_output_shape(input_shape)\n\n    def call(self, x):\n        if 0. < self.prob < 1.:\n            self.layer.kernel = K.in_train_phase(K.dropout(self.layer.kernel, self.prob), self.layer.kernel)\n            self.layer.bias = K.in_train_phase(K.dropout(self.layer.bias, self.prob), self.layer.bias)\n        return self.layer.call(x)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"03eda73e14ea3267992ab2fd2d27f577d135f94f"},"cell_type":"code","source":"def model():\n    ad = Adam(lr=0.0015, beta_1=0.9, beta_2=0.999, epsilon=None)\n    inp = Input(shape=(maxlen,))\n    x = Embedding(max_features, embed_size,trainable=True, weights=[embedding_matrix])(inp)\n    x = TimeDistributed(DropConnect(Dense(128, activation=\"relu\"), 0.3))(x)\n    x = Bidirectional(CuDNNLSTM(64, return_sequences=True))(x)\n    x = Dropout(0.4)(x)\n    x = CuDNNLSTM(120, return_sequences=True)(x)\n    \n    #y = GlobalAveragePooling1D()(x)\n    #x = GlobalMaxPool1D()(x)\n    x=Attention(maxlen)(x)\n    #x = concatenate([x,y])\n    x=DropConnect(Dense(32, activation=\"tanh\"), 0.3)(x)\n    x = Dense(64, activation=\"tanh\")(x)\n    #x = Dropout(0.2)(x)\n    x = Dense(1, activation=\"sigmoid\")(x)    \n    model = Model(inputs=inp, outputs=x)\n    model.compile(loss='binary_crossentropy', optimizer=ad, metrics=['binary_accuracy'])\n    return model\nmodel1 = model()\nmodel2 =model()\nprint(model1.summary())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"96ea8bddec6b0d73b0eea274eb77e9f579c39dd0"},"cell_type":"code","source":"## Train the model \nmodel1.fit(train_XT, train_y, batch_size=512, epochs=2, validation_data=(val_XT, val_y))\npred_cnn_val_y1 = model1.predict([val_XT], batch_size=1024, verbose=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"78835881dfd6bf1a15ff966c19b668de916d0a6c"},"cell_type":"code","source":"## Train the model \nmodel2.fit(train_XT, train_y, batch_size=512, epochs=2, validation_data=(val_XT, val_y))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"6cea0b2f8b5c038849ae483d3b4298735c4c4c1f"},"cell_type":"code","source":"\nmax_t = 0\nmax_f1 = 0\nfor thresh in np.arange(0.1, 0.701, 0.01):\n    thresh = np.round(thresh, 2)\n    f1 = metrics.f1_score(val_y, (pred_cnn_val_y1>thresh).astype(int))\n    #print(\"F1 score at threshold {0} is {1}\".format(thresh, f1))\n    if(f1>max_f1):\n        max_f1 = f1\n        max_t = thresh\nprint(max_t, max_f1) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"e903aec4ad582191d18e6403a05ea1810eb3aab8"},"cell_type":"code","source":"pred_cnn_val_y2 = model2.predict([val_XT], batch_size=1024, verbose=1)\nmax_t = 0\nmax_f1 = 0\nfor thresh in np.arange(0.1, 0.701, 0.01):\n    thresh = np.round(thresh, 2)\n    f1 = metrics.f1_score(val_y, (pred_cnn_val_y2>thresh).astype(int))\n    #print(\"F1 score at threshold {0} is {1}\".format(thresh, f1))\n    if(f1>max_f1):\n        max_f1 = f1\n        max_t = thresh\nprint(max_t, max_f1) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"3bf070a52c75d553e3a1a51bf78ac5aea5e8aa3c"},"cell_type":"code","source":"pred_cnn_val_y = pred_cnn_val_y1*0.5 + pred_cnn_val_y2*0.5\nmax_t = 0\nmax_f1 = 0\nfor thresh in np.arange(0.1, 0.701, 0.01):\n    thresh = np.round(thresh, 2)\n    f1 = metrics.f1_score(val_y, (pred_cnn_val_y>thresh).astype(int))\n    #print(\"F1 score at threshold {0} is {1}\".format(thresh, f1))\n    if(f1>max_f1):\n        max_f1 = f1\n        max_t = thresh\nprint(max_t, max_f1) \n    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"76b0798955fe522d5020ff11bd6a85d940a9440f"},"cell_type":"code","source":"pred_cnn_test_y1 = model1.predict([test_XT], batch_size=1024, verbose=1)\npred_cnn_test_y2 = model2.predict([test_XT], batch_size=1024, verbose=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"7ba5e811d62e911116d0f6ec25984886b5bbe748"},"cell_type":"code","source":"pred_cnn_test_y = pred_cnn_test_y1*0.5 + pred_cnn_test_y2*0.5\npred_test_y = (pred_cnn_test_y>max_t).astype(int)\nout_df = pd.DataFrame({\"qid\":test_df[\"qid\"].values})\nout_df['prediction'] = pred_test_y\nout_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}