{"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":"!pip install texthero","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\n\nimport texthero as hero\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')\ntrain_df.head(5)\nprint(\"*\"*50)\ntest_df.head(5)","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 = 45\nembedding_glove = '../input/glove840b300dtxt/glove.840B.300d.txt'\nembedding_para = '../input/paragram-300-sl999/paragram_300_sl999.txt'\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":"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\np = re.compile('(\\[ math \\]).+(\\[ / math \\])')\np_space = re.compile(r'[^\\x20-\\x7e]')\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\" , vocab_size)  \n\nprint(\"vocab before testing\" , 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 clean_question(x):\n    if type(x) is str:\n        x = x.lower() # transformer to lower \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        \n        x = re.sub(r'([a-zA-Z0-9+._-]+@[a-zA-Z0-9._-]+\\.[a-zA-Z0-9_-]+)', '', x) # regex to remove to emails\n       \n        x = re.sub(r'(http|ftp|https)://([\\w_-]+(?:(?:\\.[\\w_-]+)+))([\\w.,@?^=%&:/~+#-]*[\\w@?^=%&/~+#-])?', '', x)   #regex to remove URLs     \n        x = re.sub( u\"\\s+\", u\" \", x ).strip() # remove multiple  espace and back line\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":"train_df[200:210]","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":{"trusted":true},"cell_type":"code","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   ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df[200:210]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df['question_text'] = (test_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))","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":"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":"train_df[200:210]","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":"def pre_embe(data ):\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(train_df['question_text'])\n    X = pad_sequences(encoded_text, maxlen=max_length, padding='post')\n    print(\" exemple of fisrt question with encoding index \",X[1])\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":"def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32')\n\ndef load_embeddings(method):\n    embeddings_index = dict()        \n\n    if method=='glove':\n        embeddings_index.update( dict(get_coefs(*o.split(\" \")) for o in open(embedding_glove))) \n    if method=='paragram':\n        embeddings_index.update( dict(get_coefs(*o.split(\" \")) for o in open(embedding_para, encoding=\"utf8\", errors='ignore'))) \n    \n    return embeddings_index\n\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32')\n\ndef load_embeddings(method):\n    if method=='glove':\n        embedding_index = dict(get_coefs(*o.strip().split(\" \")) for o in tqdm(open(embedding_glove)))\n    if method=='paragram':\n        embedding_index = dict(get_coefs(*o.strip().split(\" \")) for o in tqdm(open(embedding_para))\n    \n    return embedding_index"},{"metadata":{"trusted":true},"cell_type":"code","source":"glove = load_embeddings('glove')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"glove.get('you').shape","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":{},"cell_type":"markdown","source":"+------------+------------+\n|   index    |  Embedding |\n+------------+------------+\n|     0      | [1.2, 3.1] |\n|     1      | [0.1, 4.2] |\n|     2      | [1.0, 3.1] |\n|     3      | [0.3, 2.1] |\n|     4      | [2.2, 1.4] |\n|     5      | [0.7, 1.7] |\n|     6      | [4.1, 2.0] |Embedding(7, 2, input_length=5)\n+------------+------------+"},{"metadata":{"trusted":true},"cell_type":"code","source":"def 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    \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)    \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    x_input = Input(shape=(max_length,))\n    \n    \n    emb = Embedding(vac, 300, input_length=max_length, weights = [matrix_vector], trainable = trainable)(x_input)\n    \n    x = SpatialDropout1D(0.2, seed=10000)(emb)\n    \n    \n    rnn = Bidirectional(LSTM(128,activation = 'tanh',return_sequences=True))(x)\n    \n    maxlstm = GlobalMaxPooling1D()(rnn)\n    \n    maxlstm = BatchNormalization()(maxlstm)\n    \n    average = Lambda(lambda x : K.sum(x, axis=1))(rnn)\n\n    average = BatchNormalization()(average)\n\n    c = concatenate([maxlstm,average], axis=1)\n    \n    c = Reshape((2, -1))(c)\n    \n    x = Dense(100, activation='relu')(c)\n    \n    x = Dropout(0.2, seed=10000)(x)\n    \n    x = BatchNormalization()(x)\n    \n    x_output = Dense(1, activation='sigmoid')(x)\n    \n    model = Model(inputs=x_input, outputs=x_output)\n    \n    model.compile(optimizer=optimizers.Adam(lr=lr), loss = 'binary_crossentropy', metrics = ['accuracy'])\n    \n    return model","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"The requirements to use the cuDNN implementation are:\n\nactivation == tanh\nrecurrent_activation == sigmoid\nrecurrent_dropout == 0\nunroll is False\nuse_bias is True\nInputs, if use masking, are strictly right-padded.\nEager execution is enabled in the outermost context."},{"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":"def run_model(model , lr=1e-3, bs=2048):\n    \n    predictions_train  = pd.DataFrame()\n    \n    for seed in range(2):\n        \n        es = callbacks.EarlyStopping( patience=4 )\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, verbose=2 )\n        \n        model.load_weights(WEIGHTS_FILE)\n        \n        p = model.predict(X_testing, batch_size=bs)\n        \n        \n        #p = model.predict(X_test_emb, batch_size = 2048)\n        \n        #predictions_test[str(seed)] = p.flatten()\n\n        #p = model.predict(X_train_emb, batch_size = 2048)\n        \n        predictions_train[str(seed)] = p.flatten()\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        plt.plot(history.history['val_loss'])\n        plt.plot(history.history['loss'])\n        plt.legend( ['test', 'train'] )\n        \n        print('****************************************')\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":"#model1 = model_create(embedding_matrix,trainable=True)\n\n#print(model1.summary())\n\n#model1.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 = model.predict(X_testing, batch_size=2048)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub_df = pd.DataFrame()\nsub_df['qid'] = df_sub.qid.values\n\nfor x in all_preds_sub:\n    if x>0.34:\n        x = 1\n    else:\n        x = 0\n        \nsub_df['prediction'] = all_preds_sub\nsub_df.to_csv('submission.csv', index=False)\n","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}