Kaggle competition: Don't Overfit! II
<SOS> metric: AUC Kaggle data source: dont-overfit!-ii<load_from_csv>
ver = 'linear_v34'
warnings.filterwarnings('ignore')
 %matplotlib inline
plt.style.use(['seaborn-darkgrid'])
 plt.rcParams['font.family'] = 'DejaVu Sans'
print(os.listdir(".. /input"))
RANDOM_STATE = 78
noise_std = 0.01
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')
 ss = pd.read_csv('.. /input/lish-moa/sample_submission.csv' )<categorify>
filename = 'subm_{}_{}_'.format(ver, datetime.now().strftime('%Y-%m-%d'))
def sub_prp(clf, filename, X_test):
prediction_ = clf.predict_proba(X_test)[:,1]
submission_ = pd.read_csv('.. /input/sample_submission.csv')
 submission_['target'] = prediction_
submission_.to_csv(filename, index=False)
 print(submission_.head())
 def sub_pr(clf, filename, X_test):
prediction_ = clf.predict(X_test)
 submission_ = pd.read_csv('.. /input/sample_submission.csv')
 submission_['target'] = prediction_
submission_.to_csv(filename, index=False)
 print(submission_.head() )
def preprocess(df):
df = df.copy()
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})
 del df['sig_id']
return df<categorify>
train = pd.read_csv('.. /input/train.csv')
 test = pd.read_csv('.. /input/test.csv' )
train = preprocess(train_features)
 test = preprocess(test_features )<drop_column>
train = pd.read_csv('.. /input/train.csv')
 test = pd.read_csv('.. /input/test.csv' )
del train_targets['sig_id']<filter>
X_train = train.drop(['id', 'target'], axis=1)
 y_train = train['target']
X_tst = test.drop(['id'], axis=1 )
train_targets = train_targets.loc[train['cp_type'] == 0].reset_index(drop=True)
 train = train.loc[train['cp_type'] == 0].reset_index(drop=True )<choose_model_class>
sc0 = StandardScaler()
sc0.fit(X_train)
 X_train = sc0.transform(X_train)
 X_test = sc0.transform(X_tst)
def create_model(num_columns):
model = tf.keras.Sequential([
tf.keras.layers.Input(num_columns),
tf.keras.layers.BatchNormalization() ,
tf.keras.layers.Dropout(0.2),
tfa.layers.WeightNormalization(tf.keras.layers.Dense(2048, activation="relu")) ,
tf.keras.layers.BatchNormalization() ,
tf.keras.layers.Dropout(0.5),
tfa.layers.WeightNormalization(tf.keras.layers.Dense(1048, activation="relu")) ,
tf.keras.layers.BatchNormalization() ,
tf.keras.layers.Dropout(0.5),
tfa.layers.WeightNormalization(tf.keras.layers.Dense(206, activation="sigmoid"))
])
 model.compile(optimizer=tfa.optimizers.Lookahead(tf.optimizers.Adam() , sync_period=10),
loss='binary_crossentropy', 
)
 return model<define_variables>
repfold = RepeatedStratifiedKFold(n_splits=10, n_repeats=20, random_state=RANDOM_STATE)
 logreg0 = LogisticRegression(C=0.5, random_state=RANDOM_STATE, solver='liblinear', penalty='l1')
 lass0 = Lasso(alpha=0.031, tol=0.01, selection='random', random_state=RANDOM_STATE)
 ridg0 = Ridge(alpha=20, fit_intercept=True, solver='auto', tol=0.0025, random_state=RANDOM_STATE)
 sgd0 = SGDClassifier(eta0=1, max_iter=1000, tol=0.0001, random_state=RANDOM_STATE, loss='log' )
