Kaggle competition: Quora Insincere Questions Classification
xgb_pred = np.expm1(xbg_model_tuned.predict(X_test))<prepare_output>
embed_size = 300
max_features = 95000
maxlen = 70
avg_pred = 0.2 * ridge_pred + 0.4 * lasso_pred + 0.4 * xgb_pred<save_to_csv>
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 sklearn.model_selection import GridSearchCV, StratifiedKFold
from sklearn.metrics import f1_score, roc_auc_score
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
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
from keras.layers import concatenate
from keras.optimizers import SGD
output = pd.DataFrame({'Id': X_test.index,
'SalePrice': avg_pred})
 output.to_csv('submission.csv', index=False )<set_options>
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_X = train_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)
 test_X = tokenizer.texts_to_sequences(test_X)
 train_X = pad_sequences(train_X, maxlen=maxlen)
 test_X = pad_sequences(test_X, maxlen=maxlen)
 train_y = train_df['target'].values
np.random.seed(2018)
 trn_idx = np.random.permutation(len(train_X))
train_X = train_X[trn_idx]
train_y = train_y[trn_idx]
return train_X, test_X, train_y, tokenizer.word_index
warnings.filterwarnings("ignore" )<load_from_csv>
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 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 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 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
train = pd.read_csv(".. /input/titanic/train.csv")
 test = pd.read_csv(".. /input/titanic/test.csv" )<data_type_conversions>
class Snapshot(Callback):
def __init__(self, folder_path, nb_epochs, nb_cycles=5, verbose=0):
if nb_cycles > nb_epochs:
raise ValueError('nb_epochs has to be lower than nb_cycles.')
 super(Snapshot, self ).__init__()
self.verbose = verbose
self.folder_path = folder_path
self.nb_epochs = nb_epochs
self.nb_cycles = nb_cycles
self.period = self.nb_epochs // self.nb_cycles
self.nb_digits = len(str(self.nb_cycles))
self.path_format = os.path.join(self.folder_path, 'weights_cycle_{}.h5')
 def on_epoch_end(self, epoch, logs=None):
if epoch == 0 or(epoch + 1)% self.period != 0: return
if not os.path.exists(self.folder_path):
os.makedirs(self.folder_path)
 cycle = int(epoch / self.period)
 cycle_str = str(cycle ).rjust(self.nb_digits, '0')
 self.model.save_weights(self.path_format.format(cycle_str), overwrite=True)
 K.set_value(self.model.optimizer.lr, self.base_lr)
 if self.verbose > 0:
print('
Epoch %05d: Reached %d-th cycle, saving model.' %(epoch, cycle))
def on_epoch_begin(self, epoch, logs=None):
if epoch <= 0: return
lr = self.schedule(epoch)
 K.set_value(self.model.optimizer.lr, lr)
 if self.verbose > 0:
print('
Epoch %05d: Snapchot modifying learning '
'rate to %s.' %(epoch + 1, lr))
def set_model(self, model):
self.model = model
if not hasattr(self.model.optimizer, 'lr'):
raise ValueError('Optimizer must have a "lr" attribute.')
 self.base_lr = float(K.get_value(self.model.optimizer.lr))
def schedule(self, epoch):
lr = math.pi *(epoch % self.period)/ self.period
lr = self.base_lr / 2 *(math.cos(lr)+ 1)
 return lr
def load_ensemble(folder, keep_last=None):
paths = glob.glob(os.path.join(folder, 'weights_cycle_*.h5'))
print('Found:', ', '.join(paths))
if keep_last is not None:
paths = sorted(paths)[-keep_last:]
print('Loading:', ', '.join(paths))
x_in = Input(shape=(maxlen,))
outputs = []
for i, path in enumerate(paths):
m = get_model(x_in)
 m.load_weights(path)
 outputs.append(m.output)
 shape = outputs[0].get_shape().as_list()
x = Lambda(lambda x: K.mean(K.stack(x, axis=0), axis=0),
output_shape=lambda _: shape )(outputs)
 model = Model(inputs=x_in, outputs=x)
 return model
train =train.astype({"Pclass":"category"})
 test =test.astype({"Pclass":"category"} )<concatenate>
def f1(y_true, y_pred):

 def recall(y_true, y_pred):

 true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
 possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))
 recall = true_positives /(possible_positives + K.epsilon())
 return recall
def precision(y_true, y_pred):

 true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
 predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))
 precision = true_positives /(predicted_positives + K.epsilon())
 return precision
precision = precision(y_true, y_pred)
 recall = recall(y_true, y_pred)
 return 2*(( precision*recall)/(precision+recall+K.epsilon()))
y=train["Survived"].values
test_index = len(y)-1
data = pd.concat([train,test],sort=False ).reset_index(drop=True)
 data.info()<feature_engineering>
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
data["Title"]= data["Name"].str.split(", ",expand=True)[1].str.split(".",expand=True)[0]
mapping = {'Mlle': 'Miss', 'Major': 'Mr', 'Col': 'Mr', 'Sir': 'Mr', 'Don': 'Mr', 'Mme': 'Miss',
'Jonkheer': 'Mr', 'Lady': 'Mrs', 'Capt': 'Mr', 'Countess': 'Mrs', 'Ms': 'Miss', 'Dona': 'Mrs'}
data.replace({'Title': mapping}, inplace=True )<categorify>
def get_model(inp):
x = Embedding(max_features, embed_size, weights=[embedding_matrix], trainable=False )(inp)
 x = SpatialDropout1D(0.1 )(x)
 x = Bidirectional(CuDNNLSTM(40, return_sequences=True))(x)
 y = Bidirectional(CuDNNGRU(40, return_sequences=True))(x)
 atten_1 = Attention(maxlen )(x)
 atten_2 = Attention(maxlen )(y)
 avg_pool = GlobalAveragePooling1D()(y)
 max_pool = GlobalMaxPooling1D()(y)
 conc = concatenate([atten_1, atten_2, avg_pool, max_pool])
 conc = Dense(16, activation="relu" )(conc)
 conc = Dropout(0.1 )(conc)
 outp = Dense(1, activation="sigmoid" )(conc)
 model = Model(inputs=inp, outputs=outp)
 return model
