{"cells":[{"metadata":{},"cell_type":"markdown","source":"## 1.import Libraries & define func"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nfrom tqdm import tqdm\nfrom sklearn.model_selection import train_test_split\nimport tensorflow as tf\nfrom keras.models import Sequential\nfrom keras.layers.recurrent import LSTM, GRU,SimpleRNN\nfrom keras.layers.core import Dense, Activation, Dropout\nfrom keras.layers.embeddings import Embedding\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.utils import np_utils\nfrom sklearn import preprocessing, decomposition, model_selection, metrics, pipeline\nfrom keras.layers import GlobalMaxPooling1D, Conv1D, MaxPooling1D, Flatten, Bidirectional, SpatialDropout1D\nfrom keras.preprocessing import sequence, text\nfrom keras.callbacks import EarlyStopping\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n%matplotlib inline\nfrom plotly import graph_objs as go\nimport plotly.express as px\nimport plotly.figure_factory as ff\nfrom tqdm import tqdm_notebook\n\ndef roc_auc(predictions,target):\n    '''\n    This methods returns the AUC Score when given the Predictions\n    and Labels\n    '''\n    \n    fpr, tpr, thresholds = metrics.roc_curve(target, predictions)\n    roc_auc = metrics.auc(fpr, tpr)\n    return roc_auc","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Configuring TPU's\n\nFor this version of Notebook we will be using TPU's as we have to built a BERT Model"},{"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    strategy = tf.distribute.get_strategy()\n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"train = pd.read_csv('/kaggle/input/jigsaw-multilingual-toxic-comment-classification/jigsaw-toxic-comment-train.csv')\nvalidation = 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')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#删除其他target,然后只保留12000,使得其训练更为快捷\ntrain.drop(['severe_toxic','obscene','threat','insult','identity_hate'],axis=1,inplace=True)\ntrain = train.loc[:12000,:]\ntrain.shape","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**检查sentence的最长长度和95%分位数长度，位sentence的padding做好准备**"},{"metadata":{"trusted":true},"cell_type":"code","source":"train['comment_text'].apply(lambda x:len(str(x).split())).max()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"np.percentile(train['comment_text'].apply(lambda x:len(str(x).split())),95)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 2.Data Preparation"},{"metadata":{"trusted":true},"cell_type":"code","source":"xtrain, xvalid, ytrain, yvalid = train_test_split(train.comment_text.values, train.toxic.values, \n                                                  stratify=train.toxic.values, \n                                                  random_state=42, \n                                                  test_size=0.2, shuffle=True)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 3.Model\n### 3.1Simple RNN （embedding层学习词向量+simpleRNN）"},{"metadata":{"trusted":true},"cell_type":"code","source":"import keras\ntoken = keras.preprocessing.text.Tokenizer(num_words = None)\nmax_len = 1500\n\n#先转化为TOEKEN然后再PADDING最后再转IDX\ntoken.fit_on_texts(list(xtrain)+list(xvalid))\nxtrain_seq = token.texts_to_sequences(xtrain)\nxvalid_seq = token.texts_to_sequences(xvalid)\n\n#用0进行Padding the sequences\nxtrain_pad = keras.preprocessing.sequence.pad_sequences(xtrain_seq,maxlen = max_len)\nxvalid_pad = keras.preprocessing.sequence.pad_sequences(xvalid_seq,maxlen = max_len)\n\n#获取index\nword_index = token.word_index","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def rnn():\n    model = Sequential()\n    model.add(Embedding(len(word_index) + 1, 300, input_length = max_len))\n    model.add(SimpleRNN(100))\n    model.add(Dense(1,activation = 'sigmoid'))\n    model.compile(loss = 'binary_crossentropy', optimizer = 'adam', metrics = ['accuracy'])\n    return model\n\nmodel = rnn()\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.fit(xtrain_pad,ytrain,epochs=5,batch_size=128)\nscores = model.predict(xvalid_pad)\nprint(\"Auc: %.2f%%\" % (roc_auc(scores,yvalid)))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"scores_model = []\nscores_model.append({'Model': 'SimpleRNN','AUC_Score': roc_auc(scores,yvalid)})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import keras\ntoken = keras.preprocessing.text.Tokenizer(num_words = None)\nmax_len = 230\n\n#先转化为TOEKEN然后再PADDING最后再转IDX\ntoken.fit_on_texts(list(xtrain)+list(xvalid))\nxtrain_seq = token.texts_to_sequences(xtrain)\nxvalid_seq = token.texts_to_sequences(xvalid)\n\n#用0进行Padding the sequences\nxtrain_pad = keras.preprocessing.sequence.pad_sequences(xtrain_seq,maxlen = max_len)\nxvalid_pad = keras.preprocessing.sequence.pad_sequences(xvalid_seq,maxlen = max_len)\n\n#获取index\nword_index = token.word_index","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def rnn():\n    model = Sequential()\n    model.add(Embedding(len(word_index) + 1,100, input_length = max_len))\n    model.add(SimpleRNN(30))\n    model.add(Dense(1,activation = 'sigmoid'))\n    model.compile(loss = 'binary_crossentropy', optimizer = 'adam', metrics = ['accuracy'])\n    return model\n\nmodel = rnn()\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.fit(xtrain_pad,ytrain,epochs=4,batch_size=128)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"scores = model.predict(xvalid_pad)\nprint(\"Auc: %.2f%%\" % (roc_auc(scores,yvalid)))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### 3.2 使用预训练的词向量+LSTM的方式\n\n注意的点:\n    \n    1.先分别提取word_idx和embedding_idx然后根据word_index和embedding_index构建embedding矩阵\n    2.train的时候直接使用embdding层定义weights,trainable=False"},{"metadata":{"trusted":true},"cell_type":"code","source":"#加载词向量\nembeddings_index = {}\nf = open('/kaggle/input/glove840b300dtxt/glove.840B.300d.txt','r',encoding='utf-8')\nfor line in tqdm(f):\n    values = line.split(' ')\n    word = values[0]\n    coefs = np.asarray([float(val) for val in values[1:]])\n    embeddings_index[word] = coefs\nf.close()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# 构建nn模型可以识别的embedding矩阵\n# 通过word_idx和embedding_idx两个字典,构建embedding矩阵\nembedding_matrix = np.zeros((len(word_index)+1,300))\n\nfor word,i in tqdm_notebook(word_index.items()):\n    embedding_vector = embeddings_index.get(word)\n    if embedding_vector is not None:\n        embedding_matrix[i] = embedding_vector","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def lstm_model():\n    model = Sequential()\n    model.add(Embedding(len(word_index)+1,300,\n              weights = [embedding_matrix],\n              input_length = max_len,\n              trainable = False))\n    model.add(LSTM(100,dropout=0.3,recurrent_dropout=0.3))\n    model.add(Dense(1,activation='sigmoid'))\n    model.compile(loss='binary_crossentropy',optimizer = 'adam',metrics = ['accuracy'])\n    \n    return model\n\nmodel = lstm_model()\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.fit(xtrain_pad, ytrain, nb_epoch=5, batch_size=128)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"scores = model.predict(xvalid_pad)\nprint(\"Auc: %.2f%%\" % (roc_auc(scores,yvalid)))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"scores_model.append({'Model': 'LSTM','AUC_Score': roc_auc(scores,yvalid)})","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### 3.3 预训练词向量+GRU的方式"},{"metadata":{"trusted":true},"cell_type":"code","source":"def gru_model():\n    model = Sequential()\n    model.add(Embedding(len(word_index) + 1,\n                        300,\n                        weights = [embedding_matrix],\n                        input_length = max_len,\n                        trainable = False))\n    model.add(SpatialDropout1D(0.3))\n    model.add(GRU(300))\n    model.add(Dense(1,activation='sigmoid'))\n    model.compile(loss = 'binary_crossentropy',optimizer = 'adam',metrics = ['accuracy'])\n    return model\n\nmodel = gru_model()\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.fit(xtrain_pad, ytrain, epochs=5, batch_size=128)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"scores = model.predict(xvalid_pad)\nprint(\"Auc: %.2f%%\" % (roc_auc(scores,yvalid)))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"scores_model.append({'Model': 'GRU','AUC_Score': roc_auc(scores,yvalid)})","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"scores_model","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### 3.4 Bi-Directional RNN\n\n背景: 有时，你有可能需要从未来的时间步骤中学习表示，以便更好地理解上下文环境并消除歧义。通过接下来的列子，“He said, Teddy bears are on sale” and “He said, Teddy Roosevelt was a great President。在上面的两句话中，当我们看到“Teddy”和前两个词“He said”的时候，我们有可能无法理解这个句子是指President还是Teddy bears。因此，为了解决这种歧义性，我们需要往前查找。这就是双向RNN所能实现的。\n\n双向RNN中的重复模块可以是常规RNN、LSTM或是GRU。双向RNN的结构和连接如图10所示。有两种类型的连接，一种是向前的，这有助于我们从之前的表示中进行学习，另一种是向后的，这有助于我们从未来的表示中进行学习。"},{"metadata":{"trusted":true},"cell_type":"code","source":"def Bidrec_model():\n    model = Sequential()\n    model.add(Embedding(len(word_index) + 1,\n                        300,\n                        weights = [embedding_matrix],\n                        input_length = max_len,\n                        trainable = False))\n    model.add(Bidirectional(LSTM(300, dropout=0.3, recurrent_dropout=0.3)))\n\n    model.add(Dense(1,activation='sigmoid'))\n    model.compile(loss='binary_crossentropy', optimizer='adam',metrics=['accuracy'])\n    \n    return model\n\nmodel = Bidrec_model()\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.fit(xtrain_pad, ytrain, epochs=5, batch_size=128)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"scores = model.predict(xvalid_pad)\nprint(\"Auc: %.2f%%\" % (roc_auc(scores,yvalid)))\nscores_model.append({'Model': 'Bi-directional LSTM','AUC_Score': roc_auc(scores,yvalid)})","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### 3.5 BERT"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Loading Dependencies\nimport os\nimport tensorflow as tf\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\n\nfrom tokenizers import BertWordPieceTokenizer","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"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')\nsub = pd.read_csv('/kaggle/input/jigsaw-multilingual-toxic-comment-classification/sample_submission.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def 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(max_length=maxlen)\n    all_ids = []\n    \n    for i in tqdm(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)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#IMP DATA FOR CONFIG\n\nAUTO = tf.data.experimental.AUTOTUNE\n\n\n# Configuration\nEPOCHS = 3\nBATCH_SIZE = 16\nMAX_LEN = 192","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Tokenization\n\nFor understanding please refer to hugging face documentation again"},{"metadata":{"trusted":true},"cell_type":"code","source":"# First load the real tokenizer\ntokenizer = transformers.DistilBertTokenizer.from_pretrained('distilbert-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)\nfast_tokenizer","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# fast_tokenizer.enable_truncation(max_length = 512)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"tokenizer.enable_truncation(max_length=maxlen)\ntokenizer.enable_padding(max_length=maxlen)\nall_ids = []\n\nfor i in tqdm(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])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_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","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x_train","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_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\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\ntest_dataset = (\n    tf.data.Dataset\n    .from_tensor_slices(x_test)\n    .batch(BATCH_SIZE)\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def 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","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Starting Training\n\nIf you want to use any another model just replace the model name in transformers._____ and use accordingly"},{"metadata":{"trusted":true},"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()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"n_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)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"n_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)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub['toxic'] = model.predict(test_dataset, verbose=1)\nsub.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}