{"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 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 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# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_train_word = pd.read_csv(\"/kaggle/input/jigsaw-multilingual-toxic-comment-classification/jigsaw-toxic-comment-train.csv\")\nx_test_word = pd.read_csv(\"/kaggle/input/jigsaw-multilingual-toxic-comment-classification/test.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"list_classes = [\"toxic\",\"severe_toxic\",\"obscene\",\"threat\",\"insult\",\"identity_hate\"]\ny_train = x_train_word[list_classes].values\nx_train = x_train_word[\"comment_text\"]\nx_test = x_test_word[\"content\"]\n# x_test1 = []\n# from googletrans import Translator\n# translator = Translator()\n# for i in range (0,len(x_test)):\n#     sent = translator.translate(x_test[i])\n#     x_test1.append(sent.text)\n    \n# print(x_test1[0])\n# # print(translator.translate(\"Doctor\"))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing.sequence import pad_sequences\n\n\ntokenizer = Tokenizer(num_words=None,\n                      filters='!\"#$%&()*+,-./:;<=>?@[\\\\]^_`{|}~\\t\\n',\n                      lower=True,\n                      split=\" \",\n                      char_level=False)\n\ntokenizer.fit_on_texts(list(x_train))\ntokenized_train = tokenizer.texts_to_sequences(x_train)\ntokenized_test = tokenizer.texts_to_sequences(x_test)\nindex = tokenizer.word_index\naverage = np.mean([len(seq) for seq in tokenized_train])\nstdev = np.std([len(seq) for seq in tokenized_train])\nmax_len = int(average + stdev * 3)\nprint()\nprocessed_X_train = pad_sequences(tokenized_train, maxlen=max_len, padding='post', truncating='post')\nprocessed_X_test = pad_sequences(tokenized_test, maxlen=max_len, padding='post', truncating='post')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"embeddings_index = {}\nf = open(os.path.join('/kaggle/input/glove-global-vectors-for-word-representation/glove.6B.200d.txt'))\nfor line in f:\n    values = line.split()\n    word = values[0]\n    coefs = np.asarray(values[1:], dtype='float32')\n    embeddings_index[word] = coefs\nf.close()\n\nprint('Found %s word vectors.' % len(embeddings_index))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Embedding_dim = 200\nembedding_matrix = np.zeros((len(index) + 1, Embedding_dim))\nfor word, i in index.items():\n    embedding_vector = embeddings_index.get(word)\n    if embedding_vector is not None:\n        embedding_matrix[i] = embedding_vector\n        ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.layers import Embedding\n\nlayer = Embedding(len(index)+1,Embedding_dim,weights = [embedding_matrix],input_length =max_len,trainable = True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import keras.backend\nfrom keras.models import Sequential\nfrom keras.layers import CuDNNGRU, Dense, Conv1D, MaxPooling1D\nfrom keras.layers import Dropout, GlobalMaxPooling1D, BatchNormalization\nfrom keras.layers import Bidirectional\nfrom keras.layers.embeddings import Embedding\nfrom keras.optimizers import Nadam\n\n\nmodel = Sequential()\nmodel.add(layer)\nmodel.add(Conv1D(filters=128, kernel_size=5, padding='same', activation='relu'))\nmodel.add(MaxPooling1D(3))\nmodel.add(GlobalMaxPooling1D())\nmodel.add(BatchNormalization())\n\n\nmodel.add(Dense(50, activation='relu'))\nmodel.add(Dropout(0.3))\nmodel.add(Dense(6, activation='sigmoid'))\n\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.callbacks import EarlyStopping, ModelCheckpoint\ndef loss(y_true,y_pred):\n    return keras.backend.binary_crossentropy(y_true,y_pred)\n\n\nsaved_model = \"weights_base.best.hdf5\"\ncheckpoint = ModelCheckpoint(saved_model, monitor='val_acc', verbose=1, save_best_only=True, mode='max')\nearly = EarlyStopping(monitor=\"val_acc\", mode=\"max\", patience=5)\ncallbacks_list = [checkpoint, early]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import tensorflow as tf\np = tf.config.experimental.list_physical_devices('GPU')\ntf.config.experimental.set_visible_devices(p[0], 'GPU')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"raw","source":"Training the model","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\n[X, X_val, y, y_val] = train_test_split(processed_X_train, y_train, test_size=0.03, shuffle=False)\nmodel.compile(loss='binary_crossentropy', optimizer='Adam',metrics=['accuracy'])\nhistory = model.fit(X, y, batch_size=1280, epochs=3,validation_data=(X_val, y_val),verbose=1,shuffle=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\n\nplt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.title(\"Model Accuracy\")\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"Accuracy\")\nplt.legend(['train','test'],loc = 'best')\nplt.show()\n\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title(\"Model Loss\")\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"Loss\")\nplt.legend(['train','test'],loc = 'best')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Function for classification","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def predi(string):\n    newString = [string]\n    newString = tokenizer.texts_to_sequences(newString)\n    newString = pad_sequences(newString,maxlen = max_len,padding = \"post\",truncating = \"post\")\n    prediction = model.predict(newString)\n#     toxic = float(prediction[0][0])\n#     if toxic>0.5:\n#         return 1.0\n#     else:\n#         return 0.0\n    \n    print(\"Severe_Toxic % is {:.0%}\".format(prediction[0][1]))\n    print(\"Obscene % is {:.0%}\".format(prediction[0][2]))\n    print(\"Threat % is {:.0%}\".format(prediction[0][3]))\n    print(\"Insult % is {:.0%}\".format(prediction[0][4]))\n    print(\"Identity Hate % is {:.0%}\".format(prediction[0][5]))      ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Submission","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"sample  = pd.read_csv(\"/kaggle/input/jigsaw-multilingual-toxic-comment-classification/sample_submission.csv\")\nsample.head\n# predic = []\n# for sent in x_test:/\n\n#     predic.append(predi(sent))\npredic = model.predict(processed_X_test)\noutput = pd.DataFrame({\"Id\":x_test_word.id,\"toxic\":predic[0][1]})\noutput.to_csv('my_submission.csv',index = False)\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Reporting Accuracy","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# data = { 'Loss' : hist.history['loss'],\n#         'val_loss': hist.history['val_loss'],\n#        'train_accuracy': hist.history['acc']}\n# # df = pd.read_csv(\"/output/kaggle/working/my_submissions.csv\")\n# # x_test[3]\n# print(data)\nmodel.evaluate(X,y)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predi(\"kill you\")","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}