Kaggle competition: Mechanisms of Action (MoA) Prediction
<SOS> metric: MeanColumnwiseLogLoss Kaggle data source: mechanisms-of-action-(moa)-prediction<filter>
!pip install.. /input/my-wheels/scikit_learn-0.21.0-cp37-cp37m-manylinux1_x86_64.whl
data_dt[(data_dt['Title'] == "Master")& data_dt['Age'].isna() ]<filter>
skopt.__version__, sklearn.__version__
data_dt[(data_dt['Title'] == "Master")]<drop_column>
def seed_everything(seed=42):
random.seed(seed)
 os.environ['PYTHONHASHSEED'] = str(seed)
 np.random.seed(seed)
 tf.random.set_seed(seed)
 seed_everything(seed=42 )
data_dt.drop(['Title'], axis=1, inplace=True)
 data_dt_proc.drop(['Name'], axis=1, inplace=True)
<categorify>
def preprocess(df):
df.loc[:, 'cp_type'] = df.loc[:, 'cp_type'].map({'trt_cp': 0, 'ctl_vehicle': 1})
 df.loc[:, 'cp_dose'] = df.loc[:, 'cp_dose'].map({'D1': 0, 'D2': 1})
 df.loc[:, 'cp_time'] = df.loc[:, 'cp_time'].map({24: 0, 48: 1, 72: 2})
 del df['sig_id']
return df
data_dt_proc_pre_dummies = data_dt_proc.copy()
data_dt_proc = pd.get_dummies(data_dt_proc)
 data_dt_proc.head()<categorify>
top_feats = [ 0, 1, 2, 3, 5, 6, 8, 9, 10, 11, 12, 14, 15,
16, 18, 19, 20, 21, 23, 24, 25, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 39, 40, 41, 42, 44, 45, 46,
48, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,
63, 64, 65, 66, 68, 69, 70, 71, 72, 73, 74, 75, 76,
78, 79, 80, 81, 82, 83, 84, 86, 87, 88, 89, 90, 92,
93, 94, 95, 96, 97, 99, 100, 101, 103, 104, 105, 106, 107,
108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120,
121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 132, 133, 134,
135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147,
149, 150, 151, 152, 153, 154, 155, 157, 159, 160, 161, 163, 164,
165, 166, 167, 168, 169, 170, 172, 173, 175, 176, 177, 178, 180,
181, 182, 183, 184, 186, 187, 188, 189, 190, 191, 192, 193, 195,
197, 198, 199, 202, 203, 205, 206, 208, 209, 210, 211, 212, 213,
214, 215, 218, 219, 220, 221, 222, 224, 225, 227, 228, 229, 230,
231, 232, 233, 234, 236, 238, 239, 240, 241, 242, 243, 244, 245,
246, 248, 249, 250, 251, 253, 254, 255, 256, 257, 258, 259, 260,
261, 263, 265, 266, 268, 270, 271, 272, 273, 275, 276, 277, 279,
282, 283, 286, 287, 288, 289, 290, 294, 295, 296, 297, 299, 300,
301, 302, 303, 304, 305, 306, 308, 309, 310, 311, 312, 313, 315,
316, 317, 320, 321, 322, 324, 325, 326, 327, 328, 329, 330, 331,
332, 333, 334, 335, 338, 339, 340, 341, 343, 344, 345, 346, 347,
349, 350, 351, 352, 353, 355, 356, 357, 358, 359, 360, 361, 362,
363, 364, 365, 366, 368, 369, 370, 371, 372, 374, 375, 376, 377,
378, 379, 380, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391,
392, 393, 394, 395, 397, 398, 399, 400, 401, 403, 405, 406, 407,
408, 410, 411, 412, 413, 414, 415, 417, 418, 419, 420, 421, 422,
423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435,
436, 437, 438, 441, 442, 443, 444, 445, 446, 447, 448, 449, 450,
452, 453, 454, 456, 457, 458, 459, 460, 461, 462, 463, 464, 465,
466, 468, 469, 471, 472, 473, 474, 475, 476, 477, 478, 479, 482,
483, 485, 486, 487, 488, 489, 491, 492, 494, 495, 496, 500, 501,
502, 503, 505, 506, 507, 509, 510, 511, 512, 513, 514, 516, 517,
518, 519, 521, 523, 525, 526, 527, 528, 529, 530, 531, 532, 533,
534, 536, 537, 538, 539, 540, 541, 542, 543, 544, 545, 546, 547,
549, 550, 553, 554, 555, 556, 557, 558, 559, 560, 561, 562, 563,
564, 565, 566, 567, 569, 570, 571, 572, 573, 574, 575, 577, 580,
581, 582, 583, 586, 587, 590, 591, 592, 593, 595, 596, 597, 598,
599, 600, 601, 602, 603, 605, 607, 608, 609, 611, 612, 613, 614,
615, 616, 617, 619, 622, 623, 625, 627, 630, 631, 632, 633, 634,
635, 637, 638, 639, 642, 643, 644, 645, 646, 647, 649, 650, 651,
652, 654, 655, 658, 659, 660, 661, 662, 663, 664, 666, 667, 668,
669, 670, 672, 674, 675, 676, 677, 678, 680, 681, 682, 684, 685,
686, 687, 688, 689, 691, 692, 694, 695, 696, 697, 699, 700, 701,
702, 703, 704, 705, 707, 708, 709, 711, 712, 713, 714, 715, 716,
717, 723, 725, 727, 728, 729, 730, 731, 732, 734, 736, 737, 738,
739, 740, 741, 742, 743, 744, 745, 746, 747, 748, 749, 750, 751,
752, 753, 754, 755, 756, 758, 759, 760, 761, 762, 763, 764, 765,
766, 767, 769, 770, 771, 772, 774, 775, 780, 781, 782, 783, 784,
785, 787, 788, 790, 793, 795, 797, 799, 800, 801, 805, 808, 809,
811, 812, 813, 816, 819, 820, 821, 822, 823, 825, 826, 827, 829,
831, 832, 833, 834, 835, 837, 838, 839, 840, 841, 842, 844, 845,
846, 847, 848, 850, 851, 852, 854, 855, 856, 858, 860, 861, 862,
864, 867, 868, 870, 871, 873, 874]
print(len(top_feats))
data_dt_proc['Pclass_1'] = pd.get_dummies(data_dt_proc['Pclass'])[1]
data_dt_proc['Pclass_2'] = pd.get_dummies(data_dt_proc['Pclass'])[2]
data_dt_proc['Pclass_3'] = pd.get_dummies(data_dt_proc['Pclass'])[3]
data_dt_proc.head()<compute_test_metric>
PERM_IMP = True
OHE = False
N_TRIALS = 15
SEED = 34
x = np.concatenate([np.ones(25), np.ones(10), np.zeros(25), np.zeros(40)])
 y = np.concatenate([np.ones(25), np.zeros(10), np.ones(25), np.zeros(40)])
 print("Acurácia {:.2f}".format(accuracy_score(y,x)))
 print("Precisão {:.2f}".format(precision_score(y,x)))
 print("Recall {:.2f}".format(recall_score(y,x)))
 print("F1 {:.2f}".format(f1_score(y,x)) )<set_options>
