Kaggle competition: Instacart Market Basket Analysis
<SOS> metric: MeanFScore Kaggle data source: instacart-market-basket-analysis<import_modules>
gc.enable()
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
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<load_from_csv>
PATH = '/kaggle/input/instacart-market-basket-analysis/'
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.001, 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<statistical_test>
print('loading files...')
 order_products_prior = pd.read_csv(PATH + 'order_products__prior.csv')
 order_products_train = pd.read_csv(PATH + 'order_products__train.csv')
 orders = pd.read_csv(PATH + 'orders.csv')
 products = pd.read_csv(PATH + 'products.csv', usecols=['product_id', 'aisle_id', 'department_id'])
 orders.eval_set = orders.eval_set.replace({'prior': 0, 'train': 1, 'test':2})
 orders.days_since_prior_order = orders.days_since_prior_order.fillna(30)
 print('done loading' )
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 = -0.005838499,0.48782197
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 = -0.0053247833,0.49346462
embed_size = all_embs.shape[1]
print(emb_mean,emb_std,"para")
 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<choose_model_class>
prior_orders = pd.merge(orders, order_products_prior, on='order_id', how='inner')
 prior_orders.head()
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<choose_model_class>
del order_products_prior
gc.collect()
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<choose_model_class>
users = prior_orders.groupby(by='user_id')['order_number'].aggregate('max' ).to_frame('u_num_of_orders' ).reset_index()
users.head()
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<choose_model_class>
total_prd_per_order = prior_orders.groupby(by=['user_id', 'order_id'])['product_id'].aggregate('count' ).to_frame('total_products_per_order' ).reset_index()
avg_products = total_prd_per_order.groupby(by=['user_id'])['total_products_per_order'].mean().to_frame('u_avg_prd' ).reset_index()
avg_products.head()
del [total_prd_per_order]
gc.collect()
avg_products.head()
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 
<choose_model_class>
reorder_u = prior_orders.groupby(by='user_id')['reordered'].aggregate('mean' ).to_frame('u_reorder_ratio' ).reset_index()
reorder_u['u_reorder_ratio'] = reorder_u['u_reorder_ratio'].astype(np.float16)
 reorder_u.head()
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<choose_model_class>
avg_days = prior_orders.groupby(by='user_id')['days_since_prior_order'].aggregate('mean' ).to_frame('average_days_between_orders')
 avg_days = avg_days.reset_index()
avg_days.head()
def model_gru_atten_3(embedding_matrix):
inp = Input(shape=(maxlen,))
x = Embedding(max_features, embed_size, weights=[embedding_matrix], trainable=False )(inp)
 x = Bidirectional(CuDNNGRU(128, return_sequences=True))(x)
 x = Bidirectional(CuDNNGRU(100, return_sequences=True))(x)
 x = Bidirectional(CuDNNGRU(64, return_sequences=True))(x)
 x = Attention(maxlen )(x)
 x = Dense(1, activation="sigmoid" )(x)
 model = Model(inputs=inp, outputs=x)
 model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
 return model<predict_on_test>
total_item = prior_orders.groupby(by='user_id' ).size().to_frame('u_total_items_bought' ).astype(np.int16)
 total_item.head()
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)
 pred_test_y = model.predict([test_X], batch_size=1024, verbose=0)
 return pred_val_y, pred_test_y<load_pretrained>
users = users.merge(avg_products, on='user_id', how='left')
 users = users.merge(dow, on='user_id', how='left')
 users = users.merge(hod, on='user_id', how='left')
 users = users.merge(reorder_u, on='user_id', how='left')
 users = users.merge(avg_days, on='user_id', how='left')
 users = users.merge(total_item, on='user_id', how='left')
 users.head()
train_X, val_X, test_X, train_y, val_y, word_index = load_and_prec()
vocab = []
for w,k in word_index.items() :
vocab.append(w)
 if k >= max_features:
