{"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":"# 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 20GB 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","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-05-31T16:16:44.106099Z","iopub.execute_input":"2023-05-31T16:16:44.107124Z","iopub.status.idle":"2023-05-31T16:16:44.116116Z","shell.execute_reply.started":"2023-05-31T16:16:44.107081Z","shell.execute_reply":"2023-05-31T16:16:44.115069Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# installing transformers\n!pip install --upgrade transformers","metadata":{"execution":{"iopub.status.busy":"2023-05-31T16:16:44.126348Z","iopub.execute_input":"2023-05-31T16:16:44.126795Z","iopub.status.idle":"2023-05-31T16:16:49.922906Z","shell.execute_reply.started":"2023-05-31T16:16:44.126756Z","shell.execute_reply":"2023-05-31T16:16:49.921321Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#imports\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n#import seaborn as sns\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nfrom sklearn.model_selection import train_test_split\nimport tensorflow as tf\nfrom keras.preprocessing import sequence, text\nfrom tensorflow.keras.preprocessing import sequence\nfrom tensorflow.keras.models import Sequential\nimport os\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\nfrom kaggle_datasets import KaggleDatasets\nimport transformers\nfrom sklearn.metrics import roc_auc_score,roc_curve,auc\n\n\nfrom tokenizers import BertWordPieceTokenizer","metadata":{"execution":{"iopub.status.busy":"2023-05-31T16:16:49.925329Z","iopub.execute_input":"2023-05-31T16:16:49.925642Z","iopub.status.idle":"2023-05-31T16:16:49.935362Z","shell.execute_reply.started":"2023-05-31T16:16:49.925612Z","shell.execute_reply":"2023-05-31T16:16:49.934156Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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)","metadata":{"execution":{"iopub.status.busy":"2023-05-31T16:16:49.936490Z","iopub.execute_input":"2023-05-31T16:16:49.936746Z","iopub.status.idle":"2023-05-31T16:16:56.573846Z","shell.execute_reply.started":"2023-05-31T16:16:49.936723Z","shell.execute_reply":"2023-05-31T16:16:56.572686Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# LOADING THE DATA\n\ntrain1 = pd.read_csv(\"/kaggle/input/jigsaw-multilingual-toxic-comment-classification/jigsaw-toxic-comment-train.csv\")\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')\nresult = pd.read_csv('/kaggle/input/jigsaw-multilingual-toxic-comment-classification/sample_submission.csv')\nresult['toxic'].value_counts()","metadata":{"execution":{"iopub.status.busy":"2023-05-31T16:16:56.576190Z","iopub.execute_input":"2023-05-31T16:16:56.576475Z","iopub.status.idle":"2023-05-31T16:16:58.546374Z","shell.execute_reply.started":"2023-05-31T16:16:56.576448Z","shell.execute_reply":"2023-05-31T16:16:58.545255Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#function fast_encode to convert a list of texts into a sequence of integers used for BERT\ndef fast_encode(texts, tokenizer, chunk_size=256, maxlen=512):\n    \"\"\"\n    Encoder for encoding the text into sequence of integers for BERT Input\n    \"\"\"\n    tokenizer.enable_truncation(max_length=maxlen)\n    tokenizer.enable_padding(length=maxlen)\n    all_ids = []\n    \n    for i in range(0, len(texts), chunk_size):\n        text_chunk = texts[i:i+chunk_size].tolist()\n        encs = tokenizer.encode_batch(text_chunk)\n        all_ids.extend([enc.ids for enc in encs])\n    \n    return np.array(all_ids)\n    ","metadata":{"execution":{"iopub.status.busy":"2023-05-31T16:16:58.547602Z","iopub.execute_input":"2023-05-31T16:16:58.547939Z","iopub.status.idle":"2023-05-31T16:16:58.556707Z","shell.execute_reply.started":"2023-05-31T16:16:58.547911Z","shell.execute_reply":"2023-05-31T16:16:58.555586Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# DATA FOR CONFIGURATION\n\nAUTO = tf.data.experimental.AUTOTUNE\n\n\n# Configuration\nEPOCHS = 3\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\nMAX_LEN = 192","metadata":{"execution":{"iopub.status.busy":"2023-05-31T16:16:58.558015Z","iopub.execute_input":"2023-05-31T16:16:58.558332Z","iopub.status.idle":"2023-05-31T16:16:58.577479Z","shell.execute_reply.started":"2023-05-31T16:16:58.558297Z","shell.execute_reply":"2023-05-31T16:16:58.576341Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# loading the tokenizer\ntokenizer = transformers.DistilBertTokenizer.from_pretrained('distilbert-base-multilingual-cased')\n# Saving the loaded tokenizer \ntokenizer.save_pretrained('.')\n# Reloading it with the huggingface tokenizers library\nfast_tokenizer = BertWordPieceTokenizer('vocab.txt', lowercase=False)\nfast_tokenizer","metadata":{"execution":{"iopub.status.busy":"2023-05-31T16:16:58.578646Z","iopub.execute_input":"2023-05-31T16:16:58.578955Z","iopub.status.idle":"2023-05-31T16:16:59.182860Z","shell.execute_reply.started":"2023-05-31T16:16:58.578928Z","shell.execute_reply":"2023-05-31T16:16:59.181209Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# preparing the datsets for training\nx_train = fast_encode(train1.comment_text.astype(str), fast_tokenizer, maxlen=MAX_LEN)\nx_valid = fast_encode(valid.comment_text.astype(str), fast_tokenizer, maxlen=MAX_LEN)\nx_test = fast_encode(test.content.astype(str), fast_tokenizer, maxlen=MAX_LEN)\n\ny_train = train1.toxic.values\ny_valid = valid.toxic.values","metadata":{"execution":{"iopub.status.busy":"2023-05-31T16:16:59.184308Z","iopub.execute_input":"2023-05-31T16:16:59.184694Z","iopub.status.idle":"2023-05-31T16:17:24.015204Z","shell.execute_reply.started":"2023-05-31T16:16:59.184652Z","shell.execute_reply":"2023-05-31T16:17:24.013583Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#creating train_dataset as a TensorFlow Dataset object\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#creating validation_dataset as a TensorFlow Dataset object\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#creating test_dataset as a TensorFlow Dataset object\ntest_dataset = (\n    tf.data.Dataset\n    .from_tensor_slices(x_test)\n    .batch(BATCH_SIZE)\n)","metadata":{"execution":{"iopub.status.busy":"2023-05-31T16:17:24.016595Z","iopub.execute_input":"2023-05-31T16:17:24.016945Z","iopub.status.idle":"2023-05-31T16:17:24.382969Z","shell.execute_reply.started":"2023-05-31T16:17:24.016909Z","shell.execute_reply":"2023-05-31T16:17:24.381905Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n# Building the model\ndef build_model(transformer, max_len=512):\n    \"\"\"\n    function for training the BERT model\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    model.compile(Adam(lr=1e-5), loss='binary_crossentropy', metrics=['accuracy'])\n    \n    return model","metadata":{"execution":{"iopub.status.busy":"2023-05-31T16:17:24.386315Z","iopub.execute_input":"2023-05-31T16:17:24.386731Z","iopub.status.idle":"2023-05-31T16:17:24.393769Z","shell.execute_reply.started":"2023-05-31T16:17:24.386703Z","shell.execute_reply":"2023-05-31T16:17:24.392640Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\nwith strategy.scope():\n    transformer_layer = (\n        transformers.TFDistilBertModel\n        .from_pretrained('distilbert-base-multilingual-cased')\n    )\n    model = build_model(transformer_layer, max_len=MAX_LEN)\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2023-05-31T16:17:24.394833Z","iopub.execute_input":"2023-05-31T16:17:24.395160Z","iopub.status.idle":"2023-05-31T16:17:35.741043Z","shell.execute_reply.started":"2023-05-31T16:17:24.395133Z","shell.execute_reply":"2023-05-31T16:17:35.739985Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Training \nn_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)","metadata":{"execution":{"iopub.status.busy":"2023-05-31T16:17:35.742343Z","iopub.execute_input":"2023-05-31T16:17:35.742729Z","iopub.status.idle":"2023-05-31T16:25:29.964448Z","shell.execute_reply.started":"2023-05-31T16:17:35.742703Z","shell.execute_reply":"2023-05-31T16:25:29.963213Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Training on 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*2\n)","metadata":{"execution":{"iopub.status.busy":"2023-05-31T16:25:29.966126Z","iopub.execute_input":"2023-05-31T16:25:29.966441Z","iopub.status.idle":"2023-05-31T16:26:37.370361Z","shell.execute_reply.started":"2023-05-31T16:25:29.966410Z","shell.execute_reply":"2023-05-31T16:26:37.369176Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# predicting on test data set\nresult['toxic'] = model.predict(test_dataset, verbose=1)","metadata":{"execution":{"iopub.status.busy":"2023-05-31T16:26:37.372307Z","iopub.execute_input":"2023-05-31T16:26:37.372619Z","iopub.status.idle":"2023-05-31T16:26:58.304334Z","shell.execute_reply.started":"2023-05-31T16:26:37.372588Z","shell.execute_reply":"2023-05-31T16:26:58.303140Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Function to calculate roc_suc score and return fpr, tpr for plotting\ndef calculate_roc_auc(predictions,target):\n    '''\n    This methods returns the AUC Score, fpr,tpr when given the Predictions\n    and Labels\n    '''\n    \n    fpr, tpr, thresholds = roc_curve(target, predictions)\n    roc_auc = auc(fpr, tpr)\n    return roc_auc,fpr,tpr","metadata":{"execution":{"iopub.status.busy":"2023-05-31T16:26:58.305640Z","iopub.execute_input":"2023-05-31T16:26:58.305986Z","iopub.status.idle":"2023-05-31T16:26:58.311857Z","shell.execute_reply.started":"2023-05-31T16:26:58.305955Z","shell.execute_reply":"2023-05-31T16:26:58.310804Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# predicting on validation set\nscores = model.predict(x_valid)\n# calling roc_auc function\nroc_auc,fpr,tpr = calculate_roc_auc(scores,y_valid)\nprint(\"Roc_Auc: %.2f%%\" % (roc_auc))","metadata":{"execution":{"iopub.status.busy":"2023-05-31T16:26:58.313059Z","iopub.execute_input":"2023-05-31T16:26:58.313423Z","iopub.status.idle":"2023-05-31T16:27:05.869830Z","shell.execute_reply.started":"2023-05-31T16:26:58.313380Z","shell.execute_reply":"2023-05-31T16:27:05.868365Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Plot ROC curve\nplt.plot(fpr, tpr, label='ROC curve (area = %0.2f)' % roc_auc)\nplt.plot([0, 1], [0, 1], 'k--')\nplt.xlim([0.0, 1.0])\nplt.ylim([0.0, 1.05])\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.title('Receiver Operating Characteristic (ROC) Curve')\nplt.legend(loc=\"lower right\",fontsize=10)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-05-31T16:27:05.871249Z","iopub.execute_input":"2023-05-31T16:27:05.871646Z","iopub.status.idle":"2023-05-31T16:27:06.193067Z","shell.execute_reply.started":"2023-05-31T16:27:05.871612Z","shell.execute_reply":"2023-05-31T16:27:06.192001Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"result['toxic'].value_counts()","metadata":{"execution":{"iopub.status.busy":"2023-05-31T16:27:06.194498Z","iopub.execute_input":"2023-05-31T16:27:06.194818Z","iopub.status.idle":"2023-05-31T16:27:06.205387Z","shell.execute_reply.started":"2023-05-31T16:27:06.194791Z","shell.execute_reply":"2023-05-31T16:27:06.204406Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#printing first 10 observation output\nresult['toxic'][:10]","metadata":{"execution":{"iopub.status.busy":"2023-05-31T16:27:06.206527Z","iopub.execute_input":"2023-05-31T16:27:06.206914Z","iopub.status.idle":"2023-05-31T16:27:06.221387Z","shell.execute_reply.started":"2023-05-31T16:27:06.206872Z","shell.execute_reply":"2023-05-31T16:27:06.220251Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"result.to_csv('submission.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2023-05-31T16:27:06.222553Z","iopub.execute_input":"2023-05-31T16:27:06.222885Z","iopub.status.idle":"2023-05-31T16:27:06.383110Z","shell.execute_reply.started":"2023-05-31T16:27:06.222846Z","shell.execute_reply":"2023-05-31T16:27:06.381876Z"},"trusted":true},"execution_count":null,"outputs":[]}]}