Kaggle competition: Natural Language Processing with Disaster Tweets
<SOS> metric: meanfscore Kaggle data source: natural-language-processing-with-disaster-tweets<load_from_csv>
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
sub_df = pd.read_csv('.. /input/sample_submission.csv')
 sub_df["target"] = predictions
sub_df[:10] 
<save_to_csv>
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
sub_df.to_csv("lightgbm.csv", index=False )<import_modules>
train = pd.read_csv('/kaggle/input/nlp-getting-started/train.csv')
 test = pd.read_csv('/kaggle/input/nlp-getting-started/test.csv')
 train.head()
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score
from xgboost import XGBClassifier
from lightgbm import LGBMClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier, GradientBoostingClassifier, AdaBoostClassifier<load_from_csv>
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 )
train = pd.read_csv('.. /input/train.csv')
 test = pd.read_csv('.. /input/test.csv' )<drop_column>
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" )
id_test = test['id'].values
train_target = train['target'].values
train = train.drop(['target', 'id'], axis = 1)
 test = test.drop(['id'], axis = 1 )<filter>
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
col_to_drop = train.columns[train.columns.str.startswith('ps_calc_')]
print(col_to_drop )<drop_column>
def remove_stopwords(x):
return ' '.join([i for i in x.split() if i not in STOPWORDS] )
train = train.drop(col_to_drop, axis=1)
 test = test.drop(col_to_drop, axis=1 )<categorify>
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 )
train = train.replace(-1, np.nan)
 test = test.replace(-1, np.nan )<define_variables>
def average_word_length(x):
x = x.split()
return np.mean([len(i)for i in x] )
cat_features = [a for a in train.columns if a.endswith('cat')]
print(cat_features )<categorify>
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]))
for column in cat_features:
temp = pd.get_dummies(pd.Series(train[column]))
train = pd.concat([train, temp], axis=1)
 train = train.drop([column], axis=1 )<categorify>
meta_train = StandardScaler().fit_transform(train.iloc[:, 2:])
 meta_test = StandardScaler().fit_transform(test.iloc[:, 1:])
for column in cat_features:
temp = pd.get_dummies(pd.Series(test[column]))
test = pd.concat([test, temp], axis = 1)
 test = test.drop([column], axis=1 )<predict_on_test>
TOKENIZER = BertTokenizer.from_pretrained("bert-base-uncased")
 enc = TOKENIZER.encode("Encode me!")
 dec = TOKENIZER.decode(enc)
 print("Encode: " + str(enc))
print("Decode: " + str(dec))
class Ensemble(object):
def __init__(self, n_splits, stacker, base_models):
self.n_splits = n_splits
self.stacker = stacker
self.base_models = base_models
def fit_predict(self, X, y, T):
increase = True
print(X.shape)
 if increase:
pos = pd.Series(y == 1)
 y = pd.Series(y)
 X = pd.concat([X, X.loc[pos]], axis = 0)
 y = pd.concat([y, y.loc[pos]], axis = 0)
 idx = np.arange(len(X))
np.random.shuffle(idx)
 X = X.iloc[idx]
y = y.iloc[idx]
print(X.shape)
 print(T.shape)
 X = np.array(X)
 y = np.array(y)
 T = np.array(T)
 folds = list(StratifiedKFold(n_splits=self.n_splits, shuffle = True, random_state=17 ).split(X, y))
S_train = np.zeros(( X.shape[0], len(self.base_models)))
 S_test = np.zeros(( T.shape[0], len(self.base_models)))
 for i, clf in enumerate(self.base_models):
S_test_i = np.zeros(( T.shape[0], self.n_splits))
for j,(train_idx, test_idx)in enumerate(folds):
X_train = X[train_idx]
y_train = y[train_idx]
X_holdout = X[test_idx]
print("fit %s fold %d " %(str(clf ).split('(')[0], j+1))
clf.fit(X_train, y_train)
 y_pred = clf.predict_proba(X_holdout)[:, 1]
S_train[test_idx, i] = y_pred
S_test_i[:, j] = clf.predict_proba(T)[:, 1]
S_test[:, i] = S_test_i.mean(axis=1)
 result = cross_val_score(self.stacker, S_train, y, cv=3)
 print("Stacker score : %.5f "%(result.mean()))
