Kaggle competition: Instacart Market Basket Analysis
<SOS> metric: MeanFScore Kaggle data source: instacart-market-basket-analysis<create_dataframe>
import pandas as pd
import gc
test_dataset =(
 tf.data.Dataset 
.from_tensor_slices(X_test_tokenized)
.batch(BATCH_SIZE)
 )<define_variables>
PATH = '/kaggle/input/instacart-market-basket-analysis/'
num_steps = len(train)// BATCH_SIZE
final_preds = np.zeros(( len(test)))
 total_preds = np.zeros(( len(train)) )<choose_model_class>
aisles = pd.read_csv(PATH + 'aisles.csv')
 products = pd.read_csv(PATH + 'products.csv')
 order_products_train = pd.read_csv(PATH + 'order_products__train.csv')
 order_products_prior = pd.read_csv(PATH + 'order_products__prior.csv')
 departments = pd.read_csv(PATH + 'departments.csv')
 orders = pd.read_csv(PATH + 'orders.csv' )
kfold = StratifiedKFold(n_splits=NUM_SPLITS, shuffle=True, random_state=SEED )<prepare_x_and_y>
op = pd.merge(orders, order_products_prior, on='order_id', how='inner')
 op.head()
for fold,(train_idx, valid_idx)in enumerate(kfold.split(X=train['text'], y=train['target'])) :
print("*"*60)
 print("*"+" "*26+f"FOLD {fold+1}"+" "*26+"*")
 print("*"*60, end="
")
 X_train = train.iloc[train_idx].reset_index(drop=True)
 X_valid = train.iloc[valid_idx].reset_index(drop=True)
 y_train = X_train["target"]
y_valid = X_valid["target"]
X_train_tokenized = fast_encode(X_train.text.astype(str), fast_tokenizer, maxlen=MAX_LEN)
 X_valid_tokenized = fast_encode(X_valid.text.astype(str), fast_tokenizer, maxlen=MAX_LEN)
 train_dataset = tf.data.Dataset.from_tensor_slices(( X_train_tokenized, to_categorical(y_train)))
 train_dataset = train_dataset.repeat()
train_dataset = train_dataset.shuffle(2048)
 train_dataset = train_dataset.batch(BATCH_SIZE)
 train_dataset = train_dataset.prefetch(tf.data.experimental.AUTOTUNE)
 valid_dataset = tf.data.Dataset
valid_dataset = valid_dataset.from_tensor_slices(( X_valid_tokenized, to_categorical(y_valid)))
 valid_dataset = valid_dataset.batch(BATCH_SIZE)
 K.clear_session()
with strategy.scope() :
transformer_layer = TFBertModel.from_pretrained('bert-base-uncased')
 model = build_model(transformer_layer, loss=focal_loss(gamma=1.5), max_len=MAX_LEN)
 history = model.fit(train_dataset,
steps_per_epoch=num_steps,
validation_data=valid_dataset,
callbacks=[eas, lrs],
epochs=EPOCHS)
 valid_preds = model.predict(valid_dataset)[:, 1]
total_preds[valid_idx] = valid_preds
test_preds = model.predict(test_dataset)[:, 1]
final_preds += test_preds<prepare_output>
total_prd_per_order = op.groupby(by=['user_id', 'order_id'])['product_id'].aggregate('count' ).to_frame('total_products_per_order' ).reset_index()
total_prd_per_order.head(10 )
actuals = train["target"].values
total_preds[total_preds >= 0.5] = 1
total_preds[total_preds < 0.5] = 0<compute_test_metric>
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()
print(f"AUC: {auc(actuals, total_preds)}")
 print(f"F1 Score: {f1_score(actuals, total_preds)}")
 print(f"MCC: {matthews_corrcoef(actuals, total_preds)}" )<load_from_csv>
del total_prd_per_order
submission = pd.read_csv(".. /input/nlp-getting-started/sample_submission.csv" )<feature_engineering>
users = users.merge(avg_products, on='user_id', how='left')
 del avg_products
users.head()
submission["target"] = final_preds/NUM_SPLITS
submission["target"] = submission["target"].apply(lambda x: 1 if x>=0.5 else 0 )<save_to_csv>
users = users.merge(dow, on='user_id', how='left')
 del dow
users.head()
submission.to_csv("submission.csv", index=False )<save_to_csv>
users = users.merge(hod, on='user_id', how='left')
 del hod
users.head()
submission.to_csv("submission.csv", index=False )<import_modules>
prd = op.groupby(by='product_id')['order_id'].agg('count' ).to_frame('prd_count_p' ).reset_index()
prd.head()
import os, re, math, string, pandas as pd, numpy as np, seaborn as sns
import matplotlib.pyplot as plt
import tensorflow as tf
from wordcloud import STOPWORDS
from sklearn.preprocessing import MinMaxScaler, StandardScaler<define_variables>
prd = prd.merge(reorder_p, on='product_id', how='left')
 del reorder_p
prd.head()
BATCH_SIZE = 16
EPOCHS = 2
CLEAN_TWEETS = False
USE_META = True
ADD_DENSE = True
DENSE_DIM = 64
ADD_DROPOUT = True
DROPOUT =.2
TRAIN_BASE = True<load_from_csv>
uxp = uxp.merge(reorder_uxp, on=['user_id', 'product_id'], how='left')
 del reorder_uxp
uxp.head()
train = pd.read_csv('/kaggle/input/nlp-getting-started/train.csv')
 test = pd.read_csv('/kaggle/input/nlp-getting-started/test.csv')
 train.head()<drop_column>
data = uxp.merge(users, on='user_id', how='left')
 data.head()
test_id = test['id']
columns = {'id', 'location'}
train = train.drop(columns = columns)
 test = test.drop(columns = columns)
 train['keyword'] = train['keyword'].fillna('unknown')
 test['keyword'] = test['keyword'].fillna('unknown')
 train['text'] = train['text'] + ' ' + train['keyword']
test['text'] = test['text'] + ' ' + test['keyword']
columns = {'keyword'}
train = train.drop(columns = columns)
 test = test.drop(columns = columns )<define_variables>
data = data.merge(prd, on='product_id', how='left')
 data.head()
contractions = {
"ain't": "am not / are not / is not / has not / have not",
"aren't": "are not / am not",
"can't": "cannot",
"can't've": "cannot have",
"'cause": "because",
"could've": "could have",
"couldn't": "could not",
"couldn't've": "could not have",
"didn't": "did not",
"doesn't": "does not",
"don't": "do not",
"hadn't": "had not",
"hadn't've": "had not have",
"hasn't": "has not",
"haven't": "have not",
"he'd": "he had / he would",
"he'd've": "he would have",
"he'll": "he shall / he will",
"he'll've": "he shall have / he will have",
"he's": "he has / he is",
"how'd": "how did",
"how'd'y": "how do you",
"how'll": "how will",
"how's": "how has / how is / how does",
"I'd": "I had / I would",
"I'd've": "I would have",
"I'll": "I shall / I will",
"I'll've": "I shall have / I will have",
"I'm": "I am",
"I've": "I have",
"isn't": "is not",
"it'd": "it had / it would",
"it'd've": "it would have",
"it'll": "it shall / it will",
"it'll've": "it shall have / it will have",
"it's": "it has / it is",
"let's": "let us",
"ma'am": "madam",
"mayn't": "may not",
"might've": "might have",
"mightn't": "might not",
"mightn't've": "might not have",
"must've": "must have",
"mustn't": "must not",
"mustn't've": "must not have",
"needn't": "need not",
"needn't've": "need not have",
"o'clock": "of the clock",
"oughtn't": "ought not",
"oughtn't've": "ought not have",
"shan't": "shall not",
"sha'n't": "shall not",
"shan't've": "shall not have",
"she'd": "she had / she would",
"she'd've": "she would have",
"she'll": "she shall / she will",
"she'll've": "she shall have / she will have",
"she's": "she has / she is",
"should've": "should have",
"shouldn't": "should not",
"shouldn't've": "should not have",
"so've": "so have",
"so's": "so as / so is",
"that'd": "that would / that had",
"that'd've": "that would have",
"that's": "that has / that is",
"there'd": "there had / there would",
"there'd've": "there would have",
"there's": "there has / there is",
"they'd": "they had / they would",
"they'd've": "they would have",
"they'll": "they shall / they will",
"they'll've": "they shall have / they will have",
"they're": "they are",
"they've": "they have",
"to've": "to have",
"wasn't": "was not",
"we'd": "we had / we would",
"we'd've": "we would have",
"we'll": "we will",
"we'll've": "we will have",
"we're": "we are",
"we've": "we have",
"weren't": "were not",
"what'll": "what shall / what will",
"what'll've": "what shall have / what will have",
"what're": "what are",
"what's": "what has / what is",
"what've": "what have",
"when's": "when has / when is",
"when've": "when have",
"where'd": "where did",
"where's": "where has / where is",
"where've": "where have",
"who'll": "who shall / who will",
"who'll've": "who shall have / who will have",
"who's": "who has / who is",
"who've": "who have",
"why's": "why has / why is",
"why've": "why have",
"will've": "will have",
"won't": "will not",
"won't've": "will not have",
"would've": "would have",
"wouldn't": "would not",
"wouldn't've": "would not have",
"y'all": "you all",
"y'all'd": "you all would",
"y'all'd've": "you all would have",
"y'all're": "you all are",
"y'all've": "you all have",
"you'd": "you had / you would",
"you'd've": "you would have",
"you'll": "you shall / you will",
"you'll've": "you shall have / you will have",
"you're": "you are",
"you've": "you have"
}
contractions_re = re.compile('(%s)' % '|'.join(contractions.keys()))
def expand_contractions(s, contractions = contractions):
def replace(match):
return contractions[match.group(0)]
return contractions_re.sub(replace, s)
 expand_contractions("can't stop won't stop" )<string_transform>
del [users, prd, uxp]
def strip_all_entities(x):
return ' '.join(re.sub("(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)"," ",x ).split())
 strip_all_entities('@shawn Titanic<string_transform>
order_future = orders.loc[(( orders.eval_set == 'train')|(orders.eval_set == 'test')) , ['user_id', 'eval_set', 'order_id']]
order_future.head()
def remove_stopwords(x):
return ' '.join([i for i in x.split() if i not in STOPWORDS] )<feature_engineering>
data = data.merge(order_future, on='user_id', how='left')
 data.head()
if CLEAN_TWEETS:
for df in [train, test]:
df['text'] = df['text'].apply(expand_contractions)
 df['text'] = df['text'].apply(strip_all_entities)
 df['text'] = df['text'].apply(remove_stopwords )<feature_engineering>
data_train = data[data.eval_set == 'train']
data_train.head()
def average_word_length(x):
x = x.split()
return np.mean([len(i)for i in x] )<feature_engineering>
data_train = data_train.merge(order_products_train[['product_id', 'order_id', 'reordered']], on=['product_id', 'order_id'], how='left')
 data_train.head()
for df in [train, test]:
df['word count'] = df['text'].apply(lambda x: len(x.split()))
df['character count'] = df['text'].apply(lambda x: len(x))
df['average word length'] = df['text'].apply(average_word_length)
 df['unique word count'] = df['text'].apply(lambda x: len(set(x.split())))
 df['stopword count'] = df['text'].apply(lambda x: len([i for i in x.lower().split() if i in STOPWORDS]))
df['stopword ratio'] = df['stopword count'] / df['word count']
df['url count'] = df['text'].apply(lambda x: len([i for i in x.lower().split() if 'http' in i or 'https' in i]))<normalization>
data_train.reordered.fillna(0, inplace=True )
meta_train = StandardScaler().fit_transform(train.iloc[:, 2:])
 meta_test = StandardScaler().fit_transform(test.iloc[:, 1:])
<categorify>
data_train = data_train.set_index(['user_id', 'product_id'])
 data_train.drop(['eval_set', 'order_id'], axis=1, inplace=True )
TOKENIZER = BertTokenizer.from_pretrained("bert-base-uncased")
 enc = TOKENIZER.encode("Encode me!")
 dec = TOKENIZER.decode(enc)
 print("Encode: " + str(enc))
print("Decode: " + str(dec))<categorify>
data_test = data[data.eval_set == 'test']
data_test.head()
TOKENIZER = RobertaTokenizer.from_pretrained("roberta-base")
 enc = TOKENIZER.encode("Encode me!")
 dec = TOKENIZER.decode(enc)
 print("Encode: " + str(enc))
print("Decode: " + str(dec))<categorify>
data_test.drop(['eval_set', 'order_id'], axis=1, inplace=True )
TOKENIZER = AlbertTokenizer.from_pretrained("albert-base-v1")
 enc = TOKENIZER.encode("Encode me!")
 dec = TOKENIZER.decode(enc)
 print("Encode: " + str(enc))
print("Decode: " + str(dec))<categorify>
data_test = data_test.set_index(['user_id', 'product_id'] )
TOKENIZER = BartTokenizer.from_pretrained('facebook/bart-large')
 enc = TOKENIZER.encode("Encode me!")
 dec = TOKENIZER.decode(enc)
 print("Encode: " + str(enc))
print("Decode: " + str(dec))<categorify>
del [aisles, departments, order_products_prior, order_products_train, orders, order_future, data]
TOKENIZER = BertTokenizer.from_pretrained('google/electra-base-generator')
 enc = TOKENIZER.encode("Encode me!")
 dec = TOKENIZER.decode(enc)
 print("Encode: " + str(enc))
print("Decode: " + str(dec))<import_modules>
data_train.reset_index(inplace=True)
 data_test.reset_index(inplace=True )
import tensorflow as tf
from transformers import TFBertModel, BertModel<load_pretrained>
data_train = data_train.merge(products[['product_id', 'aisle_id']], on='product_id', how='left')
 data_test = data_test.merge(products[['product_id', 'aisle_id']], on='product_id', how='left' )
bert_base = TFBertModel.from_pretrained('bert-base-uncased')
 TOKENIZER = BertTokenizer.from_pretrained("bert-base-uncased" )<categorify>
data_train = data_train.merge(products[['product_id', 'department_id']], on='product_id', how='left')
 data_test = data_test.merge(products[['product_id', 'department_id']], on='product_id', how='left' )
def bert_encode(data,maximum_len):
input_ids = []
attention_masks = []
for i in range(len(data.text)) :
encoded = TOKENIZER.encode_plus(data.text[i],
add_special_tokens=True,
max_length=maximum_len,
pad_to_max_length=True,
return_attention_mask=True)
 input_ids.append(encoded['input_ids'])
 attention_masks.append(encoded['attention_mask'])
 return np.array(input_ids),np.array(attention_masks )<choose_model_class>
data_test = data_test.set_index(['user_id', 'product_id'])
 data_train = data_train.set_index(['user_id', 'product_id'] )
def build_model(model_layer, learning_rate, use_meta = USE_META, add_dense = ADD_DENSE,
dense_dim = DENSE_DIM, add_dropout = ADD_DROPOUT, dropout = DROPOUT):
input_ids = tf.keras.Input(shape=(60,),dtype='int32')
 attention_masks = tf.keras.Input(shape=(60,),dtype='int32')
 meta_input = tf.keras.Input(shape =(meta_train.shape[1],))
transformer_layer = model_layer([input_ids,attention_masks])
 output = transformer_layer[1]
if use_meta:
output = tf.keras.layers.Concatenate()([output, meta_input])
 if add_dense:
print("Training with additional dense layer...")
 output = tf.keras.layers.Dense(dense_dim,activation='relu' )(output)
 if add_dropout:
print("Training with dropout...")
 output = tf.keras.layers.Dropout(dropout )(output)
 output = tf.keras.layers.Dense(1,activation='sigmoid' )(output)
 if use_meta:
print("Training with meta-data...")
 model = tf.keras.models.Model(inputs = [input_ids,attention_masks, meta_input],outputs = output)
 else:
print("Training without meta-data...")
 model = tf.keras.models.Model(inputs = [input_ids,attention_masks],outputs = output)
 model.compile(tf.keras.optimizers.Adam(lr=learning_rate), loss='binary_crossentropy', metrics=['accuracy'])
 return model
def plot_learning_curves(history):
fig, ax = plt.subplots(1, 2, figsize =(20, 10))
ax[0].plot(history.history['accuracy'], color='
ax[0].plot(history.history['val_accuracy'], '
ax[1].plot(history.history['loss'], color='
ax[1].plot(history.history['val_loss'], '
ax[0].legend(['train', 'validation'], loc = 'upper left')
 ax[1].legend(['train', 'validation'], loc = 'upper left')
 fig.suptitle("Model Learning Curves", fontsize=14)
 ax[0].set_ylabel('Accuracy')
 ax[0].set_xlabel('Epoch')
 ax[1].set_ylabel('Loss')
 ax[1].set_xlabel('Epoch')
 return plt.show()<categorify>
y_pred = xgb_clf.predict(data_test ).astype('int')
 y_pred =(xgb_clf.predict_proba(data_test)[:, 1] >= 0.21 ).astype('int')
 y_pred[0:10]
if TRAIN_BASE:
print('Encoding Tweets...')
 train_input_ids,train_attention_masks = bert_encode(train,60)
 test_input_ids,test_attention_masks = bert_encode(test,60)
 print('Tweets encoded')
 print('')
 print('Train length:', len(train_input_ids))
print('Test length:', len(test_input_ids))<load_pretrained>
data_test['prediction'] = y_pred
data_test.head()
BERT_base = build_model(bert_base, learning_rate = 1e-5)
 BERT_base.summary()<train_model>
orders = pd.read_csv(PATH + 'orders.csv')
 orders_test = orders.loc[orders.eval_set == 'test', ['user_id', 'order_id']]
orders_test.head()
if TRAIN_BASE:
if USE_META:
history = BERT_base.fit([train_input_ids,train_attention_masks, meta_train], train.target, validation_split =.2, epochs = EPOCHS, callbacks = [checkpoint], batch_size = BATCH_SIZE)
 else:
history = BERT_base.fit([train_input_ids,train_attention_masks], train.target, validation_split =.2, epochs = EPOCHS, callbacks = [checkpoint], batch_size = BATCH_SIZE )<load_pretrained>
final = final.merge(orders_test, on='user_id', how='left')
 final.head()
if TRAIN_BASE:
BERT_base.load_weights('base_model.h5' )<predict_on_test>
final = final.drop('user_id', axis=1 )
if TRAIN_BASE:
if USE_META:
preds_base = BERT_base.predict([test_input_ids,test_attention_masks,meta_test])
 else:
preds_base = BERT_base.predict([test_input_ids,test_attention_masks] )<prepare_output>
final['product_id'] = final.product_id.astype(int)
 del orders
del orders_test
gc.collect()
final.head()
if TRAIN_BASE:
submission_base = pd.DataFrame()
submission_base['id'] = test_id
submission_base['prob'] = preds_base
submission_base['target'] = np.round(submission_base['prob'] ).astype(int)
 submission_base.head(10 )<save_to_csv>
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()
d
if TRAIN_BASE:
submission_base = submission_base[['id', 'target']]
submission_base.to_csv('submission_bert_base.csv', index = False)
 print('Submission saved' )<load_pretrained>
sub = pd.DataFrame.from_dict(d, orient='index')
 sub.reset_index(inplace=True)
 sub.columns = ['order_id', 'products']
sub.head()
bert_large = TFBertModel.from_pretrained('bert-large-uncased')
 TOKENIZER = BertTokenizer.from_pretrained("bert-large-uncased")
 train_input_ids,train_attention_masks = bert_encode(train,60)
 test_input_ids,test_attention_masks = bert_encode(test,60)
 print('Train length:', len(train_input_ids))
print('Test length:', len(test_input_ids))
BERT_large = build_model(bert_large, learning_rate = 1e-5)
 BERT_large.summary()<train_model>
sub.to_csv('sub.csv', index=False )
<load_pretrained><EOS> 
gc.collect()