Kaggle competition: Quora Insincere Questions Classification
def get_df_roc(df_in, models_list=None):
df_roc = pd.DataFrame({'Model': [], 'FalsePositiveRate': [], 'TruePositiveRate': []})
 if models_list is None:
models_list = set(df_in['Model'].tolist())
 for curr_model in models_list:
fpr_list, tpr_list, _ = roc_curve(df_in.loc[df_in['Model'] == curr_model, :]['Target'].tolist() ,
df_in.loc[df_in['Model'] == curr_model, :]['Prediction'].tolist())
 model_list = [curr_model] * len(fpr_list)
 df2append = pd.DataFrame({
'Model': model_list,
'FalsePositiveRate': fpr_list,
'TruePositiveRate': tpr_list
})
 df_roc = pd.concat([df_roc, df2append], ignore_index=True)
 return df_roc
df_roc = get_df_roc(df_benchmark)
 df_roc.head()<groupby>
embed_size = 300
max_features = 95000
maxlen = 70
def get_benchmark_scores(df_in, models_list=set(df_benchmark['Model'].tolist())) :
dict_metrics = dict(Model=[], Metric=[], Value=[])
 for curr_model in models_list:
for metric in ['Accuracy', 'AUC', 'F1-Score']:
filter_cond = df_in['Model'] == curr_model
filter_cond &= df_in['Type'] == 'Test'
sorted_df = df_in.loc[filter_cond, ['Id', 'Prediction', 'Target']].sort_values(by='Id')
 predictions = sorted_df['Prediction'].tolist()
targets = sorted_df['Target'].tolist()
if metric in ['Accuracy', 'F1-Score']:
predictions = [1 if X >= 0.5 else 0 for X in predictions]
if metric == 'Accuracy':
score = accuracy_score(targets, predictions)
 elif metric == 'F1-Score':
score = accuracy_score(targets, predictions)
 elif metric == 'AUC':
fpr, tpr, _ = roc_curve(targets, predictions)
 score = auc(fpr, tpr)
 dict_metrics['Model'].append(curr_model)
 dict_metrics['Metric'].append(metric)
 dict_metrics['Value'].append(score)
 return pd.DataFrame(dict_metrics)
 df_metrics = get_benchmark_scores(df_benchmark)
 df_metrics.head()<define_variables>
import os
import time
import numpy as np
import pandas as pd
from tqdm import tqdm
import math
from sklearn.model_selection import train_test_split
from sklearn import metrics
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.layers import Dense, Input, CuDNNLSTM, Embedding, Dropout, Activation, CuDNNGRU, Conv1D
from keras.layers import Bidirectional, GlobalMaxPool1D, GlobalMaxPooling1D, GlobalAveragePooling1D
from keras.layers import Input, Embedding, Dense, Conv2D, MaxPool2D, concatenate, Lambda
from keras.layers import Reshape, Flatten, Concatenate, Dropout, SpatialDropout1D
from keras.optimizers import Adam
from keras.models import Model
from keras import backend as K
from keras.engine.topology import Layer
from keras import initializers, regularizers, constraints, optimizers, layers
dict_corr = dict(Model1=[], Model2=[], Correlation=[])
 models_list = set(df_benchmark['Model'].tolist())
 for model1 in models_list:
for model2 in models_list:
dict_corr['Model1'].append(model1)
 dict_corr['Model2'].append(model2)
 filter_cond1 = df_benchmark['Model'] == model1
filter_cond1 &= df_benchmark['Type'] == 'Test'
filter_cond2 = df_benchmark['Model'] == model2
filter_cond2 &= df_benchmark['Type'] == 'Test'
pred1 = df_benchmark.loc[filter_cond1]['Prediction'].tolist()
pred2 = df_benchmark.loc[filter_cond2]['Prediction'].tolist()
dict_corr['Correlation'].append(np.corrcoef(np.array(pred1), np.array(pred2)) [0, 1])
 dict_model_bias = {
'albert-base-v2': 'ALBERT',
'bert-base-uncased': 'BERT',
'roberta-base': 'ROBERTA',
'xlnet-large-cased': 'XLNET'
}
df_corr = pd.DataFrame(dict_corr)
 df_corr['Model1'] = df_corr['Model1'].apply(lambda X: dict_model_bias[X])
 df_corr['Model2'] = df_corr['Model2'].apply(lambda X: dict_model_bias[X])
 df_corr.head()<feature_engineering>
