{"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":"from tensorflow import keras\nfrom tensorflow.keras import layers\nimport tensorflow as tf\nimport tensorflow_hub as hub","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"SEQUENCE_LENGTH = 256\n\nDATA_PATH =  \"../input/jigsaw-multilingual-toxic-comment-classification\" # data location\nUPLOADED_DATA = '../input/train-toxic-seqlen256/'","execution_count":null,"outputs":[]},{"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    tpu_strategy = tf.distribute.get_strategy()\n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**TF Dataset**","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"#df = pd.read_csv('../input/jigsaw-multilingual-toxic-comment-classification/jigsaw-unintended-bias-train-processed-seqlen128.csv',\n                #nrows = 200000)\ndf = pd.read_csv('/kaggle/input/toxic-comments-256/jigsaw-toxic-comment-train-processed-seqlen256.csv')\ndf.head(3)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#simplification of the code for the tf dataset creation - Test Dataset\ntest = df.filter(['toxic','input_word_ids','input_mask','segment_ids'])\n#test = test.rename(columns={\"all_segment_id\": \"segment_ids\"})\ntest.head(3)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#test.to_csv('test_processed_128.csv', index = False, mode='w')\ntest.to_csv('test_processed_128.csv', index = False, mode='w')\n#validate.to_csv('validate_processed_256.csv', index = False, mode='w')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_dataset(file_path = '../working/test_processed_128.csv'):\n    dataset = tf.data.experimental.make_csv_dataset(\n      file_path,\n      batch_size=12, # Artificially small to make examples easier to show.\n      label_name='toxic',\n      na_value=\"?\",\n      num_epochs=1,\n      shuffle=False)\n    return dataset","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_data = get_dataset()\ntrain_data = train_data.unbatch()\n#validate_data = get_dataset('../working/validate_processed_128.csv')\n#validate_data = validate_data.unbatch()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"next(iter(train_data))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"validation_data = get_dataset('../working/validate_processed_256.csv')\nvalidation_data = validation_data.unbatch()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_bias_set = get_dataset('../input/bias-train-filtered-256/jigsaw-unintended-bias-train-filtered-seqlen256.csv')\ntrain_bias_set = train_bias_set.unbatch()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def parse_string_list_into_ints(strlist):\n    s = tf.strings.strip(strlist)\n    s = tf.strings.substr(s, 1, tf.strings.length(s) - 2)  # Remove parentheses around list\n    #s = tf.strings.split(s, ',', maxsplit=128)\n    s = tf.strings.split(s, ',', maxsplit=256)\n    s = tf.strings.to_number(s, tf.int32)\n    #s = tf.reshape(s, [128])  # Force shape here needed for XLA compilation (TPU)\n    s = tf.reshape(s, [256])  # Force shape here needed for XLA compilation (TPU)\n    return s","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# prototype function to process the dataset for the Bert layer\ndef elem_mod(data,label):\n    for k,v in data.items():\n        data[k] = parse_string_list_into_ints(v)\n    return data,label ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"result = train_data.map(lambda x,y:elem_mod(x,y))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"next(iter(result))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"result_val = validation_data.map(lambda x,y:elem_mod(x,y))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"result_bias = train_bias_set.map(lambda x,y:elem_mod(x,y))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def make_dataset_pipeline(dataset, repeat_and_shuffle=True):\n    \"\"\"Set up the pipeline for the given dataset.   \n    Caches, repeats, shuffles, and sets the pipeline up to prefetch batches.\"\"\"\n    cached_dataset = dataset.cache()\n    if repeat_and_shuffle:\n        cached_dataset = cached_dataset.shuffle(2048)\n    #cached_dataset = cached_dataset.batch(32 * strategy.num_replicas_in_sync)\n    cached_dataset = cached_dataset.batch(32)\n    cached_dataset = cached_dataset.prefetch(tf.data.experimental.AUTOTUNE)\n    return cached_dataset","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#cached_train_data = make_dataset_pipeline(result)\ntrain_set = make_dataset_pipeline(result)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true},"cell_type":"code","source":"cached_train_bias_data = make_dataset_pipeline(result_bias)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"next(iter(train_set))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Model Building","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"#Building the model (reformat as a function...)\nmax_seq_length = 256  # Your choice here.\ninput_word_ids = tf.keras.layers.Input(shape=(max_seq_length,), dtype=tf.int32,\n                                       name=\"input_word_ids\")\ninput_mask = tf.keras.layers.Input(shape=(max_seq_length,), dtype=tf.int32,\n                                   name=\"input_mask\")\nsegment_ids = tf.keras.layers.Input(shape=(max_seq_length,), dtype=tf.int32,\n                                    name=\"segment_ids\")\n# BERT layer from pretrained model\nbert_layer = hub.KerasLayer(\"https://tfhub.dev/tensorflow/bert_multi_cased_L-12_H-768_A-12/2\",trainable=True)\n# Dense Layers\npooled_output, sequence_output = bert_layer([input_word_ids, input_mask, segment_ids])\noutput = tf.keras.layers.Dense(32, activation='relu')(pooled_output)\noutput = tf.keras.layers.Dense(1, activation='sigmoid', name='labels')(output)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Model\nmodel = tf.keras.Model(inputs={'input_word_ids': input_word_ids,\n                                  'input_mask': input_mask,\n                                  'all_segment_id': segment_ids},\n                          outputs=output)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#strategy = tf.distribute.MirroredStrategy()\nmodel.compile(\n    loss=tf.keras.losses.BinaryCrossentropy(),\n    optimizer=tf.keras.optimizers.SGD(learning_rate=0.001),\n    metrics=[tf.keras.metrics.AUC()])\n\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Model for TPU distribution:\nwith strategy.scope():\n    max_seq_length = 256  # Your choice here.\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 layer from pretrained model\n    bert_layer = hub.KerasLayer(\"https://tfhub.dev/tensorflow/bert_multi_cased_L-12_H-768_A-12/2\",trainable=True)\n    # Dense Layers\n    pooled_output, sequence_output = bert_layer([input_word_ids, input_mask, segment_ids])\n    output = tf.keras.layers.Dense(32, activation='relu')(pooled_output)\n    output = tf.keras.layers.Dense(1, activation='sigmoid', name='labels')(output)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true},"cell_type":"code","source":"# Train on English Wikipedia comment data.\nhistory = model.fit(\n    # Set steps such that the number of examples per epoch is fixed.\n    # This makes training on different accelerators more comparable.\n    train_set,steps_per_epoch=4000//256,\n    epochs=50, verbose=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"results = model.evaluate(cached_train_data,\n                                     steps=100, verbose=0)\nprint('\\nEnglish loss, AUC before training:', results)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**Sandbox**","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"#TPU based model DON'T RUN WITHOUT TPU\n# instantiating the model in the strategy scope creates the model on the TPU\nwith tpu_strategy.scope():\n    model = tf.keras.Sequential( … ) # define your model normally\n    model.compile( … )","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}