Kaggle competition: Jigsaw Unintended Bias in Toxicity Classification
<SOS> metric: JigsawBiasAUC Kaggle data source: jigsaw-unintended-bias-in-toxicity-classification<choose_model_class>
from fastai.train import Learner
from fastai.train import DataBunch
from fastai.callbacks import *
from fastai.basic_data import DatasetType
m3_knn = KNeighborsClassifier(n_neighbors = 5 )<compute_test_metric>
import numpy as np
import pandas as pd
import os
import time
import gc
import random
from tqdm._tqdm_notebook import tqdm_notebook as tqdm
from keras.preprocessing import text, sequence
import torch
from torch import nn
from torch.utils import data
from torch.nn import functional as F
accuracy['K Nearest Neighbors'] = np.mean(cross_val_score(m3_knn, train_imputed, Survival, scoring="accuracy", cv=kfold))<choose_model_class>
def seed_everything(seed=1234):
random.seed(seed)
 os.environ['PYTHONHASHSEED'] = str(seed)
 np.random.seed(seed)
 torch.manual_seed(seed)
 torch.cuda.manual_seed(seed)
 torch.backends.cudnn.deterministic = True
seed_everything()
m4_rf = RandomForestClassifier(n_estimators=10 )<compute_test_metric>
CRAWL_EMBEDDING_PATH = '.. /input/fasttext-crawl-300d-2m/crawl-300d-2M.vec'
GLOVE_EMBEDDING_PATH = '.. /input/glove840b300dtxt/glove.840B.300d.txt'
NUM_MODELS = 2
LSTM_UNITS = 128
DENSE_HIDDEN_UNITS = 4 * LSTM_UNITS
MAX_LEN = 220
accuracy['Random Forest'] = np.mean(cross_val_score(m4_rf, train_imputed, Survival, scoring="accuracy", cv=kfold))<set_options>
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 tqdm(f))
def build_matrix(word_index, path):
embedding_index = load_embeddings(path)
 embedding_matrix = np.zeros(( len(word_index)+ 1, 300))
unknown_words = []
for word, i in word_index.items() :
try:
embedding_matrix[i] = embedding_index[word]
except KeyError:
unknown_words.append(word)
 return embedding_matrix, unknown_words
m5_svc = SVC(gamma='scale' )<compute_train_metric>
def sigmoid(x):
return 1 /(1 + np.exp(-x))
def train_model(learn,test,output_dim,lr=0.001,
batch_size=512, n_epochs=4,
enable_checkpoint_ensemble=True):
all_test_preds = []
checkpoint_weights = [2 ** epoch for epoch in range(n_epochs)]
test_loader = torch.utils.data.DataLoader(test, batch_size=batch_size, shuffle=False)
 n = len(learn.data.train_dl)
 phases = [(TrainingPhase(n ).schedule_hp('lr', lr *(0.6**(i)))) for i in range(n_epochs)]
sched = GeneralScheduler(learn, phases)
 learn.callbacks.append(sched)
 for epoch in range(n_epochs):
learn.fit(1)
 test_preds = np.zeros(( len(test), output_dim))
for i, x_batch in enumerate(test_loader):
X = x_batch[0].cuda()
y_pred = sigmoid(learn.model(X ).detach().cpu().numpy())
 test_preds[i * batch_size:(i+1)* batch_size, :] = y_pred
all_test_preds.append(test_preds)
 if enable_checkpoint_ensemble:
test_preds = np.average(all_test_preds, weights=checkpoint_weights, axis=0)
 else:
test_preds = all_test_preds[-1]
return test_preds
accuracy['SVM'] = np.mean(cross_val_score(m5_svc, train_imputed, Survival, scoring="accuracy", cv=kfold))<choose_model_class>
class SpatialDropout(nn.Dropout2d):
def forward(self, x):
x = x.unsqueeze(2)
 x = x.permute(0, 3, 2, 1)
 x = super(SpatialDropout, self ).forward(x)
 x = x.permute(0, 3, 2, 1)
 x = x.squeeze(2)
 return x
m6_gb = XGBClassifier(max_depth=3, n_estimators=300, learning_rate=0.05 )<compute_train_metric>
class Attention(nn.Module):
def __init__(self, feature_dim, step_dim, bias=True, **kwargs):
super(Attention, self ).__init__(**kwargs)
 self.supports_masking = True
self.bias = bias
self.feature_dim = feature_dim
self.step_dim = step_dim
self.features_dim = 0
weight = torch.zeros(feature_dim, 1)
 nn.init.xavier_uniform_(weight)
 self.weight = nn.Parameter(weight)
 if bias:
self.b = nn.Parameter(torch.zeros(step_dim))
def forward(self, x, mask=None):
feature_dim = self.feature_dim
step_dim = self.step_dim
eij = torch.mm(
 x.contiguous().view(-1, feature_dim),
self.weight
).view(-1, step_dim)
 if self.bias:
eij = eij + self.b
eij = torch.tanh(eij)
 a = torch.exp(eij)
 if mask is not None:
a = a * mask
a = a / torch.sum(a, 1, keepdim=True)+ 1e-10
weighted_input = x * torch.unsqueeze(a, -1)
 return torch.sum(weighted_input, 1 )
accuracy['Gradient Boosting'] = np.mean(cross_val_score(m6_gb, train_imputed, Survival, scoring="accuracy", cv=kfold))<compute_test_metric>
class NeuralNet(nn.Module):
def __init__(self, embedding_matrix, num_aux_targets):
super(NeuralNet, self ).__init__()
embed_size = embedding_matrix.shape[1]
self.embedding = nn.Embedding(max_features, embed_size)
 self.embedding.weight = nn.Parameter(torch.tensor(embedding_matrix, dtype=torch.float32))
self.embedding.weight.requires_grad = False
self.embedding_dropout = SpatialDropout(0.3)
 self.lstm1 = nn.LSTM(embed_size, LSTM_UNITS, bidirectional=True, batch_first=True)
 self.lstm2 = nn.LSTM(LSTM_UNITS * 2, LSTM_UNITS, bidirectional=True, batch_first=True)
 self.lstm1_attention = Attention(LSTM_UNITS * 2, MAX_LEN)
 self.lstm2_attention = Attention(LSTM_UNITS * 2, MAX_LEN)
 self.linear1 = nn.Linear(DENSE_HIDDEN_UNITS * 2, DENSE_HIDDEN_UNITS * 2)
 self.linear2 = nn.Linear(DENSE_HIDDEN_UNITS * 2, DENSE_HIDDEN_UNITS * 2)
 self.linear_out = nn.Linear(DENSE_HIDDEN_UNITS * 2, 1)
 self.linear_aux_out = nn.Linear(DENSE_HIDDEN_UNITS * 2, num_aux_targets)
 def forward(self, x):
h_embedding = self.embedding(x)
 h_embedding = self.embedding_dropout(h_embedding)
 h_lstm1, _ = self.lstm1(h_embedding)
 h_lstm2, _ = self.lstm2(h_lstm1)
 h_lstm1_atten = self.lstm1_attention(h_lstm1)
 h_lstm2_atten = self.lstm2_attention(h_lstm2)
 avg_pool = torch.mean(h_lstm2, 1)
 max_pool, _ = torch.max(h_lstm2, 1)
 h_conc = torch.cat(( h_lstm1_atten,h_lstm2_atten, max_pool, avg_pool), 1)
 h_conc_linear1 = F.relu(self.linear1(h_conc))
h_conc_linear2 = F.relu(self.linear2(h_conc))
hidden = h_conc + h_conc_linear1 + h_conc_linear2
result = self.linear_out(hidden)
 aux_result = self.linear_aux_out(hidden)
 out = torch.cat([result, aux_result], 1)
 return out
max_accuracy = max(accuracy, key=accuracy.get)
 print(max_accuracy, '\taccuracy:', accuracy[max_accuracy] )<train_model>
def preprocess(data):

 punct = "/-'?!.,
def clean_special_chars(text, punct):
for p in punct:
text = text.replace(p, ' ')
 return text
data = data.astype(str ).apply(lambda x: clean_special_chars(x, punct))
return data
m6_gb.fit(train_imputed, Survival)
 m6_gb.feature_importances_<train_on_grid>
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' )
param_grid = {'max_depth': [1,3,5,10,15], 'n_estimators': [50,100,200,500,1000], 'learning_rate': [1,0.1,0.01,0.001,0.0001]}
grid = GridSearchCV(XGBClassifier() , param_grid, cv=kfold)
 grid.fit(train_imputed[["Fare_", "Age_", "FamilySize", "Sex_"]], Survival)
 grid.best_params_<compute_train_metric>
x_train = preprocess(train['comment_text'])
 y_aux_train = train[['target', 'severe_toxicity', 'obscene', 'identity_attack', 'insult', 'threat']]
x_test = preprocess(test['comment_text'])
 identity_columns = [
'male', 'female', 'homosexual_gay_or_lesbian', 'christian', 'jewish',
'muslim', 'black', 'white', 'psychiatric_or_mental_illness']
weights = np.ones(( len(x_train),)) / 4
weights +=(train[identity_columns].fillna(0 ).values>=0.5 ).sum(axis=1 ).astype(bool ).astype(np.int)/ 4
weights +=(((train['target'].values>=0.5 ).astype(bool ).astype(np.int)+ 
(train[identity_columns].fillna(0 ).values<0.5 ).sum(axis=1 ).astype(bool ).astype(np.int)) > 1 ).astype(bool ).astype(np.int)/ 4
weights +=(((train['target'].values<0.5 ).astype(bool ).astype(np.int)+ 
(train[identity_columns].fillna(0 ).values>=0.5 ).sum(axis=1 ).astype(bool ).astype(np.int)) > 1 ).astype(bool ).astype(np.int)/ 4
loss_weight = 1.0 / weights.mean()
gb = XGBClassifier(max_depth=3, n_estimators=1000, learning_rate=0.01)
 np.mean(cross_val_score(gb, train_imputed[["Fare_", "Age_", "FamilySize", "Sex_"]], Survival, scoring="accuracy", cv=kfold))<predict_on_test>