def load_and_prec() :
train_df = pd.read_csv(".. /input/train.csv")
 test_df = pd.read_csv(".. /input/test.csv")
 print("Train shape : ",train_df.shape)
 print("Test shape : ",test_df.shape)
 train_df, val_df = train_test_split(train_df, test_size=0.08, random_state=2018)
 train_X = train_df["question_text"].fillna("_
val_X = val_df["question_text"].fillna("_
test_X = test_df["question_text"].fillna("_
tokenizer = Tokenizer(num_words=max_features)
 tokenizer.fit_on_texts(list(train_X))
train_X = tokenizer.texts_to_sequences(train_X)
 val_X = tokenizer.texts_to_sequences(val_X)
 test_X = tokenizer.texts_to_sequences(test_X)
 train_X = pad_sequences(train_X, maxlen=maxlen)
 val_X = pad_sequences(val_X, maxlen=maxlen)
 test_X = pad_sequences(test_X, maxlen=maxlen)
 train_y = train_df['target'].values
val_y = val_df['target'].values
np.random.seed(2018)
 trn_idx = np.random.permutation(len(train_X))
val_idx = np.random.permutation(len(val_X))
train_X = train_X[trn_idx]
val_X = val_X[val_idx]
train_y = train_y[trn_idx]
val_y = val_y[val_idx]
return train_X, val_X, test_X, train_y, val_y, tokenizer.word_index
def get_df_ensemble(df_in, name_new_model):
df_ensemble = df_in.groupby('Id' ).mean()
df_ensemble['Id'] = df_ensemble.index
train_ids = list(set(df_in[df_in['Type'] == 'Train']['Id'].tolist()))
test_ids = list(set(df_in[df_in['Type'] == 'Test']['Id'].tolist()))
df_ensemble['Id'] = df_ensemble.index
df_ensemble['Model'] = name_new_model
df_ensemble['Type'] = 'NA'
df_ensemble.loc[df_ensemble['Id'].isin(train_ids), 'Type'] = 'Train'
df_ensemble.loc[df_ensemble['Id'].isin(test_ids), 'Type'] = 'Test'
df_ensemble = df_ensemble.loc[:, ['Model', 'Type', 'Id', 'Prediction', 'Target']]
return df_ensemble
df_ensemble_all = get_df_ensemble(df_benchmark, 'ensemble_all')
 best_models = ['bert-base-uncased', 'roberta-base']
df_ensemble_best = get_df_ensemble(df_benchmark.loc[df_benchmark['Model'].isin(best_models), :], 'ensemble_best')
 df_benchmark_improved = pd.concat([df_benchmark, df_ensemble_all, df_ensemble_best], ignore_index=True)
 plot_benchmark_scores(df_benchmark_improved, models_list=best_models + ['ensemble_best', 'ensemble_all'] )<groupby>
def load_glove(word_index):
EMBEDDING_FILE = '.. /input/embeddings/glove.840B.300d/glove.840B.300d.txt'
def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32')
 embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(EMBEDDING_FILE))
all_embs = np.stack(embeddings_index.values())
 emb_mean,emb_std = all_embs.mean() , all_embs.std()
embed_size = all_embs.shape[1]
nb_words = min(max_features, len(word_index))
embedding_matrix = np.random.normal(emb_mean, emb_std,(nb_words, embed_size))
for word, i in tqdm(word_index.items()):
if i >= max_features: continue
embedding_vector = embeddings_index.get(word)
 if embedding_vector is not None: embedding_matrix[i] = embedding_vector
return embedding_matrix
def load_fasttext(word_index):
EMBEDDING_FILE = '.. /input/embeddings/wiki-news-300d-1M/wiki-news-300d-1M.vec'
def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32')
 embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(EMBEDDING_FILE)if len(o)>100)
 all_embs = np.stack(embeddings_index.values())
 emb_mean,emb_std = all_embs.mean() , all_embs.std()
embed_size = all_embs.shape[1]
nb_words = min(max_features, len(word_index))
embedding_matrix = np.random.normal(emb_mean, emb_std,(nb_words, embed_size))
for word, i in tqdm(word_index.items()):
if i >= max_features: continue
embedding_vector = embeddings_index.get(word)
 if embedding_vector is not None: embedding_matrix[i] = embedding_vector
return embedding_matrix
def load_para(word_index):
EMBEDDING_FILE = '.. /input/embeddings/paragram_300_sl999/paragram_300_sl999.txt'
def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32')
 embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(EMBEDDING_FILE, encoding="utf8", errors='ignore')if len(o)>100)
 all_embs = np.stack(embeddings_index.values())
 emb_mean,emb_std = all_embs.mean() , all_embs.std()