self.stacker.fit(S_train, y)
 res = self.stacker.predict_proba(S_test)[:, 1]
return res 
<init_hyperparams>
TOKENIZER = RobertaTokenizer.from_pretrained("roberta-base")
 enc = TOKENIZER.encode("Encode me!")
 dec = TOKENIZER.decode(enc)
 print("Encode: " + str(enc))
print("Decode: " + str(dec))
lgb_params = {
'learning_rate' : 0.02,
'n_estimators' : 650,
'max_bin' : 10,
'subsample' : 0.8,
'subsample_freq' : 10,
'colsample_bytree' : 0.8,
'min_child_samples' : 500,
'seed' : 99
}
lgb_params2 = {
'n_estimators' : 1090,
'learning_rate' : 0.02,
'colsample_bytree' : 0.3,
'subsample' : 0.7,
'subsample_freq' : 2,
'num_leaves' : 16,
'seed' : 99
}
lgb_params3 = {
'n_estimators' : 110,
'max_depth' : 4,
'learning_rate' : 0.02,
'seed' : 99
}
lgb_model = LGBMClassifier(**lgb_params)
 lgb_model2 = LGBMClassifier(**lgb_params2)
 lgb_model3 = LGBMClassifier(**lgb_params3)
 log_model = LogisticRegression()<choose_model_class>
TOKENIZER = AlbertTokenizer.from_pretrained("albert-base-v1")
 enc = TOKENIZER.encode("Encode me!")
 dec = TOKENIZER.decode(enc)
 print("Encode: " + str(enc))
print("Decode: " + str(dec))
stack = Ensemble(n_splits = 3, stacker = log_model, base_models =(lgb_model, lgb_model2)) 
<predict_on_test>
TOKENIZER = BartTokenizer.from_pretrained('facebook/bart-large')
 enc = TOKENIZER.encode("Encode me!")
 dec = TOKENIZER.decode(enc)
 print("Encode: " + str(enc))
print("Decode: " + str(dec))
y_pred = stack.fit_predict(train, train_target, test )<prepare_output>
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))
sub = pd.DataFrame()
sub['id'] = id_test
sub['target'] = y_pred<save_to_csv>
import tensorflow as tf
from transformers import TFBertModel, BertModel
sub.to_csv('submission.csv', index=False )<save_to_csv>
bert_base = TFBertModel.from_pretrained('bert-base-uncased')
 TOKENIZER = BertTokenizer.from_pretrained("bert-base-uncased" )
sub.to_csv('submission.csv', index=False )<set_options>
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 )
pd.set_option('display.max_columns', 100 )<load_from_csv>
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()
train = pd.read_csv('.. /input/train.csv')
 test = pd.read_csv('.. /input/test.csv' )<load_from_csv>
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))
train = pd.read_csv('.. /input/train.csv')
 test = pd.read_csv('.. /input/test.csv' )<define_variables>
BERT_base = build_model(bert_base, learning_rate = 1e-5)
 BERT_base.summary()
data = []
for feature in train.columns:
if feature == 'id':
use = 'id'
elif feature == 'target':
use = 'target'
else:
use = 'input'
if 'bin' in feature or feature == 'target':
type = 'binary'
elif 'cat' in feature or feature == 'id':
type = 'categorical'
elif train[feature].dtype == float or isinstance(train[feature].dtype,float):
type = 'real'
elif train[feature].dtype == int:
type = 'integer'
preserve = True
if feature =='id':
preserve = False
dtype = train[feature].dtype
category = 'none'
if 'ind' in feature:
category = 'individual'
elif 'reg' in feature:
category = 'registration'
elif 'car' in feature:
category = 'car'
elif 'calc' in feature:
category = 'calculated'
feature_dict = {
'var_name':feature,
'use':use,
'type':type,
'preserve':preserve,
'dtype':dtype,
'category':category
}
data.append(feature_dict)
 metadata = pd.DataFrame(data,columns=['var_name', 'use', 'type', 'preserve', 'dtype', 'category'])
 metadata.set_index('var_name',inplace=True )<filter>
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 )
metadata[(metadata['type']=='categorical')&(metadata.preserve)]<create_dataframe>
if TRAIN_BASE:
BERT_base.load_weights('base_model.h5' )
pd.DataFrame({'count':metadata.groupby('category')['category'].size() } ).reset_index()<create_dataframe>
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] )
pd.DataFrame({'count':metadata.groupby(['use','type'])['use'].size() } ).reset_index()<randomize_order>
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 )
desired_apriori=0.10
idx_0 = train[train.target == 0].index
idx_1 = train[train.target == 1].index
no_0 = len(train.loc[idx_0])
 no_1 = len(train.loc[idx_1])
 undersampling_rate =(( 1-desired_apriori)*no_1)/(desired_apriori*no_0)
 undersampled_no_0 = int(undersampling_rate*no_0)
 print('Rate to undersample records with target=0: {}'.format(undersampling_rate))
