Kaggle competition: Quora Insincere Questions Classification
list_of_first = []
for dateblocknum in df_block['date_block_num'].unique() :
df_first = df_block[(df_block['date_block_num'] < dateblocknum)&(df_block['first_sale_item'] == 0)].groupby(['item_category_id', 'shop_id'], as_index=False ).agg({'item_cnt_month': 'mean'})
 df_first.insert(0, 'date_block_num', dateblocknum)
 list_of_first.append(df_first)
 df_first = pd.concat(list_of_first, ignore_index=True ).rename(columns={'item_cnt_month': 'item_cnt_month_by_category_shop_first'})
 df_block = pd.merge(df_block, df_first, how='left', on=['date_block_num', 'item_category_id', 'shop_id'] )<groupby>
embed_size = 300
max_features = 95000
maxlen = 70
for i in [12, 18, 24, 30]:
list_of_first = []
for dateblocknum in df_block['date_block_num'].unique() :
df_first = df_block[(df_block['date_block_num'] >= i)&(df_block['date_block_num'] < dateblocknum)&(df_block['first_sale_item'] == 0)].groupby(['item_category_id', 'shop_id'], as_index=False ).agg({'item_cnt_month': 'mean'})
 df_first.insert(0, 'date_block_num', dateblocknum)
 list_of_first.append(df_first)
 df_first = pd.concat(list_of_first, ignore_index=True ).rename(columns={'item_cnt_month': 'item_cnt_month_by_category_shop_first_month' + str(i)+ 'onwards'})
 df_block = pd.merge(df_block, df_first, how='left', on=['date_block_num', 'item_category_id', 'shop_id'] )<merge>
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.callbacks import *
list_of_first = []
for dateblocknum in df_block['date_block_num'].unique() :
df_first = df_block[(df_block['date_block_num'] < dateblocknum)&(df_block['first_sale_item'] == 0)].groupby(['item_category_id', 'city_code'], as_index=False ).agg({'item_cnt_month': 'mean'})
 df_first.insert(0, 'date_block_num', dateblocknum)
 list_of_first.append(df_first)
 df_first = pd.concat(list_of_first, ignore_index=True ).rename(columns={'item_cnt_month': 'item_cnt_month_by_category_city_first'})
 df_block = pd.merge(df_block, df_first, how='left', on=['date_block_num', 'item_category_id', 'city_code'] )<groupby>
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
for i in [12, 18, 24, 30]:
list_of_first = []
for dateblocknum in df_block['date_block_num'].unique() :
df_first = df_block[(df_block['date_block_num'] >= i)&(df_block['date_block_num'] < dateblocknum)&(df_block['first_sale_item'] == 0)].groupby(['item_category_id', 'city_code'], as_index=False ).agg({'item_cnt_month': 'mean'})
 df_first.insert(0, 'date_block_num', dateblocknum)
 list_of_first.append(df_first)
 df_first = pd.concat(list_of_first, ignore_index=True ).rename(columns={'item_cnt_month': 'item_cnt_month_by_category_city_first_month' + str(i)+ 'onwards'})
 df_block = pd.merge(df_block, df_first, how='left', on=['date_block_num', 'item_category_id', 'city_code'] )<merge>
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
list_of_first = []
for dateblocknum in df_block['date_block_num'].unique() :
df_first = df_block[(df_block['date_block_num'] < dateblocknum)&(df_block['first_sale_item'] == 0)].groupby(['item_category_id', 'type_code'], as_index=False ).agg({'item_cnt_month': 'mean'})
 df_first.insert(0, 'date_block_num', dateblocknum)
 list_of_first.append(df_first)
 df_first = pd.concat(list_of_first, ignore_index=True ).rename(columns={'item_cnt_month': 'item_cnt_month_by_category_type_first'})
 df_block = pd.merge(df_block, df_first, how='left', on=['date_block_num', 'item_category_id', 'type_code'] )<merge>
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
list_of_first = []
for dateblocknum in df_block['date_block_num'].unique() :
df_first = df_block[(df_block['date_block_num'] < dateblocknum)&(df_block['first_sale_item'] == 0)].groupby(['item_category_id', 'subtype_code'], as_index=False ).agg({'item_cnt_month': 'mean'})
 df_first.insert(0, 'date_block_num', dateblocknum)
 list_of_first.append(df_first)
 df_first = pd.concat(list_of_first, ignore_index=True ).rename(columns={'item_cnt_month': 'item_cnt_month_by_category_subtype_first'})
 df_block = pd.merge(df_block, df_first, how='left', on=['date_block_num', 'item_category_id', 'subtype_code'] )<merge>
class CyclicLR(Callback):

 def __init__(self, base_lr=0.001, max_lr=0.006, step_size=2000., mode='triangular',
gamma=1., scale_fn=None, scale_mode='cycle'):
super(CyclicLR, self ).__init__()
self.base_lr = base_lr
self.max_lr = max_lr
self.step_size = step_size
self.mode = mode
self.gamma = gamma
if scale_fn == None:
if self.mode == 'triangular':
self.scale_fn = lambda x: 1.
 self.scale_mode = 'cycle'
elif self.mode == 'triangular2':
self.scale_fn = lambda x: 1/(2.**(x-1))
self.scale_mode = 'cycle'
elif self.mode == 'exp_range':
self.scale_fn = lambda x: gamma**(x)
 self.scale_mode = 'iterations'
