Kaggle competition: Quora Insincere Questions Classification
cat_feats=['Embarked','Sex','Titles','block','Pclass']
nullageblk_test = pd.get_dummies(nullageblk,columns=cat_feats,drop_first=False)
 nullageblk_test=nullageblk_test.drop(columns=['Name','Ticket','PassengerId','Cabin','Survived'])
 nullageblk_test.head() 
<drop_column>
embed_size = 300
max_features = 95000
maxlen = 70
X_nullageblk_test=nullageblk_test<drop_column>
import os
import time
import numpy as np
import pandas as pd
from tqdm import tqdm
import re
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,BatchNormalization
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.initializers import glorot_normal, orthogonal
import tensorflow as tf
X_nonull_df_train=X_nonull_df_train.drop(columns=['Titles_ Capt','Titles_ Col','Titles_ Dona','Titles_ Lady','Titles_ Major',
'Titles_ Mlle','Titles_ Mme','Titles_ Sir','Titles_ the Countess'])
 X_nullageblk_test=X_nullageblk_test.drop(columns=['Titles_ Ms'] )<train_model>
puncts = [',', '.', '"', ':', ')', '(', '-', '!', '?', '|', ';', "'", '$', '&', '/', '[', ']', '>', '%', '=', '
'·', '_', '{', '}', '©', '^', '®', '`', '<', '→', '°', '€', '™', '›', '♥', '←', '×', '§', '″', '′', 'Â', '█', '½', 'à', '…',
'“', '★', '”', '–', '●', 'â', '►', '−', '¢', '²', '¬', '░', '¶', '↑', '±', '¿', '▾', '═', '¦', '║', '―', '¥', '▓', '—', '‹', '─',
'▒', '：', '¼', '⊕', '▼', '▪', '†', '■', '’', '▀', '¨', '▄', '♫', '☆', 'é', '¯', '♦', '¤', '▲', 'è', '¸', '¾', 'Ã', '⋅', '‘', '∞',
'∙', '）', '↓', '、', '│', '（', '»', '，', '♪', '╩', '╚', '³', '・', '╦', '╣', '╔', '╗', '▬', '❤', 'ï', 'Ø', '¹', '≤', '‡', '√', ]
def clean_text(x):
x = str(x)
 for punct in puncts:
x = x.replace(punct, f' {punct} ')
 return x
dtreeClass.fit(X_nonull_df_train,y_nonull_df_train )<predict_on_test>
def load_and_prec() :
train_df = pd.read_csv(".. /input/train.csv")
 test_df = pd.read_csv(".. /input/test.csv")
 train_df["question_text"] = train_df["question_text"].apply(lambda x: x.lower())
 test_df["question_text"] = test_df["question_text"].apply(lambda x: x.lower())
 train_df["question_text"] = train_df["question_text"].apply(lambda x: clean_text(x))
