{"cells":[{"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":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import tensorflow as tf\nprint(\"TF version: \", tf.__version__)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"input1 = pd.read_csv('../input/jigsaw-multilingual-toxic-comment-classification/jigsaw-toxic-comment-train-processed-seqlen128.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"input2 = pd.read_csv(\"/kaggle/input/jigsaw-multilingual-toxic-comment-classification/jigsaw-unintended-bias-train.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train = input1[['comment_text', 'toxic']].copy()\ntrain = pd.concat((train,input2[['comment_text', 'toxic']].copy()))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"val = pd.read_csv('../input/jigsaw-multilingual-toxic-comment-classification/validation-processed-seqlen128.csv')\nval","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# def convert_array(string):\n#     arr = np.array(string[1:-1].split(',')).astype(int)\n#     return np.array([i for i in arr])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# train['input_word_ids'] = train['input_word_ids'].apply(convert_array)\n# train['input_mask'] = train['input_mask'].apply(convert_array)\n# train['all_segment_id'] = train['all_segment_id'].apply(convert_array)\n\n# val['input_word_ids'] = val['input_word_ids'].apply(convert_array)\n# val['input_mask'] = val['input_mask'].apply(convert_array)\n# val['all_segment_id'] = val['all_segment_id'].apply(convert_array)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\n# bert_layer = hub.KerasLayer(\"https://tfhub.dev/google/small_bert/bert_uncased_L-12_H-256_A-4/1\",\n#                             trainable=True)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import transformers\nfrom tokenizers import BertWordPieceTokenizer\nfrom transformers import TFBertModel\n\ntokenizer = transformers.BertTokenizer.from_pretrained('bert-base-multilingual-cased')\n# Save the loaded tokenizer locally\ntokenizer.save_pretrained('.')\n# Reload it with the huggingface tokenizers library\nfast_tokenizer = BertWordPieceTokenizer('vocab.txt', lowercase=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"max_seq_length = 200\n\nfast_tokenizer.enable_truncation(max_length=max_seq_length)\nfast_tokenizer.enable_padding(max_length=max_seq_length)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# train_input_ids = [tokenizer.encode(i, max_length = max_seq_length , pad_to_max_length = True) for i in train.comment_text.values[::10]]\n# val_input_ids = [tokenizer.encode(i, max_length = max_seq_length , pad_to_max_length = True) for i in val.comment_text.values[::10]]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# del tokenizer\n# del fast_tokenizer","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_input_ids = [fast_tokenizer.encode(str(i)).ids for i in train.comment_text.values[::100]]\nval_input_ids = [fast_tokenizer.encode(str(i)).ids for i in val.comment_text.values[::100]]\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\n# def create_model(): \n#     input_word_ids = tf.keras.layers.Input(shape=(max_seq_length,), dtype=tf.int32,\n#                                            name=\"input_word_ids\")\n#     input_mask = tf.keras.layers.Input(shape=(max_seq_length,), dtype=tf.int32,\n#                                        name=\"input_mask\")\n#     segment_ids = tf.keras.layers.Input(shape=(max_seq_length,), dtype=tf.int32,\n#                                         name=\"segment_ids\")\n#     bert_outputs = bert_layer([input_word_ids, input_mask, segment_ids])[0]\n#     dense = tf.keras.layers.Dense(256, activation='relu')(bert_outputs)\n#     dense = tf.keras.layers.Flatten()(dense)\n#     #dense = tf.keras.layers.Dropout(0.2)(dense)\n#     pred = tf.keras.layers.Dense(1, activation='sigmoid')(dense)\n#     model = tf.keras.models.Model(inputs=[input_word_ids, input_mask, segment_ids], outputs=pred)\n#     model.compile(loss=tf.losses.BinaryCrossentropy(from_logits=True), optimizer=tf.keras.optimizers.Adam(\n#     learning_rate=0.000001), metrics=['accuracy'])\n#     return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from transformers import TFXLMRobertaModel\ndef create_model(): \n    input_word_ids = tf.keras.layers.Input(shape=(max_seq_length,), dtype=tf.int32,\n                                           name=\"input_word_ids\")\n    bert_layer = TFBertModel.from_pretrained('bert-base-multilingual-cased')\n    #bert_layer = TFAutoModel.from_pretrained('jplu/tf-xlm-roberta-large')\n    bert_outputs = bert_layer(input_word_ids)[0]\n    pred = tf.keras.layers.Dropout(0.2)(bert_outputs)\n    pred = tf.keras.layers.Conv1D(128,2,padding='same')(pred)\n    pred = tf.keras.layers.Dropout(0.3)(pred)\n    pred = tf.keras.layers.LeakyReLU()(pred)\n    pred = tf.keras.layers.Conv1D(64,2,padding='same')(pred)\n    pred = tf.keras.layers.Dense(256, activation='relu')(pred)\n    pred = tf.keras.layers.Dense(1, activation='sigmoid')(pred)\n\n    model = tf.keras.models.Model(inputs=input_word_ids, outputs=pred)\n    model.compile(loss='binary_crossentropy', optimizer=tf.keras.optimizers.Adam(\n    learning_rate=0.00001), metrics=['accuracy'])\n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"use_tpu = True\nif use_tpu:\n    # Create distribution strategy\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.experimental.TPUStrategy(tpu)\n\n    # Create model\n    with strategy.scope():\n        model = create_model()\nelse:\n    model = create_model()\n    \nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_x = tf.constant(train_input_ids)\ntrain_y = tf.constant(train.toxic.values[::100])\ntrain_data = tf.data.Dataset.from_tensor_slices((train_x, train_y))\nval_x = tf.constant(val_input_ids)\nval_y = tf.constant(val.toxic.values[::100])\nval_data = tf.data.Dataset.from_tensor_slices((val_x, val_y))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.fit(train_data.batch(128),\n          validation_data = val_data.batch(128),\n          verbose = 1, epochs = 15, batch_size = 128)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"preds = np.round(model.predict(np.array(val_input_ids[::100])))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"yes = 0\ntotal = 0\n\nfor i,j in zip(preds, val.toxic.values[::100]):\n    if i==j: yes += 1\n    total += 1\nprint(yes/total)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# train_1 = np.array([i for i in train.input_word_ids.values])\n# train_2 = np.array([i for i in train.input_mask.values])\n# train_3 = np.array([i for i in train.all_segment_id.values])\n\n# val_1 = np.array([i for i in val.input_word_ids.values])\n# val_2 = np.array([i for i in val.input_mask.values])\n# val_3 = np.array([i for i in val.all_segment_id.values])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# model.fit([train_1[::100], train_2[::100], train_3[::100]],\n#          train.toxic.values[::100],\n#          validation_data = ([val_1[::100], val_2[::100],val_3[::100]], val.toxic.values[::100]),\n#         epochs = 1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test = pd.read_csv(\"../input/jigsaw-multilingual-toxic-comment-classification/test-processed-seqlen128.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_input_ids = [tokenizer.encode(i, max_length = max_seq_length , pad_to_max_length = True) for i in test.comment_text.values]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"len(test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"np.shape(test_input_ids)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"preds = [np.max(i) for i in model.predict(test_input_ids)]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"preds[:10]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"evaluation = test.id.copy().to_frame()\nevaluation['toxic'] = np.round(preds)\nevaluation","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"evaluation.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}