top_feats = [ 1, 2, 3, 4, 5, 6, 7, 9, 11, 14, 15, 16, 17,
18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 29, 30, 31,
32, 33, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 46,
47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 58, 59, 60,
61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73,
74, 75, 76, 78, 79, 80, 81, 82, 83, 84, 86, 87, 88,
89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101,
102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114,
115, 116, 117, 118, 120, 121, 122, 123, 124, 125, 126, 127, 128,
129, 130, 131, 132, 133, 136, 137, 138, 139, 140, 141, 142, 143,
144, 145, 146, 147, 149, 150, 151, 152, 153, 154, 155, 156, 157,
158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170,
171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183,
184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 197,
198, 199, 200, 202, 203, 204, 205, 206, 208, 209, 210, 211, 212,
213, 214, 215, 216, 217, 218, 219, 220, 221, 223, 224, 225, 226,
227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239,
240, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253,
254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266,
267, 268, 269, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280,
281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 294,
295, 296, 298, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309,
310, 311, 312, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323,
324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336,
337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349,
350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362,
363, 364, 365, 366, 367, 368, 369, 370, 371, 374, 375, 376, 377,
378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 390, 391,
392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404,
405, 406, 407, 408, 409, 411, 412, 413, 414, 415, 416, 417, 418,
419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431,
432, 434, 435, 436, 437, 438, 439, 440, 442, 443, 444, 445, 446,
447, 448, 449, 450, 453, 454, 456, 457, 458, 459, 460, 461, 462,
463, 464, 465, 466, 467, 468, 469, 470, 471, 472, 473, 474, 475,
476, 477, 478, 479, 481, 482, 483, 484, 485, 486, 487, 488, 489,
490, 491, 492, 493, 494, 495, 496, 498, 500, 501, 502, 503, 505,
506, 507, 509, 510, 511, 512, 513, 514, 515, 518, 519, 520, 521,
522, 523, 524, 525, 526, 527, 528, 530, 531, 532, 534, 535, 536,
538, 539, 540, 541, 542, 543, 544, 545, 546, 547, 549, 550, 551,
552, 554, 557, 559, 560, 561, 562, 565, 566, 567, 568, 569, 570,
571, 572, 573, 574, 575, 577, 578, 580, 581, 582, 583, 584, 585,
586, 587, 588, 589, 590, 591, 592, 593, 594, 595, 596, 597, 599,
600, 601, 602, 606, 607, 608, 609, 611, 612, 613, 615, 616, 617,
618, 619, 620, 621, 622, 623, 624, 625, 626, 627, 628, 629, 630,
631, 632, 633, 634, 635, 636, 637, 638, 639, 641, 642, 643, 644,
645, 646, 647, 648, 649, 650, 651, 652, 654, 655, 656, 658, 659,
660, 661, 662, 663, 664, 665, 666, 667, 668, 669, 670, 671, 672,
673, 674, 675, 676, 677, 678, 679, 680, 681, 682, 683, 684, 685,
686, 687, 688, 689, 691, 692, 693, 694, 695, 696, 697, 699, 700,
701, 702, 704, 705, 707, 708, 709, 710, 711, 713, 714, 716, 717,
718, 720, 721, 723, 724, 725, 726, 727, 728, 729, 730, 731, 732,
733, 734, 735, 737, 738, 739, 740, 742, 743, 744, 745, 746, 747,
748, 749, 750, 751, 752, 753, 754, 755, 756, 757, 759, 760, 761,
762, 763, 764, 765, 766, 767, 768, 769, 770, 771, 772, 773, 774,
775, 776, 777, 779, 780, 781, 782, 783, 784, 785, 786, 787, 788,
789, 790, 792, 793, 794, 795, 796, 797, 798, 800, 801, 802, 803,
804, 805, 806, 808, 809, 811, 813, 814, 815, 816, 817, 818, 819,
821, 822, 823, 825, 826, 827, 828, 829, 830, 831, 832, 834, 835,
837, 838, 839, 840, 841, 842, 845, 846, 847, 848, 850, 851, 852,
854, 855, 856, 858, 859, 860, 861, 862, 864, 866, 867, 868, 869,
870, 871, 872, 873, 874]
print(len(top_feats))<compute_test_metric>
logreg0.fit(X_train, y_train)
 sc = cross_val_score(logreg0, X_train, y_train, scoring='roc_auc', cv=repfold, n_jobs=-1, verbose=1)
 print(sc.mean() )