else:
self.scale_fn = scale_fn
self.scale_mode = scale_mode
self.clr_iterations = 0.
 self.trn_iterations = 0.
 self.history = {}
self._reset()
def _reset(self, new_base_lr=None, new_max_lr=None,
new_step_size=None):

 if new_base_lr != None:
self.base_lr = new_base_lr
if new_max_lr != None:
self.max_lr = new_max_lr
if new_step_size != None:
self.step_size = new_step_size
self.clr_iterations = 0.
 def clr(self):
cycle = np.floor(1+self.clr_iterations/(2*self.step_size))
x = np.abs(self.clr_iterations/self.step_size - 2*cycle + 1)
 if self.scale_mode == 'cycle':
return self.base_lr +(self.max_lr-self.base_lr)*np.maximum(0,(1-x)) *self.scale_fn(cycle)
 else:
return self.base_lr +(self.max_lr-self.base_lr)*np.maximum(0,(1-x)) *self.scale_fn(self.clr_iterations)
 def on_train_begin(self, logs={}):
logs = logs or {}
if self.clr_iterations == 0:
K.set_value(self.model.optimizer.lr, self.base_lr)
 else:
K.set_value(self.model.optimizer.lr, self.clr())
 def on_batch_end(self, epoch, logs=None):
logs = logs or {}
self.trn_iterations += 1
self.clr_iterations += 1
self.history.setdefault('lr', [] ).append(K.get_value(self.model.optimizer.lr))
self.history.setdefault('iterations', [] ).append(self.trn_iterations)
 for k, v in logs.items() :
self.history.setdefault(k, [] ).append(v)
 K.set_value(self.model.optimizer.lr, self.clr())
 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()))
list_of_first = []
for dateblocknum in df_block['date_block_num'].unique() :
df_first = df_block[(df_block['date_block_num'] < dateblocknum)&(df_block['first_sale_item'] == 0)].groupby(['shop_id'], as_index=False ).agg({'item_cnt_month': 'mean'})
 df_first.insert(0, 'date_block_num', dateblocknum)
 list_of_first.append(df_first)
 df_first = pd.concat(list_of_first, ignore_index=True ).rename(columns={'item_cnt_month': 'item_cnt_month_by_shop_first'})
 df_block = pd.merge(df_block, df_first, how='left', on=['date_block_num', 'shop_id'] )<merge>
def model_lstm_atten(embedding_matrix):
inp = Input(shape=(maxlen,))
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)
 model.compile(loss='binary_crossentropy', optimizer='adam', metrics=[f1])
 return model
list_of_first = []
for dateblocknum in df_block['date_block_num'].unique() :
df_first = df_block[(df_block['date_block_num'] < dateblocknum)&(df_block['first_sale_item'] == 0)].groupby(['city_code'], as_index=False ).agg({'item_cnt_month': 'mean'})
 df_first.insert(0, 'date_block_num', dateblocknum)
 list_of_first.append(df_first)
 df_first = pd.concat(list_of_first, ignore_index=True ).rename(columns={'item_cnt_month': 'item_cnt_month_by_city_first'})
 df_block = pd.merge(df_block, df_first, how='left', on=['date_block_num', 'city_code'] )<filter>
def train_pred(model, train_X, train_y, val_X, val_y, epochs=2, callback=None):
for e in range(epochs):
model.fit(train_X, train_y, batch_size=512, epochs=1, validation_data=(val_X, val_y), callbacks = callback, verbose=0)
 pred_val_y = model.predict([val_X], batch_size=1024, verbose=0)
 best_score = metrics.f1_score(val_y,(pred_val_y > 0.33 ).astype(int))
print("Epoch: ", e, "- Val F1 Score: {:.4f}".format(best_score))
pred_test_y = model.predict([test_X], batch_size=1024, verbose=0)
 print('=' * 60)
 return pred_val_y, pred_test_y, best_score
df_block = df_block[df_block['date_block_num'] > 11]<data_type_conversions>
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 )
col_fillnas = df_block.columns[df_block.isna().any() ].tolist()
df_block[col_fillnas] = df_block[col_fillnas].fillna(0 )<data_type_conversions>
embedding_matrix = np.mean([embedding_matrix_1, embedding_matrix_3], axis = 0)
 np.shape(embedding_matrix)
 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_SPLIT_SEED = 2018
clr = CyclicLR(base_lr=0.001, max_lr=0.002,
step_size=300., mode='exp_range',
gamma=0.99994 )
<prepare_x_and_y><EOS> 
train_meta = np.zeros(train_y.shape)
 test_meta = np.zeros(test_X.shape[0])
 splits = list(StratifiedKFold(n_splits=4, 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 = model_lstm_atten(embedding_matrix)
 pred_val_y, pred_test_y, best_score = train_pred(model, X_train, y_train, X_val, y_val, epochs = 8, callback = [clr,])
 train_meta[valid_idx] = pred_val_y.reshape(-1)
 test_meta += pred_test_y.reshape(-1)/ len(splits)
 sub = pd.read_csv('.. /input/sample_submission.csv')
 sub.prediction = test_meta > 0.33
sub.to_csv("submission.csv", index=False )