Kaggle competition: Digit Recognizer
def binary_focal_loss(gamma=2, alpha=0.25):

 alpha = tf.constant(alpha, dtype=tf.float32)
 gamma = tf.constant(gamma, dtype=tf.float32)
 def binary_focal_loss_fixed(y_true, y_pred):

 y_true = tf.cast(y_true, tf.float32)
 alpha_t = y_true*alpha +(K.ones_like(y_true)-y_true)*(1-alpha)
 p_t = y_true*y_pred +(K.ones_like(y_true)-y_true)*(K.ones_like(y_true)-y_pred)+ K.epsilon()
focal_loss = - alpha_t * K.pow(( K.ones_like(y_true)-p_t),gamma)* K.log(p_t)
 return K.mean(focal_loss)
 return binary_focal_loss_fixed<define_variables>
train = pd.read_csv('/kaggle/input/digit-recognizer/train.csv')
 images_train, images_val = train_test_split(train, test_size=0.3)
 label_train = images_train['label']
label_val = images_val['label']
images_train = images_train.drop(['label'],axis = 1)
 images_val = images_val.drop(['label'],axis = 1)
 label_train = pd.DataFrame(label_train)
 label_val = pd.DataFrame(label_val)
 enc = OneHotEncoder()
enc.fit(label_train)
 enc.fit(label_val)
 label_train = enc.transform(label_train ).toarray()
label_val = enc.transform(label_val ).toarray()
images_train =(images_train.values ).astype('float32')
 images_val =(images_val.values ).astype('float32')
 images_train = images_train.reshape(images_train.shape[0], 28, 28, 1)
 images_val = images_val.reshape(images_val.shape[0], 28, 28, 1 )
NUC_MODEL = '/kaggle/input/hpacellsegmentatormodelweights/dpn_unet_nuclei_v1.pth'
CELL_MODEL = '/kaggle/input/hpacellsegmentatormodelweights/dpn_unet_cell_3ch_v1.pth'
B2_CELL_CLSFR_DIR = "/kaggle/input/hpa-models/HPA - Cellwise Classification TRAINING/ebnet_b2_wdensehead/ckpt-0007-0.0901.ckpt"
DATA_DIR = "/kaggle/input/hpa-single-cell-image-classification"
TEST_IMG_DIR = os.path.join(DATA_DIR, "test")
 TEST_IMG_PATHS = sorted([os.path.join(TEST_IMG_DIR, f_name)for f_name in os.listdir(TEST_IMG_DIR)])
 print(f"...The number of testing images is {len(TEST_IMG_PATHS)}" \
f"
\t--> i.e.{len(TEST_IMG_PATHS)//4} 4-channel images...")
 PUB_SS_CSV = "/kaggle/input/hpa-sample-submission-with-extra-metadata/updated_sample_submission.csv"
SWAP_SS_CSV = os.path.join(DATA_DIR, "sample_submission.csv")
 ss_df = pd.read_csv(SWAP_SS_CSV)
 DO_TTA = True
TTA_REPEATS = 8
IS_DEMO = len(ss_df)==559
if IS_DEMO:
ss_df_1 = ss_df.drop_duplicates("ImageWidth", keep="first")
 ss_df_2 = ss_df.drop_duplicates("ImageWidth", keep="last")
 ss_df = pd.concat([ss_df_1, ss_df_2])
 del ss_df_1; del ss_df_2; gc.collect() ;
print("
SAMPLE SUBMISSION DATAFRAME
")
 display(ss_df)
 else:
print("
SAMPLE SUBMISSION DATAFRAME
")
 display(ss_df)
 if ONLY_PUBLIC:
pub_ss_df = pd.read_csv(PUB_SS_CSV)
 if IS_DEMO:
pub_ss_df_1 = pub_ss_df.drop_duplicates("ImageWidth", keep="first")
 pub_ss_df_2 = pub_ss_df.drop_duplicates("ImageWidth", keep="last")
 pub_ss_df = pd.concat([pub_ss_df_1, pub_ss_df_2])
 pub_ss_df.mask_rles = pub_ss_df.mask_rles.apply(lambda x: ast.literal_eval(x))
pub_ss_df.mask_bboxes = pub_ss_df.mask_bboxes.apply(lambda x: ast.literal_eval(x))
pub_ss_df.mask_sub_rles = pub_ss_df.mask_sub_rles.apply(lambda x: ast.literal_eval(x))
print("
TEST DATAFRAME W/ MASKS
")
 display(pub_ss_df )<categorify>
model2 = models.Sequential()
model2.add(layers.Conv2D(filters = 128, kernel_size=(5, 5), activation='relu', padding='same', input_shape =(28, 28, 1)))
 model2.add(layers.BatchNormalization())
 model2.add(layers.Conv2D(filters = 64, kernel_size=(5, 5), activation='relu', padding='same', input_shape =(28, 28, 1)))
 model2.add(layers.BatchNormalization())
 model2.add(layers.MaxPooling2D(pool_size=(2, 2)))
 model2.add(layers.Dropout(0.25))
model2.add(layers.Conv2D(64, kernel_size=(3, 3), padding='same', activation='relu'))
model2.add(layers.BatchNormalization())
 model2.add(layers.Conv2D(64, kernel_size=(3, 3), padding='same', activation='relu'))
model2.add(layers.BatchNormalization())
 model2.add(layers.MaxPooling2D(pool_size=(2, 2), strides=(2,2)))
 model2.add(layers.Dropout(0.25))
model2.add(layers.Conv2D(64, kernel_size=(3, 3), padding='same', activation='relu'))
model2.add(layers.BatchNormalization())
 model2.add(layers.Dropout(0.25))
model2.add(layers.Flatten())
 model2.add(layers.Dense(256, activation='relu'))
model2.add(layers.BatchNormalization())
 model2.add(layers.Dropout(0.25))
model2.add(layers.Dense(10, activation='softmax'))
model2.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics='accuracy')
 learning_rate_reduction = ReduceLROnPlateau(monitor='val_accuracy',
patience=3,
verbose=1,
factor=0.5,
min_lr=0.00001)
 datagen = ImageDataGenerator(
 featurewise_center=False,
samplewise_center=False,
featurewise_std_normalization=False,
samplewise_std_normalization=False,
zca_whitening=False,
rotation_range=20,
zoom_range = 0.10,
width_shift_range=0.1,
height_shift_range=0.1,
horizontal_flip=False,
vertical_flip=False)
 datagen.fit(images_train)
 estimator = model2.fit(datagen.flow(images_train,label_train, batch_size = 128),
epochs = 50, validation_data =(images_val, label_val),
steps_per_epoch=230
,callbacks=[learning_rate_reduction])
<define_variables><EOS> 
images_test = pd.read_csv('/kaggle/input/digit-recognizer/test.csv')
 images_test =(images_test.values ).astype('float32')
 images_test = images_test.reshape(images_test.shape[0], 28, 28, 1)
 y_pred = model2.predict(images_test)
 y_pred = pd.DataFrame(y_pred)
 y_pred = pd.Series(y_pred.idxmax(axis=1),index=y_pred.index)
 y_pred = pd.DataFrame({"ImageId": list(range(1,len(y_pred)+1)) ,
"Label": y_pred})
 y_pred.to_csv("submission_model2.csv", index=False, header=True )