Kaggle competition: Quora Insincere Questions Classification
FINAL_P = []
with torch.no_grad() :
for file in tqdm(files_test):
data = read_data(file)
 dataset_test = BengaliDataset(data, img_size)
 test_loader = torch.utils.data.DataLoader(dataset_test, batch_size=batch_size, shuffle=False, num_workers=num_workers)
 for(image)in tqdm(test_loader):
image = image.to(device)
 logits_1 = torch.zeros(image.shape[0], c0_dim ).to(device)
 logits_metric = torch.zeros(image.shape[0], c0_dim ).to(device)
 for mid, model in enumerate(models_arcface):
l1, l2, l3 = model(image)
 logits_1 += l1.softmax(1)
 logits_metric += l3
logits_metric /= len(models_arcface)
 pred = df_label_map.iloc[logits_metric.detach().cpu().numpy().argmax(1), :3].values
max_p = logits_metric.cpu().numpy().max(1)
 unseen_idx = np.where(max_p <= seen_th)[0]
if unseen_idx.shape[0] > 0:
logits_2_unseen = torch.zeros(unseen_idx.shape[0], c1_dim+c2_dim+c3_dim ).to(device)
 for mid, model in enumerate(models_unseen):
_, l2 = model(image[unseen_idx])
 logits_2_unseen[:, :c1_dim] += l2[:, :c1_dim].softmax(1)
 logits_2_unseen[:, c1_dim:c1_dim+c2_dim] += l2[:, c1_dim:c1_dim+c2_dim].softmax(1)
 logits_2_unseen[:, c1_dim+c2_dim:] += l2[:, c1_dim+c2_dim:].softmax(1)
 pred[unseen_idx, 0] = logits_2_unseen[:, :c1_dim].detach().cpu().numpy().argmax(1)
 pred[unseen_idx, 1] = logits_2_unseen[:, c1_dim:c1_dim+c2_dim].detach().cpu().numpy().argmax(1)
 pred[unseen_idx, 2] = logits_2_unseen[:, c1_dim+c2_dim:].detach().cpu().numpy().argmax(1)
 FINAL_P += pred.reshape(-1 ).tolist()
del data
gc.collect()<save_to_csv>
embed_size = 300
max_features = 95000
maxlen = 70
df_sub = pd.DataFrame({
'row_id': [f'Test_{i}_{p}' for i in range(len(FINAL_P)// 3)for p in ['grapheme_root', 'vowel_diacritic', 'consonant_diacritic']],
'target': FINAL_P
})
 df_sub.to_csv('submission.csv',index=False )<prepare_x_and_y>
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 *
train = pd.read_csv('.. /input/train.csv')
 x_train = train.drop(['id', 'species'], axis=1 ).values
le = LabelEncoder().fit(train['species'])
 y_train = le.transform(train['species'])
 scaler = StandardScaler().fit(x_train)
 x_train = scaler.transform(x_train)
 test = pd.read_csv('.. /input/test.csv')
 test_ids = test.pop('id')
 x_test = test.values
scaler = StandardScaler().fit(x_test)
 x_test = scaler.transform(x_test)
 xg_train = xgb.DMatrix(x_train, label=y_train)
 val = train.sample(100)
 x_val = val.drop(['id', 'species'], axis=1 ).values
y_val = le.transform(val['species'])
 xg_val = xgb.DMatrix(x_val, label=y_val)
 param = {'objective': 'multi:softmax', 'eta': 0.1, 'max_depth': 6, 'silent': 1, 'nthread': 4, 'num_class': 99}
watchlist = [(xg_train,'train'),(xg_val, 'test')]
num_round = 5
bst = xgb.train(param, xg_train, num_round, watchlist)
 pred = bst.predict(xg_val)
 print('predicting, classification error=%f' %(sum(int(pred[i])!= y_val[i] for i in range(len(y_val)))/ float(len(y_val)))) 
<save_to_csv>
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
submission = pd.DataFrame(y_test, index=test_ids, columns=le.classes_)
 submission.to_csv('submission2.csv' )<compute_test_metric>
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
clf.score(x_train, y_train )<find_best_params>
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
clf.best_estimator_<train_on_grid>
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()))
np.random.seed(42)
 train = pd.read_csv('.. /input/train.csv')
 x_train = train.drop(['id', 'species'], axis=1 ).values