def metric(y_true, y_pred):
metrics = []
for _target in train_targets.columns:
metrics.append(log_loss(y_true.loc[:, _target], y_pred.loc[:, _target].astype(float), labels=[0,1]))
return np.mean(metrics )<init_hyperparams>
perm = PermutationImportance(logreg0, random_state=RANDOM_STATE ).fit(X_train, y_train)
 eli5.show_weights(perm, top=10 )
N_STARTS = 7
tf.random.set_seed(42)
 res = train_targets.copy()
ss.loc[:, train_targets.columns] = 0
res.loc[:, train_targets.columns] = 0
for seed in range(N_STARTS):
for n,(tr, te)in enumerate(MultilabelStratifiedKFold(n_splits=7, random_state=seed, shuffle=True ).split(train_targets, train_targets)) :
print(f'Fold {n}')
 model = create_model(len(top_feats))
checkpoint_path = f'repeat:{seed}_Fold:{n}.hdf5'
reduce_lr_loss = ReduceLROnPlateau(
 monitor='val_loss',
factor=0.1, patience=3,
verbose=1,
epsilon=1e-4,
mode='min' 
)
 cb_checkpt = ModelCheckpoint(
 checkpoint_path,
monitor='val_loss',
verbose=0,
save_best_only=True,
save_weights_only=True,
mode='min' 
)
 model.fit(
 train.values[tr][:, top_feats],
train_targets.values[tr],
validation_data =(train.values[te][:, top_feats], train_targets.values[te]),
epochs=50,
batch_size=128,
callbacks=[reduce_lr_loss, cb_checkpt],
verbose=2 
)
 model.load_weights(checkpoint_path)
 test_predict = model.predict(test.values[:, top_feats])
 val_predict = model.predict(train.values[te][:, top_feats])
 ss.loc[:, train_targets.columns] += test_predict
res.loc[te, train_targets.columns] += val_predict
print('')
 ss.loc[:, train_targets.columns] /=(( n+1)* N_STARTS)
 res.loc[:, train_targets.columns] /= N_STARTS<compute_test_metric>
logreg01 = LogisticRegression(C=0.5, random_state=RANDOM_STATE, solver='liblinear', penalty='l1' )
print(f'OOF Metric: {metric(train_targets, res)}' )<feature_engineering>
logreg01.fit(X_train.T[el_df.index].T, y_train)
 sc = cross_val_score(logreg01, X_train.T[el_df.index].T, y_train, scoring='roc_auc', cv=repfold, n_jobs=-1, verbose=1)
 print(sc.mean() )
ss.loc[test['cp_type'] == 1, train_targets.columns] = 0<save_to_csv>
param_lr = {'class_weight' : ['balanced', None],
'penalty' : ['l2','l1'],
'C' : [0.001, 0.01, 0.1, 1, 10, 100, 1000]
}
ss.to_csv('submission.csv', index=False )<load_from_csv>
grid_lr = GridSearchCV(estimator = logreg0, param_grid = param_lr , scoring = 'roc_auc', verbose = 1, n_jobs = -1, cv=repfold)
 grid_lr.fit(X_train,y_train)
 print("Best Score:" + str(grid_lr.best_score_))
print("Best Parameters: " + str(grid_lr.best_params_))
submission = pd.read_csv('/kaggle/input/lish-moa/sample_submission.csv')
 public_ids = list(submission['sig_id'].values)
 submission.shape<load_from_csv>
best_parameters_lr = grid_lr.best_params_
logreg = LogisticRegression(**best_parameters_lr)
 logreg.fit(X_train,y_train)
 sc = cross_val_score(logreg, X_train, y_train, scoring='roc_auc', cv=repfold, n_jobs=-1, verbose=1)
 print(sc.mean())
 selector_lr = RFECV(logreg, min_features_to_select=12, scoring='roc_auc', step=15, verbose=0, cv=repfold, n_jobs=-1)
 selector_lr.fit(X_train,y_train)
