{"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_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"from tqdm.notebook import tqdm_notebook\ntqdm_notebook.pandas()","metadata":{"execution":{"iopub.status.busy":"2022-07-24T15:50:15.863220Z","iopub.execute_input":"2022-07-24T15:50:15.863780Z","iopub.status.idle":"2022-07-24T15:50:15.946920Z","shell.execute_reply.started":"2022-07-24T15:50:15.863660Z","shell.execute_reply":"2022-07-24T15:50:15.946168Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#print multiple statments in same line\nfrom IPython.core.interactiveshell import InteractiveShell\nInteractiveShell.ast_node_interactivity = 'all'","metadata":{"execution":{"iopub.status.busy":"2022-07-24T15:50:15.977453Z","iopub.execute_input":"2022-07-24T15:50:15.977732Z","iopub.status.idle":"2022-07-24T15:50:15.981809Z","shell.execute_reply.started":"2022-07-24T15:50:15.977696Z","shell.execute_reply":"2022-07-24T15:50:15.981039Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\n\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport re\n\nimport html\n\n# pre process data\ndef preprocess_text(sen):\n# Convert html entities to normal\n    sentence = html.unescape(sen)\n\n# Remove html tags\n    sentence = remove_tags(sentence)\n\n# Remove newline chars\n    sentence = remove_newlinechars(sentence)\n\n# Remove punctuations and numbers\n    sentence = re.sub('[^a-zA-Z]', ' ', sentence)\n\n# Convert to lowercase\n    sentence = sentence.lower()\n    return sentence\n\ndef remove_newlinechars(text):\n    return \" \".join(text.splitlines()) \n\ndef remove_tags(text):\n    TAG_RE = re.compile(r'<[^>]+>')\n    return TAG_RE.sub('', text)","metadata":{"execution":{"iopub.status.busy":"2022-07-24T15:50:16.122411Z","iopub.execute_input":"2022-07-24T15:50:16.123157Z","iopub.status.idle":"2022-07-24T15:50:16.829339Z","shell.execute_reply.started":"2022-07-24T15:50:16.123126Z","shell.execute_reply":"2022-07-24T15:50:16.828712Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train1 = pd.read_csv(\"/kaggle/input/jigsaw-multilingual-toxic-comment-classification/jigsaw-toxic-comment-train.csv\")\ntrain2 = pd.read_csv(\"/kaggle/input/jigsaw-multilingual-toxic-comment-classification/jigsaw-unintended-bias-train.csv\")\ntrain2.toxic = train2.toxic.round().astype(int)\n\nvalid = pd.read_csv('/kaggle/input/jigsaw-multilingual-toxic-comment-classification/validation.csv')\ntest = pd.read_csv('/kaggle/input/jigsaw-multilingual-toxic-comment-classification/test.csv')\nsub = pd.read_csv('/kaggle/input/jigsaw-multilingual-toxic-comment-classification/sample_submission.csv')\nsubmission = pd.read_csv('/kaggle/input/jigsaw-multilingual-toxic-comment-classification/sample_submission.csv')\n\n\n","metadata":{"execution":{"iopub.status.busy":"2022-07-24T15:55:15.857674Z","iopub.execute_input":"2022-07-24T15:55:15.857936Z","iopub.status.idle":"2022-07-24T15:55:42.392103Z","shell.execute_reply.started":"2022-07-24T15:55:15.857913Z","shell.execute_reply":"2022-07-24T15:55:42.391301Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('train1.shape : ', train1.shape)\nprint('train2.shape : ', train2.shape)\nprint('valid.shape : ', valid.shape)\nprint('test.shape : ', test.shape)\nprint('sub.shape : ', sub.shape)\nprint('submission.shape : ', submission.shape)","metadata":{"execution":{"iopub.status.busy":"2022-07-24T15:55:47.108070Z","iopub.execute_input":"2022-07-24T15:55:47.108390Z","iopub.status.idle":"2022-07-24T15:55:47.115603Z","shell.execute_reply.started":"2022-07-24T15:55:47.108358Z","shell.execute_reply":"2022-07-24T15:55:47.114657Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Combine train1 with a subset of train2\n# take only 5k records of both type to make data balaenced and also to downsize.\ntrain = pd.concat([\n    train1[['comment_text', 'toxic']].query('toxic==0').sample(n=5000, random_state=0),\n    train1[['comment_text', 'toxic']].query('toxic==1').sample(n=5000, random_state=0),\n    train2[['comment_text', 'toxic']].query('toxic==0').sample(n=5000, random_state=0),\n    train2[['comment_text', 'toxic']].query('toxic==1').sample(n=5000, random_state=0)\n])","metadata":{"execution":{"iopub.status.busy":"2022-07-24T15:58:09.392024Z","iopub.execute_input":"2022-07-24T15:58:09.393121Z","iopub.status.idle":"2022-07-24T15:58:10.097428Z","shell.execute_reply.started":"2022-07-24T15:58:09.393062Z","shell.execute_reply":"2022-07-24T15:58:10.096457Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('train.shape : ', train.shape)","metadata":{"execution":{"iopub.status.busy":"2022-07-24T15:58:17.272983Z","iopub.execute_input":"2022-07-24T15:58:17.273692Z","iopub.status.idle":"2022-07-24T15:58:17.280093Z","shell.execute_reply.started":"2022-07-24T15:58:17.273636Z","shell.execute_reply":"2022-07-24T15:58:17.279333Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.toxic.value_counts()","metadata":{"execution":{"iopub.status.busy":"2022-07-24T15:58:45.762943Z","iopub.execute_input":"2022-07-24T15:58:45.763270Z","iopub.status.idle":"2022-07-24T15:58:45.776324Z","shell.execute_reply.started":"2022-07-24T15:58:45.763231Z","shell.execute_reply":"2022-07-24T15:58:45.775479Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.head(2)\nvalid.head(2)\ntest.head(2)\nsub.head(2)\nsubmission.head(2)","metadata":{"execution":{"iopub.status.busy":"2022-07-24T15:59:23.579142Z","iopub.execute_input":"2022-07-24T15:59:23.579524Z","iopub.status.idle":"2022-07-24T15:59:23.623735Z","shell.execute_reply.started":"2022-07-24T15:59:23.579422Z","shell.execute_reply":"2022-07-24T15:59:23.622856Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('train data types \\n', train.dtypes)\nprint('test data types \\n', test.dtypes)\nprint('valid data types \\n', valid.dtypes)\nprint('sub data types \\n', sub.dtypes)","metadata":{"execution":{"iopub.status.busy":"2022-07-24T16:02:22.564353Z","iopub.execute_input":"2022-07-24T16:02:22.564949Z","iopub.status.idle":"2022-07-24T16:02:22.579070Z","shell.execute_reply.started":"2022-07-24T16:02:22.564891Z","shell.execute_reply":"2022-07-24T16:02:22.578072Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# clean the data for processing\ntrain['comment_text'] = train['comment_text'].apply(preprocess_text)\nvalid['comment_text'] = valid['comment_text'].apply(preprocess_text)\ntest['content'] = test['content'].apply(preprocess_text)","metadata":{"execution":{"iopub.status.busy":"2022-07-24T16:10:22.969305Z","iopub.execute_input":"2022-07-24T16:10:22.970144Z","iopub.status.idle":"2022-07-24T16:10:27.869054Z","shell.execute_reply.started":"2022-07-24T16:10:22.970101Z","shell.execute_reply":"2022-07-24T16:10:27.868151Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# check the dataset after cleaning \ntrain.head(2)\nprint('\\n')\nvalid.head(2)\nprint('\\n')\ntest.head(2)","metadata":{"execution":{"iopub.status.busy":"2022-07-24T16:10:32.029256Z","iopub.execute_input":"2022-07-24T16:10:32.030103Z","iopub.status.idle":"2022-07-24T16:10:32.054438Z","shell.execute_reply.started":"2022-07-24T16:10:32.030050Z","shell.execute_reply":"2022-07-24T16:10:32.053901Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_train = train.toxic.values\ny_valid = valid.toxic.values\n\n# check datatype of y_train, y_test\nprint ( 'dtype y_train ', type(y_train) )\nprint ( 'dtype y_valid ', type(y_valid) )","metadata":{"execution":{"iopub.status.busy":"2022-07-24T16:17:40.505154Z","iopub.execute_input":"2022-07-24T16:17:40.505881Z","iopub.status.idle":"2022-07-24T16:17:40.512053Z","shell.execute_reply.started":"2022-07-24T16:17:40.505838Z","shell.execute_reply":"2022-07-24T16:17:40.511317Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras.layers import Dense, Input\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.models import Model\nfrom tensorflow.keras.callbacks import ModelCheckpoint\n\nfrom kaggle_datasets import KaggleDatasets\n\nimport transformers\nfrom transformers import TFAutoModel, AutoTokenizer\n\nfrom tokenizers import Tokenizer, models, pre_tokenizers, decoders, processors","metadata":{"execution":{"iopub.status.busy":"2022-07-24T16:30:33.534548Z","iopub.execute_input":"2022-07-24T16:30:33.534880Z","iopub.status.idle":"2022-07-24T16:30:40.673454Z","shell.execute_reply.started":"2022-07-24T16:30:33.534846Z","shell.execute_reply":"2022-07-24T16:30:40.672750Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"try:\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)","metadata":{"execution":{"iopub.status.busy":"2022-07-24T16:32:38.344707Z","iopub.execute_input":"2022-07-24T16:32:38.345440Z","iopub.status.idle":"2022-07-24T16:32:44.645849Z","shell.execute_reply.started":"2022-07-24T16:32:38.345401Z","shell.execute_reply":"2022-07-24T16:32:44.644998Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Configuration\nEPOCHS = 2\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\nMAX_LEN = 275\nMODEL = 'jplu/tf-xlm-roberta-large'","metadata":{"execution":{"iopub.status.busy":"2022-07-24T16:33:20.694269Z","iopub.execute_input":"2022-07-24T16:33:20.694548Z","iopub.status.idle":"2022-07-24T16:33:20.699198Z","shell.execute_reply.started":"2022-07-24T16:33:20.694520Z","shell.execute_reply":"2022-07-24T16:33:20.698439Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# load the real tokenizer\ntokenizer = AutoTokenizer.from_pretrained(MODEL)","metadata":{"execution":{"iopub.status.busy":"2022-07-24T16:33:29.284379Z","iopub.execute_input":"2022-07-24T16:33:29.284637Z","iopub.status.idle":"2022-07-24T16:33:32.956643Z","shell.execute_reply.started":"2022-07-24T16:33:29.284596Z","shell.execute_reply":"2022-07-24T16:33:32.955795Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def regular_encode(texts, tokenizer, maxlen):\n    enc_di = tokenizer.batch_encode_plus(\n        texts.tolist(), \n        return_token_type_ids=False,\n        pad_to_max_length=True,\n        max_length=maxlen\n    )\n    \n    return np.array(enc_di['input_ids'])","metadata":{"execution":{"iopub.status.busy":"2022-07-24T16:36:45.809021Z","iopub.execute_input":"2022-07-24T16:36:45.809277Z","iopub.status.idle":"2022-07-24T16:36:45.814544Z","shell.execute_reply.started":"2022-07-24T16:36:45.809252Z","shell.execute_reply":"2022-07-24T16:36:45.813717Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# prepare features for the train validation and test data\nx_train = regular_encode(train.comment_text.values, tokenizer, maxlen=MAX_LEN)\nx_valid = regular_encode(valid.comment_text.values, tokenizer, maxlen=MAX_LEN)\nx_test = regular_encode(test.content.values, tokenizer, maxlen=MAX_LEN)","metadata":{"execution":{"iopub.status.busy":"2022-07-24T16:37:39.100734Z","iopub.execute_input":"2022-07-24T16:37:39.101004Z","iopub.status.idle":"2022-07-24T16:38:00.717173Z","shell.execute_reply.started":"2022-07-24T16:37:39.100977Z","shell.execute_reply":"2022-07-24T16:38:00.716460Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create the model to train\ndef build_model(transformer, max_len):\n    \"\"\"\n    https://www.kaggle.com/xhlulu/jigsaw-tpu-distilbert-with-huggingface-and-keras\n    \"\"\"\n    input_word_ids = Input(shape=(max_len,), dtype=tf.int32, name=\"input_word_ids\")\n    sequence_output = transformer(input_word_ids)[0]\n    cls_token = sequence_output[:, 0, :]\n    out = Dense(1, activation='sigmoid')(cls_token)\n    \n    model = Model(inputs=input_word_ids, outputs=out)\n    \n    # optimizer, loss, metrics then compile\n    model.compile(Adam(lr=1e-5), loss='binary_crossentropy', metrics=['accuracy'])\n    \n    return model","metadata":{"execution":{"iopub.status.busy":"2022-07-24T16:41:19.233121Z","iopub.execute_input":"2022-07-24T16:41:19.235112Z","iopub.status.idle":"2022-07-24T16:41:19.241730Z","shell.execute_reply.started":"2022-07-24T16:41:19.235065Z","shell.execute_reply":"2022-07-24T16:41:19.241223Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"AUTO = tf.data.experimental.AUTOTUNE\n\n# instantiate the model\nwith strategy.scope():\n    transformer_layer = TFAutoModel.from_pretrained(MODEL)\n    model = build_model(transformer_layer, max_len=MAX_LEN)\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2022-07-24T16:41:44.194296Z","iopub.execute_input":"2022-07-24T16:41:44.194591Z","iopub.status.idle":"2022-07-24T16:43:55.449388Z","shell.execute_reply.started":"2022-07-24T16:41:44.194559Z","shell.execute_reply":"2022-07-24T16:43:55.448560Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras import callbacks","metadata":{"execution":{"iopub.status.busy":"2022-07-24T17:00:10.444172Z","iopub.execute_input":"2022-07-24T17:00:10.444986Z","iopub.status.idle":"2022-07-24T17:00:10.448752Z","shell.execute_reply.started":"2022-07-24T17:00:10.444950Z","shell.execute_reply":"2022-07-24T17:00:10.447900Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# checkpoint\ndef callback():\n    cb = []\n    \"\"\"\n    Model-Checkpoint\n    \"\"\"\n    checkpoint = callbacks.ModelCheckpoint('model.h5',\n                                       save_best_only=True, \n                                       mode='min',\n                                       monitor='val_loss', #  \n                                       save_weights_only=True, verbose=0)\n\n    cb.append(checkpoint)\n    \n    # Callback that streams epoch results to a csv file.\n    log = callbacks.CSVLogger('log.csv')\n    cb.append(log)\n\n    return cb","metadata":{"execution":{"iopub.status.busy":"2022-07-24T16:57:48.758248Z","iopub.execute_input":"2022-07-24T16:57:48.758757Z","iopub.status.idle":"2022-07-24T16:57:48.764190Z","shell.execute_reply.started":"2022-07-24T16:57:48.758717Z","shell.execute_reply":"2022-07-24T16:57:48.763440Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# build thedataset compatible for the model to run\n\ntrain_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)","metadata":{"execution":{"iopub.status.busy":"2022-07-24T16:55:18.478674Z","iopub.execute_input":"2022-07-24T16:55:18.479430Z","iopub.status.idle":"2022-07-24T16:55:19.073716Z","shell.execute_reply.started":"2022-07-24T16:55:18.479393Z","shell.execute_reply":"2022-07-24T16:55:19.072820Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"calls = callback()\nn_steps = x_train.shape[0] // BATCH_SIZE\n\ntrain_history = model.fit(\n    train_dataset,\n    steps_per_epoch=n_steps,\n    validation_data=valid_dataset,\n    callbacks = calls,\n    epochs=4 # lets take 4 epochs but can also use variable EPOCHS defined in configration above\n )","metadata":{"execution":{"iopub.status.busy":"2022-07-24T17:00:16.413293Z","iopub.execute_input":"2022-07-24T17:00:16.413594Z","iopub.status.idle":"2022-07-24T17:09:12.593753Z","shell.execute_reply.started":"2022-07-24T17:00:16.413552Z","shell.execute_reply":"2022-07-24T17:09:12.592933Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# lets also train the model on remaining validation set\nn_steps = x_valid.shape[0] // BATCH_SIZE\ntrain_history_2 = model.fit(\n    valid_dataset.repeat(),\n    steps_per_epoch=n_steps,\n    epochs=EPOCHS\n)","metadata":{"execution":{"iopub.status.busy":"2022-07-24T17:11:19.019705Z","iopub.execute_input":"2022-07-24T17:11:19.020392Z","iopub.status.idle":"2022-07-24T17:13:46.807501Z","shell.execute_reply.started":"2022-07-24T17:11:19.020344Z","shell.execute_reply":"2022-07-24T17:13:46.806604Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('sub columns : ', sub.columns, '\\n')\nprint('submission columns : ', submission.columns, '\\n')","metadata":{"execution":{"iopub.status.busy":"2022-07-24T17:21:45.979558Z","iopub.execute_input":"2022-07-24T17:21:45.980520Z","iopub.status.idle":"2022-07-24T17:21:45.987487Z","shell.execute_reply.started":"2022-07-24T17:21:45.980477Z","shell.execute_reply":"2022-07-24T17:21:45.986488Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('sub Shape :', sub.shape)\nprint('test Shape :', test.shape)","metadata":{"execution":{"iopub.status.busy":"2022-07-24T17:24:42.915003Z","iopub.execute_input":"2022-07-24T17:24:42.915331Z","iopub.status.idle":"2022-07-24T17:24:42.921328Z","shell.execute_reply.started":"2022-07-24T17:24:42.915297Z","shell.execute_reply":"2022-07-24T17:24:42.920376Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# make prediction\nsub['toxic'] = model.predict(test_dataset, verbose=1)\n\n# create the submission dataset and file\nsubmission =sub[['id', 'toxic']]\n\n\n#Submission\nsubmission.to_csv('submission.csv',index=False)","metadata":{"execution":{"iopub.status.busy":"2022-07-24T17:26:29.565462Z","iopub.execute_input":"2022-07-24T17:26:29.566200Z","iopub.status.idle":"2022-07-24T17:27:57.157179Z","shell.execute_reply.started":"2022-07-24T17:26:29.566162Z","shell.execute_reply":"2022-07-24T17:27:57.156438Z"},"trusted":true},"execution_count":null,"outputs":[]}]}