Kaggle competition: Bengali.AI Handwritten Grapheme Classification
<SOS> metric: WeightedCategorizationAccuracy Kaggle data source: bengali.ai-handwritten-grapheme-classification<predict_on_test>
!pip install '.. /input/kerasefficientnetb3/efficientnet-1.0.0-py3-none-any.whl'
test_ds = get_test_dataset(ordered=True)
 print('Computing predictions...')
 test_images_ds = test_ds.map(lambda image, idnum: image)
 probabilities1 = model1.predict(test_images_ds)
 probabilities2 = model2.predict(test_images_ds)
 probabilities3 = model3.predict(test_images_ds)
 probabilities4 = model4.predict(test_images_ds)
 probabilities =(probabilities1 + probabilities2 + probabilities3 + probabilities4)/ 4
predictions = np.argmax(probabilities, axis=-1)
 print('Generating submission.csv file...')
 test_ids_ds = test_ds.map(lambda image, idnum: idnum ).unbatch()
test_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES)) ).numpy().astype('U')
 np.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')
 print('Done !' )<import_modules>
HEIGHT = 137
WIDTH = 236
FACTOR = 0.70
HEIGHT_NEW = int(HEIGHT * FACTOR)
 WIDTH_NEW = int(WIDTH * FACTOR)
 CHANNELS = 3
BATCH_SIZE = 16
DIR = '.. /input/bengaliai-cv19'
print("Tensorflow version " + tf.__version__ )<set_options>
print(HEIGHT_NEW)
 print(WIDTH_NEW)
 def resize_image(img, WIDTH_NEW, HEIGHT_NEW):
img = 255 - img
img =(img *(255.0 / img.max())).astype(np.uint8)
 img = img.reshape(HEIGHT, WIDTH)
 image_resized = cv2.resize(img,(WIDTH_NEW, HEIGHT_NEW), interpolation = cv2.INTER_AREA)
 return image_resized.reshape(-1 )
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>
gm_exp = tf.Variable(3.0, dtype = tf.float32)
 def generalized_mean_pool_2d(X):
pool =(tf.reduce_mean(tf.abs(X**(gm_exp)) ,
axis = [1, 2],
keepdims = False)+ 1.e-7)**(1./gm_exp)
 return pool
GCS_DS_PATH = KaggleDatasets().get_gcs_path()<define_variables>
def create_model(input_shape):
input = Input(shape = input_shape)
 x_model = efn.EfficientNetB3(weights = None, include_top = False, input_tensor = input, pooling = None, classes = None)
 for layer in x_model.layers:
layer.trainable = True
lambda_layer = Lambda(generalized_mean_pool_2d)
 lambda_layer.trainable_weights.extend([gm_exp])
 x = lambda_layer(x_model.output)
 grapheme_root = Dense(168, activation = 'softmax', name = 'root' )(x)
 vowel_diacritic = Dense(11, activation = 'softmax', name = 'vowel' )(x)
 consonant_diacritic = Dense(7, activation = 'softmax', name = 'consonant' )(x)
 model = Model(inputs = x_model.input, outputs = [grapheme_root, vowel_diacritic, consonant_diacritic])
 return model