test = pd.read_csv('/kaggle/input/lish-moa/test_features.csv')
 test_ids = list(test['sig_id'].values)
 private_ids = list(set(test_ids)-set(public_ids))
len(private_ids )<load_from_csv>
selector_lr.score(X_train, y_train )
kernels = pd.read_csv('/kaggle/input/moa-public-kernels/kernels.csv', index_col='id' )<load_from_csv>
def acc_model(params):
clf = LogisticRegression(**params)
 return cross_val_score(clf, X_train, y_train, scoring='roc_auc', cv=repfold ).mean()
def make_filename(idx):
return glob.glob('/kaggle/input/moa-public-kernels/' + str(idx)+ '__submission.csv')[0]
def read_predictions(idx):
temp = pd.read_csv(make_filename(idx))
return temp
predictions = [read_predictions(idx)for idx in kernels.index]
len(predictions )<prepare_x_and_y>
print(pr[-1])
 best_lr = pr[-1]
logreg1 = LogisticRegression(**best_lr)
 logreg1.fit(X_train,y_train)
 sc = cross_val_score(logreg1, X_train, y_train, scoring='roc_auc', cv=repfold, n_jobs=-1, verbose=1)
 print(sc.mean())
y_pred = pd.DataFrame()
y_pred['sig_id'] = predictions[0]['sig_id']
for column in target_columns:
column_data = []
for i in range(len(predictions)) :
column_data.append(predictions[i][column])
 y_pred[column] = np.mean(column_data, axis=0)
 y_pred.shape<define_variables>
selector_lr1 = RFECV(logreg1, min_features_to_select=12, scoring='roc_auc', step=15, verbose=0, cv=repfold, n_jobs=-1)
 selector_lr1.fit(X_train,y_train)
scores = 1.- kernels['score']
sum_scores = sum(scores)
 weights = [x / sum_scores for x in scores]<prepare_output>
perm = PermutationImportance(logreg1, random_state=RANDOM_STATE ).fit(X_train, y_train)
 eli5.show_weights(perm, top=10 )
weighted_y_pred = pd.DataFrame()
weighted_y_pred['sig_id'] = predictions[0]['sig_id']
for column in target_columns:
column_data = []
for i in range(len(predictions)) :
column_data.append(predictions[i][column] * weights[i])
 weighted_y_pred[column] = np.sum(column_data, axis=0)
 weighted_y_pred.shape<prepare_output>
lass0.fit(X_train, y_train)
 sc = cross_val_score(lass0, X_train, y_train, scoring='roc_auc', cv=repfold, n_jobs=-1, verbose=1)
 print(sc.mean() )
y_pred = weighted_y_pred<save_to_csv>
perm = PermutationImportance(lass0, random_state=RANDOM_STATE ).fit(X_train, y_train)
 eli5.show_weights(perm, top=10 )
submission = pd.DataFrame(index = public_ids + private_ids, columns=target_columns)
 submission.index.name = 'sig_id'
submission[:] = 0
submission.loc[y_pred.sig_id,:] = y_pred[target_columns].values
submission.loc[test[test.cp_type == 'ctl_vehicle'].sig_id] = 0
submission.to_csv('submission.csv', index=True)
 submission.head().T<set_options>
param_lass = {
'alpha' : [0.022, 0.021, 0.02, 0.019, 0.023, 0.024, 0.025, 0.026, 0.027, 0.029, 0.031],
'tol' : [0.0013, 0.0014, 0.001, 0.0015, 0.0011, 0.0012, 0.0016, 0.0017]
}
warnings.filterwarnings('ignore')
 def seed_everything(seed=42):
random.seed(seed)
 os.environ['PYTHONHASHSEED'] = str(seed)
 np.random.seed(seed)
 torch.manual_seed(seed)
 torch.cuda.manual_seed(seed)
 torch.backends.cudnn.deterministic = True
class MoADataset:
def __init__(self, features, targets):
self.features = features
self.targets = targets
def __len__(self):
return(self.features.shape[0])
 def __getitem__(self, idx):