test_df["question_text"] = test_df["question_text"].apply(lambda x: clean_text(x))
print("Train shape : ",train_df.shape)
 print("Test shape : ",test_df.shape)
 train_df, val_df = train_test_split(train_df, test_size=0.04, 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
predictions_nullageblk = dtreeClass.predict(X_nullageblk_test)
 predictions_nullageblk<prepare_output>
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 = -0.005838499,0.48782197
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 = -0.0053247833,0.49346462
embed_size = all_embs.shape[1]
print(emb_mean,emb_std,"para")
 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
predictions_nullageblk=pd.DataFrame(predictions_nullageblk, columns=['block_A','block_B','block_C','block_D','block_E','block_F','block_G'])
 predictions_nullageblk['block']=np.where(predictions_nullageblk['block_A']==1,'A','')
 predictions_nullageblk['block']=np.where(predictions_nullageblk['block_B']==1,'B',predictions_nullageblk['block'])
 predictions_nullageblk['block']=np.where(predictions_nullageblk['block_C']==1,'C',predictions_nullageblk['block'])
 predictions_nullageblk['block']=np.where(predictions_nullageblk['block_D']==1,'D',predictions_nullageblk['block'])
 predictions_nullageblk['block']=np.where(predictions_nullageblk['block_E']==1,'E',predictions_nullageblk['block'])
 predictions_nullageblk['block']=np.where(predictions_nullageblk['block_F']==1,'F',predictions_nullageblk['block'])
 predictions_nullageblk['block']=np.where(predictions_nullageblk['block_G']==1,'G',predictions_nullageblk['block'])
 predictions_nullageblk.head()<prepare_output>
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
predictions_nullageblk=predictions_nullageblk['block'].values<drop_column>
def squash(x, axis=-1):
s_squared_norm = K.sum(K.square(x), axis, keepdims=True)
 scale = K.sqrt(s_squared_norm + K.epsilon())
 return x / scale
class Capsule(Layer):
def __init__(self, num_capsule, dim_capsule, routings=3, kernel_size=(9, 1), share_weights=True,
activation='default', **kwargs):
super(Capsule, self ).__init__(**kwargs)
 self.num_capsule = num_capsule
self.dim_capsule = dim_capsule
self.routings = routings
self.kernel_size = kernel_size
self.share_weights = share_weights
if activation == 'default':
self.activation = squash
else:
self.activation = Activation(activation)
 def build(self, input_shape):
super(Capsule, self ).build(input_shape)
 input_dim_capsule = input_shape[-1]
if self.share_weights:
self.W = self.add_weight(name='capsule_kernel',
shape=(1, input_dim_capsule,
self.num_capsule * self.dim_capsule),
initializer='glorot_uniform',
trainable=True)
 else:
input_num_capsule = input_shape[-2]
self.W = self.add_weight(name='capsule_kernel',
shape=(input_num_capsule,
input_dim_capsule,
self.num_capsule * self.dim_capsule),
initializer='glorot_uniform',
trainable=True)
 def call(self, u_vecs):
if self.share_weights:
u_hat_vecs = K.conv1d(u_vecs, self.W)
 else:
u_hat_vecs = K.local_conv1d(u_vecs, self.W, [1], [1])
 batch_size = K.shape(u_vecs)[0]
input_num_capsule = K.shape(u_vecs)[1]
u_hat_vecs = K.reshape(u_hat_vecs,(batch_size, input_num_capsule,
self.num_capsule, self.dim_capsule))
u_hat_vecs = K.permute_dimensions(u_hat_vecs,(0, 2, 1, 3))
b = K.zeros_like(u_hat_vecs[:, :, :, 0])
 for i in range(self.routings):
b = K.permute_dimensions(b,(0, 2, 1))
c = K.softmax(b)
 c = K.permute_dimensions(c,(0, 2, 1))
b = K.permute_dimensions(b,(0, 2, 1))
outputs = self.activation(tf.keras.backend.batch_dot(c, u_hat_vecs, [2, 2]))
if i < self.routings - 1:
b = tf.keras.backend.batch_dot(outputs, u_hat_vecs, [2, 3])
 return outputs
def compute_output_shape(self, input_shape):
return(None, self.num_capsule, self.dim_capsule )
nullageblk.drop(columns=['block'])
 nullageblk['block']=predictions_nullageblk
nullageblk<categorify>
def capsule(embedding_matrix):
inp = Input(shape=(maxlen,))
x = Embedding(max_features, embed_size, weights=[embedding_matrix], trainable=False )(inp)
 x = SpatialDropout1D(rate=0.2 )(x)
 x = Bidirectional(CuDNNGRU(100, return_sequences=True,
kernel_initializer=glorot_normal(seed=12300), recurrent_initializer=orthogonal(gain=1.0, seed=10000)) )(x)
 x = Capsule(num_capsule=10, dim_capsule=10, routings=4, share_weights=True )(x)
 x = Flatten()(x)
 x = Dense(100, activation="relu", kernel_initializer=glorot_normal(seed=12300))(x)
 x = Dropout(0.12 )(x)
 x = BatchNormalization()(x)
 x = Dense(1, activation="sigmoid" )(x)
 model = Model(inputs=inp, outputs=x)
 model.compile(loss='binary_crossentropy', optimizer=Adam() ,)
 return model
df['Age'] = df['Age'].mask(df['Age'].eq(0)).fillna(df['PassengerId'].map(nullageblk.set_index('PassengerId')['Age']))
df['CabinOccupancy'] = df['CabinOccupancy'].mask(df['CabinOccupancy'].eq(0)).fillna(df['PassengerId'].map(nullageblk.set_index('PassengerId')['CabinOccupancy']))
df['block'] = df['block'].mask(df['block'].eq(0)).fillna(df['PassengerId'].map(nullageblk.set_index('PassengerId')['block'])) 
<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
df[df['PassengerId']==6]<filter>
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
nonull_df=df[(df['Fare'].notnull())&(df['Age'].notnull())&(df['Embarked'].notnull())&(df['block'].notnull())]
nonull_df.count() ['PassengerId'] 
<categorify>
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
cat_feats=['Embarked','Sex','Titles','block','Pclass','CabinOccupancy']
nonull_df_train = pd.get_dummies(nonull_df,columns=cat_feats,drop_first=False)
 nonull_df_train=nonull_df_train.drop(columns=['Cabin','Name','PassengerId','Survived','Ticket'])
 nonull_df_train.head() 
<prepare_x_and_y>
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
X_nonull_df_train = nonull_df_train.drop(columns=['CabinOccupancy_1','CabinOccupancy_2','CabinOccupancy_3','CabinOccupancy_4','CabinOccupancy_5','CabinOccupancy_6'],axis=1)
 y_nonull_df_train = nonull_df_train[['CabinOccupancy_1','CabinOccupancy_2','CabinOccupancy_3','CabinOccupancy_4','CabinOccupancy_5','CabinOccupancy_6']]<categorify>
def model_gru_atten_3(embedding_matrix):
inp = Input(shape=(maxlen,))
x = Embedding(max_features, embed_size, weights=[embedding_matrix], trainable=False )(inp)
 x = Bidirectional(CuDNNGRU(128, return_sequences=True))(x)
 x = Bidirectional(CuDNNGRU(100, return_sequences=True))(x)
 x = Bidirectional(CuDNNGRU(64, return_sequences=True))(x)
 x = Attention(maxlen )(x)
 x = Dense(1, activation="sigmoid" )(x)
 model = Model(inputs=inp, outputs=x)
 model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
 return model
nullblk=df[df['block'].isnull() & df['Age'].notnull() ]
cat_feats=['Embarked','Sex','Titles','block','Pclass']
nullblk_test = pd.get_dummies(nullblk,columns=cat_feats,drop_first=False)
 nullblk_test=nullblk_test.drop(columns=['Name','Ticket','PassengerId','Cabin','Survived'])
 nullblk_test.head() 
<prepare_x_and_y>
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))
print("Val best_thresh: {:.2f}".format(best_thresh))
pred_test_y = model.predict([test_X], batch_size=1024, verbose=0)
 return pred_val_y, pred_test_y, best_score
