{"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":{},"cell_type":"markdown","source":"#  import library"},{"metadata":{"trusted":true},"cell_type":"code","source":"import re\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, MaxPooling1D, GlobalMaxPooling1D , LSTM\nfrom tensorflow.keras.optimizers import Adam\nfrom keras import optimizers, callbacks \nfrom sklearn.metrics import log_loss\nfrom keras.layers import Flatten\nimport matplotlib.pyplot as plt\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df = pd.read_csv('../input/quora-insincere-questions-classification/train.csv')\ntrain_df.head(5)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"print(train_df.columns)\nprint(train_df['target'].value_counts())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df['question_text'].str.len().hist()","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)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"max_length = 45","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"all most questions with max word is 45"},{"metadata":{"trusted":true},"cell_type":"code","source":"contractions = { \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 \"}","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"rare word "},{"metadata":{"trusted":true},"cell_type":"code","source":"all_text = ' '.join(train_df['question_text'])\nall_text = all_text.split()\nfrequence  = pd.Series(all_text).value_counts()\n\none_word = frequence[frequence.values == 1]\none_word[5:20]","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 key in contractions:\n            value = contractions[key]\n            x = x.replace(key, value)\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","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(train_df['question_text'][:6])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\ntoken = Tokenizer() \ntoken.fit_on_texts(train_df['question_text'])\nvac = token.index_word\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"dict(list(vac.items())[0:10]) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#declaring the vocab_size\nvocab_size  = len(token.word_index) + 1\nvocab_size","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"##### conversion to numerical formats\n\nencoded_text = token.texts_to_sequences(train_df['question_text'])\nprint(encoded_text[:3])\n\n#padding='post' means that we padding post the sentence(keeping values 0 if the tokens are not there)\n\nX = pad_sequences(encoded_text, maxlen=max_length, padding='post')\nprint(X[:2])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\nglove_vectors = dict()\n\nfile = open('../input/nlpword2vecembeddingspretrained/glove.6B.200d.txt', encoding='utf-8')\n\nfor line in file:\n    values = line.split()\n    word = values[0]\n    #storing the word in the variable\n    vectors = np.asarray(values[1: ])\n    #storing the vector representation of the respective word in the dictionary\n    glove_vectors[word] = vectors\nfile.close()\n\n#printing length of glove vectors\nlen(glove_vectors)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"glove_vectors.get('you').shape","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Now we are creating a matrix for the tokens which we are having in our dataset and then storing their vector representation values in the matrix if it matches with glove_vectors words"},{"metadata":{"trusted":true},"cell_type":"code","source":"word_vector_matrix = np.zeros((vocab_size, 200))\n\nfor word, index in token.word_index.items():\n    vector = glove_vectors.get(word)\n    if vector is not None:\n        word_vector_matrix[index] = vector","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"word_vector_matrix[3]","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)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"vector_size = 200\nWEIGHTS_PATH = './w0.h5'\nmc = callbacks.ModelCheckpoint( filepath=WEIGHTS_PATH, monitor='val_loss', mode='min', save_best_only=True )\nmodel = Sequential()\nmodel.add(Embedding(vocab_size, vector_size, input_length=max_length, weights = [word_vector_matrix], trainable = False))\nmodel.add(LSTM(64))\nmodel.add(Dense(100, activation='relu'))\n\n\nmodel.add(Dense(1, activation='sigmoid'))\n\nmodel.compile(optimizer=Adam(learning_rate = 0.0001), loss = 'binary_crossentropy', metrics = ['accuracy'])\nes = callbacks.EarlyStopping( patience=1 )\nhistory = model.fit(X_train, y_train, epochs = 2, validation_data = (X_test, y_test) , callbacks=[es , mc] , batch_size=2048 )\nplt.plot(history.history['val_loss'])\nplt.plot(history.history['loss'])\nplt.legend( ['test', 'train'] )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(y_test[:10])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"preds = model.predict( X_test , batch_size=2048)\n\nprint ( 'test ssscore : ', preds[:10] ,log_loss(y_test, preds, eps = 1e-7) )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","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}