{"cells":[{"metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","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":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nfrom nltk.corpus import stopwords\nfrom nltk.stem.porter import PorterStemmer\nimport codecs\nfrom tqdm import tqdm\n\nfrom nltk.tokenize import RegexpTokenizer\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing import sequence\nimport keras\nfrom keras.models import Sequential, Model\nfrom keras.layers import Dense, Conv1D, Conv2D, MaxPooling1D, GlobalMaxPool1D, Bidirectional, GlobalMaxPooling1D\nfrom keras.layers import LSTM, GRU, Dropout , BatchNormalization, Embedding, Flatten, GlobalAveragePooling1D, concatenate, Input\n!pip install 'keras_tqdm'\nfrom keras_tqdm import TQDMNotebookCallback\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.layers import Dense, Input, LSTM, Embedding, Dropout,Conv1D,Flatten,Concatenate\nfrom keras.models import Model\nfrom keras import optimizers\nfrom keras.callbacks import ModelCheckpoint\nfrom sklearn.metrics import accuracy_score\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df = pd.read_csv('../input/jigsaw-multilingual-toxic-comment-classification/jigsaw-toxic-comment-train.csv')\ntest = pd.read_csv('../input/jigsaw-multilingual-toxic-comment-classification/test.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import nltk\nnltk.download('stopwords')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sentences_train = df[\"comment_text\"].fillna(\"_na_\").values\nclasses = [\"toxic\", \"severe_toxic\", \"obscene\", \"threat\", \"insult\", \"identity_hate\"]\ny = df[classes].values\nsentences_test = test[\"content\"].fillna(\"_na_\").values","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Embedding parameter set\nembed_size = 100 # how big is each word vector\nmax_features = 20000 # how many unique words to use (i.e num rows in embedding vector)\nmaxlen = 50 # max number of words in a comment to use","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"tokenizer = Tokenizer(num_words=max_features)\ntokenizer.fit_on_texts(list(sentences_train))\ntokens_train = tokenizer.texts_to_sequences(sentences_train)\ntokens_test = tokenizer.texts_to_sequences(sentences_test)\nX_train = pad_sequences(tokens_train, maxlen=maxlen)\nX_test = pad_sequences(tokens_test, maxlen=maxlen)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"inp = Input(shape=(maxlen,))\nx = Embedding(max_features, embed_size)(inp)\nx = LSTM(4, return_sequences=True, dropout=0.2, recurrent_dropout=0.1)(x)\nx = Conv1D(16,4,activation='relu')(x)\nx = Flatten()(x)\nx = Dense(100, activation=\"relu\")(x)\nx = Dropout(0.1)(x)\nx = Dense(6, activation=\"sigmoid\")(x)\nmodel = Model(inputs=inp, outputs=x)\nmodel.compile(loss='binary_crossentropy', optimizer=optimizers.rmsprop(lr = 0.001,decay = 1e-06), metrics=['accuracy'])\nfilepath=\"toxic_comment/weights-improvement.hdf5\"\ncheckpoint = ModelCheckpoint(filepath, monitor='val_acc', verbose=1, save_best_only=True, mode='max')\ncallbacks_list = [checkpoint]\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.fit(X_train, y, batch_size=32, epochs=5,callbacks=callbacks_list, verbose=1, validation_split=0.2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_test=model.predict(X_test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample_submission=pd.read_csv(\"../input/jigsaw-multilingual-toxic-comment-classification/sample_submission.csv\")\nsample_submission[classes]=y_test\nsample_submission.to_csv(\"submission.csv\",index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.models import model_from_json\nimport os\nmodel_json = model.to_json()\nwith open(\"model.json\", \"w\") as json_file:\n    json_file.write(model_json)\n# serialize weights to HDF5\nmodel.save_weights(\"model.h5\")\nprint(\"Saved model to disk\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# # load json and create model\n# json_file = open('model.json', 'r')\n# loaded_model_json = json_file.read()\n# json_file.close()\n# loaded_model = model_from_json(loaded_model_json)\n# # load weights into new model\n# loaded_model.load_weights(\"model.h5\")\n# print(\"Loaded model from disk\")","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.6.5"}},"nbformat":4,"nbformat_minor":4}