embed_size = all_embs.shape[1]
nb_words = min(max_features, len(word_index))
embedding_matrix = np.random.normal(emb_mean, emb_std,(nb_words, embed_size))
for word, i in tqdm(word_index.items()):
if i >= max_features: continue
embedding_vector = embeddings_index.get(word)
 if embedding_vector is not None: embedding_matrix[i] = embedding_vector
return embedding_matrix
df_submission_ensemble_all = df_submission.groupby('Id' ).mean()
df_submission_ensemble_all['Id'] = df_submission_ensemble_all.index
df_submission_ensemble_all['Model'] = 'ensemble_all'
df_submission_ensemble_all = df_submission_ensemble_all.loc[:, ['Model', 'Id', 'Proba']]
df_submission_ensemble_best = df_submission.loc[df_submission['Model'].isin(best_models), :].groupby('Id' ).mean()
df_submission_ensemble_best['Id'] = df_submission_ensemble_best.index
df_submission_ensemble_best['Model'] = 'ensemble_best'
df_submission_ensemble_best = df_submission_ensemble_best.loc[:, ['Model', 'Id', 'Proba']]
df_submission_enhanced = pd.concat([df_submission, df_submission_ensemble_all, df_submission_ensemble_best], ignore_index=True)
 df_submission_enhanced.tail()<save_to_csv>
def model_cnn(embedding_matrix):
filter_sizes = [1,2,3,5]
num_filters = 36
inp = Input(shape=(maxlen,))
x = Embedding(max_features, embed_size, weights=[embedding_matrix] )(inp)
 x = Reshape(( maxlen, embed_size, 1))(x)
 maxpool_pool = []
for i in range(len(filter_sizes)) :
conv = Conv2D(num_filters, kernel_size=(filter_sizes[i], embed_size),
kernel_initializer='he_normal', activation='elu' )(x)
 maxpool_pool.append(MaxPool2D(pool_size=(maxlen - filter_sizes[i] + 1, 1))(conv))
z = Concatenate(axis=1 )(maxpool_pool)
 z = Flatten()(z)
 z = Dropout(0.1 )(z)
 outp = Dense(1, activation="sigmoid" )(z)
 model = Model(inputs=inp, outputs=outp)
 model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
 return model
def model_cnn_flip(embedding_matrix):
filter_sizes = [1,2,3,5]
num_filters = 36
inp = Input(shape=(maxlen,))
x = Lambda(lambda x: K.reverse(x,axes=-1))(inp)
 x = Embedding(max_features, embed_size, weights=[embedding_matrix] )(x)
 x = Reshape(( maxlen, embed_size, 1))(x)
 maxpool_pool = []
for i in range(len(filter_sizes)) :
conv = Conv2D(num_filters, kernel_size=(filter_sizes[i], embed_size),
kernel_initializer='he_normal', activation='elu' )(x)
 maxpool_pool.append(MaxPool2D(pool_size=(maxlen - filter_sizes[i] + 1, 1))(conv))
z = Concatenate(axis=1 )(maxpool_pool)
 z = Flatten()(z)
 z = Dropout(0.1 )(z)
 outp = Dense(1, activation="sigmoid" )(z)
 model = Model(inputs=inp, outputs=outp)
 model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
 return model