print('Number of records with target=0 after undersampling: {}'.format(undersampled_no_0))
undersampled_idx = shuffle(idx_0,random_state=242,n_samples=undersampled_no_0)
 idx_list = list(undersampled_idx)+list(idx_1)
 train = train.loc[idx_list].reset_index(drop=True )<sort_values>
if TRAIN_BASE:
submission_base = submission_base[['id', 'target']]
submission_base.to_csv('submission_bert_base.csv', index = False)
 print('Submission saved' )
df_null =(train == -1 ).sum().sort_values(ascending=False ).reset_index()
df_null.columns = ['features','count']
df_null = df_null[df_null['count'] > 0]
df_null<filter>
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()
metadata.loc[col_to_drop,'preserve']<drop_column>
if USE_META:
history = BERT_large.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_large.fit([train_input_ids,train_attention_masks], train.target, validation_split =.2, epochs = EPOCHS, callbacks = [checkpoint], batch_size = BATCH_SIZE )
col_to_drop = train.columns[train.columns.str.startswith('ps_calc_')]
metadata.loc[col_to_drop,'preserve'] = False
train = train.drop(col_to_drop,axis=1)
 test = test.drop(col_to_drop,axis=1 )<drop_column>
BERT_large.load_weights('large_model.h5' )
vars_to_drop = ['ps_car_03_cat','ps_car_05_cat']
train = train.drop(vars_to_drop,axis=1)
 test = test.drop(vars_to_drop,axis=1)
 metadata.loc[(vars_to_drop),'preserve'] = False<filter>
if USE_META:
preds_large = BERT_large.predict([test_input_ids,test_attention_masks,meta_test])
 else:
preds_large = BERT_large.predict([test_input_ids,test_attention_masks] )
dummy = metadata.loc[df_null.features,:]
dummy[(dummy.type=='real')|(dummy.type=='integer')]<data_type_conversions>
submission_large = pd.DataFrame()
submission_large['id'] = test_id
submission_large['prob'] = preds_large
submission_large['target'] = np.round(submission_large['prob'] ).astype(int)
 submission_large.head(10 )
mean_imputer = Imputer(missing_values=-1,strategy='mean',axis=0)
 dummy = metadata.loc[df_null.features,:]
real_int_cols = dummy[(dummy.type=='real')|(dummy.type=='integer')].index
for col in real_int_cols:
if metadata.loc[col].type =='real':
train[col] = mean_imputer.fit_transform(pd.DataFrame(train[col])).ravel()
train[col] = train[col].astype(float)
 test[col] = mean_imputer.transform(pd.DataFrame(test[col])).ravel()
test[col] = test[col].astype(float)
 if metadata.loc[col].type == 'integer':
train[col] = mean_imputer.fit_transform(pd.DataFrame(train[col])).ravel()
train[col] = train[col].astype(float)
 test[col] = mean_imputer.transform(pd.DataFrame(test[col])).ravel()
test[col] = test[col].astype(float )<data_type_conversions>
submission_large = submission_large[['id', 'target']]
submission_large.to_csv('submission_bert_large.csv', index = False)
 print('Submission saved' )
<categorify><EOS> 
submission_final = pd.DataFrame()
submission_final['id'] = test_id
if TRAIN_BASE:
submission_final['base prob'] = preds_base
submission_final['large prob'] = preds_large
submission_final.head(10 )