Kaggle competition: Allstate Claims Severity
<SOS> metric: MAE Kaggle data source: allstate-claims-severity<predict_on_test>
warnings.filterwarnings('ignore')
 dataset = pandas.read_csv(".. /input/train.csv")
 dataset_test = pandas.read_csv(".. /input/test.csv")
 ID = dataset_test['id']
dataset_test.drop('id',axis=1,inplace=True)
 pandas.set_option('display.max_rows', None)
 pandas.set_option('display.max_columns', None)
 print(dataset.head(5))
if VALIDATION:
images, labels = next(batch)
 probabilities =(model1.predict(images)+model2.predict(images)) /2
predictions = np.argmax(probabilities, axis=-1)
 display_batch_of_images(( images, labels), predictions )<install_modules>
dataset = dataset.iloc[:,1:]
!pip install efficientnet tensorflow_addons==0.9.1 tensorflow==2.1.0<import_modules>
def categories(series):
return range(int(series.min()), int(series.max())+ 1)
 def chi_square_of_df_cols(df, col1, col2):
df_col1, df_col2 = df[col1], df[col2]
le1 = LE()
df_col1 = le1.fit_transform(df_col1)
 df_col2 = le1.fit_transform(df_col2)
 result = [[sum(( df_col1 == cat1)&(df_col2 == cat2))
for cat2 in categories(df_col2)]
for cat1 in categories(df_col1)]
return scs.chi2_contingency(result)
import math
import re
import random
import os
import tensorflow as tf
import tensorflow_addons as tfa
import numpy as np
import tensorflow.keras.backend as K
import efficientnet.tfkeras as efn
from matplotlib import pyplot as plt
from datetime import datetime<define_variables>
print(f'Numpy version : {np.__version__}')
 print(f'Tensorflow version {tf.__version__}')
 AUTO = tf.data.experimental.AUTOTUNE
START_TIME = datetime.now()
SEED = 42
os.environ['PYTHONHASHSEED']=str(SEED)
 random.seed(SEED)
 np.random.seed(SEED)
 tf.random.set_seed(SEED )<set_options>
y = dataset.loss
dataset.drop(["loss"], axis=1, inplace=True )
try:
tpu = tf.distribute.cluster_resolver.TPUClusterResolver()
print('Running on TPU ', tpu.master())
 except ValueError:
tpu = None
if tpu:
tf.config.experimental_connect_to_cluster(tpu)
 tf.tpu.experimental.initialize_tpu_system(tpu)
 strategy = tf.distribute.experimental.TPUStrategy(tpu)
 else:
strategy = tf.distribute.get_strategy()
print("REPLICAS: ", strategy.num_replicas_in_sync )<define_variables>
shapeTrain = dataset.shape
GCS_DS_PATH = KaggleDatasets().get_gcs_path()
GCS_DS_PATH<define_variables>
data = dataset.append(dataset_test )
IMAGE_SIZE = [512, 512]
VALIDATE_WARMUP = False
EPOCHS_WARMUP = 3
DO_AUG_WARMUP = False
VALIDATE = False
EPOCHS = 30
DO_AUG = True
BATCH_SIZE = 16 * strategy.num_replicas_in_sync
GCS_PATH_SELECT = {
192: GCS_DS_PATH + '/tfrecords-jpeg-192x192',
224: GCS_DS_PATH + '/tfrecords-jpeg-224x224',
331: GCS_DS_PATH + '/tfrecords-jpeg-331x331',
512: GCS_DS_PATH + '/tfrecords-jpeg-512x512'
}
GCS_PATH = GCS_PATH_SELECT[IMAGE_SIZE[0]]
TRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/train/*.tfrec')
 VALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec')
 TEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec')
 CLASSES = ['pink primrose', 'hard-leaved pocket orchid', 'canterbury bells', 'sweet pea', 'wild geranium', 'tiger lily', 'moon orchid', 'bird of paradise', 'monkshood', 'globe thistle',
'snapdragon', "colt's foot", 'king protea', 'spear thistle', 'yellow iris', 'globe-flower', 'purple coneflower', 'peruvian lily', 'balloon flower', 'giant white arum lily',
'fire lily', 'pincushion flower', 'fritillary', 'red ginger', 'grape hyacinth', 'corn poppy', 'prince of wales feathers', 'stemless gentian', 'artichoke', 'sweet william',
'carnation', 'garden phlox', 'love in the mist', 'cosmos', 'alpine sea holly', 'ruby-lipped cattleya', 'cape flower', 'great masterwort', 'siam tulip', 'lenten rose',
'barberton daisy', 'daffodil', 'sword lily', 'poinsettia', 'bolero deep blue', 'wallflower', 'marigold', 'buttercup', 'daisy', 'common dandelion',
'petunia', 'wild pansy', 'primula', 'sunflower', 'lilac hibiscus', 'bishop of llandaff', 'gaura', 'geranium', 'orange dahlia', 'pink-yellow dahlia',
'cautleya spicata', 'japanese anemone', 'black-eyed susan', 'silverbush', 'californian poppy', 'osteospermum', 'spring crocus', 'iris', 'windflower', 'tree poppy',
'gazania', 'azalea', 'water lily', 'rose', 'thorn apple', 'morning glory', 'passion flower', 'lotus', 'toad lily', 'anthurium',
'frangipani', 'clematis', 'hibiscus', 'columbine', 'desert-rose', 'tree mallow', 'magnolia', 'cyclamen ', 'watercress', 'canna lily',
'hippeastrum ', 'bee balm', 'pink quill', 'foxglove', 'bougainvillea', 'camellia', 'mallow', 'mexican petunia', 'bromelia', 'blanket flower',
'trumpet creeper', 'blackberry lily', 'common tulip', 'wild rose']<categorify>
catCols = data.columns[:116]
WasteCat = []
for col in catCols:
if data[col].value_counts() [0] > 310000:
print(col)
 WasteCat.append(col)
 print(len(WasteCat))
def decode_image(image_data):
image = tf.image.decode_jpeg(image_data, channels=3)
 image = tf.cast(image, tf.float32)/ 255.0
image = tf.reshape(image, [*IMAGE_SIZE, 3])
 return image
def read_labeled_tfrecord(example):
LABELED_TFREC_FORMAT = {
"image": tf.io.FixedLenFeature([], tf.string),
"class": tf.io.FixedLenFeature([], tf.int64),
}
example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)
 image = decode_image(example['image'])
 label = tf.cast(example['class'], tf.int32)
 return image, label
def read_unlabeled_tfrecord(example):
UNLABELED_TFREC_FORMAT = {
"image": tf.io.FixedLenFeature([], tf.string),
"id": tf.io.FixedLenFeature([], tf.string),
}
example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT)
 image = decode_image(example['image'])
 idnum = example['id']
return image, idnum
def load_dataset(filenames, labeled=True, ordered=False):
ignore_order = tf.data.Options()
if not ordered:
ignore_order.experimental_deterministic = False
dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO)
 dataset = dataset.with_options(ignore_order)
 dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls=AUTO)
 return dataset
def get_train_val_dataset(do_aug=True):
dataset = load_dataset(TRAINING_FILENAMES + VALIDATION_FILENAMES, labeled=True)
 if do_aug:
dataset = dataset.map(image_augmentation, num_parallel_calls=AUTO)
 dataset = dataset.repeat()
dataset = dataset.shuffle(2048)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.prefetch(AUTO)
 return dataset
def get_training_dataset(do_aug=True):
dataset = load_dataset(TRAINING_FILENAMES, labeled=True)
 if do_aug:
dataset = dataset.map(image_augmentation, num_parallel_calls=AUTO)
 dataset = dataset.repeat()
dataset = dataset.shuffle(2048)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.prefetch(AUTO)
 return dataset
def get_validation_dataset(ordered=False):
dataset = load_dataset(VALIDATION_FILENAMES, labeled=True, ordered=ordered)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.cache()
dataset = dataset.prefetch(AUTO)
 return dataset
def get_test_dataset(ordered=False):
dataset = load_dataset(TEST_FILENAMES, labeled=False, ordered=ordered)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.prefetch(AUTO)
 return dataset
def count_data_items(filenames):
n = [int(re.compile(r"-([0-9]*)\." ).search(filename ).group(1)) for filename in filenames]
return np.sum(n)
 NUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)
 NUM_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES)
 NUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)
 STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE
print(f'Total training image: {NUM_TRAINING_IMAGES}')
 print(f'Total validation image: {NUM_VALIDATION_IMAGES}')
 print(f'Total test image: {NUM_TEST_IMAGES}')
 print(f'Steps per epoch : {STEPS_PER_EPOCH}' )<normalization>
data.drop(WasteCat,axis=1,inplace=True)
 data.drop(["cont1","cont11"], axis=1, inplace=True )
def get_mat(rotation, shear, height_zoom, width_zoom, height_shift, width_shift):
rotation = math.pi * rotation / 180.
 shear = math.pi * shear / 180.
 c1 = tf.math.cos(rotation)
 s1 = tf.math.sin(rotation)
 one = tf.constant([1],dtype='float32')
 zero = tf.constant([0],dtype='float32')
 rotation_matrix = tf.reshape(tf.concat([c1,s1,zero, -s1,c1,zero, zero,zero,one],axis=0),[3,3])
 c2 = tf.math.cos(shear)
 s2 = tf.math.sin(shear)
 shear_matrix = tf.reshape(tf.concat([one,s2,zero, zero,c2,zero, zero,zero,one],axis=0),[3,3])
 zoom_matrix = tf.reshape(tf.concat([one/height_zoom,zero,zero, zero,one/width_zoom,zero, zero,zero,one],axis=0),[3,3])
 shift_matrix = tf.reshape(tf.concat([one,zero,height_shift, zero,one,width_shift, zero,zero,one],axis=0),[3,3])
 return K.dot(K.dot(rotation_matrix, shear_matrix), K.dot(zoom_matrix, shift_matrix))
def transform(image):
DIM = IMAGE_SIZE[0]
XDIM = DIM%2
if np.random.randint(0, 2)== 0:
rot = 17.* tf.random.normal([1],dtype='float32')
 else:
rot = tf.constant([0],dtype='float32')
 if np.random.randint(0, 2)== 0:
shr = 5.5 * tf.random.normal([1],dtype='float32')
 else:
shr = tf.constant([0],dtype='float32')
 if np.random.randint(0, 3)== 0:
h_zoom = tf.random.normal([1],dtype='float32')/8.5
if h_zoom > 0:
h_zoom = 1.0 + h_zoom * -1
else:
h_zoom = 1.0 + h_zoom
else:
h_zoom = tf.constant([1],dtype='float32')
 if np.random.randint(0, 3)== 0:
w_zoom = tf.random.normal([1],dtype='float32')/8.5
if w_zoom > 0:
w_zoom = 1.0 + w_zoom * -1
else:
w_zoom = 1.0 + w_zoom
else:
w_zoom = tf.constant([1],dtype='float32')
 if np.random.randint(0, 3)== 0:
h_shift = 18.* tf.random.normal([1],dtype='float32')
 else:
h_shift = tf.constant([0],dtype='float32')
 if np.random.randint(0, 3)== 0:
w_shift = 18.* tf.random.normal([1],dtype='float32')
 else:
w_shift = tf.constant([0],dtype='float32')
 m = get_mat(rot,shr,h_zoom,w_zoom,h_shift,w_shift)
 x = tf.repeat(tf.range(DIM//2,-DIM//2,-1), DIM)
 y = tf.tile(tf.range(-DIM//2,DIM//2),[DIM])
 z = tf.ones([DIM*DIM],dtype='int32')
 idx = tf.stack([x,y,z])
 idx2 = K.dot(m,tf.cast(idx,dtype='float32'))
idx2 = K.cast(idx2,dtype='int32')
 idx2 = K.clip(idx2,-DIM//2+XDIM+1,DIM//2)
 idx3 = tf.stack([DIM//2-idx2[0,], DIM//2-1+idx2[1,]])
 d = tf.gather_nd(image,tf.transpose(idx3))
return tf.reshape(d,[DIM,DIM,3] )<prepare_x_and_y>
catCols = data.columns[:84]
for col in catCols:
print(col)
 data[col] = LE().fit_transform(data[col] )
def transform_grid_mark(image, inv_mat, image_shape):
h, w, c = image_shape
cx, cy = w//2, h//2
new_xs = tf.repeat(tf.range(-cx, cx, 1), h)
 new_ys = tf.tile(tf.range(-cy, cy, 1), [w])
 new_zs = tf.ones([h*w], dtype=tf.int32)
 old_coords = tf.matmul(inv_mat, tf.cast(tf.stack([new_xs, new_ys, new_zs]), tf.float32))
old_coords_x, old_coords_y = tf.round(old_coords[0, :] + w//2), tf.round(old_coords[1, :] + h//2)
 clip_mask_x = tf.logical_or(old_coords_x<0, old_coords_x>w-1)
 clip_mask_y = tf.logical_or(old_coords_y<0, old_coords_y>h-1)
 clip_mask = tf.logical_or(clip_mask_x, clip_mask_y)
 old_coords_x = tf.boolean_mask(old_coords_x, tf.logical_not(clip_mask))
old_coords_y = tf.boolean_mask(old_coords_y, tf.logical_not(clip_mask))
new_coords_x = tf.boolean_mask(new_xs+cx, tf.logical_not(clip_mask))
new_coords_y = tf.boolean_mask(new_ys+cy, tf.logical_not(clip_mask))
old_coords = tf.cast(tf.stack([old_coords_y, old_coords_x]), tf.int32)
 new_coords = tf.cast(tf.stack([new_coords_y, new_coords_x]), tf.int64)
 rotated_image_values = tf.gather_nd(image, tf.transpose(old_coords))
rotated_image_channel = list()
for i in range(c):
vals = rotated_image_values[:,i]
sparse_channel = tf.SparseTensor(tf.transpose(new_coords), vals, [h, w])
 rotated_image_channel.append(tf.sparse.to_dense(sparse_channel, default_value=0, validate_indices=False))
return tf.transpose(tf.stack(rotated_image_channel), [1,2,0])
 def random_rotate(image, angle, image_shape):
def get_rotation_mat_inv(angle):
angle = math.pi * angle / 180
cos_val = tf.math.cos(angle)
 sin_val = tf.math.sin(angle)
 one = tf.constant([1], tf.float32)
 zero = tf.constant([0], tf.float32)
 rot_mat_inv = tf.concat([cos_val, sin_val, zero,
-sin_val, cos_val, zero,
zero, zero, one], axis=0)
 rot_mat_inv = tf.reshape(rot_mat_inv, [3,3])
 return rot_mat_inv
angle = float(angle)* tf.random.normal([1],dtype='float32')
 rot_mat_inv = get_rotation_mat_inv(angle)
 return transform_grid_mark(image, rot_mat_inv, image_shape)
 def GridMask() :
h, w = IMAGE_SIZE[0], IMAGE_SIZE[1]
image_height, image_width =(h, w)
 d1 = 100
d2 = 160
rotate_angle = 45
ratio = 0.5
hh = int(np.ceil(np.sqrt(h*h+w*w)))
 hh = hh+1 if hh%2==1 else hh
d = tf.random.uniform(shape=[], minval=d1, maxval=d2, dtype=tf.int32)
 l = tf.cast(tf.cast(d,tf.float32)*ratio+0.5, tf.int32)
 st_h = tf.random.uniform(shape=[], minval=0, maxval=d, dtype=tf.int32)
 st_w = tf.random.uniform(shape=[], minval=0, maxval=d, dtype=tf.int32)
 y_ranges = tf.range(-1 * d + st_h, -1 * d + st_h + l)
 x_ranges = tf.range(-1 * d + st_w, -1 * d + st_w + l)
 for i in range(0, hh//d+1):
s1 = i * d + st_h
s2 = i * d + st_w
y_ranges = tf.concat([y_ranges, tf.range(s1,s1+l)], axis=0)
 x_ranges = tf.concat([x_ranges, tf.range(s2,s2+l)], axis=0)
 x_clip_mask = tf.logical_or(x_ranges <0 , x_ranges > hh-1)
 y_clip_mask = tf.logical_or(y_ranges <0 , y_ranges > hh-1)
 clip_mask = tf.logical_or(x_clip_mask, y_clip_mask)
 x_ranges = tf.boolean_mask(x_ranges, tf.logical_not(clip_mask))
y_ranges = tf.boolean_mask(y_ranges, tf.logical_not(clip_mask))
hh_ranges = tf.tile(tf.range(0,hh), [tf.cast(tf.reduce_sum(tf.ones_like(x_ranges)) , tf.int32)])
 x_ranges = tf.repeat(x_ranges, hh)
 y_ranges = tf.repeat(y_ranges, hh)
 y_hh_indices = tf.transpose(tf.stack([y_ranges, hh_ranges]))
x_hh_indices = tf.transpose(tf.stack([hh_ranges, x_ranges]))
y_mask_sparse = tf.SparseTensor(tf.cast(y_hh_indices, tf.int64), tf.zeros_like(y_ranges), [hh, hh])
 y_mask = tf.sparse.to_dense(y_mask_sparse, 1, False)
 x_mask_sparse = tf.SparseTensor(tf.cast(x_hh_indices, tf.int64), tf.zeros_like(x_ranges), [hh, hh])
 x_mask = tf.sparse.to_dense(x_mask_sparse, 1, False)
 mask = tf.expand_dims(tf.clip_by_value(x_mask + y_mask, 0, 1), axis=-1)
 mask = random_rotate(mask, rotate_angle, [hh, hh, 1])
 mask = tf.image.crop_to_bounding_box(mask,(hh-h)//2,(hh-w)//2, image_height, image_width)
 return mask
def apply_grid_mask(image):
mask = GridMask()
mask = tf.concat([mask, mask, mask], axis=-1)
 return image * tf.cast(mask, 'float32' )<statistical_test>
y = np.log1p(y )
def image_augmentation(image, label):
image = tf.image.random_flip_left_right(image)
 if np.random.randint(0, 2)== 0:
image = tf.image.random_brightness(image, 0.1)
 if np.random.randint(0, 2)== 0:
image = tf.image.random_contrast(image, 0.9, 1.1)
 if np.random.randint(0, 2)== 0:
image = tf.image.random_saturation(image, 0.9, 1.1)
 if np.random.randint(0, 2)== 0:
image = tf.image.random_hue(image, 0.05)
 image = transform(image)
 if np.random.randint(0, 2)== 0:
image = apply_grid_mask(image)
 return image, label<import_modules>
Xtrain = data.iloc[:shapeTrain[0],:]
from tensorflow.keras.models import Model, Sequential
from tensorflow.keras.layers import Input, Flatten, Dense, Dropout, AveragePooling2D, GlobalAveragePooling2D, SpatialDropout2D<choose_model_class>
model = RFG(n_estimators=40,n_jobs=4)
 model2 = GBR(n_estimators=120 )
es_val_acc = tf.keras.callbacks.EarlyStopping(
 monitor='val_sparse_categorical_accuracy', min_delta=0.001, patience=5, verbose=1, mode='auto',
baseline=None, restore_best_weights=True 
)
 es_val_loss = tf.keras.callbacks.EarlyStopping(
 monitor='val_loss', min_delta=0.001, patience=5, verbose=1, mode='auto',
baseline=None, restore_best_weights=True 
)
 es_acc = tf.keras.callbacks.EarlyStopping(
 monitor='sparse_categorical_accuracy', min_delta=0.001, patience=5, verbose=1, mode='auto',
baseline=None, restore_best_weights=False 
)
 es_loss = tf.keras.callbacks.EarlyStopping(
 monitor='loss', min_delta=0.001, patience=5, verbose=1, mode='auto',
baseline=None, restore_best_weights=False
)<choose_model_class>
X_train,X_test,y_train,y_test = tts(Xtrain,y,test_size=0.0,random_state = 1 )
with strategy.scope() :
efn7 = efn.EfficientNetB7(weights='noisy-student', include_top=False, input_shape=(IMAGE_SIZE[0], IMAGE_SIZE[1], 3))
for layer in efn7.layers[:745]:
layer.trainable = False
for layer in efn7.layers[745:]:
layer.trainable = True
model = Sequential([
efn7,
GlobalAveragePooling2D() ,
Dense(len(CLASSES), activation='softmax')
 ], name='b7-flower')
 densenet201 = DenseNet201(weights='imagenet', include_top=False, input_shape=(IMAGE_SIZE[0], IMAGE_SIZE[1], 3))
model.compile(optimizer=tfa.optimizers.LAMB() , loss='sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy'])
 model.summary()<choose_model_class>
model2.fit(X_train,y_train)
 print("Gradient Fitted")
 model.fit(X_train,y_train)
 print("Random Fitted" )
with strategy.scope() :
densenet201 = tf.keras.applications.densenet.DenseNet201(weights='imagenet', include_top=False, input_shape=(IMAGE_SIZE[0], IMAGE_SIZE[1], 3))
for layer in densenet201.layers[:481]:
layer.trainable = False
for layer in densenet201.layers[481:]:
layer.trainable = True
model2 = Sequential([
densenet201,
GlobalAveragePooling2D() ,
Dense(len(CLASSES), activation='softmax')
 ], name='dn201-flower')
 model2.compile(optimizer=tfa.optimizers.LAMB() , loss='sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy'])
 model2.summary()<choose_model_class>
Xtest = data.iloc[shapeTrain[0]:,:]
def lrfn(epoch):
initial_lr = 0.0001
current_lr = initial_lr + 0.00015 * epoch
return current_lr
lr_schedule = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose = True)
 plt_lr(EPOCHS_WARMUP )<train_model>
if VALIDATE_WARMUP:
model.fit(
 get_training_dataset(do_aug=DO_AUG_WARMUP), steps_per_epoch=STEPS_PER_EPOCH, epochs=EPOCHS_WARMUP,
validation_data=get_validation_dataset() , callbacks=[lr_schedule], verbose=1 
)
 else:
model.fit(
 get_train_val_dataset(do_aug=DO_AUG_WARMUP), steps_per_epoch=STEPS_PER_EPOCH, epochs=EPOCHS_WARMUP,
callbacks=[lr_schedule], verbose=1
)<compute_test_metric>
X_train,X_test,y_train,y_test = tts(Xtrain,y,test_size=0.0,random_state=1)
 model3 = XGBR(n_estimators=1000,nthread=4)
 model3.fit(X_train,y_train )
h = model.history
plt_acc(h)
 plt_loss(h )<train_model>
if VALIDATE_WARMUP:
model2.fit(
 get_training_dataset(do_aug=DO_AUG_WARMUP), steps_per_epoch=STEPS_PER_EPOCH, epochs=EPOCHS_WARMUP,
validation_data=get_validation_dataset() , callbacks=[lr_schedule], verbose=1 
)
 else:
model2.fit(
 get_train_val_dataset(do_aug=DO_AUG_WARMUP), steps_per_epoch=STEPS_PER_EPOCH, epochs=EPOCHS_WARMUP,
callbacks=[lr_schedule], verbose=1
)<init_hyperparams>
predAns = model3.predict(Xtest )
LR_START = 0.0006
LR_MAX = 0.003
LR_MIN = 0.0003
LR_RAMPUP_EPOCHS = 4
LR_SUSTAIN_EPOCHS = 0
LR_EXP_DECAY = 0.91
def lrfn(epoch):
if epoch < LR_RAMPUP_EPOCHS:
lr =(LR_MAX - LR_START)/ LR_RAMPUP_EPOCHS * epoch + LR_START
elif epoch < LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS:
lr = LR_MAX
else:
lr =(LR_MAX - LR_MIN)* LR_EXP_DECAY**(epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS)+ LR_MIN
return lr
lr_schedule = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose = True)
 plt_lr(EPOCHS )<choose_model_class>
predAns = np.expm1(predAns )
for layer in model.layers:
layer.trainable = True
model.compile(optimizer=tfa.optimizers.LAMB() , loss='sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy'])
 model.summary()<train_model>
output = pandas.DataFrame({"id":ID,"loss":predAns} )
<compute_test_metric><EOS> 
output.to_csv("output.csv",index=False )