def export_model(model_name):
df_export = df_submission_enhanced.loc[df_submission_enhanced['Model'] == model_name, :]
df_export.loc[:, 'Target'] = df_export['Proba'].apply(lambda X: 1 if X >= 0.5 else 0)
 df_export = df_export.loc[:, ['Id', 'Target']]
df_export.rename({'Id': 'id', 'Target': 'target'}, inplace=True)
 df_export.to_csv(output_dir + model_name + '.csv', index=False )<import_modules>
class Attention(Layer):
def __init__(self, step_dim,
W_regularizer=None, b_regularizer=None,
W_constraint=None, b_constraint=None,
bias=True, **kwargs):
self.supports_masking = True
self.init = initializers.get('glorot_uniform')
 self.W_regularizer = regularizers.get(W_regularizer)
 self.b_regularizer = regularizers.get(b_regularizer)
 self.W_constraint = constraints.get(W_constraint)
 self.b_constraint = constraints.get(b_constraint)
 self.bias = bias
self.step_dim = step_dim
self.features_dim = 0
super(Attention, self ).__init__(**kwargs)
 def build(self, input_shape):
assert len(input_shape)== 3
self.W = self.add_weight(( input_shape[-1],),
initializer=self.init,
name='{}_W'.format(self.name),
regularizer=self.W_regularizer,
constraint=self.W_constraint)
 self.features_dim = input_shape[-1]
if self.bias:
self.b = self.add_weight(( input_shape[1],),
initializer='zero',
name='{}_b'.format(self.name),
regularizer=self.b_regularizer,
constraint=self.b_constraint)
 else:
self.b = None
self.built = True
def compute_mask(self, input, input_mask=None):
return None
def call(self, x, mask=None):
features_dim = self.features_dim
step_dim = self.step_dim
eij = K.reshape(K.dot(K.reshape(x,(-1, features_dim)) ,
K.reshape(self.W,(features_dim, 1))),(-1, step_dim))
if self.bias:
eij += self.b
eij = K.tanh(eij)
 a = K.exp(eij)
 if mask is not None:
a *= K.cast(mask, K.floatx())
 a /= K.cast(K.sum(a, axis=1, keepdims=True)+ K.epsilon() , K.floatx())
 a = K.expand_dims(a)
 weighted_input = x * a
return K.sum(weighted_input, axis=1)
 def compute_output_shape(self, input_shape):
return input_shape[0], self.features_dim
export_model('ensemble_all')
 export_model('ensemble_best')
 export_model('bert-base-uncased')
 export_model('roberta-base' )<import_modules>
def model_lstm_atten(embedding_matrix):
inp = Input(shape=(maxlen,))
x = Embedding(max_features, embed_size, weights=[embedding_matrix], trainable=False )(inp)
 x = Bidirectional(CuDNNLSTM(128, return_sequences=True))(x)
 x = Bidirectional(CuDNNLSTM(64, return_sequences=True))(x)
 x = Attention(maxlen )(x)
 x = Dense(64, activation="relu" )(x)
 x = Dense(1, activation="sigmoid" )(x)
 model = Model(inputs=inp, outputs=x)
 model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
 return model
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import BatchNormalization
from keras.utils import np_utils
from keras.optimizers import Adam<load_from_csv>
def model_gru_srk_atten(embedding_matrix):
inp = Input(shape=(maxlen,))
x = Embedding(max_features, embed_size, weights=[embedding_matrix] )(inp)
 x = Bidirectional(CuDNNGRU(64, return_sequences=True))(x)
 x = Attention(maxlen )(x)
 x = Dense(16, activation="relu" )(x)
 x = Dropout(0.1 )(x)
 x = Dense(1, activation="sigmoid" )(x)
 model = Model(inputs=inp, outputs=x)
 model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
 return model