X_nullblk_test=nullblk_test<drop_column>
train_X, val_X, test_X, train_y, val_y, word_index = load_and_prec()
vocab = []
for w,k in word_index.items() :
vocab.append(w)
 if k >= max_features:
break
embedding_matrix_1 = load_glove(word_index)
 embedding_matrix_3 = load_para(word_index )
X_nonull_df_train=X_nonull_df_train.drop(columns=['Titles_ Capt','Titles_ Dona','Titles_ Lady','Titles_ Major',
'Titles_ Mlle','Titles_ Mme','Titles_ Sir','Titles_ the Countess',
'block_A','block_B','block_C','block_D','block_E','block_F','block_G'])
 X_nullblk_test=X_nullblk_test.drop(columns=['CabinOccupancy','Titles_ Jonkheer','Titles_ Don','Titles_ Rev'] )<train_model>
embedding_matrix = np.mean([embedding_matrix_1, embedding_matrix_3], axis = 0)
 np.shape(embedding_matrix )
dtreeClass.fit(X_nonull_df_train,y_nonull_df_train )<predict_on_test>
outputs = []
predictions_nullblk = dtreeClass.predict(X_nullblk_test)
 predictions_nullblk<prepare_output>
pred_val_y, pred_test_y, best_score = train_pred(model_gru_atten_3(embedding_matrix), epochs = 3)
 outputs.append([pred_val_y, pred_test_y, best_score, '3 GRU w/ atten'] )