train_features = pd.read_csv('.. /input/lish-moa/train_features.csv')
 train_targets = pd.read_csv('.. /input/lish-moa/train_targets_scored.csv')
 test_features = pd.read_csv('.. /input/lish-moa/test_features.csv')
 train_targets_nonscored = pd.read_csv('.. /input/lish-moa/train_targets_nonscored.csv')
 subm = pd.read_csv('.. /input/lish-moa/sample_submission.csv' )
%matplotlib inline
plt.figure(figsize=(10,10))
sns.countplot(x='Survived',data=train_data )<define_variables>
cat_features = ['cp_type', 'cp_time', 'cp_dose']
num_features = [c for c in train_features.columns if train_features.dtypes[c] != 'object']
num_features = [c for c in num_features if c not in cat_features]
target_cols = [c for c in train_targets.columns if c not in ['sig_id']]
targets = train_targets[target_cols]
train_x = preprocess(train_features)
 test_x = preprocess(test_features)
 print('Tensor shapes:', train_x.shape, targets.shape, test_x.shape)
 if PERM_IMP:
train_x = train_x.iloc[:, top_feats]
test_x = test_x.iloc[:, top_feats]
if OHE:
train_x = pd.get_dummies(train_x, columns=train_x[cat_features].columns)
 test_x = pd.get_dummies(test_x, columns=test_x[cat_features].columns)
 print('Final tensor shapes:', train_x.shape, targets.shape, test_x.shape )
print("Classificador One Rule:")
 women = train_data[train_data.Sex == 'female']["Survived"]