le = LabelEncoder().fit(train['species'])
 y_train = le.transform(train['species'])
 scaler = StandardScaler().fit(x_train)
 x_train = scaler.transform(x_train)
 params = {'C':[1, 10, 50, 100, 500, 1000, 2000], 'tol': [0.001, 0.0001, 0.005]}
log_reg = LogisticRegression(solver='lbfgs', multi_class='multinomial')
 clf = GridSearchCV(log_reg, params, scoring='log_loss', refit='True', n_jobs=1, cv=5)
 clf.fit(x_train, y_train)
 print("best params: " + str(clf.best_params_))
for params, mean_score, scores in clf.grid_scores_:
print("%0.3f(+/-%0.03f)for %r" %(mean_score, scores.std() , params))
print(scores)
 test = pd.read_csv('.. /input/test.csv')
 test_ids = test.pop('id')
 x_test = test.values
scaler = StandardScaler().fit(x_test)
 x_test = scaler.transform(x_test)
 y_test = clf.predict_proba(x_test)
 submission = pd.DataFrame(y_test, index=test_ids, columns=le.classes_)
 submission.to_csv('submission.csv' )<import_modules>
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
SimpleRNN, LSTM,
Bidirectional, Lambda, Embedding, Dropout, Conv1D, MaxPooling1D)
<load_from_csv>
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_train = pd.read_csv('.. /input/nlp-getting-started/train.csv')
 df_test = pd.read_csv('.. /input/nlp-getting-started/test.csv')
 df = pd.concat([df_train, df_test], keys=['train', 'test'])
 df.text = df.text.astype("string" )<define_variables>
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 )
vocab_size = 30000
sequence_length = 30<categorify>
embedding_matrix = np.mean([embedding_matrix_1, embedding_matrix_3], axis = 0)
 np.shape(embedding_matrix )
regex_nonalpha = re.compile('[^a-zA-Z0-9\s]')
 regex_http = re.compile("http\S*")
 regex_apostrophe = re.compile("'")
 regex_space = re.compile("\s\s+")
 def alphanumeric(text):
text = regex_http.sub("", text)
 text = regex_apostrophe.sub("", text)
 text = regex_nonalpha.sub(" ", text)
 text = regex_space.sub(" ", text)
 return text.lower().strip()<string_transform>
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
def alphanumeric_tf(text_tensor):
text_tensor = tf.strings.regex_replace(text_tensor, "http\S*", "")
 text_tensor = tf.strings.regex_replace(text_tensor, "'", "")
 text_tensor = tf.strings.regex_replace(text_tensor, "[^a-zA-Z0-9\s]", " ")
 text_tensor = tf.strings.regex_replace(text_tensor, "\s\s+", " ")
 return tf.strings.strip(tf.strings.lower(text_tensor))<data_type_conversions>
DATA_SPLIT_SEED = 2018
clr = CyclicLR(base_lr=0.001, max_lr=0.002,
step_size=300., mode='exp_range',
gamma=0.99994)
 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 )
text_vectorizer = TextVectorization(max_tokens=vocab_size,
standardize=alphanumeric_tf,
output_sequence_length=sequence_length, 
)
 text_vectorizer.adapt(df.text.to_numpy())
 vocab = text_vectorizer.get_vocabulary()<data_type_conversions>
sub = pd.read_csv('.. /input/sample_submission.csv')
 sub.prediction = test_meta > 0.33
sub.to_csv("submission.csv", index=False )
<prepare_x_and_y><EOS> 
f1_score(y_true=train_y, y_pred=train_meta > 0.33 )