y_train = np.vstack([(train['target'].values>=0.5 ).astype(np.int),weights] ).T
gb.fit(train_imputed[["Fare_", "Age_", "FamilySize", "Sex_"]], Survival)
 predictions = gb.predict(test_imputed[["Fare_", "Age_", "FamilySize", "Sex_"]] )<save_to_csv>
max_features = None
submission = pd.DataFrame({ 'PassengerId': test.PassengerId,
'Survived': predictions })
 submission.to_csv("TitanicSubmission.csv", index=False )<set_options>
tokenizer = text.Tokenizer()
tokenizer.fit_on_texts(list(x_train)+ list(x_test))
x_train = tokenizer.texts_to_sequences(x_train)
 x_test = tokenizer.texts_to_sequences(x_test)
 x_train = sequence.pad_sequences(x_train, maxlen=MAX_LEN)
 x_test = sequence.pad_sequences(x_test, maxlen=MAX_LEN )
warnings.filterwarnings('ignore' )<load_from_csv>
max_features = max_features or len(tokenizer.word_index)+ 1
max_features
train_original = pd.read_csv('.. /input/train.csv')
 test_original = pd.read_csv('.. /input/test.csv')
 train_original.sample(10)
 total = [train_original,test_original] 
<feature_engineering>
crawl_matrix, unknown_words_crawl = build_matrix(tokenizer.word_index, CRAWL_EMBEDDING_PATH)
 print('n unknown words(crawl): ', len(unknown_words_crawl))
for dataset in total:
dataset['Salutation'] = dataset.Name.str.extract('([A-Za-z]+)\.', expand=False )<categorify>
glove_matrix, unknown_words_glove = build_matrix(tokenizer.word_index, GLOVE_EMBEDDING_PATH)
 print('n unknown words(glove): ', len(unknown_words_glove))
for dataset in total:
dataset['Salutation'] = dataset['Salutation'].replace(['Lady', 'Countess','Capt', 'Col','Don', 'Dr', 'Major', 'Rev', 'Sir', 'Jonkheer', 'Dona'], 'Rare')
 dataset['Salutation'] = dataset['Salutation'].replace('Mlle', 'Miss')
 dataset['Salutation'] = dataset['Salutation'].replace('Ms', 'Miss')
 dataset['Salutation'] = dataset['Salutation'].replace('Mme', 'Mrs')
<categorify>
embedding_matrix = np.concatenate([crawl_matrix, glove_matrix], axis=-1)
 embedding_matrix.shape
del crawl_matrix
del glove_matrix
gc.collect()
for dataset in total:
dataset['Salutation'] = pd.factorize(dataset['Salutation'])[0]<drop_column>
x_train_torch = torch.tensor(x_train, dtype=torch.long)
 y_train_torch = torch.tensor(np.hstack([y_train, y_aux_train]), dtype=torch.float32 )
train=train_original.drop(['PassengerId','Name','Ticket','Cabin'], axis=1)
 test=test_original.drop(['PassengerId','Name','Ticket','Cabin'], axis=1)
 total = [train,test]
train.shape, test.shape<count_missing_values>
x_test_torch = torch.tensor(x_test, dtype=torch.long )
train.isnull().sum()<categorify>
batch_size = 512
train_dataset = data.TensorDataset(x_train_torch, y_train_torch)
 valid_dataset = data.TensorDataset(x_train_torch[:batch_size], y_train_torch[:batch_size])
 test_dataset = data.TensorDataset(x_test_torch)
 train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
 valid_loader = torch.utils.data.DataLoader(valid_dataset, batch_size=batch_size, shuffle=False)
 databunch = DataBunch(train_dl=train_loader,valid_dl=valid_loader )
def fill_missing_age(dataset):
for i in range(1,8):
median_age=dataset[dataset["Salutation"]==i]["Age"].median()
dataset["Age"]=dataset["Age"].fillna(median_age)
 return dataset
train = fill_missing_age(train )<filter>
def custom_loss(data, targets):

 bce_loss_1 = nn.BCEWithLogitsLoss(weight=targets[:,1:2] )(data[:,:1],targets[:,:1])
 bce_loss_2 = nn.BCEWithLogitsLoss()(data[:,1:],targets[:,2:])
 return(bce_loss_1 * loss_weight)+ bce_loss_2
train[train['Embarked'].isnull() ]<feature_engineering>
all_test_preds = []
for model_idx in range(NUM_MODELS):
print('Model ', model_idx)
 seed_everything(1234 + model_idx)
 model = NeuralNet(embedding_matrix, y_aux_train.shape[-1])
 learn = Learner(databunch,model,loss_func=custom_loss)
 test_preds = train_model(learn,test_dataset,output_dim=7)
 all_test_preds.append(test_preds )
train["Embarked"] = train["Embarked"].fillna('C' )<count_missing_values>
submission = pd.DataFrame.from_dict({
'id': test['id'],
'prediction': np.mean(all_test_preds, axis=0)[:, 0]
})
 submission.to_csv('submission.csv', index=False )