{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import pandas as pd\nfrom tqdm import tqdm\ntqdm.pandas()\nimport 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\n\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\nfrom keras.layers import Bidirectional, GlobalMaxPool1D\nfrom keras.models import Model\nfrom keras import initializers, regularizers, constraints, optimizers, layers\nimport gc","execution_count":1,"outputs":[{"output_type":"stream","text":"Using TensorFlow backend.\n","name":"stderr"}]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"train = pd.read_csv(\"../input/train.csv\").drop('target', axis=1)\ntest = pd.read_csv(\"../input/test.csv\")\ndf = pd.concat([train ,test])\nprint(\"Number of texts: \", df.shape[0])\ndel train, test","execution_count":2,"outputs":[{"output_type":"stream","text":"Number of texts:  1681928\n","name":"stdout"}]},{"metadata":{},"cell_type":"markdown","source":"### Impove the coverage of embeddings"},{"metadata":{"trusted":true},"cell_type":"code","source":"import operator\n\ndef build_vocab(texts):\n    sentences = texts.apply(lambda x: x.split()).values\n    vocab = {}\n    for sentence in sentences:\n        for word in sentence:\n            try:\n                vocab[word] += 1\n            except KeyError:\n                vocab[word] = 1\n    return vocab\n\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    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    return unknown_words\n\ndef add_lower(embedding, vocab):\n    count = 0\n    for word in vocab:\n        if word in embedding and word.lower() not in embedding:  \n            embedding[word.lower()] = embedding[word]\n            count += 1\n    print(f\"Added {count} words to embedding\")\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\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\" }\npunct = \"/-'?!.,#$%\\'()*+-/:;<=>@[\\\\]^_`{|}~\" + '\"\"“”’' + '∞θ÷α•à−β∅³π‘₹´°£€\\×™√²—–&'\npunct_mapping = {\"‘\": \"'\", \"₹\": \"e\", \"´\": \"'\", \"°\": \"\", \"€\": \"e\", \"™\": \"tm\", \"√\": \" sqrt \", \"×\": \"x\", \"²\": \"2\", \"—\": \"-\", \"–\": \"-\", \"’\": \"'\", \"_\": \"-\", \"`\": \"'\", '“': '\"', '”': '\"', '“': '\"', \"£\": \"e\", '∞': 'infinity', 'θ': 'theta', '÷': '/', 'α': 'alpha', '•': '.', 'à': 'a', '−': '-', 'β': 'beta', '∅': '', '³': '3', 'π': 'pi', }\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 clean_special_chars(text, punct, mapping):\n    for p in mapping:\n        text = text.replace(p, mapping[p])  \n    for p in punct:\n        text = text.replace(p, f' {p} ') \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    return text\n\ndef correct_spelling(x, dic):\n    for word in dic.keys():\n        x = x.replace(word, dic[word])\n    return x","execution_count":3,"outputs":[]},{"metadata":{"_kg_hide-input":false,"trusted":true},"cell_type":"code","source":"vocab = build_vocab(df['question_text'])\ndel df","execution_count":4,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## load embeddings"},{"metadata":{"trusted":true},"cell_type":"code","source":"def load_embed(file):\n    def get_coefs(word,*arr): \n        return word, np.asarray(arr, dtype='float32')\n    if file == '../input/embeddings/wiki-news-300d-1M/wiki-news-300d-1M.vec':\n        embeddings_index = dict(get_coefs(*o.split(\" \")) for o in open(file) if len(o)>100)\n    else:\n        embeddings_index = dict(get_coefs(*o.split(\" \")) for o in open(file, encoding='latin'))\n    return embeddings_index","execution_count":5,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## preprocess"},{"metadata":{"trusted":true},"cell_type":"code","source":"train = pd.read_csv(\"../input/train.csv\")\ntest = pd.read_csv(\"../input/test.csv\")","execution_count":6,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def preprocess(df):\n    df[\"question_text\"] = df[\"question_text\"].progress_apply(lambda x: x.lower())\n    df[\"question_text\"] = df[\"question_text\"].progress_apply(lambda x: clean_contractions(x, contraction_mapping))\n    df[\"question_text\"] = df[\"question_text\"].progress_apply(lambda x: clean_special_chars(x, punct, punct_mapping))\n    df[\"question_text\"] = df[\"question_text\"].progress_apply(lambda x: correct_spelling(x, mispell_dict))","execution_count":7,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"preprocess(train)   # in-place operation","execution_count":8,"outputs":[{"output_type":"stream","text":"100%|██████████| 1306122/1306122 [00:01<00:00, 686473.07it/s]\n100%|██████████| 1306122/1306122 [00:07<00:00, 179835.58it/s]\n100%|██████████| 1306122/1306122 [00:36<00:00, 35678.15it/s]\n100%|██████████| 1306122/1306122 [00:18<00:00, 71988.85it/s]\n","name":"stderr"}]},{"metadata":{"trusted":true},"cell_type":"code","source":"preprocess(test)","execution_count":9,"outputs":[{"output_type":"stream","text":"100%|██████████| 375806/375806 [00:00<00:00, 641306.42it/s]\n100%|██████████| 375806/375806 [00:02<00:00, 181717.53it/s]\n100%|██████████| 375806/375806 [00:10<00:00, 34776.02it/s]\n100%|██████████| 375806/375806 [00:05<00:00, 70807.38it/s]\n","name":"stderr"}]},{"metadata":{"trusted":true},"cell_type":"code","source":"## split to train and val\ntrain_df, val_df = train_test_split(train, test_size=0.1, random_state=2018)\n\n## some config values \nembed_size = 300 # how big is each word vector\nmax_features = 100000 # how many unique words to use (i.e num rows in embedding vector)\nmaxlen = 80 # max number of words in a question to use\n\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[\"question_text\"].fillna(\"_na_\").values\n\n## Tokenize the sentences\ntokenizer = Tokenizer(num_words=max_features)\ntokenizer.fit_on_texts(list(train_X))\ntrain_X = tokenizer.texts_to_sequences(train_X)\nval_X = tokenizer.texts_to_sequences(val_X)\ntest_X = tokenizer.texts_to_sequences(test_X)\n\n## Pad the sentences \ntrain_X = pad_sequences(train_X, maxlen=maxlen)\nval_X = pad_sequences(val_X, maxlen=maxlen)\ntest_X = pad_sequences(test_X, maxlen=maxlen)\n\n## Get the target values\ntrain_y = train_df['target'].values\nval_y = val_df['target'].values","execution_count":10,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_reserved = train  # for checking coverage later\ndel train, train_df, val_df","execution_count":11,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## glove"},{"metadata":{"trusted":true},"cell_type":"code","source":"glove = '../input/embeddings/glove.840B.300d/glove.840B.300d.txt'\nprint(\"Extracting GloVe embedding\")\nembed_glove = load_embed(glove)","execution_count":12,"outputs":[{"output_type":"stream","text":"Extracting GloVe embedding\n","name":"stdout"}]},{"metadata":{"trusted":true},"cell_type":"code","source":"add_lower(embed_glove, vocab)","execution_count":13,"outputs":[{"output_type":"stream","text":"Added 17744 words to embedding\n","name":"stdout"}]},{"metadata":{"trusted":true},"cell_type":"code","source":"vocab_temp = build_vocab(train_reserved['question_text'])\noov = check_coverage(vocab_temp, embed_glove)\nprint(oov[:20])\ndel oov, vocab_temp\ntime.sleep(5)","execution_count":14,"outputs":[{"output_type":"stream","text":"Found embeddings for 69.76% of vocab\nFound embeddings for  99.58% of all text\n[('quorans', 858), ('brexit', 524), ('cryptocurrencies', 499), ('redmi', 383), ('coinbase', 149), ('oneplus', 139), ('uceed', 123), ('bhakts', 115), ('upwork', 111), ('pokémon', 109), ('machedo', 108), ('gdpr', 107), ('adityanath', 106), ('boruto', 102), ('bnbr', 100), ('alshamsi', 92), ('dceu', 90), ('litecoin', 87), ('iiest', 86), ('unacademy', 86)]\n","name":"stdout"}]},{"metadata":{"trusted":true},"cell_type":"code","source":"embeddings_index = embed_glove\nall_embs = np.stack(embeddings_index.values())\nemb_mean,emb_std = all_embs.mean(), all_embs.std()\nembed_size = all_embs.shape[1]\n\nword_index = tokenizer.word_index\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: embedding_matrix[i] = embedding_vector\n        \ninp = Input(shape=(maxlen,))\nx = Embedding(max_features, embed_size, weights=[embedding_matrix])(inp)\nx = Bidirectional(CuDNNGRU(64, return_sequences=True))(x)\nx = GlobalMaxPool1D()(x)\nx = Dense(16, activation=\"relu\")(x)\nx = Dropout(0.1)(x)\nx = Dense(1, activation=\"sigmoid\")(x)\nmodel = Model(inputs=inp, outputs=x)\nmodel.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\nmodel.fit(train_X, train_y, batch_size=512, epochs=2, validation_data=(val_X, val_y))","execution_count":15,"outputs":[{"output_type":"stream","text":"/opt/conda/lib/python3.6/site-packages/ipykernel_launcher.py:2: FutureWarning: arrays to stack must be passed as a \"sequence\" type such as list or tuple. Support for non-sequence iterables such as generators is deprecated as of NumPy 1.16 and will raise an error in the future.\n  \n","name":"stderr"},{"output_type":"stream","text":"WARNING:tensorflow:From /opt/conda/lib/python3.6/site-packages/tensorflow/python/framework/op_def_library.py:263: colocate_with (from tensorflow.python.framework.ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nColocations handled automatically by placer.\nWARNING:tensorflow:From /opt/conda/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py:3445: calling dropout (from tensorflow.python.ops.nn_ops) with keep_prob is deprecated and will be removed in a future version.\nInstructions for updating:\nPlease use `rate` instead of `keep_prob`. Rate should be set to `rate = 1 - keep_prob`.\nWARNING:tensorflow:From /opt/conda/lib/python3.6/site-packages/tensorflow/python/ops/math_ops.py:3066: to_int32 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nUse tf.cast instead.\nWARNING:tensorflow:From /opt/conda/lib/python3.6/site-packages/tensorflow/python/ops/math_grad.py:102: div (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\nInstructions for updating:\nDeprecated in favor of operator or tf.math.divide.\nTrain on 1175509 samples, validate on 130613 samples\nEpoch 1/2\n1175509/1175509 [==============================] - 90s 76us/step - loss: 0.1195 - acc: 0.9528 - val_loss: 0.1007 - val_acc: 0.9595\nEpoch 2/2\n1175509/1175509 [==============================] - 86s 74us/step - loss: 0.0941 - acc: 0.9627 - val_loss: 0.0998 - val_acc: 0.9599\n","name":"stdout"},{"output_type":"execute_result","execution_count":15,"data":{"text/plain":"<keras.callbacks.History at 0x7f4c213daa58>"},"metadata":{}}]},{"metadata":{"_kg_hide-input":false,"trusted":true},"cell_type":"code","source":"pred_glove_val_y = model.predict([val_X], 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, metrics.f1_score(val_y, (pred_glove_val_y>thresh).astype(int))))","execution_count":16,"outputs":[{"output_type":"stream","text":"130613/130613 [==============================] - 2s 15us/step\nF1 score at threshold 0.1 is 0.5892546256933479\nF1 score at threshold 0.11 is 0.5983542157714097\nF1 score at threshold 0.12 is 0.6064820668436802\nF1 score at threshold 0.13 is 0.61445317531882\nF1 score at threshold 0.14 is 0.6203437145598883\nF1 score at threshold 0.15 is 0.625238074146255\nF1 score at threshold 0.16 is 0.6303683737646001\nF1 score at threshold 0.17 is 0.6355353075170843\nF1 score at threshold 0.18 is 0.6396858396858397\nF1 score at threshold 0.19 is 0.645532871324218\nF1 score at threshold 0.2 is 0.6505269154087154\nF1 score at threshold 0.21 is 0.653792573377528\nF1 score at threshold 0.22 is 0.6572081045624606\nF1 score at threshold 0.23 is 0.6597310825399941\nF1 score at threshold 0.24 is 0.6615064007144983\nF1 score at threshold 0.25 is 0.6632949424136204\nF1 score at threshold 0.26 is 0.6652162914242348\nF1 score at threshold 0.27 is 0.667415615584946\nF1 score at threshold 0.28 is 0.6693132604660755\nF1 score at threshold 0.29 is 0.6717684418762039\nF1 score at threshold 0.3 is 0.6735647880666001\nF1 score at threshold 0.31 is 0.6747984726347052\nF1 score at threshold 0.32 is 0.6756901348170341\nF1 score at threshold 0.33 is 0.6780300987108259\nF1 score at threshold 0.34 is 0.6792863359442993\nF1 score at threshold 0.35 is 0.6802370240316032\nF1 score at threshold 0.36 is 0.6807992472463608\nF1 score at threshold 0.37 is 0.680283497963056\nF1 score at threshold 0.38 is 0.6807144064454336\nF1 score at threshold 0.39 is 0.6803889236367772\nF1 score at threshold 0.4 is 0.6792431192660551\nF1 score at threshold 0.41 is 0.6795880583198334\nF1 score at threshold 0.42 is 0.6798248175182481\nF1 score at threshold 0.43 is 0.6791985857395404\nF1 score at threshold 0.44 is 0.6798644551453541\nF1 score at threshold 0.45 is 0.677063339731286\nF1 score at threshold 0.46 is 0.6756282167726309\nF1 score at threshold 0.47 is 0.6738425784355697\nF1 score at threshold 0.48 is 0.6726800939083158\nF1 score at threshold 0.49 is 0.6707438841737394\nF1 score at threshold 0.5 is 0.669400113543178\n","name":"stdout"}]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred_glove_test_y = model.predict([test_X], batch_size=1024, verbose=1)","execution_count":17,"outputs":[{"output_type":"stream","text":"375806/375806 [==============================] - 5s 13us/step\n","name":"stdout"}]},{"metadata":{"trusted":true},"cell_type":"code","source":"del word_index, embeddings_index, all_embs, embedding_matrix, model, inp, x, embed_glove\nimport gc; gc.collect()\ntime.sleep(10)","execution_count":18,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## fasttext"},{"metadata":{"trusted":true},"cell_type":"code","source":"wiki_news = '../input/embeddings/wiki-news-300d-1M/wiki-news-300d-1M.vec'\nprint(\"Extracting FastText embedding\")\nembed_fasttext = load_embed(wiki_news)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"add_lower(embed_fasttext, vocab)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"vocab_temp = build_vocab(train_reserved['question_text'])\noov = check_coverage(vocab_temp, embed_fasttext)\nprint(oov[:20])\ndel oov, vocab_temp\ntime.sleep(5)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"embeddings_index = embed_fasttext\nall_embs = np.stack(embeddings_index.values())\nemb_mean,emb_std = all_embs.mean(), all_embs.std()\nembed_size = all_embs.shape[1]\n\nword_index = tokenizer.word_index\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: embedding_matrix[i] = embedding_vector\n        \ninp = Input(shape=(maxlen,))\nx = Embedding(max_features, embed_size, weights=[embedding_matrix])(inp)\nx = Bidirectional(CuDNNGRU(64, return_sequences=True))(x)\nx = GlobalMaxPool1D()(x)\nx = Dense(16, activation=\"relu\")(x)\nx = Dropout(0.1)(x)\nx = Dense(1, activation=\"sigmoid\")(x)\nmodel = Model(inputs=inp, outputs=x)\nmodel.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\nmodel.fit(train_X, train_y, batch_size=512, epochs=2, validation_data=(val_X, val_y))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred_fasttext_val_y = model.predict([val_X], 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, metrics.f1_score(val_y, (pred_fasttext_val_y > thresh).astype(int))))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred_fasttext_test_y = model.predict([test_X], batch_size=1024, verbose=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"del word_index, embeddings_index, all_embs, embedding_matrix, model, inp, x, embed_fasttext\nimport gc; gc.collect()\ntime.sleep(10)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### paragram"},{"metadata":{"trusted":true},"cell_type":"code","source":"paragram =  '../input/embeddings/paragram_300_sl999/paragram_300_sl999.txt'\nprint(\"Extracting Paragram embedding\")\nembed_paragram = load_embed(paragram)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"add_lower(embed_paragram, vocab)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"vocab_temp = build_vocab(train_reserved['question_text'])\noov = check_coverage(vocab_temp, embed_paragram)\nprint(oov[:20])\ndel oov, vocab_temp\ntime.sleep(5)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"embeddings_index = embed_paragram\nall_embs = np.stack(embeddings_index.values())\nemb_mean,emb_std = all_embs.mean(), all_embs.std()\nembed_size = all_embs.shape[1]\n\nword_index = tokenizer.word_index\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: embedding_matrix[i] = embedding_vector\n        \ninp = Input(shape=(maxlen,))\nx = Embedding(max_features, embed_size, weights=[embedding_matrix])(inp)\nx = Bidirectional(CuDNNGRU(64, return_sequences=True))(x)\nx = GlobalMaxPool1D()(x)\nx = Dense(16, activation=\"relu\")(x)\nx = Dropout(0.1)(x)\nx = Dense(1, activation=\"sigmoid\")(x)\nmodel = Model(inputs=inp, outputs=x)\nmodel.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\nmodel.fit(train_X, train_y, batch_size=512, epochs=2, validation_data=(val_X, val_y))","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":false,"trusted":true},"cell_type":"code","source":"pred_paragram_val_y = model.predict([val_X], 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, metrics.f1_score(val_y, (pred_paragram_val_y>thresh).astype(int))))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred_paragram_test_y = model.predict([test_X], batch_size=1024, verbose=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"del word_index, embeddings_index, all_embs, embedding_matrix, model, inp, x, embed_paragram\nimport gc; gc.collect()\ntime.sleep(10)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## blend"},{"metadata":{"trusted":true},"cell_type":"code","source":"pred_val_y = 0.34*pred_glove_val_y + 0.33*pred_fasttext_val_y + 0.33*pred_paragram_val_y \n\nbest_score = 0\nbest_threshold = None\nfor thresh in np.arange(0.1, 0.501, 0.01):\n    thresh = np.round(thresh, 2)\n    score = metrics.f1_score(val_y, (pred_val_y>thresh))\n    print(\"F1 score at threshold {0} is {1}\".format(thresh, score))\n    if score > best_score:\n        best_score = score\n        best_threshold = thresh\n    \nprint('Best score: {0}, best threshold: {1}'.format(best_score, best_threshold))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred_test_y = 0.34*pred_glove_test_y + 0.33*pred_fasttext_test_y + 0.33*pred_paragram_test_y\npred_test_y = (pred_test_y > best_threshold).astype(int)\nout_df = pd.DataFrame({\"qid\":test[\"qid\"].values})\nout_df['prediction'] = pred_test_y\nout_df.to_csv(\"submission.csv\", index=False)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## References\n1. https://www.kaggle.com/sudalairajkumar/a-look-at-different-embeddings\n2. https://www.kaggle.com/theoviel/improve-your-score-with-some-text-preprocessing"}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.4","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}