data["Fam_size"] = data["SibSp"]+data["Parch"]+1
def mapping(title,tick_size):
for(ind,val)in zip(age_impute,age_impute.values()):
if(( ind[0]==title)&(ind[1]==tick_size)) :
return val
age_impute=data.groupby(["Title","Fam_size"])["Age"].median().astype("float64" ).to_dict()<feature_engineering>
def train_pred(model, train_X, train_y, val_X, val_y, epochs=2):
cbs = [Snapshot('snapshots', nb_epochs=epochs, verbose=0, nb_cycles=3)]
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=[f1])
 model.fit(train_X, train_y, batch_size=512, epochs=epochs, validation_data=(val_X, val_y), callbacks=cbs, verbose=0)
 del model
model = load_ensemble('snapshots', 2)
 model.compile(loss='binary_crossentropy', optimizer='adam', metrics=[f1])
 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
data.loc[data["Age"].isnull() ,"Age"]= data.loc[data["Age"].isnull() ,["Title","Fam_size"]].apply(lambda x: mapping(x[0],x[1]),axis=1 )<categorify>
train_X, test_X, train_y, word_index = load_and_prec()
embedding_matrix_1 = load_glove(word_index)
 embedding_matrix_3 = load_para(word_index )
data["Age_bin"] = pd.qcut(data["Age"],10,duplicates="drop")
 label = LabelEncoder()
data['Age_bin'] = label.fit_transform(data['Age_bin'].astype(str))<feature_engineering>
embedding_matrix = np.mean([embedding_matrix_1, embedding_matrix_3], axis = 0)
 np.shape(embedding_matrix )
data["Fare"].fillna(data[~data["Fare"].isnull() ].groupby("Pclass")["Fare"].mean() [3],inplace=True)
 data['Last_Name'] = data['Name'].apply(lambda x: str.split(x, ",")[0])
 data['Family_Survival'] = 0.5
for grp, grp_data in data[['Survived','Name', 'Last_Name', 'Fare', 'Ticket', 'PassengerId',
'SibSp', 'Parch', 'Age', 'Cabin']].groupby(['Last_Name', 'Fare']):
if(len(grp_data)!= 1):
for ind, row in grp_data.iterrows() :
vmax = grp_data.drop(ind)['Survived'].max()
vmin = grp_data.drop(ind)['Survived'].min()
passid = row['PassengerId']
if(vmax == 1.0):
data.loc[data['PassengerId'] == passid, 'Family_Survival'] = 1
elif(vmin==0.0):
data.loc[data['PassengerId'] == passid, 'Family_Survival'] = 0
for grp, grp_data in data.groupby('Ticket'):
if(len(grp_data)!= 1):
for ind, row in grp_data.iterrows() :
if(row['Family_Survival'] == 0)|(row['Family_Survival']== 0.5):
vmax = grp_data.drop(ind)['Survived'].max()
vmin = grp_data.drop(ind)['Survived'].min()
passid = row['PassengerId']
if(vmax == 1.0):
data.loc[data['PassengerId'] == passid, 'Family_Survival'] = 1
elif(vmin==0.0):
data.loc[data['PassengerId'] == passid, 'Family_Survival'] = 0 
<feature_engineering>
def threshold_search(y_true, y_proba):
best_threshold = 0
best_score = 0
for threshold in [i * 0.01 for i in range(100)]:
score = f1_score(y_true=y_true, y_pred=y_proba > threshold)
 if score > best_score:
best_threshold = threshold
best_score = score
search_result = {'threshold': best_threshold, 'f1': best_score}
return search_result
data["Embarked"].fillna(data["Embarked"].mode() [0],inplace=True)
 data["Fare"]=data["Fare"]/data["Fam_size"]
data["Fare"].fillna(data[~data["Fare"].isnull() ].groupby("Pclass")["Fare"].mean() [3],inplace=True )<categorify>
DATA_SPLIT_SEED = 2018
train_meta = np.zeros(train_y.shape)
 test_meta = np.zeros(test_X.shape[0])
 splits = list(StratifiedKFold(n_splits=5, shuffle=True, random_state=DATA_SPLIT_SEED ).split(train_X, train_y))
for idx,(train_idx, valid_idx)in enumerate(splits):
X_train = train_X[train_idx]
y_train = train_y[train_idx]
X_val = train_X[valid_idx]
y_val = train_y[valid_idx]
model = get_model(Input(shape=(maxlen,)))
 pred_val_y, pred_test_y, best_score = train_pred(model, X_train, y_train, X_val, y_val, epochs = 6)
 train_meta[valid_idx] = pred_val_y.reshape(-1)
 test_meta += pred_test_y.reshape(-1)/ len(splits )
<drop_column><EOS> 
search_result = threshold_search(train_y, train_meta)
 print(search_result)
 sub = pd.read_csv('.. /input/sample_submission.csv')
 sub.prediction = test_meta > search_result['threshold']
sub.to_csv("submission.csv", index=False )