Kaggle competition: Kannada MNIST
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})
 del df['sig_id']
return df
train = preprocess(train_features)
 test = preprocess(test_features)
 del train_targets['sig_id']<choose_model_class>
train_df=pd.read_csv(".. /input/Kannada-MNIST/train.csv")
 test_df=pd.read_csv(".. /input/Kannada-MNIST/test.csv")
 x_train=train_df.drop(["label"], axis=1 ).values.astype('float32')
 y_train=train_df["label"].values.astype("int32")
 x_test=test_df.drop(["id"],axis=1 ).values.astype('float32')
def create_model(num_columns):
model = tf.keras.Sequential([
tf.keras.layers.Input(num_columns),
tf.keras.layers.BatchNormalization() ,
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(2048, 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>
x_train,x_val,y_train,y_val=train_test_split(x_train, y_train, test_size=0.2 )
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))<train_model>
X=Input(shape=[28,28,1])
 x=Conv2D(16,(3,3), strides=1, padding="same", name="conv1" )(X)
 x=BatchNormalization(momentum=0.1, epsilon=1e-5, gamma_initializer="uniform", name="batch1" )(x)
 x=Activation('relu',name='relu1' )(x)
 x=Dropout(0.1 )(x)
 x=Conv2D(32,(3,3), strides=1, padding="same", name="conv2" )(x)
 x=BatchNormalization(momentum=0.15, epsilon=1e-5, gamma_initializer="uniform", name="batch2" )(x)
 x=Activation('relu',name='relu2' )(x)
 x=Dropout(0.15 )(x)
 x=MaxPooling2D(pool_size=2, strides=2, padding="same", name="max2" )(x)
 x=Conv2D(64,(5,5), strides=1, padding ="same", name="conv3" )(x)
 x=BatchNormalization(momentum=0.17, epsilon=1e-5, gamma_initializer="uniform", name="batch3" )(x)
 x=Activation('relu', name="relu3" )(x)
 x=MaxPooling2D(pool_size=2, strides=2, padding="same", name="max3" )(x)
 x=Conv2D(128,(5,5), strides=1, padding="same", name="conv4" )(x)
 x=BatchNormalization(momentum=0.15, epsilon=1e-5, gamma_initializer="uniform", name="batch4" )(x)
 x=Activation('relu', name="relu4" )(x)
 x=Dropout(0.17 )(x)
 x=Conv2D(64,(3,3), strides=1, padding="same", name="conv5" )(x)
 x=BatchNormalization(momentum=0.15, epsilon=1e-5, gamma_initializer="uniform", name="batch5" )(x)
 x=Activation('relu', name='relu5' )(x)
 x=Dropout(0.2 )(x)
 x=Conv2D(32,(3,3), strides=1, padding="same", name="conv6" )(x)
 x=BatchNormalization(momentum=0.15, epsilon=1e-5, gamma_initializer="uniform", name="batch6" )(x)
 x=Activation('relu', name="relu6" )(x)
 x=Dropout(0.05 )(x)
 x=Flatten()(x)
 x=Dense(50, name="Dense1" )(x)
 x=Activation('relu', name='relu7' )(x)
 x=Dropout(0.05 )(x)
 x=Dense(25, name="Dense2" )(x)
 x=Activation('relu', name='relu8' )(x)
 x=Dropout(0.03 )(x)
 x=Dense(10, name="Dense3" )(x)
 x=Activation('softmax' )(x)
 model=Model(inputs=X, outputs=x)
N_STARTS = 3
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(KFold(n_splits=7, random_state=seed, shuffle=True ).split(train_targets)) :
print(f'Fold {n}')
 model = create_model(len(top_feats))
reduce_lr_loss = ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=3, verbose=1, epsilon=1e-4, mode='min')
 model.fit(train.values[tr][:, top_feats],
train_targets.astype(float ).values[tr],
validation_data=(train.values[te][:, top_feats], train_targets.astype(float ).values[te]),
epochs=30, batch_size=128,
callbacks=[reduce_lr_loss], verbose=2 
)
 ss.loc[:, train_targets.columns] += model.predict(test_features.values[:, top_feats])
 res.loc[te, train_targets.columns] += model.predict(train.values[te][:, top_feats])
 print('')
 ss.loc[:, train_targets.columns] /=(( n+1)* N_STARTS)
 res.loc[:, train_targets.columns] /= N_STARTS<compute_test_metric>
checkpoint=ModelCheckpoint('bestweights.hdf5', monitor='val_acc', verbose=1, save_best_only=True, mode="max")
 epochs=80
lr=0.002
optimizer=Adam(lr=lr, decay=lr/(epochs*1.5))
model.compile(optimizer=optimizer, loss="sparse_categorical_crossentropy",metrics=["accuracy"])
 datagenerator=ImageDataGenerator(rotation_range=9, zoom_range=0.25, width_shift_range=0.25, height_shift_range=0.25)
 datagenerator.fit(x_train)
 batch_size=64
history=model.fit_generator(datagenerator.flow(x_train, y_train, batch_size=batch_size), epochs=epochs, validation_data=(x_val, y_val), verbose=2,steps_per_epoch=x_train.shape[0]//batch_size, callbacks=[checkpoint])
 model.load_weights("bestweights.hdf5" )
metrics = []
for _target in train_targets.columns:
metrics.append(log_loss(train_targets.loc[:, _target], res.loc[:, _target]))
print(f'OOF Metric: {np.mean(metrics)}' )<compute_train_metric>
results=model.predict(x_test )
metrics = []
res.loc[train['cp_type']==1, train_targets.columns] = 0
for _target in train_targets.columns:
metrics.append(log_loss(train_targets.loc[:, _target], res.loc[:, _target]))
print(f'OOF Metric with postprocessing: {np.mean(metrics)}' )<feature_engineering>
results=np.argmax(results, axis=1 )
ss.loc[test['cp_type']==1, train_targets.columns] = 0<save_to_csv>
dg=pd.DataFrame()
dg['id']=list(test_df.values[0:,0] )
ss.to_csv('submission.csv', index=False )<set_options>
dg['label']=results
!pip install --no-index --find-links /kaggle/input/pytorchtabnet/pytorch_tabnet-2.0.0-py3-none-any.whl pytorch-tabnet
!pip install /kaggle/input/iterative-stratification/iterative-stratification-master/
warnings.filterwarnings("ignore")
 os.environ["CUDA_LAUNCH_BLOCKING"] = '1'
plt.style.use("fivethirtyeight")
 c_ = Fore.CYAN
m_ = Fore.MAGENTA
r_ = Fore.RED
b_ = Fore.BLUE
y_ = Fore.YELLOW
g_ = Fore.GREEN 
<set_options>
dg.to_csv("submission.csv", index=False )