Kaggle competition: Jigsaw Unintended Bias in Toxicity Classification
<SOS> metric: JigsawBiasAUC Kaggle data source: jigsaw-unintended-bias-in-toxicity-classification<concatenate>
print(os.listdir(".. /input"))
seed = 42
np.random.seed(seed )
test_data2=pd.concat([test_data,dummies_test],axis='columns' )<drop_column>
BATCH_SIZE = 512
LSTM_UNITS = 128
DENSE_HIDDEN_UNITS = LSTM_UNITS
WORD_EMBED_DIM = 300
EPOCHS = 3
WORD_MAX_LEN = 220
MAX_FEATURES = None
train_data2.drop('Embarked',axis=1,inplace=True )<drop_column>
EMBEDDING_FILES = [
'.. /input/fasttext-crawl-300d-2m/crawl-300d-2M.vec',
'.. /input/glove840b300dtxt/glove.840B.300d.txt'
]
test_data2.drop('Embarked',axis=1,inplace=True )<count_values>
def get_coefs(word, *arr):
return word, np.asarray(arr, dtype='float32')
 def load_embeddings(path):
with open(path)as f:
return dict(get_coefs(*line.strip().split(' ')) for line in f)
 def build_matrix(word_index, path):
embedding_index = load_embeddings(path)
 embedding_matrix = np.zeros(( len(word_index)+ 1, 300))