train_data=pd.read_csv('.. /input/train.csv' ).drop(columns=['PassengerId','Name','Ticket','Cabin'] )<count_values>
def model_lstm_du(embedding_matrix):
inp = Input(shape=(maxlen,))
x = Embedding(max_features, embed_size, weights=[embedding_matrix] )(inp)
 x = Bidirectional(CuDNNGRU(64, return_sequences=True))(x)
 avg_pool = GlobalAveragePooling1D()(x)
 max_pool = GlobalMaxPooling1D()(x)
 conc = concatenate([avg_pool, max_pool])
 conc = Dense(64, activation="relu" )(conc)
 conc = Dropout(0.1 )(conc)
 outp = Dense(1, activation="sigmoid" )(conc)
 model = Model(inputs=inp, outputs=outp)
 model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
 return model
sum(train_data['Fare']==0 )<groupby>
def train_pred(model, epochs=2):
for e in range(epochs):
model.fit(train_X, train_y, batch_size=512, epochs=1, validation_data=(val_X, val_y))
pred_val_y = model.predict([val_X], batch_size=1024, verbose=0)
 best_thresh = 0.5
best_score = 0.0
for thresh in np.arange(0.1, 0.501, 0.01):
thresh = np.round(thresh, 2)
 score = metrics.f1_score(val_y,(pred_val_y > thresh ).astype(int))
if score > best_score:
best_thresh = thresh
best_score = score
print("Val F1 Score: {:.4f}".format(best_score))
pred_test_y = model.predict([test_X], batch_size=1024, verbose=0)
 return pred_val_y, pred_test_y, best_score
train_data.groupby(["Embarked", "Pclass"] ).Fare.mean()<feature_engineering>
train_X, val_X, test_X, train_y, val_y, word_index = load_and_prec()
embedding_matrix_1 = load_glove(word_index)
 embedding_matrix_2 = load_fasttext(word_index)
 embedding_matrix_3 = load_para(word_index )
train_data.loc[(train_data['Pclass'] == 1)&(train_data['Fare'] == 0.0),'Fare'] = 70.36
train_data.loc[(train_data['Pclass'] == 2)&(train_data['Fare'] == 0.0),'Fare'] = 20.33
train_data.loc[(train_data['Pclass'] == 3)&(train_data['Fare'] == 0.0),'Fare'] = 14.64<count_missing_values>
outputs = []
train_data.Age.isna().sum()<groupby>
outputs = []
pred_val_y, pred_test_y, best_score = train_pred(model_gru_srk_atten(embedding_matrix), epochs = 2)
 outputs.append([pred_val_y, pred_test_y, best_score, 'gru atten srk'] )
means = train_data.groupby(['Sex', 'Pclass'] ).Age.mean()
train_data.Age = train_data.apply(lambda x: means[x.Sex][x.Pclass] if pd.isnull(x.Age)else x.Age, axis=1 )<categorify>
pred_val_y, pred_test_y, best_score = train_pred(model_cnn(embedding_matrix), epochs = 2)
 outputs.append([pred_val_y, pred_test_y, best_score, '2d CNN'] )
train_data['Sex'] = pd.Categorical(train_data['Sex'])
 dfDummies = pd.get_dummies(train_data['Sex'], prefix = 'category')
 train_data = pd.concat([train_data.drop(columns=['Sex']), dfDummies], axis=1)
 train_data['Pclass'] = pd.Categorical(train_data['Pclass'])
 dfDummies = pd.get_dummies(train_data['Pclass'], prefix = 'category')
 train_data = pd.concat([train_data.drop(columns=['Pclass']), dfDummies], axis=1)
 train_data['Embarked'] = pd.Categorical(train_data['Embarked'])
 dfDummies = pd.get_dummies(train_data['Embarked'], prefix = 'category')
 train_data = pd.concat([train_data.drop(columns=['Embarked']), dfDummies], axis=1 )<data_type_conversions>
pred_val_y, pred_test_y, best_score = train_pred(model_cnn_flip(embedding_matrix), epochs = 2)
 outputs.append([pred_val_y, pred_test_y, best_score, '2d CNN flip'] )