break
embedding_matrix_1 = load_glove(word_index)
 embedding_matrix_3 = load_para(word_index )<define_variables>
del [reorder_u, dow, hod, avg_products, avg_days, total_item]
gc.collect()
outputs = []<predict_on_test>
prd = prior_orders.groupby(by='product_id')['order_id'].aggregate('count' ).to_frame('p_num_of_times' ).reset_index()
prd.head()
pred_val_y, pred_test_y = train_pred(model_gru_atten_3(embedding_matrix), epochs = 3)
 outputs.append([pred_val_y, pred_test_y, '3 GRU w/ atten'] )<predict_on_test>
reorder_p = prior_orders.groupby(by='product_id')['reordered'].aggregate('mean' ).to_frame('p_reorder_ratio' ).reset_index()
reorder_p.head()
pred_val_y, pred_test_y = train_pred(model_gru_srk_atten(embedding_matrix), epochs = 2)
 outputs.append([pred_val_y, pred_test_y, 'gru atten srk'] )<predict_on_test>
add_to_cart = prior_orders.groupby(by='product_id')['add_to_cart_order'].aggregate('mean' ).to_frame('p_avg_cart_position' ).reset_index()
add_to_cart.head()
pred_val_y, pred_test_y = train_pred(model_cnn(embedding_matrix), epochs = 2)
 outputs.append([pred_val_y, pred_test_y, '2d CNN'] )<predict_on_test>
prd = prd.merge(reorder_p, on='product_id', how='left')
 prd = prd.merge(add_to_cart, on='product_id', how='left')
 del [reorder_p, add_to_cart]
gc.collect()
pred_val_y, pred_test_y = train_pred(model_cnn(embedding_matrix_1), epochs = 2)
 outputs.append([pred_val_y, pred_test_y, '2d CNN GloVe'] )<predict_on_test>
uxp = prior_orders.groupby(by=['user_id', 'product_id'])['order_id'].aggregate('count' ).to_frame('uxp_times_bought')
 uxp = uxp.reset_index()
uxp.head()
pred_val_y, pred_test_y = train_pred(model_lstm_du(embedding_matrix), epochs = 2)
 outputs.append([pred_val_y, pred_test_y, 'LSTM DU'] )<predict_on_test>
times = prior_orders.groupby(by=['user_id', 'product_id'])['order_id'].aggregate('count' ).to_frame('times_bought')
 times = times.reset_index()
times.head()
pred_val_y, pred_test_y = train_pred(model_lstm_atten(embedding_matrix), epochs = 3)
 outputs.append([pred_val_y, pred_test_y, '2 LSTM w/ attention'] )<predict_on_test>
total_orders = prior_orders.groupby('user_id')['order_number'].max().to_frame('total_orders' ).reset_index()
total_orders.head()
pred_val_y, pred_test_y = train_pred(model_lstm_atten(embedding_matrix_1), epochs = 3)
 outputs.append([pred_val_y, pred_test_y, '2 LSTM w/ attention GloVe'] )<predict_on_test>
span = pd.merge(total_orders, first_order_num, on='user_id', how='right')
 span.head()
pred_val_y, pred_test_y = train_pred(model_lstm_atten(embedding_matrix_3), epochs = 3)
 outputs.append([pred_val_y, pred_test_y, '2 LSTM w/ attention Para'] )<save_to_csv>
span['Order_Range_D'] = span.total_orders - span.first_order_num + 1
span.head()
pred_test_y = np.mean([outputs[i][1] for i in range(len(outputs)) ], axis = 0)
 pred_test_y =(pred_test_y > 0.33 ).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 )<set_options>
uxp_ratio = pd.merge(times, span, on=['user_id', 'product_id'], how='left')
 uxp_ratio.head()
np.random.seed(7418880)
 tf.set_random_seed(7418880)