rate_women = sum(women)/len(women)*100
print("% de mulheres que sobrevivem: {:.2f}".format(rate_women))<categorify>
x_train, x_val, y_train, y_val = train_test_split(train_x, targets, test_size=0.2)
 x_train.shape, x_val.shape
data_dt_proc_pre_dummies['Sex'] = pd.factorize(data_dt_proc_pre_dummies['Sex'])[0]
data_dt_proc_pre_dummies['Embarked'] = pd.factorize(data_dt_proc_pre_dummies['Embarked'])[0]
data_dt_proc_pre_dummies['Title'] = pd.factorize(data_dt_proc_pre_dummies['Title'])[0]<prepare_x_and_y>
dim_num_dense_nodes_3 = Integer(low=256, high=512, name='num_dense_nodes_3')
 dim_activation = Categorical(categories=['relu', 'elu'], name='activation')
 dim_dropout1 = Integer(low=1, high=5, name='dp1')
 dim_dropout2 = Integer(low=1, high=5, name='dp2')
 dim_dropout3 = Integer(low=1, high=5, name='dp3')
 dim_dropout4 = Integer(low=1, high=5, name='dp4')
 dim_look_ahead = Integer(low=5, high=15, name='look_ahead')
 dimensions = [
dim_num_dense_nodes_3,
dim_activation,
dim_dropout1,
dim_dropout2,
dim_dropout3,
dim_dropout4,
dim_look_ahead
]
default_params = [512, 'relu', 5, 5, 5, 5, 6]
assert len(default_params)==len(dimensions), 'Error: check shapes!'
y = train_data['Survived']
data_dt_proc.drop(['Survived'], axis=1, inplace=True)
 features_all = ["Pclass", "Age", "Pclass_1","Pclass_2","Pclass_3", "Fare", "Sex_female","Sex_male", "SibSp", "Parch", 'FamilySize', 'Embarked_C', 'Embarked_Q', 'Embarked_S',
'Title_Master', 'Title_Miss', 'Title_Mr', 'Title_Mrs', 'Title_Officer', 'Title_Royalty']
features_selected = ["Pclass_1","Pclass_2","Pclass_3", "Sex_female","Sex_male", "Fare", 'Title_Master', 'Title_Miss', 'Title_Mr', 'Title_Mrs', 'Title_Officer', 'Title_Royalty']
features = ["Pclass_1","Pclass_2","Pclass_3", "Sex_female","Sex_male", "Fare", "Parch", 'FamilySize', 'Embarked_C', 'Embarked_Q', 'Embarked_S']
train_data_all = data_dt_proc[features_all][:891]
test_data_all = data_dt_proc[features_all][891:]
train_data_selected = data_dt_proc[features_selected][:891]
test_data_selected = data_dt_proc[features_selected][891:]
train_data_proc = data_dt_proc[features][:891]
test_data_proc = data_dt_proc[features][891:]
y_test = pd.read_csv(".. /input/titanic-leaked/titanic.csv")
 y_test = y_test['Survived']<set_options>
n_inputs = len(top_feats)
 n_outs = len(target_cols)
 def create_model(
 num_dense_nodes_3,
activation,
dp1,
dp2,
dp3,
dp4,
look_ahead 
):
weight_norm = False
inp = tf.keras.layers.Input(n_inputs)
 x = tf.keras.layers.BatchNormalization()(inp)
 x = tf.keras.layers.Dropout(0.2 )(x)
 x = tf.keras.layers.Dense(2048, activation=activation )(x)
 if weight_norm:
x = tfa.layers.WeightNormalization(x)
 x = tf.keras.layers.BatchNormalization()(x)
 x = tf.keras.layers.Dropout(0.1*dp1 )(x)
 x = tf.keras.layers.Dense(1024, activation=activation )(x)
 if weight_norm:
x = tfa.layers.WeightNormalization(x)
 x = tf.keras.layers.BatchNormalization()(x)
 x = tf.keras.layers.Dropout(0.1*dp2 )(x)
 x = tf.keras.layers.Dense(512, activation=activation )(x)
 if weight_norm:
x = tfa.layers.WeightNormalization(x)
 x = tf.keras.layers.BatchNormalization()(x)
 x = tf.keras.layers.Dropout(0.1*dp3 )(x)
 x = tf.keras.layers.Dense(num_dense_nodes_3, activation=activation )(x)
 if weight_norm:
x = tfa.layers.WeightNormalization(x)
 x = tf.keras.layers.BatchNormalization()(x)
 x = tf.keras.layers.Dropout(0.1*dp4 )(x)
 out = tf.keras.layers.Dense(n_outs, activation="sigmoid" )(x)
 model = tf.keras.models.Model(inp, out)
 opt = tf.keras.optimizers.Adam(lr=1e-3)
 opt = tfa.optimizers.Lookahead(opt, sync_period=int(look_ahead))
model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['AUC'])
 return model
def warn(*args, **kwargs):
pass
warnings.warn = warn
def run_all_classifiers(x, y, x_test, y_test):
classifiers = {
'knn': KNeighborsClassifier(1),
'svm': SVC(probability=True),
'decision_tree' : DecisionTreeClassifier() ,
'random_forest' : RandomForestClassifier(n_estimators=50, max_depth=5, random_state=1),
'ada_boost' : AdaBoostClassifier() ,
'gradient_boost' : GradientBoostingClassifier() ,
'xgboost': XGBClassifier() ,
'gaussian_nb' : GaussianNB() ,
'linear_disc' : LinearDiscriminantAnalysis() ,
'quadratic_disc' : QuadraticDiscriminantAnalysis() ,
'log_regression' : LogisticRegression(verbose=False),
'mlp' : MLPClassifier(solver='adam', alpha=1e-3, hidden_layer_sizes=(12,1), random_state=1, max_iter=500,verbose=False)
 }
best_acc = {'classifier' : None,
'accuracy' : 0.0}
all_results = {}
for clf in classifiers:
clf_model = classifiers[clf]
clf_model.fit(x, y)
 y_pred = clf_model.predict(x_test)
 all_results[clf] = y_pred
