{"cells":[{"metadata":{"trusted":true},"cell_type":"code","source":"import re\nimport  numpy as np\nimport pandas as pd\nimport tensorflow as tf\n\nimport transformers\n\nimport matplotlib.pyplot as plt\n\nfrom tqdm import tqdm\ntqdm.pandas()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"try:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n    print('Running on TPU: ', tpu.master())\n    \nexcept Exception as e:\n    tpu = None\n    \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)\n    \nelse:\n    strategy = tf.distribute.get_strategy()\n    \nprint('Number of clusters: ', strategy.num_replicas_in_sync)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data = pd.read_csv('/kaggle/input/jigsaw-multilingual-toxic-comment-classification/jigsaw-toxic-comment-train.csv')\n# data = data.sample(80000)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_data = pd.read_csv('/kaggle/input/jigsaw-multilingual-toxic-comment-classification/test.csv')\ntest_data.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"valid_data = pd.read_csv('/kaggle/input/jigsaw-multilingual-toxic-comment-classification/validation.csv')\nvalid_data.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"contractions_dict = {     \n\"ain't\": \"am not\",\n\"aren't\": \"are not\",\n\"can't\": \"cannot\",\n\"can't've\": \"cannot have\",\n\"'cause\": \"because\",\n\"could've\": \"could have\",\n\"couldn't\": \"could not\",\n\"couldn't've\": \"could not have\",\n\"didn't\": \"did not\",\n\"doesn't\": \"does not\",\n\"don't\": \"do not\",\n\"hadn't\": \"had not\",\n\"hadn't've\": \"had not have\",\n\"hasn't\": \"has not\",\n\"haven't\": \"have not\",\n\"he'd\": \"he had\",\n\"he'd've\": \"he would have\",\n\"he'll\": \"he will\",\n\"he'll've\": \"he will have\",\n\"he's\": \"he is\",\n\"how'd\": \"how did\",\n\"how'd'y\": \"how do you\",\n\"how'll\": \"how will\",\n\"how's\": \"how is\",\n\"I'd\": \"I had\",\n\"I'd've\": \"I would have\",\n\"I'll\": \"I will\",\n\"I'll've\": \"I will have\",\n\"I'm\": \"I am\",\n\"I've\": \"I have\",\n\"isn't\": \"is not\",\n\"it'd\": \"it had\",\n\"it'd've\": \"it would have\",\n\"it'll\": \"it will\",\n\"it'll've\": \"iit will have\",\n\"it's\": \"it is\",\n\"let's\": \"let us\",\n\"ma'am\": \"madam\",\n\"mayn't\": \"may not\",\n\"might've\": \"might have\",\n\"mightn't\": \"might not\",\n\"mightn't've\": \"might not have\",\n\"must've\": \"must have\",\n\"mustn't\": \"must not\",\n\"mustn't've\": \"must not have\",\n\"needn't\": \"need not\",\n\"needn't've\": \"need not have\",\n\"o'clock\": \"of the clock\",\n\"oughtn't\": \"ought not\",\n\"oughtn't've\": \"ought not have\",\n\"shan't\": \"shall not\",\n\"sha'n't\": \"shall not\",\n\"shan't've\": \"shall not have\",\n\"she'd\": \"she had\",\n\"she'd've\": \"she would have\",\n\"she'll\": \"she will\",\n\"she'll've\": \"she will have\",\n\"she's\": \"she is\",\n\"should've\": \"should have\",\n\"shouldn't\": \"should not\",\n\"shouldn't've\": \"should not have\",\n\"so've\": \"so have\",\n\"so's\": \"so is\",\n\"that'd\": \"that had\",\n\"that'd've\": \"that would have\",\n\"that's\": \"that is\",\n\"there'd\": \"there had\",\n\"there'd've\": \"there would have\",\n\"there's\": \"there is\",\n\"they'd\": \"they had\",\n\"they'd've\": \"they would have\",\n\"they'll\": \"they will\",\n\"they'll've\": \"they will have\",\n\"they're\": \"they are\",\n\"they've\": \"they have\",\n\"to've\": \"to have\",\n\"wasn't\": \"was not\",\n\"we'd\": \"we had\",\n\"we'd've\": \"we would have\",\n\"we'll\": \"we will\",\n\"we'll've\": \"we will have\",\n\"we're\": \"we are\",\n\"we've\": \"we have\",\n\"weren't\": \"were not\",\n\"what'll\": \"what will\",\n\"what'll've\": \"what will have\",\n\"what're\": \"what are\",\n\"what's\": \"what is\",\n\"what've\": \"what have\",\n\"when's\": \"when is\",\n\"when've\": \"when have\",\n\"where'd\": \"where did\",\n\"where's\": \"where is\",\n\"where've\": \"where have\",\n\"who'll\": \"who will\",\n\"who'll've\": \"who will have\",\n\"who's\": \"who is\",\n\"who've\": \"who have\",\n\"why's\": \"why is\",\n\"why've\": \"why have\",\n\"will've\": \"will have\",\n\"won't\": \"will not\",\n\"won't've\": \"will not have\",\n\"would've\": \"would have\",\n\"wouldn't\": \"would not\",\n\"wouldn't've\": \"would not have\",\n\"y'all\": \"you all\",\n\"y'all'd\": \"you all would\",\n\"y'all'd've\": \"you all would have\",\n\"y'all're\": \"you all are\",\n\"y'all've\": \"you all have\",\n\"you'd\": \"you had\",\n\"you'd've\": \"you would have\",\n\"you'll\": \"you will\",\n\"you'll've\": \"you will have\",\n\"you're\": \"you are\",\n\"you've\": \"you have\"\n}","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def clean(text, contractions=contractions_dict, remove_stop=False):\n    text = text.lower()\n    text = re.sub(r'\\([^)]*\\)', '', text)\n    text = ' '.join([contractions[t] if t in contractions else t for t in text.split(' ')])\n    text = re.sub(r\"'s\\b\", \"\", text)\n    text = re.sub(r'[^a-zA-Z]', ' ', text)\n    text = re.sub('[m]{2, }', 'mm', text)\n    \n    return ' '.join(text.strip().split())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print('* BEFORE CLEANING: ', data.comment_text.iloc[0], '\\n')\nprint('* AFTER CLEANING: ', clean(data.comment_text.iloc[0]))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data['comment_text_clean'] = data['comment_text'].apply(clean)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# max_len = int(np.percentile(data['comment_text_clean'].str.split().apply(len), 90))\nmax_len = 256\n# max_len = int(max(data['comment_text_clean'].str.split().apply(len))) - 250\nprint('Max comment length: ', max_len)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def encode(texts, tokenizer, maxlen=512):\n    enc_di = tokenizer.batch_encode_plus(\n        texts, \n        return_attention_masks=False, \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'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"AUTO_TUNE = tf.data.experimental.AUTOTUNE\nEPOCHS = 15\nBATCH_SIZE = 10 * strategy.num_replicas_in_sync\nMAX_LEN = max_len\nNUM_CLASSES = 1","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"tokenizer = transformers.AutoTokenizer.from_pretrained('jplu/tf-xlm-roberta-large')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data['comment_text_clean'] = data['comment_text'].apply(clean)\nvalid_data['comment_text_clean'] = valid_data['comment_text'].apply(clean)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train = encode(data.comment_text_clean.astype(str), tokenizer, maxlen=MAX_LEN)\nX_test = encode(test_data.content.astype(str), tokenizer, maxlen=MAX_LEN)\nX_valid = encode(valid_data.comment_text_clean.astype(str), tokenizer, maxlen=MAX_LEN)\n\ny_train = data.toxic.values\ny_valid = valid_data.toxic.values","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_dataset = (tf.data.Dataset\n                .from_tensor_slices((X_train, y_train))\n                .repeat()\n                .shuffle(2048)\n                .batch(BATCH_SIZE)\n                .prefetch(AUTO_TUNE))\n\ntest_dataset = (\n    tf.data.Dataset\n    .from_tensor_slices(X_test)\n    .batch(BATCH_SIZE)\n)\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_TUNE)\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def build_model(transformer, max_len=MAX_LEN):\n    input_word_ids = tf.keras.layers.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 = tf.keras.layers.Dense(NUM_CLASSES, activation='sigmoid')(cls_token)\n    \n    model = tf.keras.models.Model(inputs=input_word_ids, outputs=out)\n    \n    model.compile(tf.keras.optimizers.Adam(lr=1e-5), loss='binary_crossentropy', metrics=['accuracy'])\n    \n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with strategy.scope():\n    transformer_layer = transformers.TFAutoModel.from_pretrained('jplu/tf-xlm-roberta-large')\n    model = build_model(transformer_layer, max_len=MAX_LEN)\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"callbacks = [tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=2)]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"n_steps = X_train.shape[0] // BATCH_SIZE\nhistory = model.fit(train_dataset,\n                    steps_per_epoch=n_steps,\n                    epochs=EPOCHS,\n                    validation_data=valid_dataset,\n                    callbacks=callbacks)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"n_steps = X_valid.shape[0] // BATCH_SIZE\nhistory_test = model.fit(valid_dataset.repeat(),\n                    steps_per_epoch=n_steps,\n                    epochs=EPOCHS,\n                    callbacks=callbacks)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(12, 8))\n    \nplt.subplot(1, 2, 1)\nplt.plot(history.history['accuracy'], c='b', label='Train Acc')\nplt.plot(history.history['val_accuracy'], c='g', label='Test Acc')\nplt.title('XLM Roberta Large - Training/Testig Accuracy')\n\nplt.legend()\n\nplt.subplot(1, 2, 2)\nplt.plot(history.history['loss'], c='r', label='Train Loss')\nplt.plot(history.history['val_loss'], c='g', label='Test Loss')\nplt.title('XLM Roberta Large - Testing Loss')\n\nplt.legend()\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"markdown","source":"### Submission","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"submission_file = pd.read_csv('/kaggle/input/jigsaw-multilingual-toxic-comment-classification/sample_submission.csv')\nsubmission_file.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission_file['toxic'] = model.predict(test_dataset, verbose=1)\nsubmission_file.to_csv('submission.csv', index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def toxicity(x):\n    x = encode(np.array([x]), tokenizer, maxlen=MAX_LEN)\n    return model.predict(x, verbose=0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"toxicity('That was not so bad, I like it')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"toxicity('Go burn in hell you idiot')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## References: \n#### https://www.kaggle.com/tanulsingh077/deep-learning-for-nlp-zero-to-transformers-bert\n#### https://www.kaggle.com/xhlulu/jigsaw-tpu-xlm-roberta","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"","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}