{"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\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 read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import re\nfrom keras.preprocessing.sequence import pad_sequences\n\n\nfrom tensorflow.keras.preprocessing.text import Tokenizer\nfrom tensorflow.keras.preprocessing.sequence import pad_sequences\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense,Flatten,Embedding,Activation, Dropout\nfrom tensorflow.keras.layers import Conv1D,GlobalAveragePooling1D, MaxPooling1D, GlobalMaxPooling1D , LSTM , Bidirectional, SpatialDropout1D, BatchNormalization\nfrom tensorflow.keras.optimizers import Adam,SGD\nfrom keras import optimizers, callbacks \nfrom sklearn.metrics import log_loss\nfrom keras.layers import Flatten\nimport matplotlib.pyplot as plt\nimport nltk\nfrom nltk.corpus import stopwords\nfrom nltk.stem import WordNetLemmatizer\nfrom tensorflow.keras import layers\nfrom tensorflow.keras import regularizers\nfrom gensim.models import KeyedVectors\nfrom keras.regularizers import l2\nfrom keras.layers import Input\nfrom keras.layers import Lambda\nfrom keras.layers import concatenate,Reshape\nimport keras.backend as K\nfrom keras import initializers\nfrom keras.models import Model\nimport zipfile\nimport tensorflow as tf\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df = pd.read_csv('../input/quora-insincere-questions-classification/train.csv')\ntest_df = pd.read_csv('../input/quora-insincere-questions-classification/test.csv',  encoding='utf-8', engine='python')\n\ntrain_df.head(5)\ntest_df.head(5)\ntest_df.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with zipfile.ZipFile(\"../input/quora-insincere-questions-classification/embeddings.zip\",\"r\") as z:\n    z.extractall(\".\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df['question_text'].str.split().map(lambda x : len(x)).hist(bins=64)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"all question with max length is 45"},{"metadata":{"trusted":true},"cell_type":"code","source":"max_length = 55\nembedding_glove = './glove.840B.300d/glove.840B.300d.txt'\nembedding_para = './paragram_300_sl999/paragram_300_sl999.txt'\n\n\n\n\nWEIGHTS_FILE = './w0.h5'\ncontractions = { \n\"ain't\": \"am not\",\n\"aren't\": \"are not\",\n\"can't\": \"cannot\",\n\"can't've\": \"cannot have\",\n\"'cause\": \"because\",\n\"could've\": \"could have\",\n\"couldn't\": \"could not\",\n\"couldn't've\": \"could not have\",\n\"didn't\": \"did not\",\n\"doesn't\": \"does not\",\n\"don't\": \"do not\",\n\"hadn't\": \"had not\",\n\"hadn't've\": \"had not have\",\n\"hasn't\": \"has not\",\n\"haven't\": \"have not\",\n\"he'd\": \"he would\",\n\"he'd've\": \"he would have\",\n\"he'll\": \"he will\",\n\"he'll've\": \"he will have\",\n\"he's\": \"he is\",\n\"how'd\": \"how did\",\n\"how'd'y\": \"how do you\",\n\"how'll\": \"how will\",\n\"how's\": \"how does\",\n\"i'd\": \"i would\",\n\"i'd've\": \"i would have\",\n\"i'll\": \"i will\",\n\"i'll've\": \"i will have\",\n\"i'm\": \"i am\",\n\"i've\": \"i have\",\n\"isn't\": \"is not\",\n\"it'd\": \"it would\",\n\"it'd've\": \"it would have\",\n\"it'll\": \"it will\",\n\"it'll've\": \"it will have\",\n\"it's\": \"it is\",\n\"let's\": \"let us\",\n\"ma'am\": \"madam\",\n\"mayn't\": \"may not\",\n\"might've\": \"might have\",\n\"mightn't\": \"might not\",\n\"mightn't've\": \"might not have\",\n\"must've\": \"must have\",\n\"mustn't\": \"must not\",\n\"mustn't've\": \"must not have\",\n\"needn't\": \"need not\",\n\"needn't've\": \"need not have\",\n\"o'clock\": \"of the clock\",\n\"oughtn't\": \"ought not\",\n\"oughtn't've\": \"ought not have\",\n\"shan't\": \"shall not\",\n\"sha'n't\": \"shall not\",\n\"shan't've\": \"shall not have\",\n\"she'd\": \"she would\",\n\"she'd've\": \"she would have\",\n\"she'll\": \"she will\",\n\"she'll've\": \"she will have\",\n\"she's\": \"she is\",\n\"should've\": \"should have\",\n\"shouldn't\": \"should not\",\n\"shouldn't've\": \"should not have\",\n\"so've\": \"so have\",\n\"so's\": \"so is\",\n\"that'd\": \"that would\",\n\"that'd've\": \"that would have\",\n\"that's\": \"that is\",\n\"there'd\": \"there would\",\n\"there'd've\": \"there would have\",\n\"there's\": \"there is\",\n\"they'd\": \"they would\",\n\"they'd've\": \"they would have\",\n\"they'll\": \"they will\",\n\"they'll've\": \"they will have\",\n\"they're\": \"they are\",\n\"they've\": \"they have\",\n\"to've\": \"to have\",\n\"wasn't\": \"was not\",\n\" u \": \" you \",\n\" ur \": \" your \",\n\" n \": \" and \"}\n\n\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"*\"*50)\n\ntest_df.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"puncts = '\\'!\"#$%&()*+,-./:;<=>?@[\\\\]^_`{|}~\\t\\n'\npunct_mapping = {\"‘\": \"'\", \"₹\": \"e\", \"´\": \"'\", \"°\": \"\", \"€\": \"e\", \"™\": \"tm\", \"√\": \" sqrt \", \"×\": \"x\", \"²\": \"2\",\n                 \"—\": \"-\", \"–\": \"-\", \"’\": \"'\", \"_\": \"-\", \"`\": \"'\", '”': '\"', '“': '\"', \"£\": \"e\",\n                 '∞': 'infinity', 'θ': 'theta', '÷': '/', 'α': 'alpha', '•': '.', 'à': 'a', '−': '-', 'β': 'beta',\n                 '∅': '', '³': '3', 'π': 'pi', '\\u200b': ' ', '…': ' ... ', '\\ufeff': '', 'करना': '', 'है': ''}\nfor p in puncts:\n    punct_mapping[p] = ' %s ' % p\n\n\nprint(punct_mapping[\"∞\"])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"all_text  = ' '.join(train_df['question_text'])\n\nall_test  = ' '.join(test_df['question_text'])\n\nall_text  = all_text.split()\n\nall_test  = all_test.split()\n\nfrequence  = pd.Series(all_text).value_counts()\none_word = frequence[frequence.values == 1]\none_word[5:20]\n\n\ntoken = Tokenizer()\ntoken.fit_on_texts(all_text)\nvocab_size  = len(token.word_index) + 1\n\ntoken1 = Tokenizer()\ntoken1.fit_on_texts(all_test)\nvocab_size_test  = len(token1.word_index) + 1\n    \nprint(\"vocab before cleaning of train data\" , vocab_size)  \n\nprint(\"vocab before cleaning of test data\" , vocab_size_test)  \n    \n\naccents = [ (u\"é\", u\"e\"), (u\"ē\", u\"e\"), (u\"è\", u\"e\"), (u\"ê\", u\"e\"), (u\"à\", u\"a\"),\n                    (u\"â\", u\"a\"), (u\"ô\", u\"o\"), (u\"ō\", u\"o\"), (u\"ü\", u\"u\"), (u\"ï\", u\"i\"),\n                    (u\"ç\", u\"c\"), (u\"\\xed\", u\"i\")]\n            ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def preprocess( x ):\n    x = re.sub( u\"\\s+\", u\" \", x ).strip() # remove multiple  espace and back line\n    x = x.split(' ')[:55]\n    return ' '.join(x)\n\ndef clean_question(x):\n    x = preprocess(x)\n    if type(x) is str:\n        x = x.lower()\n        # transformer to lower \n        \n        for p in punct_mapping:\n            x = x.replace(p,punct_mapping[p])\n        for key in contractions:\n            value = contractions[key]\n            x = x.replace(key, value)\n            \n        for i,j in accents :\n             x = re.sub(i, j, x)\n            \n        regex = re.compile(r'[\\n\\r\\t]')\n        x = regex.sub(\" \", x)\n        x = re.sub(r'([a-zA-Z0-9+._-]+@[a-zA-Z0-9._-]+\\.[a-zA-Z0-9_-]+)', '', x) # regex to remove to emails\n        x = re.sub(u\"[^a-z\\s0-9]\", u\" \", x)\n        x = u\" \".join( re.sub(u\"^\\d+(?:[.,]\\d*)?$\", u\"number\", w)  for w in x.split(\" \"))\n        x = re.sub(u\"[^a-z\\s]\", u\" \", x)\n        \n        x = re.sub(r'(http|ftp|https)://([\\w_-]+(?:(?:\\.[\\w_-]+)+))([\\w.,@?^=%&:/~+#-]*[\\w@?^=%&/~+#-])?', '', x)   #regex to remove URLs     \n       \n        x = ' '.join([t for t in x.split() if t not in one_word])  # combining all the text excluding rare words.\n        return x\n    else:\n        return x\n\ntrain_df['question_text'] = train_df['question_text'].apply(lambda x: clean_question(x))\ntrain_df['question_text'] = train_df['question_text'].tolist()\n\ntest_df['question_text'] = test_df['question_text'].apply(lambda x: clean_question(x))\ntest_df['question_text'] = test_df['question_text'].tolist()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df.shape","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"preparing embedding matrix "},{"metadata":{},"cell_type":"markdown","source":"Lemmatization is the process of converting a word to its base form. The difference between stemming and lemmatization is, lemmatization considers the context and converts the word to its meaningful base form, whereas stemming just removes the last few characters, often leading to incorrect meanings and spelling errors."},{"metadata":{},"cell_type":"markdown","source":"train_df['question_text'] = (train_df['question_text'].pipe(hero.remove_angle_brackets)\n                    .pipe(hero.remove_brackets)\n                    .pipe(hero.remove_curly_brackets)\n                    .pipe(hero.remove_diacritics)\n                    .pipe(hero.remove_round_brackets)\n                    .pipe(hero.remove_square_brackets)\n                    .pipe(hero.remove_punctuation)\n                    .pipe(hero.remove_stopwords))\n"},{"metadata":{},"cell_type":"markdown","source":""},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"lemm = WordNetLemmatizer()\n\ndef word_lemma(text):\n    words = nltk.word_tokenize(text)\n    lemma = [lemm.lemmatize(word) for word in words]\n    joined_text = \" \".join(lemma)\n    return joined_text\n\ntrain_df['question_text'] = train_df['question_text'].apply(lambda x: word_lemma(x))\n\ntest_df['question_text'] = test_df['question_text'].apply(lambda x: word_lemma(x))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df[200:210]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df['question_text']\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def pre_embe(data  ):\n    print(data.shape)\n    token = Tokenizer()\n    token.fit_on_texts(data)\n    vocab_size  = len(token.word_index) + 1\n    print(\" vocabolury size :  \" ,vocab_size)\n    encoded_text = token.texts_to_sequences(data)\n    print(encoded_text[:1])\n    X = pad_sequences(encoded_text, maxlen=55, padding='post')\n    print(\" exemple of fisrt question with encoding index \",X[1])\n    print(X.shape)\n    return X , vocab_size , token.word_index\n\nX , vac , word_index= pre_embe(train_df['question_text'] )\n    \nX_testing , vac_test , word_index_test = pre_embe(test_df['question_text'] )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_testing.shape\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import zipfile\nfrom gensim.models import KeyedVectors\nimport io\nfrom tqdm import tqdm\n\ndef load_embeddings(method):\n    embeddings_index={}      \n\n    if method=='glove':\n        \n        with zipfile.ZipFile(\"../input/quora-insincere-questions-classification/embeddings.zip\") as zf:\n             with io.TextIOWrapper(zf.open(\"glove.840B.300d/glove.840B.300d.txt\"), encoding=\"utf-8\") as f:\n                    \n                    \n                    for line in tqdm(f):\n                        \n                        values=line.split(' ') # \".split(' ')\" only for glove-840b-300d; for all other files, \".split()\" works\n                        word=values[0]\n                        vectors=np.asarray(values[1:],'float32')\n                        embeddings_index[word]=vectors\n    if method=='paragram':\n        with zipfile.ZipFile(\"../input/quora-insincere-questions-classification/embeddings.zip\") as zf:\n             with io.TextIOWrapper(zf.open(\"paragram_300_sl999/paragram_300_sl999.txt\"), encoding=\"utf8\" , errors='ignore') as f:\n                    \n                    \n                    for line in tqdm(f):\n                        \n                        values=line.split(' ') # \".split(' ')\" only for glove-840b-300d; for all other files, \".split()\" works\n                        word=values[0]\n                        vectors=np.asarray(values[1:],'float32')\n                        embeddings_index[word]=vectors\n    return embeddings_index\n\n\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"glove = load_embeddings('glove')\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"paragram = load_embeddings('paragram')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"paragram.get('you').shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import gc\ndef convert_embidding(word_index,embeddings_index,vocabulaire_size) : \n    \n    matrix_vector = np.zeros((vocabulaire_size, 300))\n\n    for word, index in word_index.items():\n        vector = embeddings_index.get(word)\n        if vector is not None:\n            matrix_vector[index] = vector\n      \n    return matrix_vector\n    \n    \nembedding_matrix_glove    =  convert_embidding(word_index,glove,vac)  \nembedding_matrix_paragram =  convert_embidding(word_index,paragram,vac)    \n \ndel embedding_matrix_glove\ndel embedding_matrix_paragram\ngc.collect()\n\n#Meta embidding    \n    \nembedding_matrix = np.mean([1.4 * embedding_matrix_glove, \n                            0.6 * embedding_matrix_paragram], \n                           axis = 0)\n\n\n#matrix_vector = convert_embidding(word_index,glove,vac)    \n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"embedding_matrix_glove_test    =  convert_embidding(word_index_test,glove,vac_test)  \nembedding_matrix_paragram_test =  convert_embidding(word_index_test,paragram,vac_test)    \ndel embedding_matrix_glove_test\ndel embedding_matrix_paragram_test\ngc.collect()\n  \n#Meta embidding    \n    \nembedding_matrix_test = np.mean([1.4 * embedding_matrix_glove_test, \n                            0.6 * embedding_matrix_paragram_test], \n                           axis = 0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y = train_df['target']\nX_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 42, test_size = 0.2, stratify = y)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def model_create(matrix_vector , trainable=False , lr=0.001, seed = 42):\n    \n    np.random.seed(seed)\n    \n    model = Sequential()\n\n    model.add(Embedding(vac, 300, input_length=max_length, weights = [matrix_vector], trainable = trainable))\n    \n    model.add(Bidirectional(LSTM(64,activation = 'tanh')))\n    \n    model.add(BatchNormalization())\n    \n    model.add(Dropout(0.2))\n\n    model.add(Dense(16, kernel_regularizer=regularizers.l2(1e-3), bias_regularizer=regularizers.l2(1e-4), activation='relu'))\n\n    model.add(Dropout(0.2))\n\n    model.add(Dense(16, activation='relu'))\n \n    model.add(Dense(1, activation='sigmoid'))\n   \n    \n    model.compile(optimizer=optimizers.Adam(lr=lr), loss = 'binary_crossentropy', metrics = ['accuracy'])\n    \n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = model_create(embedding_matrix)\n\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def run_model(model , lr=1e-3, bs=2048):\n    \n    for seed in range(1):\n        \n        es = callbacks.EarlyStopping( patience = 4 )\n        \n        mc = callbacks.ModelCheckpoint( filepath=WEIGHTS_FILE, monitor='val_loss', mode='min', save_best_only=True )\n        \n        history = model.fit(X_train, y_train, validation_data=(X_test, y_test), callbacks=[es, mc],\n                            batch_size=bs, epochs=100 )\n        \n        model.load_weights(WEIGHTS_FILE)\n        \n        p = model.predict(X_testing, batch_size=bs)\n\n        #print ( 'BAGGING SCORE Test: ' , log_loss(y_test,  predictions_test.mean(axis=1), eps = 1e-7) )\n        #print ( 'BAGGING SCORE Train: ', log_loss(y_train, predictions_train.mean(axis=1), eps = 1e-7) )\n        \n        print(\"test\"+\"*\"*50)\n        print(y_test[1:10])\n        print(\"result_test\"+\"*\"*50)\n        print(p[1:10])\n        \n        ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"run_model(model , lr=1e-3,bs=2048)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"tf.keras.backend.clear_session()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\n\nmodel1 = model_create(embedding_matrix,trainable=True)\n\nprint(model1.summary())\n\nmodel1.load_weights(WEIGHTS_FILE)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"run_model(model1 , lr=1e-3,bs=2048)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"all_preds_sub = model1.predict([X_testing], batch_size=2048)\nall_preds_sub[2:]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub_df = pd.DataFrame()\n\nall_preds_sub = (all_preds_sub > 0.35).astype(int)\n\nsub_df['qid'] = test_df.qid.values  \n\nsub_df['prediction'] = all_preds_sub\n\nsub_df.to_csv(\"submission.csv\", index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\n#for lr in [1e-5, 1e-4, 1e-3]:\n           \n  #  run_model(model1, lr=lr,bs=2048)\n            \n   # print(\"**********************************************************************\")\n    \n","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":4}