|
| 1 | +# https://deeplearningcourses.com/c/deep-learning-advanced-nlp |
| 2 | +from __future__ import print_function, division |
| 3 | +from builtins import range |
| 4 | +# Note: you may need to update your version of future |
| 5 | +# sudo pip install -U future |
| 6 | + |
| 7 | +import os |
| 8 | +import sys |
| 9 | +import numpy as np |
| 10 | +import pandas as pd |
| 11 | +import matplotlib.pyplot as plt |
| 12 | +from keras.preprocessing.text import Tokenizer |
| 13 | +from keras.preprocessing.sequence import pad_sequences |
| 14 | +from keras.layers import Dense, Input, GlobalMaxPooling1D |
| 15 | +from keras.layers import Conv1D, MaxPooling1D, Embedding |
| 16 | +from keras.models import Model |
| 17 | +from sklearn.metrics import roc_auc_score |
| 18 | + |
| 19 | + |
| 20 | +# Download the data: |
| 21 | +# https://www.kaggle.com/c/jigsaw-toxic-comment-classification-challenge |
| 22 | +# Download the word vectors: |
| 23 | +# http://nlp.stanford.edu/data/glove.6B.zip |
| 24 | + |
| 25 | + |
| 26 | +# some configuration |
| 27 | +MAX_SEQUENCE_LENGTH = 100 |
| 28 | +MAX_VOCAB_SIZE = 20000 |
| 29 | +EMBEDDING_DIM = 100 |
| 30 | +VALIDATION_SPLIT = 0.2 |
| 31 | +BATCH_SIZE = 128 |
| 32 | +EPOCHS = 10 |
| 33 | + |
| 34 | + |
| 35 | + |
| 36 | +# load in pre-trained word vectors |
| 37 | +print('Loading word vectors...') |
| 38 | +word2vec = {} |
| 39 | +with open(os.path.join('../large_files/glove.6B/glove.6B.%sd.txt' % EMBEDDING_DIM)) as f: |
| 40 | + # is just a space-separated text file in the format: |
| 41 | + # word vec[0] vec[1] vec[2] ... |
| 42 | + for line in f: |
| 43 | + values = line.split() |
| 44 | + word = values[0] |
| 45 | + vec = np.asarray(values[1:], dtype='float32') |
| 46 | + word2vec[word] = vec |
| 47 | +print('Found %s word vectors.' % len(word2vec)) |
| 48 | + |
| 49 | + |
| 50 | + |
| 51 | +# prepare text samples and their labels |
| 52 | +print('Loading in comments...') |
| 53 | + |
| 54 | +train = pd.read_csv("../large_files/toxic-comment/train.csv") |
| 55 | +sentences = train["comment_text"].fillna("DUMMY_VALUE").values |
| 56 | +possible_labels = ["toxic", "severe_toxic", "obscene", "threat", "insult", "identity_hate"] |
| 57 | +targets = train[possible_labels].values |
| 58 | + |
| 59 | +print("max sequence length:", max(len(s) for s in sentences)) |
| 60 | +print("min sequence length:", min(len(s) for s in sentences)) |
| 61 | +s = sorted(len(s) for s in sentences) |
| 62 | +print("median sequence length:", s[len(s) // 2]) |
| 63 | + |
| 64 | + |
| 65 | + |
| 66 | + |
| 67 | +# convert the sentences (strings) into integers |
| 68 | +tokenizer = Tokenizer(num_words=MAX_VOCAB_SIZE) |
| 69 | +tokenizer.fit_on_texts(sentences) |
| 70 | +sequences = tokenizer.texts_to_sequences(sentences) |
| 71 | +# print("sequences:", sequences); exit() |
| 72 | + |
| 73 | + |
| 74 | +# get word -> integer mapping |
| 75 | +word2idx = tokenizer.word_index |
| 76 | +print('Found %s unique tokens.' % len(word2idx)) |
| 77 | + |
| 78 | + |
| 79 | +# pad sequences so that we get a N x T matrix |
| 80 | +data = pad_sequences(sequences, maxlen=MAX_SEQUENCE_LENGTH) |
| 81 | +print('Shape of data tensor:', data.shape) |
| 82 | + |
| 83 | + |
| 84 | + |
| 85 | +# prepare embedding matrix |
| 86 | +print('Filling pre-trained embeddings...') |
| 87 | +num_words = min(MAX_VOCAB_SIZE, len(word2idx) + 1) |
| 88 | +embedding_matrix = np.zeros((num_words, EMBEDDING_DIM)) |
| 89 | +for word, i in word2idx.items(): |
| 90 | + if i < MAX_VOCAB_SIZE: |
| 91 | + embedding_vector = word2vec.get(word) |
| 92 | + if embedding_vector is not None: |
| 93 | + # words not found in embedding index will be all zeros. |
| 94 | + embedding_matrix[i] = embedding_vector |
| 95 | + |
| 96 | + |
| 97 | + |
| 98 | +# load pre-trained word embeddings into an Embedding layer |
| 99 | +# note that we set trainable = False so as to keep the embeddings fixed |
| 100 | +embedding_layer = Embedding( |
| 101 | + num_words, |
| 102 | + EMBEDDING_DIM, |
| 103 | + weights=[embedding_matrix], |
| 104 | + input_length=MAX_SEQUENCE_LENGTH, |
| 105 | + trainable=False |
| 106 | +) |
| 107 | + |
| 108 | + |
| 109 | +print('Building model...') |
| 110 | + |
| 111 | +# train a 1D convnet with global maxpooling |
| 112 | +input_ = Input(shape=(MAX_SEQUENCE_LENGTH,)) |
| 113 | +x = embedding_layer(input_) |
| 114 | +x = Conv1D(128, 3, activation='relu')(x) |
| 115 | +x = MaxPooling1D(3)(x) |
| 116 | +x = Conv1D(128, 3, activation='relu')(x) |
| 117 | +x = MaxPooling1D(3)(x) |
| 118 | +x = Conv1D(128, 3, activation='relu')(x) |
| 119 | +x = GlobalMaxPooling1D()(x) |
| 120 | +x = Dense(128, activation='relu')(x) |
| 121 | +output = Dense(len(possible_labels), activation='sigmoid')(x) |
| 122 | + |
| 123 | +model = Model(input_, output) |
| 124 | +model.compile( |
| 125 | + loss='binary_crossentropy', |
| 126 | + optimizer='rmsprop', |
| 127 | + metrics=['accuracy'] |
| 128 | +) |
| 129 | + |
| 130 | +print('Training model...') |
| 131 | +r = model.fit( |
| 132 | + data, |
| 133 | + targets, |
| 134 | + batch_size=BATCH_SIZE, |
| 135 | + epochs=EPOCHS, |
| 136 | + validation_split=VALIDATION_SPLIT |
| 137 | +) |
| 138 | + |
| 139 | + |
| 140 | +# plot some data |
| 141 | +plt.plot(r.history['loss'], label='loss') |
| 142 | +plt.plot(r.history['val_loss'], label='val_loss') |
| 143 | +plt.legend() |
| 144 | +plt.show() |
| 145 | + |
| 146 | +# accuracies |
| 147 | +plt.plot(r.history['acc'], label='acc') |
| 148 | +plt.plot(r.history['val_acc'], label='val_acc') |
| 149 | +plt.legend() |
| 150 | +plt.show() |
| 151 | + |
| 152 | +# plot the mean AUC over each label |
| 153 | +p = model.predict(data) |
| 154 | +aucs = [] |
| 155 | +for j in range(6): |
| 156 | + auc = roc_auc_score(targets[:,j], p[:,j]) |
| 157 | + aucs.append(auc) |
| 158 | +print(np.mean(aucs)) |
0 commit comments