acc = accuracy_score(y_pred, y_test)* 100
if acc > best_acc['accuracy']:
best_acc['accuracy'] = acc
best_acc['classifier'] = clf
print("Acurácia de {}: {:.2f}%".format(clf, acc))
print("
O melhor classificador foi {} com acurácia de {:.2f}%".format(best_acc['classifier'], best_acc['accuracy']))
return all_results, best_acc<split>
path_best_model = './model.h5'
best_loss = np.inf
print("Resultado com todas as características: ")
 all_results_all, best_acc_all = run_all_classifiers(train_data_all, y, test_data_all, y_test )<split>
@use_named_args(dimensions=dimensions)
 def fitness(num_dense_nodes_3, activation, dp1, dp2, dp3, dp4, look_ahead):

 print('num_dense_nodes layer-4:', num_dense_nodes_3)
 print('activation:',activation)
 print('dropout 1:', dp1*0.1)
 print('dropout 2:', dp2*0.1)
 print('dropout 3:', dp3*0.1)
 print('dropout 4:', dp4*0.1)
 print('look ahead:',look_ahead)
 print()
model = create_model(
 num_dense_nodes_3,
activation,
dp1,
dp2,
dp3,
dp4,
look_ahead)
 cbs = [
tf.keras.callbacks.EarlyStopping('val_loss', patience=30, verbose=1),
tf.keras.callbacks.ReduceLROnPlateau('val_loss', patience=3, factor=0.1)]
hist = model.fit(x = x_train,
y = y_train,
epochs=65,
batch_size=128,
validation_data=(x_val, y_val),
callbacks=cbs,
verbose = 0)
 log_loss = min(hist.history['val_loss'])
 print('-'*20)
 print(f"> Log loss: {log_loss}")
 print('-'*20)
 global best_loss
if log_loss < best_loss:
model.save(path_best_model)
 best_loss = log_loss
del model
gc.collect()
K.clear_session()
return log_loss
print("Resultado com as características selecionadas apenas via correlação: ")
 all_results_selected, best_acc_selected = run_all_classifiers(train_data_selected, y, test_data_selected, y_test )<compute_test_metric>
search_result = skopt.gp_minimize(func=fitness,
dimensions=dimensions,
acq_func='EI',
n_calls=N_TRIALS,
random_state=SEED,
x0=default_params )
print("Resultado com as características selecionadas manualmente: ")
 all_results_proc, best_acc_proc = run_all_classifiers(train_data_proc, y, test_data_proc, y_test )<save_to_csv>
print('optimal hyper-parameters')
 print()
print(f'dense_units 3: {search_result.x[0]}')
 print(f'activation: {search_result.x[1]}')
 print(f'dropout 1: {search_result.x[2]}')
 print(f'dropout 2: {search_result.x[3]}')
 print(f'dropout 3: {search_result.x[4]}')
 print(f'dropout 4: {search_result.x[5]}')
 print(f'Look ahead: {search_result.x[6]}')
output = pd.DataFrame({'PassengerId': test_data.PassengerId, 'Survived': all_results_proc[best_acc_proc['classifier']] })
 output.to_csv('my_submission.csv', index=False)
 print("Arquivo de submissão gerado com sucesso!!" )<load_from_csv>
pd.DataFrame(sorted(zip(search_result.func_vals, search_result.x_iters)) , index=np.arange(N_TRIALS), columns=['score', 'params'] )
y_gender = pd.read_csv(".. /input/titanic/gender_submission.csv")
 y_gender = y_gender['Survived']
acc_gender = round(accuracy_score(y_gender, y_test)* 100, 2)
 print("Acurácia com Genero: {}".format(acc_gender))
print("Diferença com proc de {:.2f}%".format(best_acc_proc['accuracy'] - acc_gender))
print("Diferença com selected de {:.2f}%".format(best_acc_selected['accuracy'] - acc_gender))
print("Diferença com all de {:.2f}%".format(best_acc_all['accuracy'] - acc_gender))<train_model>
model = create_model(*search_result.x)
 model.summary()
class TaskDataset(Dataset):
def __init__(self, path, name, mode='train'):
self.tokenizer = BertTokenizer('vocab.txt')
 self.items = self.__load(path, name, mode)
 def __load(self, path, name, mode):
items = []
task = Task(path, name)
 self.task_width, self.task_height, _ = task.max_size()
max_length = 2 +(self.task_width + 1)* self.task_height
if mode == 'train':
for inp, out in task.get_train() :
inp = self.__tokenize(inp, max_length)
 out = self.__tokenize(out, max_length)
 items.append(( name, inp, out))
if mode == 'valid':
for inp, out in task.get_valid() :
inp = self.__tokenize(inp, max_length)
 out = self.__tokenize(out, max_length)
 items.append(( name, inp, out))
if mode == 'tests':
for inp in task.get_tests() :
inp = self.__tokenize(inp, max_length)
 items.append(( name, inp, inp))
return items
def __tokenize(self, sequ, max_length):
sequ_dict = self.tokenizer.encode_plus(sequ, add_special_tokens=False, max_length=max_length, pad_to_max_length=True)
 return np.array(sequ_dict['input_ids'], dtype=np.int64), np.array(sequ_dict['attention_mask'], dtype=np.int64), np.array(sequ_dict['token_type_ids'], dtype=np.int64),
def __len__(self):
return len(self.items)
 def __getitem__(self, idx):
return self.items[idx] 
<init_hyperparams>
metrics = []
for _target in target_cols:
metrics.append(log_loss(targets.loc[:, _target], oof.loc[:, _target]))
print(f'OOF Metric: {np.mean(metrics ).round(8)}' )
INTERMEDIATE_SIZE = 1024
HIDDEN_SIZE = 1024
VOCAB_SIZE = 16
def create_model_config(w, h):
return {
"architectures": [
"BertForMaskedLM"
],
"attention_probs_dropout_prob": 0.5,
"hidden_act": "gelu",
"hidden_dropout_prob": 0.5,
"hidden_size": HIDDEN_SIZE,
"initializer_range": 0.02,
"intermediate_size": INTERMEDIATE_SIZE,
"max_position_embeddings": 2 +(w + 1)* h,
"num_attention_heads": 8,
"num_hidden_layers": 8,
"type_vocab_size": 1,
"vocab_size": VOCAB_SIZE,
"num_labels": 1
}
class Network(BertPreTrainedModel):
def __init__(self, w, h):
config = BertConfig.from_dict(create_model_config(w, h))
super(Network, self ).__init__(config)
 self.bert = BertModel(config)
 self.fc = nn.Linear(HIDDEN_SIZE, VOCAB_SIZE)
 self.init_weights()
def forward(self, X):
ids = X[0]
msk = X[1]
typ = X[2]
output = self.bert(ids, attention_mask=msk, token_type_ids=typ)
 x = output[0]
x = F.relu(self.fc(x))
x = x.transpose(1, 2)
 return x 
<init_hyperparams>
oof.loc[train_x['cp_type']==1, target_cols] = 0
metrics = []
for _target in target_cols:
metrics.append(log_loss(targets.loc[:, _target], oof.loc[:, _target]))
print(f'OOF Metric(with post-processing): {np.mean(metrics ).round(8)}' )
<define_variables><EOS> 
subm.loc[test_x['cp_type']==1, target_cols] = 0
subm.to_csv('submission.csv', index=False )