IMAGE_SIZE = [512, 512, 3]
BATCH_SIZE = 16 * strategy.num_replicas_in_sync
NUM_TRAINING_IMAGES = 12753
NUM_TEST_IMAGES = 7382
STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE
TRAINING_FILENAMES = tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-%sx%s' %(IMAGE_SIZE[0], IMAGE_SIZE[1])+ '/train/*.tfrec')
 VALIDATION_FILENAMES = tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-%sx%s' %(IMAGE_SIZE[0], IMAGE_SIZE[1])+ '/val/*.tfrec')
 TEST_FILENAMES = tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-%sx%s' %(IMAGE_SIZE[0], IMAGE_SIZE[1])+ '/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']
WARMUP_EPOCHS = 20
WARMUP_LEARNING_RATE = 3e-3
TUNING_EPOCHS = 8
LR_MIN = 1e-10
LR_PEAK = 2e-4
LR_RAMPUP_EPOCHS = 4
LR_DECAY = 0.3
RE_PROBABILITY = 1
RE_S_LOW = 0.1
RE_S_HIGH = 0.6
RE_RATIO = 0.3
CROP_MIN = tf.cast(IMAGE_SIZE[0]*0.6, dtype=tf.int32)
 CROP_MAX = tf.cast(IMAGE_SIZE[0]*0.95, dtype=tf.int32 )<data_type_conversions>
model1 = create_model(input_shape =(HEIGHT_NEW, WIDTH_NEW, CHANNELS))
model2 = create_model(input_shape =(HEIGHT_NEW, WIDTH_NEW, CHANNELS))
model3 = create_model(input_shape =(HEIGHT_NEW, WIDTH_NEW, CHANNELS))
model4 = create_model(input_shape =(HEIGHT_NEW, WIDTH_NEW, CHANNELS))
model5 = create_model(input_shape =(HEIGHT_NEW, WIDTH_NEW, CHANNELS))
fig, ax = plt.subplots()
blank = tf.constant(1, shape=(IMAGE_SIZE[0], IMAGE_SIZE[1], IMAGE_SIZE[2]), dtype=tf.float32)
 erasure = random_erasing(blank)
 ax.imshow(np.asarray(erasure.numpy()))
plt.show()<categorify>
model1.load_weights('.. /input/kerasefficientnetb3/Train1_model_59.h5')
 model2.load_weights('.. /input/kerasefficientnetb3/Train1_model_64.h5')
 model3.load_weights('.. /input/kerasefficientnetb3/Train1_model_68.h5')
 model4.load_weights('.. /input/kerasefficientnetb3/Train1_model_57.h5')
 model5.load_weights('.. /input/kerasefficientnetb3/Train1_model_70.h5' )
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)
 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)
 dataset = dataset.with_options(ignore_order)
 dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord)
 return dataset
def get_training_dataset() :
dataset = load_dataset(TRAINING_FILENAMES, labeled=True)
 dataset = dataset.map(augment_dataset)
 dataset = dataset.repeat()
dataset = dataset.shuffle(2048)
 dataset = dataset.batch(BATCH_SIZE)
 return dataset
def get_training_dataset_preview(ordered=True):
dataset = load_dataset(TRAINING_FILENAMES, labeled=True, ordered=ordered)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.cache()
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()
return dataset
def get_test_dataset(ordered=False):
dataset = load_dataset(TEST_FILENAMES, labeled=False, ordered=ordered)
 dataset = dataset.batch(BATCH_SIZE)
 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)
 training_dataset = get_training_dataset()
validation_dataset = get_validation_dataset()<choose_model_class>
class TestDataGenerator(keras.utils.Sequence):
def __init__(self, X, batch_size = 16, img_size =(512, 512, 3), *args, **kwargs):
self.X = X
self.indices = np.arange(len(self.X))
self.batch_size = batch_size
self.img_size = img_size
def __len__(self):
return int(ceil(len(self.X)/ self.batch_size))
def __getitem__(self, index):
indices = self.indices[index*self.batch_size:(index+1)*self.batch_size]
X = self.__data_generation(indices)
 return X
def __data_generation(self, indices):
X = np.empty(( self.batch_size, *self.img_size))
for i, index in enumerate(indices):
image = self.X[index]
image = np.stack(( image,)*CHANNELS, axis=-1)
 image = image.reshape(-1, HEIGHT_NEW, WIDTH_NEW, CHANNELS)
 X[i,] = image
return X
with strategy.scope() :
pretrained_model = tf.keras.applications.DenseNet201(
 weights = 'imagenet',
include_top = False,
input_shape = IMAGE_SIZE)
 pretrained_model.trainable = False
model = tf.keras.Sequential([
pretrained_model,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(104, activation = 'softmax')
 ])
 warmup_optimizer = tf.keras.optimizers.Adam(lr = WARMUP_LEARNING_RATE)
 model.compile(
 optimizer = warmup_optimizer,
loss = 'sparse_categorical_crossentropy',
metrics = ['sparse_categorical_accuracy'] 
)
 model.summary()
warmup_history = model.fit(
 training_dataset,
steps_per_epoch = STEPS_PER_EPOCH,
epochs = WARMUP_EPOCHS,
validation_data = validation_dataset )<choose_model_class>
tgt_cols = ['grapheme_root','vowel_diacritic','consonant_diacritic']
row_ids, targets = [], []
for i in range(0, 4):
test_files = []
df = pd.read_parquet(os.path.join(DIR, 'test_image_data_'+str(i)+'.parquet'))
image_ids = df['image_id'].values
df = df.drop(['image_id'], axis = 1)
 X = []
for image_id, index in zip(image_ids, range(df.shape[0])) :
test_files.append(image_id)
 X.append(resize_image(df.loc[df.index[index]].values, WIDTH_NEW, HEIGHT_NEW))
data_generator_test = TestDataGenerator(X, batch_size = BATCH_SIZE, img_size =(HEIGHT_NEW, WIDTH_NEW, CHANNELS))
preds1 = model1.predict_generator(data_generator_test, verbose = 1)
 preds2 = model2.predict_generator(data_generator_test, verbose = 1)
 preds3 = model3.predict_generator(data_generator_test, verbose = 1)
 preds4 = model4.predict_generator(data_generator_test, verbose = 1)
 preds5 = model5.predict_generator(data_generator_test, verbose = 1)
 for i, image_id in zip(range(len(test_files)) , test_files):
for subi, col in zip(range(len(preds1)) , tgt_cols):
sub_preds1 = preds1[subi]
sub_preds2 = preds2[subi]
sub_preds3 = preds3[subi]
sub_preds4 = preds4[subi]
sub_preds5 = preds5[subi]
row_ids.append(str(image_id)+'_'+col)
 sub_pred_value = np.argmax(( sub_preds1[i] + sub_preds2[i] + sub_preds3[i] + sub_preds4[i] + sub_preds5[i])/ 5)
 targets.append(sub_pred_value)
 del df
gc.collect()
for layer in model.layers:
layer.trainable = True
tuning_optimizer = tf.keras.optimizers.Adam(lr = LR_PEAK)
 model.compile(
 optimizer = tuning_optimizer,
loss = 'sparse_categorical_crossentropy',
metrics = ['sparse_categorical_accuracy'] 
)
 model.summary()
lr_callback = tf.keras.callbacks.LearningRateScheduler(scheduler)
 tuning_history = model.fit(
 training_dataset,
steps_per_epoch = STEPS_PER_EPOCH,
epochs = TUNING_EPOCHS,
validation_data = validation_dataset,
callbacks = lr_callback )<save_to_csv>
submit_df = pd.DataFrame({'row_id':row_ids,'target':targets}, columns = ['row_id','target'])
 submit_df.to_csv('submission.csv', index = False)
 print(submit_df.head(40))