{"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":"train = pd.read_csv(\"../input/jigsaw-toxic-comment-classification-cleaned-data/train_data.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import transformers\nfrom tokenizers import BertWordPieceTokenizer\nfrom transformers import TFBertModel\n\ntokenizer = transformers.AutoTokenizer.from_pretrained('roberta-large')\n# Save the loaded tokenizer locally","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"max_seq_length = 200","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\n\ntrain, val = train_test_split(train, test_size = 0.1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_input_ids = [tokenizer.encode(str(i), max_length = max_seq_length , pad_to_max_length = True) for i in train.cleaned_text.values]\nval_input_ids = [tokenizer.encode(str(i), max_length = max_seq_length , pad_to_max_length = True) for i in val.cleaned_text.values]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def 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('roberta-large')\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)\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)\nval_data = tf.data.Dataset.from_tensor_slices((val_x, val_y))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"batch_size = 256\n\nmodel.fit(train_data.batch(batch_size),\n          validation_data = val_data.batch(batch_size),\n          verbose = 1, epochs = 2, batch_size = batch_size)","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":"preds = [np.max(i) for i in preds]\npreds","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":"test = pd.read_csv(\"../input/jigsaw-toxic-comment-classification-cleaned-data/test_data.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":"dummy = train.cleaned_text.values[0]\ntest.cleaned_text[pd.isnull(test.cleaned_text)] = dummy","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_input_ids = [tokenizer.encode(str(i), max_length = max_seq_length , pad_to_max_length = True) for i in test.cleaned_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}