{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"markdown","source":"Inspired by [Dieter: Augmentation for text](https://www.kaggle.com/c/quora-insincere-questions-classification/discussion/71083) and [Extending Train Data with Markov Chains - AUC](https://www.kaggle.com/jpmiller/extending-train-data-with-markov-chains-auc). I have tried augment train text using Markov Chains in this competition. \n\nIf I understand correctly, this operation doesn't against the rule ? Please let me know if I have made any mistakes. Happy Kaggling! :)"},{"metadata":{"trusted":true,"_uuid":"b84121c387ae0b9a9c4d7afedda2620795883e8a"},"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport operator \nimport re\nimport matplotlib.pyplot as plt\nimport seaborn as sns\ncolor = sns.color_palette()\n%matplotlib inline\n\nfrom sklearn.model_selection import train_test_split\n\nfrom keras import backend as K\nfrom keras.layers import *\nfrom keras import initializers, regularizers, constraints, optimizers, layers\nfrom keras.models import Model\nfrom keras.preprocessing import text, sequence\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.callbacks import Callback, ReduceLROnPlateau, ModelCheckpoint, EarlyStopping\nfrom keras.initializers import glorot_normal,orthogonal\n\nimport gc\nimport warnings\nwarnings.filterwarnings('ignore')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"d2059d60342954534cc2b4c1d3ad807e5bb9830d"},"cell_type":"code","source":"train = pd.read_csv(\"../input/train.csv\")\ntrain_y = train['target'].values\n# test = pd.read_csv(\"../input/test.csv\")","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"# preprocessing: https://www.kaggle.com/theoviel/improve-your-score-with-some-text-preprocessing\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\ntrain['question_text'] = train['question_text'].apply(lambda x: clean_contractions(x, contraction_mapping))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"35707ec772bf1b9727b94d206f06069b953f1ac7"},"cell_type":"code","source":"punct = \"/-'?!.,#$%\\'()*+-/:;<=>@[\\\\]^_`{|}~\" + '\"\"“”’' + '∞θ÷α•à−β∅³π‘₹´°£€\\×™√²—–&'\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        if p in text:\n            text = text.replace(p, mapping[p])\n    \n    for p in punct:\n        if p in text:\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        if s in text:\n            text = text.replace(s, specials[s])\n    \n    return text\n\ntrain['question_text'] = train['question_text'].apply(lambda x: clean_special_chars(x, punct, punct_mapping))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"c1eb559d10e395683cce82ba0adad48bd4351078"},"cell_type":"code","source":"mispell_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        if word in x:\n            x = x.replace(word, dic[word])\n    return x\n\ntrain['question_text'] = train['question_text'].apply(lambda x: correct_spelling(x, mispell_dict))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"246000c48bdb57251dd9da0cb84e34635f64e49b"},"cell_type":"code","source":"# clean LaTeX tags: https://www.kaggle.com/sunnymarkliu/latex-cannot-be-used-in-a-quora-question\ndef clean_latex_tag(text):\n    corr_t = []\n    for t in text.split(\" \"):\n        t = t.strip()\n        if t != '':\n            corr_t.append(t)\n    text = ' '.join(corr_t)\n    \n    text = re.sub('(\\[ math \\]).+(\\[ / math \\])', 'mathematical formula', text)\n    return text\n\ntrain['question_text'] = train['question_text'].map(clean_latex_tag)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"9aceb01acc96a2f8787c2d15132a843d7930501c"},"cell_type":"code","source":"train_text, valid_text, y_train, y_valid = train_test_split(train['question_text'], train_y, test_size=0.1, random_state=2018)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"3bc3b4403fb3e4bc0368735bec26b34ec4a5fdd0"},"cell_type":"code","source":"EMBED_SIZE = 300\nMAX_WORDS_LEN = 70\nMAX_VOCAB_FEATURES = 200000","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"5dcb7cb32f3afdd0b5a0f1d887537f2bbc54da1b"},"cell_type":"code","source":"%%time\nprint('tokenize and padding')\ntokenizer = Tokenizer(num_words=MAX_VOCAB_FEATURES, filters='')\ntokenizer.fit_on_texts(train_text)\n\n# tokenize\ntrain_X = tokenizer.texts_to_sequences(train_text)\nvalid_X = tokenizer.texts_to_sequences(valid_text)\n\n# Pad the sentences \ntrain_X = pad_sequences(train_X, maxlen=MAX_WORDS_LEN)\nvalid_X = pad_sequences(valid_X, maxlen=MAX_WORDS_LEN)\n\nword_index = tokenizer.word_index\nnb_words = min(MAX_VOCAB_FEATURES, len(word_index))\n\ndef load_glove():\n    print(\"Extracting Glove embedding\")\n    EMBEDDING_FILE = '../input/embeddings/glove.840B.300d/glove.840B.300d.txt'\n    emb_mean, emb_std = -0.005838499, 0.48782197\n\n    embedding_matrix = np.random.normal(emb_mean, emb_std, (nb_words, EMBED_SIZE))\n    with open(EMBEDDING_FILE, 'r', encoding=\"utf8\") as f:\n        for line in f:\n            word, vec = line.split(' ', 1)\n            if word not in word_index:\n                continue\n            i = word_index[word]\n\n            if i >= nb_words:\n                continue\n            embedding_vector = np.asarray(vec.split(' '), dtype='float32')[:300]\n            if len(embedding_vector) == 300:\n                embedding_matrix[i] = embedding_vector\n\n    print('Glove:', embedding_matrix.shape)\n    return embedding_matrix\n\nglove_embedding_matrix = load_glove()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"1aebd5ccd53bb05b86ca3c552cdadb9d491ab47e"},"cell_type":"code","source":"def f1(y_true, y_pred):\n    '''\n    metric from here \n    https://stackoverflow.com/questions/43547402/how-to-calculate-f1-macro-in-keras\n    '''\n    def recall(y_true, y_pred):\n        \"\"\"Recall metric.\n\n        Only computes a batch-wise average of recall.\n\n        Computes the recall, a metric for multi-label classification of\n        how many relevant items are selected.\n        \"\"\"\n        true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n        possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))\n        recall = true_positives / (possible_positives + K.epsilon())\n        return recall\n\n    def precision(y_true, y_pred):\n        \"\"\"Precision metric.\n\n        Only computes a batch-wise average of precision.\n\n        Computes the precision, a metric for multi-label classification of\n        how many selected items are relevant.\n        \"\"\"\n        true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n        predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\n        precision = true_positives / (predicted_positives + K.epsilon())\n        return precision\n    \n    precision = precision(y_true, y_pred)\n    recall = recall(y_true, y_pred)\n    return 2*((precision*recall)/(precision+recall+K.epsilon()))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"1eaa62b2537b2467a4e1988b086e0cd4c67f19ef"},"cell_type":"code","source":"# https://www.kaggle.com/sudalairajkumar/a-look-at-different-embeddings/notebook\ndef simple_model(embedding_matrix):\n    inp = Input(shape=(MAX_WORDS_LEN,))\n    x = Embedding(nb_words, EMBED_SIZE, weights=[embedding_matrix], trainable=False)(inp)\n    x = Bidirectional(CuDNNGRU(64, return_sequences=True))(x)\n    x = GlobalMaxPool1D()(x)\n    x = Dense(16, activation=\"relu\")(x)\n    x = Dropout(0.1)(x)\n    x = Dense(1, activation=\"sigmoid\")(x)\n    model = Model(inputs=inp, outputs=x)\n    model.compile(loss='binary_crossentropy', optimizer='adam', metrics=[f1])\n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"1a3dddbc7ce919de48ffe83d75909f9824e57cc6"},"cell_type":"code","source":"model = simple_model(glove_embedding_matrix)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"dbb21de5ee45389a3a406372ffce2eee95ba45fc"},"cell_type":"code","source":"model.fit(train_X, y_train, batch_size=512, epochs=2, validation_data=(valid_X, y_valid))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"97c9764c5415e63688d79167092b5c8a1bbd453a"},"cell_type":"markdown","source":"## Augment training text with Markov Chains"},{"metadata":{"trusted":true,"_uuid":"447599b781c91dcc42f4b611b049828896f0e054"},"cell_type":"markdown","source":"In this experiment,  I use [markovify](https://github.com/jsvine/markovify) to augment insincere training data."},{"metadata":{"trusted":true,"_uuid":"a01a1dda38c691125f326a89d70efe9450154f4f"},"cell_type":"code","source":"import psutil\nimport multiprocessing\nimport markovify as mk\n\nclass MarkovifyTextAugmentor(object):\n    \n    def __init__(self, docs, gen_max_len, filter_min_len=10):\n        \"\"\"\n        Build Markov models from large corpora of text, and generating random sentences from that.\n        \"\"\"\n        self.mk_text_model = mk.Text(docs)\n        self.gen_max_len = gen_max_len\n        self.filter_min_len = filter_min_len\n    \n    def genenerate(self, count):\n        texts = []\n        \n        for _ in range(count):\n            text = self.mk_text_model.make_short_sentence(self.gen_max_len)\n            if text and len(text.split(' ')) > self.filter_min_len:\n                texts.append(text)\n        \n        return texts","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"3d6d01d5c24a543ddbc91427de47811a2c4c28c8"},"cell_type":"code","source":"insincere_docs = train_text[train['target'] == 1]\nins_doc_median_len = int(insincere_docs.str.len().median())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"fe470f17267ccfa7c0d69bf66cf9e36c8901fe45"},"cell_type":"code","source":"%%time\nmk_augmentor = MarkovifyTextAugmentor(insincere_docs, ins_doc_median_len, filter_min_len=6)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"6302a099c5ecb950aaa0b89c547c1209a27746ab"},"cell_type":"code","source":"augment_insincere_count = 2000","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"461ac032d69c60ab4afa3cc8bcb5400491c74221"},"cell_type":"code","source":"%%time\ndef gen_text_process(count):\n    return mk_augmentor.genenerate(count)\n\nnum_cores = psutil.cpu_count()  # number of cores on your machine\n\npool = multiprocessing.Pool(processes=num_cores)\napply_results = []\nprocess_counts = augment_insincere_count // num_cores\nfor _ in range(num_cores):\n    apply_results.append(pool.apply_async(gen_text_process, (process_counts,)))\n\npool.close()\npool.join()\n\nall_gen_texts = []\nfor res in apply_results:\n    all_gen_texts.extend(res.get())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"940f2e0497957526a51a399bf3e81947f24051ee"},"cell_type":"code","source":"print('generate {} insincere questions'.format(len(all_gen_texts)))\nprint(all_gen_texts[:10])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"8a71bbb48f76831d2ca73c10c5732e12e6b42670"},"cell_type":"code","source":"%%time\naug_train_text = np.array(train_text.values.tolist() + all_gen_texts)\naug_y_train = np.array(y_train.tolist() + [1] * len(all_gen_texts))\n\n# shuffle\nshuf_idx = np.random.permutation(len(aug_train_text))\naug_train_text = aug_train_text[shuf_idx]\naug_y_train = aug_y_train[shuf_idx]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"020b857162c19a733465d4b6fe0eec9f895c8c8d"},"cell_type":"code","source":"%%time\nprint('tokenize and padding')\ntokenizer = Tokenizer(num_words=MAX_VOCAB_FEATURES, filters='')\ntokenizer.fit_on_texts(aug_train_text)\n\n# tokenize\naug_train_X = tokenizer.texts_to_sequences(aug_train_text)\nvalid_X = tokenizer.texts_to_sequences(valid_text)\n\n# Pad the sentences \naug_train_X = pad_sequences(aug_train_X, maxlen=MAX_WORDS_LEN)\nvalid_X = pad_sequences(valid_X, maxlen=MAX_WORDS_LEN)\n\nword_index = tokenizer.word_index\nnb_words = min(MAX_VOCAB_FEATURES, len(word_index))\n\ndef load_glove():\n    print(\"Extracting Glove embedding\")\n    EMBEDDING_FILE = '../input/embeddings/glove.840B.300d/glove.840B.300d.txt'\n    emb_mean, emb_std = -0.005838499, 0.48782197\n\n    embedding_matrix = np.random.normal(emb_mean, emb_std, (nb_words, EMBED_SIZE))\n    with open(EMBEDDING_FILE, 'r', encoding=\"utf8\") as f:\n        for line in f:\n            word, vec = line.split(' ', 1)\n            if word not in word_index:\n                continue\n            i = word_index[word]\n\n            if i >= nb_words:\n                continue\n            embedding_vector = np.asarray(vec.split(' '), dtype='float32')[:300]\n            if len(embedding_vector) == 300:\n                embedding_matrix[i] = embedding_vector\n\n    print('Glove:', embedding_matrix.shape)\n    return embedding_matrix\n\nglove_embedding_matrix = load_glove()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"fa3138299470da809613248df6a09d5e1a5d91c0"},"cell_type":"code","source":"model = simple_model(glove_embedding_matrix)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"d328bc4d6cc40de21c753cc5a72f6fb440e4c92a"},"cell_type":"code","source":"model.fit(aug_train_X, aug_y_train, batch_size=512, epochs=2, validation_data=(valid_X, y_valid))","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"c0744b56c2b9beff2a099dc433757497e4ef110b"},"cell_type":"markdown","source":"We can see that after augmenting the train insincere question:\n\n- epoch1 valid f1_score increased from **0.62x** to **0.64x**. \n- epoch2 valid f1_score increased from **0.61x** to **0.63x**. \n\nAnd two things that I have found that:\n\n- Augment heavily may causes overfitting, because of the limit vocabulary in the training insincere questions\n- Combine Markov Chains and other method like synonyms replacement may help increase the vocabulary and may prevent overfitting.\n\nWe need more check because the randomness. Hope this can help you! :)"},{"metadata":{"trusted":true,"_uuid":"9d226e457396f061c4ee73c42ec33691d2f022e8"},"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}