dct = {
'x' : torch.tensor(self.features[idx, :], dtype=torch.float),
'y' : torch.tensor(self.targets[idx, :], dtype=torch.float)
 }
return dct
class TestDataset:
def __init__(self, features):
self.features = features
def __len__(self):
return(self.features.shape[0])
 def __getitem__(self, idx):
dct = {
'x' : torch.tensor(self.features[idx, :], dtype=torch.float)
 }
return dct
def train_fn(model, optimizer, scheduler, loss_fn, dataloader, device):
model.train()
final_loss = 0
for data in dataloader:
optimizer.zero_grad()
inputs, targets = data['x'].to(device), data['y'].to(device)
 outputs = model(inputs)
 loss = loss_fn(outputs, targets)
 loss.backward()
optimizer.step()
scheduler.step()
final_loss += loss.item()
final_loss /= len(dataloader)
 return final_loss
def valid_fn(model, loss_fn, dataloader, device):
model.eval()
final_loss = 0
valid_preds = []
for data in dataloader:
inputs, targets = data['x'].to(device), data['y'].to(device)
 outputs = model(inputs)
 loss = loss_fn(outputs, targets)
 final_loss += loss.item()
valid_preds.append(outputs.sigmoid().detach().cpu().numpy())
 final_loss /= len(dataloader)
 valid_preds = np.concatenate(valid_preds)
 return final_loss, valid_preds
def inference_fn(model, dataloader, device):
model.eval()
preds = []
for data in dataloader:
inputs = data['x'].to(device)
 with torch.no_grad() :
outputs = model(inputs)
 preds.append(outputs.sigmoid().detach().cpu().numpy())
 preds = np.concatenate(preds)
 return preds
class Model(nn.Module):
def __init__(self, num_features, num_targets, hidden_size):
super(Model, self ).__init__()
self.batch_norm1 = nn.BatchNorm1d(num_features)
 self.dropout1 = nn.Dropout(0.2)
 self.dense1 = nn.utils.weight_norm(nn.Linear(num_features, hidden_size))
self.batch_norm2 = nn.BatchNorm1d(hidden_size)
 self.dropout2 = nn.Dropout(0.2)
 self.dense2 = nn.utils.weight_norm(nn.Linear(hidden_size, hidden_size))
self.batch_norm3 = nn.BatchNorm1d(hidden_size)
 self.dropout3 = nn.Dropout(0.25)
 self.dense3 = nn.utils.weight_norm(nn.Linear(hidden_size, num_targets))
def forward(self, x):
x = self.batch_norm1(x)
 x = self.dropout1(x)
 x = F.relu(self.dense1(x))
x = self.batch_norm2(x)
 x = self.dropout2(x)
 x = F.relu(self.dense2(x))
x = self.batch_norm3(x)
 x = self.dropout3(x)
 x = self.dense3(x)
 return x
def process_data(data):
data = pd.get_dummies(data, columns=['cp_time','cp_dose'])
 return data
seed_everything(seed=42 )<load_from_csv>
grid_lass = GridSearchCV(estimator = lass0, param_grid = param_lass , scoring = 'roc_auc', verbose = 1, n_jobs = -1, cv=repfold)
 grid_lass.fit(X_train,y_train)
 print("Best Score:" + str(grid_lass.best_score_))
print("Best Parameters: " + str(grid_lass.best_params_))
train_features = pd.read_csv('.. /input/lish-moa/train_features.csv')
 train_targets_scored = pd.read_csv('.. /input/lish-moa/train_targets_scored.csv')
 train_targets_nonscored = pd.read_csv('.. /input/lish-moa/train_targets_nonscored.csv')
 test_features = pd.read_csv('.. /input/lish-moa/test_features.csv')
 sample_submission = pd.read_csv('.. /input/lish-moa/sample_submission.csv' )<define_variables>
