{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"scrolled":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\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"3c0661acc9f1236284ef2a99ece0dd89f5af2f25"},"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\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\n\nfrom sklearn.model_selection import KFold, StratifiedKFold\nnp.random.seed(2018)\n","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"## some config values \nembed_size = 300 # how big is each word vector\nmax_features = 95000 # how many unique words to use (i.e num rows in embedding vector)\nmaxlen = 70 # max number of words in a question to use","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"87a23511c215e6d76c7bdc8009c8a4006f2b005e"},"cell_type":"markdown","source":"**Timer**"},{"metadata":{"trusted":true,"_uuid":"8fafb2b2e09f0f37e79e3b643fe540f85f774b40"},"cell_type":"code","source":"import time\ntime_steps = []\ntime_steps.append(time.time())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"8c6228db9e74a4dbdfea6967abc632aa8411778a"},"cell_type":"code","source":"def show_timer():\n    time_steps.append(time.time())\n    last_step = time_steps[-1] - time_steps[-2]\n    total = time_steps[-1] - time_steps[0]\n    print('Last step time: {:.1f} (s) - Total time: {:.1f} (s)'.format(last_step, total))","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"db8bd684dd659d0ff8bf68017c71e73aa12b5cde"},"cell_type":"markdown","source":"**Pre-process**"},{"metadata":{"trusted":true,"_uuid":"b0906eb23bba982b9ca10dea2b3f2927bdee0222"},"cell_type":"code","source":"def clean_text(x):\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\n\nimport re\ndef clean_numbers(x):\n    x = re.sub('[0-9]{5,}', '#####', x)\n    x = re.sub('[0-9]{4}', '####', x)\n    x = re.sub('[0-9]{3}', '###', x)\n    x = re.sub('[0-9]{2}', '##', x)\n    return x\n\ndef _get_mispell(mispell_dict):\n    mispell_re = re.compile('(%s)' % '|'.join(mispell_dict.keys()))\n    return mispell_dict, mispell_re\n\nmispell_dict = {'colour':'color',\n                'centre':'center',\n                'didnt':'did not',\n                'doesnt':'does not',\n                'isnt':'is not',\n                'shouldnt':'should not',\n                'favourite':'favorite',\n                'travelling':'traveling',\n                'counselling':'counseling',\n                'theatre':'theater',\n                'cancelled':'canceled',\n                'labour':'labor',\n                'organisation':'organization',\n                'wwii':'world war 2',\n                'citicise':'criticize',\n                'instagram': 'social medium',\n                'whatsapp': 'social medium',\n                'snapchat': 'social medium'\n\n                }\nmispellings, mispellings_re = _get_mispell(mispell_dict)\n\ndef replace_typical_misspell(text):\n    def replace(match):\n        return mispellings[match.group(0)]\n    return mispellings_re.sub(replace, text)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"56b714640c4b6e31ef625a112157d2613985ea7e"},"cell_type":"code","source":"def pre_process(x):\n    x = clean_text(x)\n    x = clean_numbers(x)\n    x = replace_typical_misspell(x)\n    return x","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"e15f645704cae95a0da8a98b780c96403e2d90b9"},"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)\n\ntrain_df[\"question_text\"] = train_df[\"question_text\"].apply(lambda x: pre_process(x))\ntest_df[\"question_text\"] = test_df[\"question_text\"].apply(lambda x: pre_process(x))\n\n#     ## fill up the missing values\ntrain_X_all = train_df[\"question_text\"].fillna(\"_##_\").values\ntest_X = test_df[\"question_text\"].fillna(\"_##_\").values\n\n## Tokenize the sentences\ntokenizer = Tokenizer(num_words=max_features)\ntokenizer.fit_on_texts(list(train_X_all))\ntrain_X_all = tokenizer.texts_to_sequences(train_X_all)\ntest_X = tokenizer.texts_to_sequences(test_X)\nword_index = tokenizer.word_index\n## Pad the sentences \ntrain_X_all = pad_sequences(train_X_all, maxlen=maxlen)\ntest_X = pad_sequences(test_X, maxlen=maxlen)\n\n## Get the target values\ntrain_y_all = train_df['target'].values\nshow_timer()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"50180c89cc4fb8d09faad2a9d17ce505dca1cfe2"},"cell_type":"code","source":"def load_and_prec(trn_idx, val_idx):\n    trn_idx = np.random.permutation(trn_idx)\n    val_idx = np.random.permutation(val_idx)\n    train_X = train_X_all[trn_idx]\n    val_X = train_X_all[val_idx]\n    train_y = train_y_all[trn_idx]\n    val_y = train_y_all[val_idx]\n    return train_X, val_X, test_X, train_y, val_y","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"6ff74b37bf108c1ebcfeb0089d897a5e62012777"},"cell_type":"markdown","source":"**Load embedding**"},{"metadata":{"trusted":true,"_uuid":"7f6824e7739ba3dd5ea9e7ec633445bb79db0cf1"},"cell_type":"code","source":"def load_glove(word_index):\n    EMBEDDING_FILE = '../input/embeddings/glove.840B.300d/glove.840B.300d.txt'\n    def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32')\n    embeddings_index = dict(get_coefs(*o.split(\" \")) for o in open(EMBEDDING_FILE))\n\n\n    all_embs = np.stack(embeddings_index.values())\n    emb_mean,emb_std = all_embs.mean(), all_embs.std()\n    embed_size = all_embs.shape[1]\n\n    # word_index = tokenizer.word_index\n    nb_words = min(max_features, len(word_index))\n    embedding_matrix = np.random.normal(emb_mean, emb_std, (nb_words, embed_size))\n    for 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            \n    return embedding_matrix \n    \ndef load_fasttext(word_index):    \n    EMBEDDING_FILE = '../input/embeddings/wiki-news-300d-1M/wiki-news-300d-1M.vec'\n    def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32')\n    embeddings_index = dict(get_coefs(*o.split(\" \")) for o in open(EMBEDDING_FILE) if len(o)>100)\n\n    all_embs = np.stack(embeddings_index.values())\n    emb_mean,emb_std = all_embs.mean(), all_embs.std()\n    embed_size = all_embs.shape[1]\n\n    # word_index = tokenizer.word_index\n    nb_words = min(max_features, len(word_index))\n    embedding_matrix = np.random.normal(emb_mean, emb_std, (nb_words, embed_size))\n    for 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\n    return embedding_matrix\n\ndef load_para(word_index):\n    EMBEDDING_FILE = '../input/embeddings/paragram_300_sl999/paragram_300_sl999.txt'\n    def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32')\n    embeddings_index = dict(get_coefs(*o.split(\" \")) for o in open(EMBEDDING_FILE, encoding=\"utf8\", errors='ignore') if len(o)>100)\n\n    all_embs = np.stack(embeddings_index.values())\n    emb_mean,emb_std = all_embs.mean(), all_embs.std()\n    embed_size = all_embs.shape[1]\n\n    # word_index = tokenizer.word_index\n    nb_words = min(max_features, len(word_index))\n    embedding_matrix = np.random.normal(emb_mean, emb_std, (nb_words, embed_size))\n    for 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    \n    return embedding_matrix","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"cfaf9a76bc9f8c847f62ab18206da2e79b713671"},"cell_type":"markdown","source":"**Attention**"},{"metadata":{"trusted":true,"_uuid":"877c9af6ef3361a250cbc31ef727b12bc96a60f1"},"cell_type":"code","source":"# https://www.kaggle.com/suicaokhoailang/lstm-attention-baseline-0-652-lb\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","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"dfae1b328d0d6b10065a2988f54f613ca838777f"},"cell_type":"markdown","source":"**LSTM models**"},{"metadata":{"trusted":true,"_uuid":"f8f8ce77585e24471a0a503aed459c0c1b5d00fa"},"cell_type":"code","source":"def model_lstm_atten(embedding_matrix):\n    inp = Input(shape=(maxlen,))\n    x = Embedding(max_features, embed_size, weights=[embedding_matrix], trainable=False)(inp)\n    x = Bidirectional(CuDNNLSTM(128, return_sequences=True))(x)\n    x = Bidirectional(CuDNNLSTM(64, return_sequences=True))(x)\n    x = Attention(maxlen)(x)\n    x = Dense(64, activation=\"relu\")(x)\n    x = Dense(1, activation=\"sigmoid\")(x)\n    model = Model(inputs=inp, outputs=x)\n    model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\n    \n    return model","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"82ef5bc7e538166a0b2b4ddf7c4d4e7bafa1f871"},"cell_type":"markdown","source":"**Train and predict**"},{"metadata":{"trusted":true,"_uuid":"b992ea9fd0e639653bef1f4e5084bc1d0f530a50"},"cell_type":"code","source":"# https://www.kaggle.com/strideradu/word2vec-and-gensim-go-go-go\ndef train_pred(model, epochs=2):\n    for e in range(epochs):\n        model.fit(train_X, train_y, batch_size=512, epochs=1, validation_data=(val_X, val_y))\n        pred_val_y = model.predict([val_X], batch_size=1024, verbose=0)\n\n        best_thresh = 0.5\n        best_score = 0.0\n        for 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).astype(int))\n            if score > best_score:\n                best_thresh = thresh\n                best_score = score\n\n        print(\"Val F1 Score: {:.4f}\".format(best_score))\n\n    pred_test_y = model.predict([test_X], batch_size=1024, verbose=0)\n    return pred_val_y, pred_test_y, best_score","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"477940c1b91efc5800999b19d505cf5e24313071"},"cell_type":"markdown","source":"**Main part: load, train, pred and blend**"},{"metadata":{"trusted":true,"_uuid":"555f788e5e61c7780562c38401850ece312fbe0d"},"cell_type":"code","source":"# train_X, val_X, test_X, train_y, val_y, word_index = load_and_prec()\nembedding_matrix_1 = load_glove(word_index)\n# embedding_matrix_2 = load_fasttext(word_index)\nembedding_matrix_3 = load_para(word_index)\nembedding_matrix = np.mean([embedding_matrix_1, embedding_matrix_3], axis = 0)\nnp.shape(embedding_matrix)\nshow_timer()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"bdc7627acef638814c95e1d160e1efb511f024b0"},"cell_type":"code","source":"outputs = []","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"2cb3a596463c9ce32f97ca6ea5b69759633ab7d0"},"cell_type":"code","source":"nsplits = 5\nnfiles = np.arange(len(train_df))\nkfold = StratifiedKFold(nsplits, shuffle=True).split(train_X_all, train_y_all)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"a9ec533da1d1a621c7d9a633ab5553ee5e0ad260"},"cell_type":"code","source":"idx = 0\nfor train_idx, val_idx in kfold:\n    train_X, val_X, test_X, train_y, val_y = load_and_prec(train_idx, val_idx)\n    pred_val_y, pred_test_y, best_score = train_pred(model_lstm_atten(embedding_matrix), epochs = 3)\n    outputs.append([pred_val_y, pred_test_y, best_score, f'2 LSTM w/ attention fold id {idx}'])\n    idx += 1","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"26d08603680be063ec07c45637e2d85ebb400939"},"cell_type":"code","source":"show_timer()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true,"_uuid":"bef4e5503c4885b9e96c0aac8aa9ca56849362dd"},"cell_type":"code","source":"# pred_val_y = outputs[0][0]\n\n# thresholds = []\n# for thresh in np.arange(0.1, 0.501, 0.01):\n#     thresh = np.round(thresh, 2)\n#     res = metrics.f1_score(val_y, (pred_val_y > thresh).astype(int))\n#     thresholds.append([thresh, res])\n#     print(\"F1 score at threshold {0} is {1}\".format(thresh, res))\n    \n# thresholds.sort(key=lambda x: x[1], reverse=True)\n# best_thresh = thresholds[0][0]\n# print(\"Best threshold: \", best_thresh)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"ec8a28af771ad02c3dae9416e800d1baf304c432"},"cell_type":"code","source":"best_thresh = 0.32\npred_test_y = np.mean([outputs[i][1] for i in range(len(outputs))], axis = 0)\n\npred_test_y2 = (pred_test_y > best_thresh).astype(int)\ntest_df = pd.read_csv(\"../input/test.csv\", usecols=[\"qid\"])\nout_df = pd.DataFrame({\"qid\":test_df[\"qid\"].values})\nout_df['prediction'] = pred_test_y2\nout_df.to_csv(\"submission.csv\", index=False)\nshow_timer()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"21aed5abdd29e4eccb2834bff101128767aa8b3a"},"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}