Kaggle competition: Quora Insincere Questions Classification
def life_step_1(X):

 nbrs_count = sum(np.roll(np.roll(X, i, 0), j, 1)
 for i in(-1, 0, 1)for j in(-1, 0, 1)
 if(i != 0 or j != 0))
return(nbrs_count == 3)|(X &(nbrs_count == 2))<load_from_csv>
embed_size = 300
max_features = 95000
maxlen = 70
train_df = pd.read_csv('/kaggle/input/conways-reverse-game-of-life-2020/train.csv')
 test_df = pd.read_csv('/kaggle/input/conways-reverse-game-of-life-2020/test.csv')
 print(train_df.shape)
 print(test_df.shape )<groupby>
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, Lambda
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
train_df.groupby(['delta'] ).size()<string_transform>
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.08, 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
sample_start = train_sample.loc[:, train_sample.columns.str.startswith('start')]
sample_stop = train_sample.loc[:, train_sample.columns.str.startswith('stop')]<train_model>
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 tqdm(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 tqdm(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 tqdm(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
start_arr = np.asarray(sample_start ).reshape(25, 25)
 stop_arr = np.asarray(sample_stop ).reshape(25, 25)
 time_step = train_sample['delta'].values[0]
print(time_step )<define_variables>
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
def model_cnn_flip(embedding_matrix):
filter_sizes = [1,2,3,5]
num_filters = 36
inp = Input(shape=(maxlen,))
x = Lambda(lambda x: K.reverse(x,axes=-1))(inp)
 x = Embedding(max_features, embed_size, weights=[embedding_matrix] )(x)
 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
updated_arr = np.copy(start_arr)
 steps = []
steps.append(updated_arr)
 for x in range(time_step):
updated_arr = life_step_1(updated_arr)
 steps.append(updated_arr )<filter>
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
single_step_df = train_df.loc[train_df['delta'] == 1]<data_type_conversions>
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
idx = 13970
single_img = np.asarray(single_step_df.loc[idx][2:627] ).reshape(25,25 ).astype('uint8' )<feature_engineering>
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
end_single_img_33 = life_step_1(single_img_33 )<categorify>
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
def postprocess(arr):
return arr[4:-4, 4:-4]<define_variables>
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
start_key = ['start_' + str(i)for i in range(625)]
stop_key = ['stop_' + str(i)for i in range(625)]<import_modules>
train_X, val_X, test_X, train_y, val_y, word_index = load_and_prec()
embedding_matrix_1 = load_glove(word_index)
 embedding_matrix_2 = load_fasttext(word_index)
 embedding_matrix_3 = load_para(word_index )
concatenate, Dropout, Lambda, MaxPooling2D, BatchNormalization 
<categorify>
outputs = []
K.image_data_format()<categorify>
outputs = []
pred_val_y, pred_test_y, best_score = train_pred(model_gru_srk_atten(embedding_matrix), epochs = 2)
 outputs.append([pred_val_y, pred_test_y, best_score, 'gru atten srk'] )
<prepare_x_and_y>
pred_val_y, pred_test_y, best_score = train_pred(model_cnn(embedding_matrix), epochs = 2)
 outputs.append([pred_val_y, pred_test_y, best_score, '2d CNN'] )
trainY = single_step_df.loc[:, single_step_df.columns.str.startswith('start')].values.reshape(-1, 25, 25)
 trainX = single_step_df.loc[:, single_step_df.columns.str.startswith('stop')].values.reshape(-1, 25, 25 )<data_type_conversions>
pred_val_y, pred_test_y, best_score = train_pred(model_cnn_flip(embedding_matrix), epochs = 2)
 outputs.append([pred_val_y, pred_test_y, best_score, '2d CNN flip'] )
trainX = np.array([preprocess(xi)for xi in trainX] ).astype(np.float32)
 trainX = np.expand_dims(trainX, axis=-1 ).astype(np.float32 )<data_type_conversions>
pred_val_y, pred_test_y, best_score = train_pred(model_cnn(embedding_matrix_1), epochs = 2)
 outputs.append([pred_val_y, pred_test_y, best_score, '2d CNN GloVe'] )
trainY = np.array([preprocess(xi)for xi in trainY] ).astype(np.float32)
 trainY = np.expand_dims(trainY, axis=-1 ).astype(np.float32 )<normalization>
pred_val_y, pred_test_y, best_score = train_pred(model_cnn_flip(embedding_matrix_1), epochs = 2)
 outputs.append([pred_val_y, pred_test_y, best_score, '2d CNN GloVe flip'] )
def life_step_1_tensor(X):

 nbrs_count = tf.stack([tf.roll(tf.roll(X, i, 0), j, 1)
 for i in(-1, 0, 1)for j in(-1, 0, 1)
 if(i != 0 or j != 0)])
 nbrs_count = tf.squeeze(K.sum(nbrs_count, axis=0, keepdims=True), axis=0)
 nbrs_count =(nbrs_count == 3)|(( X == 1)&(nbrs_count == 2))
return tf.cast(nbrs_count, dtype=tf.uint32 )<categorify>
pred_val_y, pred_test_y, best_score = train_pred(model_lstm_du(embedding_matrix), epochs = 2)
 outputs.append([pred_val_y, pred_test_y, best_score, 'LSTM DU'] )
def postprocess_tensor(arr):
return arr[4:-4, 4:-4,:]<categorify>
pred_val_y, pred_test_y, best_score = train_pred(model_lstm_atten(embedding_matrix), epochs = 3)
 outputs.append([pred_val_y, pred_test_y, best_score, '2 LSTM w/ attention'] )
def wrap_pad(t, extra_dims):
s = tf.shape(t)
 m = tf.constant([extra_dims[0], extra_dims[1]])
 d = tf.constant([1, 3, 3, s.numpy() [-1]])
 t = tf.tile(t, d)[:, s[1]-m[0]:m[0]-s[1], s[2]-m[1]:m[1]-s[2], :]
paddings = tf.constant([[0,0],[1, 1],[1, 1], [0,0]])
 t = tf.pad(t, paddings, 'CONSTANT')
 return t<split>
pred_val_y, pred_test_y, best_score = train_pred(model_lstm_atten(embedding_matrix_1), epochs = 3)
 outputs.append([pred_val_y, pred_test_y, best_score, '2 LSTM w/ attention GloVe'] )
t = trainY[0, :, :, :]<compute_test_metric>
pred_val_y, pred_test_y, best_score = train_pred(model_lstm_atten(embedding_matrix_3), epochs = 3)
 outputs.append([pred_val_y, pred_test_y, best_score, '2 LSTM w/ attention Para'] )
def custom_loss(y_actual,y_pred):
pred_fwd = y_pred
actual_fwd = y_actual
y_actual_f = tf.cast(K.flatten(actual_fwd), tf.float32)
 y_pred_f = tf.cast(K.flatten(pred_fwd), tf.float32)
 bce = BinaryCrossentropy(from_logits=False)
 return bce(y_actual_f, y_pred_f )<define_search_model>
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 )
def crglnet_v1() :
inputShape =(33, 33, 1)
 inputs = Input(inputShape)
 c1 = Conv2D(64,(3, 3), activation='elu', padding='same' )(inputs)
 c2 = Conv2D(64,(3, 3), activation='elu', padding='same' )(c1)
 c3 = Conv2D(128,(5, 5), activation='elu', padding='same' )(c2)
 c4 = Conv2D(64,(3, 3), activation='elu', padding='same' )(c3)
 c5 = Conv2D(64,(3, 3), activation='elu', padding='same' )(c4)
 c6 = Conv2D(1,(1, 1), activation='sigmoid' )(c5)
 model = Model(inputs=[inputs], outputs=[c6])
 return model 
<define_search_model>
X = np.asarray([outputs[i][0] for i in range(len(outputs)) ])
 X = X[...,0]
reg = LinearRegression().fit(X.T, val_y)
 print(reg.score(X.T, val_y),reg.coef_ )
def crglnet_v2() :
inputShape =(33, 33, 1)
 inputs = Input(inputShape)
 c1 = Conv2D(32,(3, 3), activation='elu', padding='same' )(inputs)
 c2 = Conv2D(64,(3, 3), activation='elu', padding='same' )(c1)
 c3 = Conv2D(128,(5, 5), activation='elu', padding='same' )(c2)
 c4 = concatenate([Conv2D(64,(3, 3), activation='elu', padding='same' )(c3), c2])
 c5 = concatenate([Conv2D(32,(3, 3), activation='elu', padding='same' )(c4), c1])
 c6 = Conv2D(64,(3, 3), activation='elu', padding='same' )(c5)
 c7 = Conv2D(32,(3, 3), activation='elu', padding='same' )(c6)
 c8 = Conv2D(1,(1, 1), activation='sigmoid' )(c7)
 model = Model(inputs=[inputs], outputs=[c8])
 return model<train_on_grid>
pred_val_y = np.sum([outputs[i][0] * reg.coef_[i] 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 )
<choose_model_class><EOS> 
pred_test_y = np.sum([outputs[i][1] * reg.coef_[i] 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 )