best_parameters_lass = grid_lass.best_params_
lass = Lasso(**best_parameters_lass)
 lass.fit(X_train,y_train)
 sc = cross_val_score(lass, X_train, y_train, scoring='roc_auc', cv=repfold, n_jobs=-1, verbose=1)
 print(sc.mean())
 selector_lass = RFECV(lass, min_features_to_select=12, scoring='roc_auc', step=15, verbose=0, cv=repfold, n_jobs=-1)
 selector_lass.fit(X_train,y_train)
GENES = [col for col in train_features.columns if col.startswith('g-')]
CELLS = [col for col in train_features.columns if col.startswith('c-')]<concatenate>
def acc_model(params):
clf = Lasso(**params)
 return cross_val_score(clf, X_train, y_train, scoring='roc_auc', cv=repfold ).mean()
n_comp = 29
data = pd.concat([pd.DataFrame(train_features[GENES]), pd.DataFrame(test_features[GENES])])
 data2 =(PCA(n_components=n_comp, random_state=42 ).fit_transform(data[GENES]))
train2 = data2[:train_features.shape[0]]; test2 = data2[-test_features.shape[0]:]
train2 = pd.DataFrame(train2, columns=[f'pca_G-{i}' for i in range(n_comp)])
 test2 = pd.DataFrame(test2, columns=[f'pca_G-{i}' for i in range(n_comp)])
 train_features = pd.concat(( train_features, train2), axis=1)
 test_features = pd.concat(( test_features, test2), axis=1)
 n_comp = 4
data = pd.concat([pd.DataFrame(train_features[CELLS]), pd.DataFrame(test_features[CELLS])])
 data2 =(PCA(n_components=n_comp, random_state=42 ).fit_transform(data[CELLS]))
train2 = data2[:train_features.shape[0]]; test2 = data2[-test_features.shape[0]:]
train2 = pd.DataFrame(train2, columns=[f'pca_C-{i}' for i in range(n_comp)])
 test2 = pd.DataFrame(test2, columns=[f'pca_C-{i}' for i in range(n_comp)])
 train_features = pd.concat(( train_features, train2), axis=1)
 test_features = pd.concat(( test_features, test2), axis=1 )<create_dataframe>
space4lass = {'alpha' : hp.uniform('alpha',.01, 1),
'tol' : hp.uniform('tol',.001, 0.1),
'random_state': RANDOM_STATE,
'max_iter': hp.choice('max_iter', [50000]),
}
best = 0
pr = []
def f(params):
global best
acc = acc_model(params)
 if acc > best:
best = acc
print('new best:', best, params)
 pr.append(params)
 return {'loss': -acc, 'status': STATUS_OK}
trials = Trials()
best = fmin(f, space4lass, algo=tpe.suggest, max_evals=3000, trials=trials)
 print('best for lasso: ')
 print(pr[-1] )
var_thresh = VarianceThreshold(threshold=0.7)
 data = train_features.append(test_features)
 data_transformed = var_thresh.fit_transform(data.iloc[:, 4:])
 train_features_transformed = data_transformed[ : train_features.shape[0]]
test_features_transformed = data_transformed[-test_features.shape[0] : ]
train_features = pd.DataFrame(train_features[['sig_id','cp_type','cp_time','cp_dose']].values.reshape(-1, 4),\
columns=['sig_id','cp_type','cp_time','cp_dose'])
 train_features = pd.concat([train_features, pd.DataFrame(train_features_transformed)], axis=1)
 test_features = pd.DataFrame(test_features[['sig_id','cp_type','cp_time','cp_dose']].values.reshape(-1, 4),\
columns=['sig_id','cp_type','cp_time','cp_dose'])
 test_features = pd.concat([test_features, pd.DataFrame(test_features_transformed)], axis=1)
 train_features<merge>
print(pr[-1])
 best_lass = pr[-1]
lass1 = Lasso(**best_lass)
 lass1.fit(X_train,y_train)
 sc = cross_val_score(lass1, X_train, y_train, scoring='roc_auc', cv=repfold, n_jobs=-1, verbose=1)
 print(sc.mean())