<load_from_csv>
uxp_ratio['uxp_reorder_ratio'] = uxp_ratio.times_bought / uxp_ratio.Order_Range_D
uxp_ratio.head()
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("_na_" ).values
test_X = test_df["question_text"].fillna("_na_" ).values
train_y = train_df['target'].values
embed_size = 300
max_words = 50000
max_len = 70 
<string_transform>
uxp_ratio.drop(['times_bought', 'total_orders', 'first_order_num', 'Order_Range_D'], axis=1, inplace=True)
 uxp_ratio.head()
start_time = time.time()
tokenizer = Tokenizer(num_words=max_words)
 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=max_len)
 test_X = pad_sequences(test_X, maxlen=max_len)
 print(train_X.shape, test_X.shape)
 print("Total time for tokenizing = {:.0f} s".format(time.time() -start_time))<statistical_test>
del [times, span, first_order_num, total_orders]
gc.collect()
start_time = time.time()
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.rstrip().rsplit(' ')) 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]
word_index = tokenizer.word_index
nb_words = min(max_words, 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_words: continue
embedding_vector = embeddings_index.get(word)
 if embedding_vector is not None: embedding_matrix[i] = embedding_vector
print("Total time for embedding = {:.0f} s".format(time.time() -start_time))<choose_model_class>
uxp = uxp.merge(uxp_ratio, on=['user_id', 'product_id'], how='left')
 del uxp_ratio
gc.collect()
def generate_model() :
input = Input(shape=(max_len,))
embed = Embedding(max_words, embed_size, weights=[embedding_matrix] )(input)
 x = Bidirectional(CuDNNLSTM(64, return_sequences=True))(embed)
 x = Bidirectional(CuDNNGRU(64, return_sequences=True))(x)
 x = GlobalMaxPool1D()(x)
 x = Dense(16, activation="relu" )(x)
 x = Dropout(0.1 )(x)
 y = Bidirectional(CuDNNGRU(64, return_sequences=True))(embed)
 y = Bidirectional(CuDNNLSTM(64, return_sequences=True))(y)
 y = GlobalMaxPool1D()(y)
 y = Dense(16, activation="relu" )(y)
 y = Dropout(0.1 )(y)
 z= Concatenate()([x,y])
 output = Dense(1, activation="sigmoid" )(z)
 model = Model(inputs=input, outputs=output)
 return model<train_model>
start_time = time.time()
uid = 1
version =1
n_splits = 5
n_epochs =2
batch_size =1024
skf = StratifiedKFold(n_splits=n_splits, random_state = 7418880, shuffle=False)
 val_preds = defaultdict(list)
 test_preds = {}
historyD={}
for ii,(train_index, val_index)in enumerate(skf.split(train_X, train_y)) :
X_train, X_val = train_X[train_index], train_X[val_index]
y_train, y_val = train_y[train_index], train_y[val_index]
model = generate_model()
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
 hist = model.fit(X_train, y_train, batch_size=batch_size, epochs=n_epochs,
validation_data=(X_val, y_val), verbose= True)
 historyD["fold{}".format(ii+1)] = hist.history
pred_val_y = model.predict([X_val], batch_size=batch_size, verbose=1)
 val_preds['fold{}'.format(ii+1)] = [pred_val_y.ravel() ,y_val]
pred_test_y = model.predict([test_X], batch_size=batch_size, verbose=1)
 test_preds['fold{}'.format(ii+1)] = pred_test_y.ravel()
del model
gc.collect()
with open('train_history_uid{}_v{}.pkl'.format(uid, version),'wb')as pklfile:
pickle.dump(historyD,pklfile)
 with open('val_preds_uid{}_v{}.pkl'.format(uid, version),'wb')as pklfile:
pickle.dump(val_preds,pklfile)
 with open('test_preds_uid{}_v{}.pkl'.format(uid, version),'wb')as pklfile:
pickle.dump(test_preds,pklfile)
 print("Total time for training = {:.0f} s".format(time.time() -start_time)) 
<compute_test_metric>
prior_orders['order_number_back'] = prior_orders.groupby(by=['user_id'])['order_number'].transform(max)- prior_orders.order_number + 1
prior_orders.head()
test01_df = pd.DataFrame()
for ii in range(len(val_preds)) :
threshL = []
y_preds, y_actual =(val_preds['fold{}'.format(ii+1)])
 for idx, thresh in enumerate(np.arange(0.1, 0.51, 0.01)) :
thresh = np.round(thresh,2)
 y_01 = [ 0 if x <thresh else 1 for x in y_preds]
threshL.append(( metrics.f1_score(y_actual,y_01), thresh))
threshL=sorted(threshL)
 best_F1, opt_thresh = threshL[-1]
print("For fold {0}, best validation F1 of {1:.5f} at threshold {2:.2f}".format(ii+1, best_F1,opt_thresh))
test01_df['fold{}'.format(ii)] = [ 0 if x<opt_thresh else 1 for x in test_preds['fold{}'.format(ii+1)]]<count_values>
last_five['uxp_ratio_last_five'] = last_five.uxp_last_five / 5.0
last_five.head()
print(test01_df.sum(axis=1 ).value_counts() )<save_to_csv>
out_df = pd.DataFrame({"qid":test_df["qid"].values})
 out_df['prediction'] = [ 0 if x<2.5 else 1 for x in test01_df.sum(axis=1)]
out_df.to_csv("submission.csv", index=False )<define_variables>
uxp = uxp.merge(last_five, on=['user_id', 'product_id'], how='left')
 del [last_five, temp]
gc.collect()
uxp.head()
embed_size = 300
max_features = 95000
maxlen = 70<import_modules>
uxp.fillna(0, inplace=True)
 uxp.head(10 )
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
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<load_from_csv>
data = uxp.merge(users, on='user_id', how='left')
 data.head()
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.05, 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<statistical_test>
data = data.merge(prd, on='product_id', how='left')
 data.head()
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<choose_model_class>
del [users, prd, uxp]
gc.collect()
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<choose_model_class>
orders_future = orders.loc[(( orders.eval_set == 1)|(orders.eval_set == 2)) , ['user_id', 'eval_set', 'order_id']]
orders_future.head()
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<choose_model_class>
data = data.merge(orders_future, on='user_id', how='left')
 data.head()
def fusion_model_1(embedding_matrix_1, embedding_matrix_2):
inp = Input(shape=(maxlen,))
emb_1 = Embedding(max_features, embed_size, weights=[embedding_matrix_1], trainable=False )(inp)
 emb_2 = Embedding(max_features, embed_size, weights=[embedding_matrix_2], trainable=False )(inp)
 x1 = Bidirectional(CuDNNLSTM(128, return_sequences=True))(emb_1)
 x1 = Bidirectional(CuDNNLSTM(64, return_sequences=True))(x1)
 x1 = Attention(maxlen )(x1)
 x1 = Dense(64, activation="relu" )(x1)
 filter_sizes = [1,2,3,5]
num_filters = 36
x2 = Reshape(( maxlen, embed_size, 1))(emb_1)
 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' )(x2)
 maxpool_pool.append(MaxPool2D(pool_size=(maxlen - filter_sizes[i] + 1, 1))(conv))
z2 = Concatenate(axis=1 )(maxpool_pool)
 z2 = Flatten()(z2)
 z2 = Dense(64, activation="relu" )(z2)
 x3 = Bidirectional(CuDNNGRU(64, return_sequences=True))(emb_2)
 x3 = Attention(maxlen )(x3)
 x3 = Dense(16, activation="relu" )(x3)
 x4 = Bidirectional(CuDNNGRU(128, return_sequences=True))(emb_2)
 x4 = Bidirectional(CuDNNGRU(100, return_sequences=True))(x4)
 x4 = Bidirectional(CuDNNGRU(64, return_sequences=True))(x4)
 x4 = Attention(maxlen )(x4)
 x4 = Dense(16, activation="relu" )(x4)
 x = Concatenate(axis=1 )([x1, z2, x3, x4])
 x = Dense(128, 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<choose_model_class>
data_train = data[data.eval_set == 1]
data_train.head()
def fusion_model_2(embedding_matrix):
new_embed_size = embedding_matrix.shape[1]
inp = Input(shape=(maxlen,))
emb = Embedding(max_features, new_embed_size, weights=[embedding_matrix] )(inp)
 x1 = Bidirectional(CuDNNLSTM(128, return_sequences=True))(emb)
 x1 = Bidirectional(CuDNNLSTM(64, return_sequences=True))(x1)
 x1 = Attention(maxlen )(x1)
 x1 = Dense(64, activation="relu" )(x1)
 filter_sizes = [1,2,3,5]
num_filters = 36
x2 = Reshape(( maxlen, new_embed_size, 1))(emb)
 maxpool_pool = []
for i in range(len(filter_sizes)) :
conv = Conv2D(num_filters, kernel_size=(filter_sizes[i], new_embed_size),
kernel_initializer='he_normal', activation='elu' )(x2)
 maxpool_pool.append(MaxPool2D(pool_size=(maxlen - filter_sizes[i] + 1, 1))(conv))
z2 = Concatenate(axis=1 )(maxpool_pool)
 z2 = Flatten()(z2)
 z2 = Dense(64, activation="relu" )(z2)
 x = Concatenate(axis=1 )([x1, z2])
 x = Dropout(0.3 )(x)
 x = Dense(128, 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<choose_model_class>
data_train = data_train.merge(order_products_train[['product_id', 'order_id', 'reordered']], on=['product_id', 'order_id'], how='left')
 data_train.head()
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<choose_model_class>
data_train.drop(['eval_set', 'order_id'], axis=1, inplace=True )
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 
<choose_model_class>
data_test = data[data.eval_set == 2]
data_test.head()
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<choose_model_class>
data_test.drop(['eval_set', 'order_id'], axis=1, inplace=True )
def model_gru_atten_3(embedding_matrix):
inp = Input(shape=(maxlen,))
x = Embedding(max_features, embed_size, weights=[embedding_matrix], trainable=False )(inp)
 x = Bidirectional(CuDNNGRU(128, return_sequences=True))(x)
 x = Bidirectional(CuDNNGRU(100, return_sequences=True))(x)
 x = Bidirectional(CuDNNGRU(64, return_sequences=True))(x)
 x = Attention(maxlen )(x)
 x = Dense(1, activation="sigmoid" )(x)
 model = Model(inputs=inp, outputs=x)
 model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
 return model<find_best_params>
products = pd.read_csv(PATH + 'products.csv', usecols=['product_id', 'aisle_id', 'department_id'])
 data_train = data_train.merge(products, on='product_id', how='left')
 data_test = data_test.merge(products, on='product_id', how='left')
 data_train = data_train.set_index(['user_id', 'product_id'])
 data_test = data_test.set_index(['user_id', 'product_id'] )
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<split>
columns_mean = ['aisle_id', 'department_id']
for col in columns_mean:
mean = data_train.groupby(col ).reordered.mean()
data_train[col] = data_train[col].map(mean)
 data_test[col] = data_test[col].map(mean )
train_X, val_X, test_X, train_y, val_y, word_index = load_and_prec()
embedding_matrix_1 = load_glove(word_index)
 embedding_matrix_3 = load_para(word_index )<define_variables>
del [data, orders_future, products, order_products_train]
gc.collect()
outputs = []<predict_on_test>
from sklearn.model_selection import train_test_split, GridSearchCV, KFold
from sklearn.metrics import f1_score, classification_report
from scikitplot.metrics import plot_confusion_matrix
from scikitplot.classifiers import plot_feature_importances
import xgboost as xgb
import lightgbm as lgb
pred_val_y, pred_test_y, best_score = train_pred(fusion_model_2(embedding_matrix_c), epochs = 2)
 outputs.append([pred_val_y, pred_test_y, best_score, 'Fusion model 1 - LSTM and CNN'] )<predict_on_test>
X = data_train.drop(['reordered', 'uxp_ratio_last_five'], axis=1)
 y = data_train.reordered
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=10 )
pred_val_y, pred_test_y, best_score = train_pred(fusion_model_1(embedding_matrix_1, embedding_matrix_3), epochs = 3)
 outputs.append([pred_val_y, pred_test_y, best_score, 'Fusion model 1 - LSTM, CNN, GRU and GRU3'] )<sort_values>
del [X, y]
gc.collect()
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 )<compute_test_metric>
lgbm.fit(data_train.drop(['reordered', 'uxp_ratio_last_five'], axis=1), data_train.reordered )
pred_val_y = np.mean([outputs[i][0] 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 )<save_to_csv>
y_pred_test =(lgbm.predict_proba(data_test.drop('uxp_ratio_last_five', axis=1)) [:, 1] >= 0.21 ).astype('int' )
pred_test_y = np.mean([outputs[i][1] 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 )<import_modules>
data_test['prediction'] = y_pred_test
data_test.head()
import numpy as np
import pandas as pd
import os
from tqdm import tqdm, trange
import string
import re
import sys
import math
from keras.models import Sequential
from keras.layers import CuDNNLSTM, Dense, Bidirectional, Dropout, BatchNormalization, Activation
import random
from keras.preprocessing.sequence import pad_sequences
from time import time
from sklearn import metrics
from keras.optimizers import Adam
from keras.regularizers import l1_l2<load_from_csv>
orders = pd.read_csv(PATH + 'orders.csv')
 orders_test = orders.loc[orders.eval_set == 'test', ['user_id', 'order_id']]
orders_test.head()
df=pd.read_csv('.. /input/train.csv')
 df=df[['question_text','target']]
df=df.dropna()<count_values>
final = final.merge(orders_test, on='user_id', how='left')
 final.head()
pos_pct=df['target'].value_counts() [1]/len(df)
 print(f'Caustic questions percentage is {pos_pct*100:.2f}%' )<string_transform>
final = final.drop('user_id', axis=1 )
trans_table={key:' ' for key in string.punctuation}
def get_words(s):

 s=s.translate(str.maketrans(trans_table)).lower().strip()
s=re.sub(' +',' ',s)
 s=s.split(' ')
 return len(s )<feature_engineering>
final['product_id'] = final.product_id.astype(int)
 del orders
del orders_test
gc.collect()
final.head()
df['n_words']=df['question_text'].apply(get_words )<filter>
d = dict()
for row in final.itertuples() :
if row.prediction== 1:
try:
d[row.order_id] += ' ' + str(row.product_id)
 except:
d[row.order_id] = str(row.product_id)
 for order in final.order_id:
if order not in d:
d[order] = 'None'
gc.collect()
df=df[df['n_words']<=60]<feature_engineering>
sub = pd.DataFrame.from_dict(d, orient='index')
 sub.reset_index(inplace=True)
 sub.columns = ['order_id', 'products']
sub.head()
embedding_path='glove.840B.300d/glove.840B.300d.txt'
vocab={}
with open('.. /input/embeddings/' + embedding_path,'r')as f:
for line_number,line in enumerate(tqdm(f)) :
key,values=line.split(' ')[0],line.split(' ')[1:]
if not any(char in string.punctuation for char in key):
vocab[key]=np.asarray(values,dtype='float32')
 print(f'Total of {len(vocab.keys())} words in vocabulary' )<categorify>
sub.to_csv('sub.csv', index=False, header=True )
<define_variables><EOS> 
del [X, y, X_train, y_train, y_test, X_test, lgbm, y_pred]
gc.collect()