Kaggle competition: Quora Insincere Questions Classification
upper_limit = train_df.revenue.quantile(0.75)+(1.5* iqr(train_df.revenue))
lower_limit = train_df.revenue.quantile(0.25)-(1.5* iqr(train_df.revenue))
condition =(train_df.revenue > upper_limit)|(train_df.revenue<lower_limit)
 train_df[condition]<count_unique_values>
dim = 300
num_words = 50000
max_len = 100
print('Fiting tokenizer')
 tokenizer = Tokenizer(num_words=num_words)
 tokenizer.fit_on_texts(df['question_text'])
 print('spliting data')
 df_train,df_test = train_test_split(df, random_state=1)
 print('text to sequence')
 x_train = tokenizer.texts_to_sequences(df_train['question_text'])
 x_test = tokenizer.texts_to_sequences(df_test['question_text'])
 print('pad sequence')
 x_train = pad_sequences(x_train,maxlen=max_len)
 x_test = pad_sequences(x_test, maxlen=max_len)
 y_train = df_train['target'].values
y_test = df_test['target'].values
print(x_train.shape)
 print(y_train.shape)
len(train_df.Id.unique())== train_df.shape[0]<count_unique_values>
print('Glove...')
 def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32')
 embeddings_index = dict(get_coefs(*o.split(" ")) for o in open('.. /input/embeddings/glove.840B.300d/glove.840B.300d.txt'))
all_embs = np.stack(embeddings_index.values())
 emb_mean,emb_std = all_embs.mean() , all_embs.std()
print(len(all_embs))
word_index = tokenizer.word_index
embedding_matrix_glov = np.random.normal(emb_mean, emb_std,(num_words, dim))
count=0
for word, i in word_index.items() :
if i >= num_words:
break
embedding_vector = embeddings_index.get(word)
 if embedding_vector is not None:
embedding_matrix_glov[i] = embedding_vector
else:
count += 1
print('embedding matrix size:',embedding_matrix_glov.shape)
 print('Number of words not in vocab:',count)
 del embeddings_index,all_embs
gc.collect()
len(test_df.Id.unique())== test_df.shape[0]<drop_column>
print('Para...')
 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()
print(len(all_embs))
word_index = tokenizer.word_index
embedding_matrix_para = np.random.normal(emb_mean, emb_std,(num_words, dim))
count=0
for word, i in word_index.items() :
if i >= num_words:
break
embedding_vector = embeddings_index.get(word)
 if embedding_vector is not None:
embedding_matrix_para[i] = embedding_vector
else:
count += 1
print('embedding matrix size:',embedding_matrix_glov.shape)
 print('Number of words not in vocab:',count)
 del embeddings_index,all_embs
gc.collect()
train_df.drop('Id',axis=1,inplace=True)
 test_df.drop('Id', axis=1, inplace=True )<count_values>
print('Wiki...')
 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()
print(len(all_embs))
word_index = tokenizer.word_index
embedding_matrix_wiki = np.random.normal(emb_mean, emb_std,(num_words, dim))
count=0
for word, i in word_index.items() :
if i >= num_words:
break
embedding_vector = embeddings_index.get(word)
 if embedding_vector is not None:
embedding_matrix_wiki[i] = embedding_vector
else:
count += 1
print('embedding matrix size:',embedding_matrix_wiki.shape)
 print('Number of words not in vocab:',count)
 del embeddings_index,all_embs
gc.collect()
train_df['Open Date'].value_counts()<feature_engineering>
matrixes = [embedding_matrix_glov,embedding_matrix_wiki,embedding_matrix_para]
matrix = np.mean(matrixes,axis=0)
 del embedding_matrix_glov,embedding_matrix_wiki,embedding_matrix_para
gc.collect()
train_df['open_year'] = train_df['Open Date'].dt.year
test_df['open_year'] = test_df['Open Date'].dt.year<count_values>
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
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()))
adam = optimizers.Adam()
print('LR:',K.eval(adam.lr))
batch_size = int(x_train.shape[0]*K.eval(adam.lr))
print('Batch size = ',batch_size)
 inp1 = Input(shape=(max_len,))
x = Embedding(num_words, dim, weights=[matrix],trainable = False, )(inp1)
 x = SpatialDropout1D(0.1 )(x)
 x1 = Bidirectional(CuDNNLSTM(int(max_len/2), return_sequences=True))(x)
 x = Bidirectional(CuDNNLSTM(int(max_len/2), return_sequences=True))(x1)
 x = Bidirectional(CuDNNLSTM(int(max_len/2), return_sequences=True))(x)
 x = Bidirectional(CuDNNLSTM(int(max_len/2), return_sequences=True))(x)
 x = Add()([x1,x])
 atten_1 = Attention(max_len )(x)
 avg_pool = GlobalAveragePooling1D()(x)
 max_pool = GlobalMaxPooling1D()(x)
 x = concatenate([atten_1, avg_pool, max_pool])
 x = Dense(100, activation="relu",kernel_regularizer=regularizers.l2(0.0001))(x)
 x = Dropout(0.2 )(x)
 x = Dense(1, activation='sigmoid',kernel_regularizer=regularizers.l2(0.0001))(x)
 model = Model(inputs=inp1, outputs=x)
 model.compile(loss='binary_crossentropy', optimizer=adam, metrics=['accuracy',f1])
 print(model.summary())
 patience = 5
modelcheck = ModelCheckpoint('model.h5',save_best_only=True)
 stop = EarlyStopping(patience=patience)
 reduce = ReduceLROnPlateau(patience=1,verbose=2)
 history = model.fit(x_train,y_train,
batch_size=batch_size,
validation_split=0.2,
epochs=100,
callbacks=[modelcheck,stop,reduce])
 print('training finished...' )
train_df['City Group'].value_counts()<count_unique_values>
model.load_weights('model.h5')
 y_pred = model.predict(x_train,batch_size=batch_size, verbose=1)
 search_result = threshold_search(y_train, y_pred)
 print(search_result)
 y_pred = y_pred>search_result['threshold']
y_pred = y_pred.astype(int)
 print('RESULTS ON TRAINING SET:
',classification_report(y_train,y_pred))
y_pred = model.predict(x_test,batch_size=batch_size, verbose=1)
 search_result = threshold_search(y_test, y_pred)
 print(search_result)
 y_pred = y_pred>search_result['threshold']
y_pred = y_pred.astype(int)
 print('RESULTS ON TEST SET:
',classification_report(y_test,y_pred))
<drop_column><EOS> 
print('Loading test data...')
 df_final = pd.read_csv('.. /input/test.csv')
 df_final["question_text"].fillna("_
x_final=tokenizer.texts_to_sequences(df_final['question_text'])
 x_final = pad_sequences(x_final,maxlen=max_len)
 y_pred = model.predict(x_final,batch_size=batch_size,verbose=1)
 y_pred = y_pred > search_result['threshold']
y_pred = y_pred.astype(int)
 print(y_pred[:5])
 df_subm = pd.DataFrame()
df_subm['qid'] = df_final.qid
df_subm['prediction'] = y_pred
print(df_subm.head())
 df_subm.to_csv('submission.csv', index=False )