for word, i in word_index.items() :
try:
embedding_matrix[i] = embedding_index[word]
except KeyError:
pass
return embedding_matrix
thresh_title_counts=10
title_names=(train_data2.title.value_counts() < thresh_title_counts )<feature_engineering>
contraction_mapping = {"ain't": "is not", "aren't": "are not","can't": "cannot", "'cause": "because", "could've": "could have", "couldn't": "could not", "didn't": "did not", "doesn't": "does not", "don't": "do not", "hadn't": "had not", "hasn't": "has not", "haven't": "have not", "he'd": "he would","he'll": "he will", "he's": "he is", "how'd": "how did", "how'd'y": "how do you", "how'll": "how will", "how's": "how is", "I'd": "I would", "I'd've": "I would have", "I'll": "I will", "I'll've": "I will have","I'm": "I am", "I've": "I have", "i'd": "i would", "i'd've": "i would have", "i'll": "i will", "i'll've": "i will have","i'm": "i am", "i've": "i have", "isn't": "is not", "it'd": "it would", "it'd've": "it would have", "it'll": "it will", "it'll've": "it will have","it's": "it is", "let's": "let us", "ma'am": "madam", "mayn't": "may not", "might've": "might have","mightn't": "might not","mightn't've": "might not have", "must've": "must have", "mustn't": "must not", "mustn't've": "must not have", "needn't": "need not", "needn't've": "need not have","o'clock": "of the clock", "oughtn't": "ought not", "oughtn't've": "ought not have", "shan't": "shall not", "sha'n't": "shall not", "shan't've": "shall not have", "she'd": "she would", "she'd've": "she would have", "she'll": "she will", "she'll've": "she will have", "she's": "she is", "should've": "should have", "shouldn't": "should not", "shouldn't've": "should not have", "so've": "so have","so's": "so as", "this's": "this is","that'd": "that would", "that'd've": "that would have", "that's": "that is", "there'd": "there would", "there'd've": "there would have", "there's": "there is", "here's": "here is","they'd": "they would", "they'd've": "they would have", "they'll": "they will", "they'll've": "they will have", "they're": "they are", "they've": "they have", "to've": "to have", "wasn't": "was not", "we'd": "we would", "we'd've": "we would have", "we'll": "we will", "we'll've": "we will have", "we're": "we are", "we've": "we have", "weren't": "were not", "what'll": "what will", "what'll've": "what will have", "what're": "what are", "what's": "what is", "what've": "what have", "when's": "when is", "when've": "when have", "where'd": "where did", "where's": "where is", "where've": "where have", "who'll": "who will", "who'll've": "who will have", "who's": "who is", "who've": "who have", "why's": "why is", "why've": "why have", "will've": "will have", "won't": "will not", "won't've": "will not have", "would've": "would have", "wouldn't": "would not", "wouldn't've": "would not have", "y'all": "you all", "y'all'd": "you all would","y'all'd've": "you all would have","y'all're": "you all are","y'all've": "you all have","you'd": "you would", "you'd've": "you would have", "you'll": "you will", "you'll've": "you will have", "you're": "you are", "you've": "you have" }
mispell_dict = {'colour': 'color', 'centre': 'center', 'favourite': 'favorite', 'travelling': 'traveling', 'counselling': 'counseling', 'theatre': 'theater', 'cancelled': 'canceled', 'labour': 'labor', 'organisation': 'organization', 'wwii': 'world war 2', 'citicise': 'criticize', 'youtu ': 'youtube ', 'Qoura': 'Quora', 'sallary': 'salary', 'Whta': 'What', 'narcisist': 'narcissist', 'howdo': 'how do', 'whatare': 'what are', 'howcan': 'how can', 'howmuch': 'how much', 'howmany': 'how many', 'whydo': 'why do', 'doI': 'do I', 'theBest': 'the best', 'howdoes': 'how does', 'mastrubation': 'masturbation', 'mastrubate': 'masturbate', "mastrubating": 'masturbating', 'pennis': 'penis', 'Etherium': 'Ethereum', 'narcissit': 'narcissist', 'bigdata': 'big data', '2k17': '2017', '2k18': '2018', 'qouta': 'quota', 'exboyfriend': 'ex boyfriend', 'airhostess': 'air hostess', "whst": 'what', 'watsapp': 'whatsapp', 'demonitisation': 'demonetization', 'demonitization': 'demonetization', 'demonetisation': 'demonetization'}
punct_mapping = {"‘": "'", "₹": "e", "´": "'", "°": "", "€": "e", "™": "tm", "√": " sqrt ", "×": "x", "²": "2", "—": "-", "–": "-", "’": "'", "_": "-", "`": "'", '“': '"', '”': '"', '“': '"', "£": "e", '∞': 'infinity', 'θ': 'theta', '÷': '/', 'α': 'alpha', '•': '.', 'à': 'a', '−': '-', 'β': 'beta', '∅': '', '³': '3', 'π': 'pi', }
puncts = [',', '.', '"', ':', ')', '(', '-', '!', '?', '|', ';', "'", '$', '&', '/', '[', ']', '>', '%', '=', '
'·', '_', '{', '}', '©', '^', '®', '`', '<', '→', '°', '€', '™', '›', '♥', '←', '×', '§', '″', '′', 'Â', '█', '½', 'à', '…',
'“', '★', '”', '–', '●', 'â', '►', '−', '¢', '²', '¬', '░', '¶', '↑', '±', '¿', '▾', '═', '¦', '║', '―', '¥', '▓', '—', '‹', '─',
'▒', '：', '¼', '⊕', '▼', '▪', '†', '■', '’', '▀', '¨', '▄', '♫', '☆', 'é', '¯', '♦', '¤', '▲', 'è', '¸', '¾', 'Ã', '⋅', '‘', '∞',
'∙', '）', '↓', '、', '│', '（', '»', '，', '♪', '╩', '╚', '³', '・', '╦', '╣', '╔', '╗', '▬', '❤', 'ï', 'Ø', '¹', '≤', '‡', '√', '\t', '
']
def clean_words(x):
for dic in [contraction_mapping, mispell_dict]:
for word in dic.keys() :
x = x.replace(word, dic[word])
 return x
def clean_punct_mapping(x):
for word in punct_mapping.keys() :
x = x.replace(word, f' {word} ')
 return x
def clean_puncts(x):
x = str(x)
 for punct in puncts:
x = x.replace(punct, ' ')
 return x
def clean_text(text):

 text = text.lower()
text = clean_words(text)
 text = clean_punct_mapping(text)
 text = clean_puncts(text)
 return text
def preprocess(data):
data = data.astype(str ).apply(lambda x: clean_text(x))
return data
train_data2['title']=train_data2.title.apply(lambda x:'Misc' if title_names.loc[x]==True else x )<count_values>
train = pd.read_csv('.. /input/jigsaw-unintended-bias-in-toxicity-classification/train.csv')
 test = pd.read_csv('.. /input/jigsaw-unintended-bias-in-toxicity-classification/test.csv' )
distinct_keys=list(train_data2['title'].value_counts().keys() )<drop_column>
x_train = preprocess(train['comment_text'])
 y_train = np.where(train['target'] >= 0.5, 1, 0)
 y_aux_train = train[['target', 'severe_toxicity', 'obscene', 'identity_attack', 'insult', 'threat']]
x_test = preprocess(test['comment_text'] )
distinct_keys.remove('Misc' )<feature_engineering>
tokenizer = text.Tokenizer()
tokenizer.fit_on_texts(list(x_train)+ list(x_test))
test_data2['title']=test_data2.title.apply(lambda x:'Misc' if x not in distinct_keys else x )<count_values>
class Generator(keras.utils.Sequence):
def __init__(self, x, y, y_aux, batch_size=128):
self.x = x
self.y = y
self.y_aux = y_aux
self.batch_size = batch_size
self.on_epoch_end()
def __len__(self):
'Denotes the number of batches per epoch'
return len(self.x)//self.batch_size
def __getitem__(self, index):
'Generate one batch of data'
indexes = self.indexes[index*self.batch_size:(index+1)*self.batch_size]
batch_x = self.x[index*self.batch_size:(index+1)*self.batch_size]
batch_y = self.y[index*self.batch_size:(index+1)*self.batch_size]
batch_y_aux = self.y_aux[index*self.batch_size:(index+1)*self.batch_size]
word_batch_x = tokenizer.texts_to_sequences(batch_x)
 word_batch_x = sequence.pad_sequences(word_batch_x, maxlen=WORD_MAX_LEN)
 return [word_batch_x], [batch_y, batch_y_aux]
def on_epoch_end(self):
'Updates indexes after each epoch'
self.indexes = np.arange(len(self.x))
test_data2['title'].value_counts()<categorify>
def build_model(embedding_matrix, num_aux_targets, lr=0.0, lr_d=0.0, dr=0.0):
word_input = Input(shape=(WORD_MAX_LEN,), name="word_input")
 word_embed = Embedding(*embedding_matrix.shape, weights=[embedding_matrix], trainable=False )(word_input)
 embed = word_embed
embed = SpatialDropout1D(dr )(embed)
 x = Bidirectional(CuDNNGRU(LSTM_UNITS, return_sequences=True))(embed)
 x = Bidirectional(CuDNNGRU(LSTM_UNITS, return_sequences=True))(x)
 avg_pool1 = GlobalAveragePooling1D()(x)
 max_pool1 = GlobalMaxPooling1D()(x)
 hidden = Concatenate()([avg_pool1, max_pool1])
 hidden = Add()([hidden, Dense(hidden.shape[-1].value, activation='relu' )(hidden)])
 result = Dense(1, activation='sigmoid', name="result" )(hidden)
 aux_result = Dense(num_aux_targets, activation='sigmoid', name="aux" )(hidden)
 model = Model(inputs=[word_input], outputs=[result, aux_result])
 model.compile(loss = "binary_crossentropy", optimizer = Adam(lr=lr, decay=lr_d), metrics=["acc"])
 return model
dummies_embarked_train=pd.get_dummies(train_data2['title'] )<categorify>
%%time
embedding_matrix = np.concatenate([build_matrix(tokenizer.word_index, f)for f in EMBEDDING_FILES], axis=-1 )
dummies_embarked_test=pd.get_dummies(test_data2['title'] )<concatenate>
train_gen = Generator(x_train, y_train, y_aux_train, batch_size=BATCH_SIZE )
train_data3=pd.concat([train_data2,dummies_embarked_train],axis='columns' )<concatenate>
word_x_test = tokenizer.texts_to_sequences(x_test)
 word_x_test = sequence.pad_sequences(word_x_test, maxlen=WORD_MAX_LEN )
test_data3=pd.concat([test_data2,dummies_embarked_test],axis='columns' )<drop_column>
checkpoint_predictions = []
for i in range(EPOCHS):
model.fit_generator(train_gen, steps_per_epoch=train_gen.__len__() , epochs=1)
 p = model.predict([word_x_test], batch_size=2048, verbose=1)[0].flatten()
checkpoint_predictions.append(p )
train_data3.drop('title',axis=1,inplace=True )<drop_column>
lstm_pred = np.average(checkpoint_predictions, axis=0 )
<count_missing_values><EOS> 
predictions = lstm_pred
submission = pd.DataFrame.from_dict({
'id': test['id'],
'prediction': predictions
})
 submission.to_csv('submission.csv', index=False )