train = train_features.merge(train_targets_scored, on='sig_id')
 train = train[train['cp_type']!='ctl_vehicle'].reset_index(drop=True)
 test = test_features[test_features['cp_type']!='ctl_vehicle'].reset_index(drop=True)
 target = train[train_targets_scored.columns]
train = train.drop('cp_type', axis=1)
 test = test.drop('cp_type', axis=1)
<drop_column>
selector_lass1 = RFECV(lass1, min_features_to_select=12, scoring='roc_auc', step=15, verbose=0, cv=repfold, n_jobs=-1)
 selector_lass1.fit(X_train,y_train )
target_cols = target.drop('sig_id', axis=1 ).columns.values.tolist()<split>
perm = PermutationImportance(lass1, random_state=RANDOM_STATE ).fit(X_train, y_train)
 eli5.show_weights(perm, top=10 )
folds = train.copy()
mskf = MultilabelStratifiedKFold(n_splits=3)
 for f,(t_idx, v_idx)in enumerate(mskf.split(X=train, y=target)) :
folds.loc[v_idx, 'kfold'] = int(f)
 folds['kfold'] = folds['kfold'].astype(int )<define_variables>
def cross_validation(train_, target_, params,
num_folds = 5, repeats = 20, rs = 0):
print(params)
 clfs = []
folds = RepeatedStratifiedKFold(n_splits = num_folds, n_repeats = repeats, random_state = rs)
 valid_pred = pd.DataFrame(index = train_.index)
 for n_fold,(train_idx, valid_idx)in enumerate(folds.split(target_, target_)) :
print('--- Fold {} started at {}'.format(n_fold, time.ctime()))
train_x, train_y = train_.iloc[train_idx], target_.iloc[train_idx]
valid_x, valid_y = train_.iloc[valid_idx], target_.iloc[valid_idx]
clf = LogisticRegression(**params)
 clf.fit(train_x, train_y)
 clfs.append(clf)
 predict = clf.predict_proba(valid_x)[:, 1]
tn, fp, fn, tp = confusion_matrix(valid_y,(predict >=.5)* 1 ).ravel()
auc = roc_auc_score(valid_y, predict)
 acc = accuracy_score(valid_y,(predict >=.5)* 1)
 loss = log_loss(valid_y, predict)
 print('TN =', tn, 'FN =', fn, 'FP =', fp, 'TP =', tp)
 print('AUC = ', auc, 'Loss =', loss, 'Acc =', acc)
 valid_pred[n_fold] = pd.Series(predict, index = valid_x.index)
 del train_x, train_y, valid_x, valid_y, predict
gc.collect()
return clfs, valid_pred
def save_submit(test_, clfs_, filename):
subm = pd.DataFrame(np.zeros(test_.shape[0]), index = test_.index, columns = ['target'])
 for clf in clfs_:
subm['target'] += clf.predict_proba(test_)[:, 1]
subm['target'] /= len(clfs_)
 subm = subm.reset_index()
subm.columns = ['id', 'target']
subm.to_csv(filename, index = False)
feature_cols = [c for c in process_data(folds ).columns if c not in target_cols]
feature_cols = [c for c in feature_cols if c not in ['kfold','sig_id']]
len(feature_cols )<define_variables>
clfs, pred = cross_validation(pd.DataFrame(X_train), y_train, best_lr )
DEVICE =('cuda' if torch.cuda.is_available() else 'cpu')
 EPOCHS = 20
BATCH_SIZE = 64
LEARNING_RATE = 1e-3
WEIGHT_DECAY = 1e-5
NFOLDS = 3
EARLY_STOPPING_STEPS = 11
EARLY_STOP = True
num_features=len(feature_cols)
 num_targets=len(target_cols)
 hidden_size=1024<prepare_x_and_y>
sub_prp(logreg1, filename+'lr1.csv', X_test)
 sub_prp(selector_lr1, filename+'sel_lr1.csv', X_test )
<categorify><EOS> 
save_submit(pd.DataFrame(X_test, index=test.id), clfs, filename+'lr_cv_Anna.csv' )