{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Getting Started with the competition","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"This notebook is an introduction to the ongoing Jigsaw Multilingual Toxic Comment Challenge. The challenge contains of comments from previous two competitions of Jigsaw Toxic comment classification. The train dataset contains of comments in English whereas validation and test set contain of comments in different languages. The task is to predict whether the comment is toxic or not.\nWe will be using DistilBert along with Keras for this competition since it is faster than BERT and performance is roughly the same as that of BERT. \n\nRead following articles to get a headstart about Bert and how it works:\n* http://jalammar.github.io/a-visual-guide-to-using-bert-for-the-first-time/\n* https://stackabuse.com/text-classification-with-bert-tokenizer-and-tf-2-0-in-python/\n\nHuggingFace has an awesome documentation. Do read the documentation to understand various concepts and code below.\n* https://huggingface.co/transformers/quickstart.html\n\n**Acknowledgements**\n* https://www.kaggle.com/xhlulu/jigsaw-tpu-distilbert-with-huggingface-and-keras\n* https://www.kaggle.com/tanulsingh077/deep-learning-for-nlp-zero-to-transformers-bert (Do give this notebook a read as @Mr_KnowNothing has curated a list of amazing articles and tutorials for anyone who is getting started with NLP and his notebook has given me the headstart to this competition.)","execution_count":null},{"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":{"trusted":true},"cell_type":"code","source":"import transformers\nfrom tokenizers import BertWordPieceTokenizer\nimport tensorflow as tf\nfrom tqdm import tqdm\nfrom tensorflow.keras.optimizers import Adam","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# TPU Config","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"For understanding TPU refer to following links:\n* https://www.tensorflow.org/guide/tpu\n* https://www.tensorflow.org/api_docs/python/tf/distribute/experimental/TPUStrategy\n* https://www.tensorflow.org/guide/data_performance\n","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":" #Detect hardware, return appropriate distribution strategy\ntry:\n    # TPU detection. No parameters necessary if TPU_NAME environment variable is\n    # set: this is always the case on Kaggle.\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n    print('Running on TPU ', tpu.master())\nexcept ValueError:\n    tpu = None\n\nif tpu:\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.experimental.TPUStrategy(tpu)\nelse:\n    # Default distribution strategy in Tensorflow. Works on CPU and single GPU.\n    strategy = tf.distribute.get_strategy()\n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#IMP DATA FOR CONFIG\n\nAUTO = tf.data.experimental.AUTOTUNE\n\n\n# Configuration\nEPOCHS = 3\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\nMAX_LEN = 192","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def fast_encode(texts, tokenizer, chunk_size=256, maxlen=512):\n    '''\n    Function for fast encoding\n    '''\n    all_ids = []\n    for i in tqdm(range(0, len(texts), chunk_size)):\n        text_chunk = list(texts[i:chunk_size+i])\n        encs = tokenizer.batch_encode_plus(text_chunk, max_length=maxlen, pad_to_max_length = True)\n        all_ids.extend(encs['input_ids'])\n        \n    return np.array(all_ids)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train = pd.read_csv('../input/jigsaw-multilingual-toxic-comment-classification/jigsaw-toxic-comment-train.csv')\nvalidation = pd.read_csv('../input/jigsaw-multilingual-toxic-comment-classification/validation.csv')\ntest = pd.read_csv('../input/jigsaw-multilingual-toxic-comment-classification/test.csv')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Tokenization","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# Refer the HuggingFace Documention\nfast_tokenizer = transformers.DistilBertTokenizerFast.from_pretrained('distilbert-base-multilingual-cased')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_train = fast_encode(train.comment_text.astype(str), fast_tokenizer, maxlen=MAX_LEN)\nx_valid = fast_encode(validation.comment_text.astype(str), fast_tokenizer, maxlen=MAX_LEN)\nx_test = fast_encode(test.content.astype(str), fast_tokenizer, maxlen=MAX_LEN)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_train = train.toxic.values\ny_valid = validation.toxic.values","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Creating Data Objects\n\nTo understand how to create the data objects refer to the links provided under TPU config section","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"train_dataset = (\n    tf.data.Dataset\n    .from_tensor_slices((x_train,y_train))\n    .repeat()\n    .shuffle(2048)\n    .batch(BATCH_SIZE)\n    .prefetch(AUTO)\n)\n\nvalid_dataset = (\n    tf.data.Dataset\n    .from_tensor_slices((x_valid,y_valid))\n    .batch(BATCH_SIZE)\n    .cache()\n    .prefetch(AUTO)\n)\n\ntest_dataset = (\n    tf.data.Dataset\n    .from_tensor_slices(x_test)\n    .batch(BATCH_SIZE)\n)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Building the model to start the training","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def build_model(transformer, maxlen=512):\n    input_word_ids = tf.keras.layers.Input(shape=(maxlen,), dtype=tf.int32, name='input_word_ids')\n    sequence_output = transformer(input_word_ids)[0]\n    \n    clf_output = sequence_output[:,0,:]\n    out = tf.keras.layers.Dense(1, activation='sigmoid')(clf_output)\n    \n    model = tf.keras.models.Model(inputs = input_word_ids, outputs=out)\n    model.compile(Adam(lr=1e-5), loss='binary_crossentropy', metrics=['accuracy'])\n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with strategy.scope():\n    transformer_layer = (\n        transformers.TFDistilBertModel\n        .from_pretrained('distilbert-base-multilingual-cased')\n    )\n    model = build_model(transformer_layer, maxlen=MAX_LEN)\n    \nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Training on English Data","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"n_steps = x_train.shape[0]//BATCH_SIZE\ntrain_history = model.fit(\n    train_dataset,\n    steps_per_epoch = n_steps,\n    validation_data = valid_dataset,\n    epochs = EPOCHS\n)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Since we have trained the model on training data, now we will train the model on validation data because it contains comments in different languages.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"n_steps_valid = x_valid.shape[0]//BATCH_SIZE\nvalid_history = model.fit(\n    valid_dataset.repeat(),\n    steps_per_epoch = n_steps_valid,\n    epochs = EPOCHS*2\n)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Predicting the results","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"sub = pd.read_csv('../input/jigsaw-multilingual-toxic-comment-classification/sample_submission.csv')\nsub['toxic'] = model.predict(test_dataset, verbose=1)\nsub.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}