{"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 5GB 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":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd \nfrom sklearn.model_selection import train_test_split\nimport tensorflow as tf\nimport tensorflow.keras as keras\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import LSTM\nfrom tensorflow.keras.layers import Dense, Activation, Dropout\nfrom tensorflow.keras.layers import Embedding,Bidirectional\nfrom sklearn import preprocessing \nfrom tensorflow.keras.layers import Bidirectional\nfrom tensorflow.keras.preprocessing import sequence, text\nimport os\nfrom nltk.corpus import stopwords\nimport re\nimport warnings\nwarnings.filterwarnings('ignore')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train = pd.read_csv('/kaggle/input/jigsaw-multilingual-toxic-comment-classification/jigsaw-toxic-comment-train.csv')\nvalidation = pd.read_csv('/kaggle/input/jigsaw-multilingual-toxic-comment-classification/validation.csv')\ntrain.drop(['id', 'severe_toxic', 'obscene', 'threat', 'insult', 'identity_hate'], axis=1, inplace=True)\ntrain.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"stop_words = set(stopwords.words('english'))\n\ndef data_text_preprocess(total_text, ind, col):\n    # Remove int values from text data as that might not be imp\n    if type(total_text) is not int:\n        string = \"\"\n        # replacing all special char with space\n        total_text = re.sub('[^a-zA-Z0-9\\n]', ' ', str(total_text))\n        # replacing multiple spaces with single space\n        total_text = re.sub('\\s+',' ', str(total_text))\n        # bring whole text to same lower-case scale.\n        total_text = total_text.lower()\n        \n        \n        for word in total_text.split():\n        # if the word is a not a stop word then retain that word from text\n            if not word in stop_words:\n                string += word + \" \"\n        \n        train[col][ind] = string\n        \nfor index, row in train.iterrows():\n    if type(row['comment_text']) is str:\n        data_text_preprocess(row['comment_text'], index, 'comment_text')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"xtrain, xvalid, ytrain, yvalid = train_test_split( train.comment_text.values, train.toxic.values, \n                                                   stratify=train.toxic.values, \n                                                   random_state=42, \n                                                   test_size=0.2, shuffle=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"token = text.Tokenizer(num_words=None)\ntoken.fit_on_texts(list(xtrain) + list(xvalid))\nxtrain_seq = token.texts_to_sequences(xtrain)\nxvalid_seq = token.texts_to_sequences(xvalid)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"max_len = 100\nxtrain_pad = sequence.pad_sequences(xtrain_seq, maxlen=max_len)\nxvalid_pad = sequence.pad_sequences(xvalid_seq, maxlen=max_len)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"xtrain_pad[200]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"word_index = token.word_index","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Sequential()\nmodel.add(Embedding(len(word_index) + 1,256,input_length=max_len))\nmodel.add(Bidirectional(LSTM(64)))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(1, activation='sigmoid'))\n    \nmodel.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])\n   ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%time model.fit(xtrain_pad, ytrain, epochs=2, batch_size = 128, validation_data=(xvalid_pad, yvalid))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"scores = model.predict(xvalid_pad)\n\ntest_loss, test_acc = model.evaluate(scores,  yvalid, verbose=1)\nprint('\\nTest accuracy:', test_acc)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test = pd.read_csv('/kaggle/input/jigsaw-multilingual-toxic-comment-classification/test.csv')\ntest.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def data_text_preprocess(total_text, ind, col):\n    # Remove int values from text data as that might not be imp\n    if type(total_text) is not int:\n        string = \"\"\n        # replacing all special char with space\n        total_text = re.sub('[^a-zA-Z0-9\\n]', ' ', str(total_text))\n        # replacing multiple spaces with single space\n        total_text = re.sub('\\s+',' ', str(total_text))\n        # bring whole text to same lower-case scale.\n        total_text = total_text.lower()\n        \n        \n        for word in total_text.split():\n        # if the word is a not a stop word then retain that word from text\n            if not word in stop_words:\n                string += word + \" \"\n        \n        test[col][ind] = string\n        \nfor index, row in test.iterrows():\n    if type(row['content']) is str:\n        data_text_preprocess(row['content'], index, 'content')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_data = token.texts_to_sequences(test.content)\ntest_data_seq = sequence.pad_sequences(test_data, maxlen=max_len)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test['toxic'] = model.predict(test_data_seq, verbose=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test[['id', 'toxic']].to_csv('submission.csv', index=False)","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}