predictions_nullblk=pd.DataFrame(predictions_nullblk, columns=['1','2','3','4','5','6'])
 predictions_nullblk['CabinOccupancy']=np.where(predictions_nullblk['1']==1,'1','')
 predictions_nullblk['CabinOccupancy']=np.where(predictions_nullblk['2']==1,'2',predictions_nullblk['CabinOccupancy'])
 predictions_nullblk['CabinOccupancy']=np.where(predictions_nullblk['3']==1,'3',predictions_nullblk['CabinOccupancy'])
 predictions_nullblk['CabinOccupancy']=np.where(predictions_nullblk['4']==1,'4',predictions_nullblk['CabinOccupancy'])
 predictions_nullblk['CabinOccupancy']=np.where(predictions_nullblk['5']==1,'5',predictions_nullblk['CabinOccupancy'])
 predictions_nullblk['CabinOccupancy']=np.where(predictions_nullblk['6']==1,'6',predictions_nullblk['CabinOccupancy'])
 predictions_nullblk.head()<prepare_output>
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'])
predictions_nullblk=predictions_nullblk['CabinOccupancy'].values<drop_column>
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'] )
nullblk.drop(columns=['CabinOccupancy'])
 nullblk['CabinOccupancy']=predictions_nullblk
nullblk<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'] )
cat_feats=['Embarked','Sex','Titles','block','Pclass']
nonull_df_train = pd.get_dummies(nonull_df,columns=cat_feats,drop_first=False)
 nonull_df_train=nonull_df_train.drop(columns=['Cabin','Name','PassengerId','Survived','Ticket'])
 nonull_df_train.head() 
<prepare_x_and_y>
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'])
X_nonull_df_train = nonull_df_train.drop(['block_A','block_B','block_C','block_D','block_E','block_F','block_G'],axis=1)
 y_nonull_df_train = nonull_df_train[['block_A','block_B','block_C','block_D','block_E','block_F','block_G']]<categorify>
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'] )
cat_feats=['Embarked','Sex','Titles','block','Pclass']
nullblk_test = pd.get_dummies(nullblk,columns=cat_feats,drop_first=False)
 nullblk_test=nullblk_test.drop(columns=['Name','Ticket','PassengerId','Cabin','Survived'])
 nullblk_test.head() 
<prepare_x_and_y>
pred_val_y, pred_test_y, best_score = train_pred(capsule(embedding_matrix), epochs = 3)
 outputs.append([pred_val_y, pred_test_y, best_score, 'capsule'] )
X_nullblk_test=nullblk_test<drop_column>
X_nonull_df_train=X_nonull_df_train.drop(columns=['Titles_ Capt','Titles_ Dona','Titles_ Lady','Titles_ Major',
'Titles_ Mlle','Titles_ Mme','Titles_ Sir','Titles_ the Countess'])
 X_nullblk_test=X_nullblk_test.drop(columns=['Titles_ Jonkheer','Titles_ Don','Titles_ Rev'] )<train_model>
color = sns.color_palette()
sns.set_style('dark')
 plt.figure(figsize=(10, 8))
mask = np.zeros_like(dd, dtype=np.bool)
 mask[np.triu_indices_from(mask)] = True
cmap = sns.diverging_palette(220, 10, as_cmap=True)
 g = sns.heatmap(dd, mask=mask, cmap=cmap, square=True, annot=True, fmt='0.2f')
 plt.show()
dtreeClass.fit(X_nonull_df_train,y_nonull_df_train )<predict_on_test>
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)
 for output in outputs:
print(output[2], output[3])
 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_)
 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.2, 0.601, 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)
 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 )