for i in range(len(train_data)) :
if train_data.loc[i, "SibSp"] + train_data.loc[i, "Parch"] == 0:
train_data.loc[i, "Alone"] = 1
else:
train_data.loc[i, "Alone"] = 0
train_data.Alone = train_data.Alone.astype(int )<define_variables>
pred_val_y, pred_test_y, best_score = train_pred(model_cnn(embedding_matrix_1), epochs = 2)
 outputs.append([pred_val_y, pred_test_y, best_score, '2d CNN GloVe'] )
features = ['Age','SibSp','Parch','Fare','category_female','category_male','category_1','category_2','category_3','category_C','category_Q','category_S','Alone']<prepare_x_and_y>
pred_val_y, pred_test_y, best_score = train_pred(model_cnn_flip(embedding_matrix_1), epochs = 2)
 outputs.append([pred_val_y, pred_test_y, best_score, '2d CNN GloVe flip'] )
y = train_data['Survived']
x = train_data.drop(columns=['Survived'] )<normalization>
pred_val_y, pred_test_y, best_score = train_pred(model_lstm_du(embedding_matrix), epochs = 2)
 outputs.append([pred_val_y, pred_test_y, best_score, 'LSTM DU'] )
scaler = MinMaxScaler()<train_model>
pred_val_y, pred_test_y, best_score = train_pred(model_lstm_atten(embedding_matrix), epochs = 3)
 outputs.append([pred_val_y, pred_test_y, best_score, '2 LSTM w/ attention'] )
scaler.fit(x )<normalization>
pred_val_y, pred_test_y, best_score = train_pred(model_lstm_atten(embedding_matrix_1), epochs = 3)
 outputs.append([pred_val_y, pred_test_y, best_score, '2 LSTM w/ attention GloVe'] )
x = scaler.transform(x )<create_dataframe>
pred_val_y, pred_test_y, best_score = train_pred(model_lstm_atten(embedding_matrix_3), epochs = 3)
 outputs.append([pred_val_y, pred_test_y, best_score, '2 LSTM w/ attention Para'] )
x = pd.DataFrame(x, columns=features )<choose_model_class>
outputs.sort(key=lambda x: x[2])
 weights = [i for i in range(1, len(outputs)+ 1)]
weights = [float(i)/ sum(weights)for i in weights]
print(weights )
model = Sequential()
model.add(Dense(64, input_shape=(13,), activation='sigmoid'))
model.add(BatchNormalization())
 model.add(Dropout(0.2))
model.add(Dense(64, activation='sigmoid'))
model.add(Dense(1, activation="sigmoid"))
model.compile(optimizer="adadelta", loss='binary_crossentropy', metrics=["binary_accuracy"])
<train_model>
X = np.asarray([outputs[i][0] for i in range(len(outputs)) ])
 X = X[...,0]
reg = LinearRegression().fit(X.T, val_y)
 print(reg.score(X.T, val_y),reg.coef_ )
model_result = model.fit(x, y, batch_size=100, epochs=200, validation_split= 0.2, shuffle = True )<train_model>
pred_val_y = np.sum([outputs[i][0] * reg.coef_[i] for i in range(len(outputs)) ], axis = 0)
 thresholds = []
for thresh in np.arange(0.1, 0.501, 0.01):
thresh = np.round(thresh, 2)
 res = metrics.f1_score(val_y,(pred_val_y > thresh ).astype(int))
thresholds.append([thresh, res])
 print("F1 score at threshold {0} is {1}".format(thresh, res))
thresholds.sort(key=lambda x: x[1], reverse=True)
 best_thresh = thresholds[0][0]
print("Best threshold: ", best_thresh )
print("<-------Final Metrics------->")
 print("Loss = ",model_result.history['val_loss'][199])
 print("Accuracy = ",model_result.history['val_binary_accuracy'][199] )<load_from_csv>
pred_test_y = np.sum([outputs[i][1] * reg.coef_[i] for i in range(len(outputs)) ], axis = 0)
 pred_test_y =(pred_test_y > best_thresh ).astype(int)
 test_df = pd.read_csv(".. /input/test.csv", usecols=["qid"])
 out_df = pd.DataFrame({"qid":test_df["qid"].values})
 out_df['prediction'] = pred_test_y
out_df.to_csv("submission.csv", index=False )