Kaggle competition: Bengali.AI Handwritten Grapheme Classification
<SOS> metric: WeightedCategorizationAccuracy Kaggle data source: bengali.ai-handwritten-grapheme-classification<choose_model_class>
import pickle
import gc
import os
import cv2
from cv2 import resize
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pathlib import Path
import torch
from torch import nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
from typing import Union
from typing import List
with strategy.scope() :
enet = efn.EfficientNetB7(
 input_shape=(512, 512, 3),
weights='noisy-student',
include_top=False 
)
 model = tf.keras.Sequential([
enet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model.compile(
 optimizer=tf.keras.optimizers.Adam(lr=0.0001),
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 model.summary()<train_model>
DEFAULT_H, DEFAULT_W = 137, 236
SIZE = 128
LABEL_PATH = Path('train.csv')
 DATADIR = Path('/kaggle/input/bengaliai-cv19')
 TEST_FORM = 'test_image_data_ID.parquet'
WEIGHTS_FILE = '/kaggle/input/densenet121-80-epochs-ohem-07/model_2020-03-07T12_40_50.436927.pt'
test = pd.read_csv(DATADIR/'test.csv')
 train = pd.read_csv(DATADIR/'train.csv')
 train_labels = train[['grapheme_root', 'vowel_diacritic', 'consonant_diacritic']].values
submission_df = pd.read_csv(DATADIR/'sample_submission.csv' )
history = model.fit(
 get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS,
callbacks=[lr_callback],
validation_data=None if SKIP_VALIDATION else get_validation_dataset()
)<choose_model_class>
def load_images(train_test, indices=['0', '1', '2', '3']):

 path_form = {
'test': TEST_FORM
}[train_test]
imgs_list = []
for id in indices:
path = DATADIR / path_form.replace('ID', id)
 print('Loading', path)
 df = pd.read_parquet(path)
 imgs = df.iloc[:, 1:].to_numpy()
imgs_list.append(imgs)
 del imgs
gc.collect()
imgs_list = np.concatenate(imgs_list)
 imgs_list = imgs_list.reshape(-1, DEFAULT_H, DEFAULT_W)
 return imgs_list
with strategy.scope() :
rnet = DenseNet201(
 input_shape=(512, 512, 3),
weights='imagenet',
include_top=False 
)
 model2 = tf.keras.Sequential([
rnet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model2.compile(
 optimizer=tf.keras.optimizers.Adam(lr=0.0001),
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 model2.summary()<train_model>
def get_data(train_test, indices=['0', '1', '2', '3']):

 imgs = load_images(train_test, indices=indices)
 if train_test == 'train':
labels = load_labels()
all_data = list(zip(imgs, labels))
else:
all_data = imgs
return all_data
history2 = model2.fit(
 get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS,
callbacks=[lr_callback],
validation_data=None if SKIP_VALIDATION else get_validation_dataset()
)<predict_on_test>
dataset_cfg = {'aug_cfg': {
'resize_shape':(128, 128),
'crop': True,
'to_rgb': True,
'normalize_mean': [0.485, 0.456, 0.406],
'normalize_std': [0.229, 0.224, 0.225]
}
}
if not SKIP_VALIDATION:
cmdataset = get_validation_dataset(ordered=True)
 images_ds = cmdataset.map(lambda image, label: image)
 labels_ds = cmdataset.map(lambda image, label: label ).unbatch()
cm_correct_labels = next(iter(labels_ds.batch(NUM_VALIDATION_IMAGES)) ).numpy()
m = model.predict(images_ds)
 m2 = model2.predict(images_ds)
 scores = []
for alpha in np.linspace(0,1,100):
cm_probabilities = alpha*m+(1-alpha)*m2
cm_predictions = np.argmax(cm_probabilities, axis=-1)
 scores.append(f1_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro'))
print("Correct labels: ", cm_correct_labels.shape, cm_correct_labels)
 print("Predicted labels: ", cm_predictions.shape, cm_predictions)
 plt.plot(scores)
 best_alpha = np.argmax(scores)/100
cm_probabilities = best_alpha*m+(1-best_alpha)*m2
cm_predictions = np.argmax(cm_probabilities, axis=-1)
 else:
best_alpha = 0.51<define_variables>
def content_crop(img, pad_to_square: bool, white_background: bool):

 img = img[5:-5, 5:-5]
if white_background:
y_list, x_list = np.where(img < 235)
 else:
y_list, x_list = np.where(img > 80)
 xmin, xmax = np.min(x_list), np.max(x_list)
 ymin, ymax = np.min(y_list), np.max(y_list)
 xmin = xmin - 13 if(xmin > 13)else 0
ymin = ymin - 10 if(ymin > 10)else 0
xmax = xmax + 13 if(xmax < 223)else 236
ymax = ymax + 10 if(ymax < 127)else 137
img = img[ymin:ymax, xmin:xmax]
if white_background:
img[img > 235] = 255
else:
img[img < 28] = 0
if pad_to_square:
lx, ly = xmax - xmin, ymax - ymin
l = max(lx, ly)+ 16
if white_background:
constant_pad = 255
else:
constant_pad = 0
img = np.pad(img, [(( l - ly)// 2,),(( l - lx)// 2,)], mode='constant', constant_values=constant_pad)
 return img
class Preprocessor(object):
def __init__(self, dataset_cfg):
aug_cfg = dataset_cfg['aug_cfg']
self.resize_shape = aug_cfg['resize_shape']
self.crop = aug_cfg['crop']
self.to_rgb = aug_cfg['to_rgb']
self.normalize_mean = aug_cfg['normalize_mean']
self.normalize_std = aug_cfg['normalize_std']
def __call__(self, img, normalize=True):
if self.crop:
img = content_crop(img, pad_to_square=True, white_background=True)
 img = resize(img, self.resize_shape)
 if self.to_rgb:
img = np.repeat(np.expand_dims(img, axis=-1), 3, axis=-1)
 if not normalize:
return img
img = img / 255.
 if self.normalize_mean is not None:
img =(img - self.normalize_mean)/ self.normalize_std
img = torch.tensor(img)
 img = img.permute([2, 0, 1])
 return img
if not SKIP_VALIDATION:
cmdataset_with_id = get_validation_dataset_with_id(ordered=True)
 ids_ds = cmdataset_with_id.map(lambda image, label, idnum: idnum ).unbatch()
ids = next(iter(ids_ds.batch(NUM_VALIDATION_IMAGES)) ).numpy().astype('U')
 val_batch = iter(cmdataset.unbatch().batch(1))
noip = sum(cm_predictions!=cm_correct_labels)
 print('Number of incorrect predictions: ' + str(noip)+ '('+str(round(noip/NUM_VALIDATION_IMAGES*100,1)) +'%)')
 for fi in range(NUM_VALIDATION_IMAGES):
x = next(val_batch)
 if cm_predictions[fi] != cm_correct_labels[fi]:
print("Image id: '" + ids[fi] + "'")
 display_batch_of_images(x,np.array([cm_predictions[fi]]),figsize = 2 )<compute_test_metric>
class BengaliDataset(Dataset):

 def __init__(self, data_list, data_cfg, fname, indices=None):

 self.data_list = data_list
self.data_size = len(data_list)
 if indices is None:
indices = np.arange(self.data_size)
 self.indices = indices
self.preprocessor = Preprocessor(data_cfg)
 if fname:
self.df = pd.read_parquet(DATADIR / fname)
 self.fname = fname
def __len__(self)-> int:
return len(self.indices)
 def __getitem__(self, idx: int)->(np.ndarray, np.ndarray):
idx = self.indices[idx]
img = self.data_list[idx]
img = self.preprocessor(img)
 name = self.df.iloc[idx, 0]
return img, name
if not SKIP_VALIDATION:
cmat = confusion_matrix(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)))
 score = f1_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
 precision = precision_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
 recall = recall_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
 display_confusion_matrix(cmat, score, precision, recall)
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score, precision, recall))<save_to_csv>
test_ds = get_test_dataset(ordered=True)
 print('Computing predictions...')
 test_images_ds = test_ds.map(lambda image, idnum: image)
 probabilities = best_alpha*model.predict(test_images_ds)+(1-best_alpha)*model2.predict(test_images_ds)
 predictions = np.argmax(probabilities, axis=-1)
 print(predictions)
 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='' )<install_modules>
__all__ = ['DenseNet', 'densenet121']
model_urls = {
'densenet121': 'https://download.pytorch.org/models/densenet121-a639ec97.pth',
}
class _DenseLayer(nn.Module):
def __init__(self, num_input_features, growth_rate, bn_size, drop_rate, memory_efficient=False):
super(_DenseLayer, self ).__init__()
self.add_module('norm1', nn.BatchNorm2d(num_input_features)) ,
self.add_module('relu1', nn.ReLU(inplace=True)) ,
self.add_module('conv1', nn.Conv2d(num_input_features, bn_size *
growth_rate, kernel_size=1, stride=1,
bias=False)) ,
self.add_module('norm2', nn.BatchNorm2d(bn_size * growth_rate)) ,
self.add_module('relu2', nn.ReLU(inplace=True)) ,
self.add_module('conv2', nn.Conv2d(bn_size * growth_rate, growth_rate,
kernel_size=3, stride=1, padding=1,
bias=False)) ,
self.drop_rate = float(drop_rate)
 self.memory_efficient = memory_efficient
def bn_function(self, inputs):
concated_features = torch.cat(inputs, 1)
 bottleneck_output = self.conv1(self.relu1(self.norm1(concated_features)))
 return bottleneck_output
def any_requires_grad(self, input):
for tensor in input:
if tensor.requires_grad:
return True
return False
@torch.jit.unused
def call_checkpoint_bottleneck(self, input):
def closure(*inputs):
return self.bn_function(*inputs)
 return cp.checkpoint(closure, input)
 @torch.jit._overload_method
def forward(self, input):
pass
@torch.jit._overload_method
def forward(self, input):
pass
def forward(self, input):
if isinstance(input, Tensor):
prev_features = [input]
else:
prev_features = input
if self.memory_efficient and self.any_requires_grad(prev_features):
if torch.jit.is_scripting() :
raise Exception("Memory Efficient not supported in JIT")
 bottleneck_output = self.call_checkpoint_bottleneck(prev_features)
 else:
bottleneck_output = self.bn_function(prev_features)
 new_features = self.conv2(self.relu2(self.norm2(bottleneck_output)))
 if self.drop_rate > 0:
new_features = F.dropout(new_features, p=self.drop_rate,
training=self.training)
 return new_features
class _DenseBlock(nn.ModuleDict):
_version = 2
def __init__(self, num_layers, num_input_features, bn_size, growth_rate, drop_rate, memory_efficient=False):
super(_DenseBlock, self ).__init__()
for i in range(num_layers):
layer = _DenseLayer(
 num_input_features + i * growth_rate,
growth_rate=growth_rate,
bn_size=bn_size,
drop_rate=drop_rate,
memory_efficient=memory_efficient, 
)
 self.add_module('denselayer%d' %(i + 1), layer)
 def forward(self, init_features):
features = [init_features]
for name, layer in self.items() :
new_features = layer(features)
 features.append(new_features)
 return torch.cat(features, 1)
 class _Transition(nn.Sequential):
def __init__(self, num_input_features, num_output_features):
super(_Transition, self ).__init__()
self.add_module('norm', nn.BatchNorm2d(num_input_features))
self.add_module('relu', nn.ReLU(inplace=True))
self.add_module('conv', nn.Conv2d(num_input_features, num_output_features,
kernel_size=1, stride=1, bias=False))
self.add_module('pool', nn.AvgPool2d(kernel_size=2, stride=2))
class DenseNet(nn.Module):
r
__constants__ = ['features']
def __init__(self, growth_rate=32, block_config=(6, 12, 24, 16),
num_init_features=64, bn_size=4, drop_rate=0, num_classes=1000, memory_efficient=False):
super(DenseNet, self ).__init__()
self.features = nn.Sequential(OrderedDict([ 
('conv0', nn.Conv2d(3, num_init_features, kernel_size=7, stride=2,
padding=3, bias=False)) , 
('norm0', nn.BatchNorm2d(num_init_features)) , 
('relu0', nn.ReLU(inplace=True)) , 
('pool0', nn.MaxPool2d(kernel_size=3, stride=2, padding=1)) ,
]))
num_features = num_init_features
for i, num_layers in enumerate(block_config):
block = _DenseBlock(
 num_layers=num_layers,
num_input_features=num_features,
bn_size=bn_size,
growth_rate=growth_rate,
drop_rate=drop_rate,
memory_efficient=memory_efficient 
)
 self.features.add_module('denseblock%d' %(i + 1), block)
 num_features = num_features + num_layers * growth_rate
if i != len(block_config)- 1:
trans = _Transition(num_input_features=num_features,
num_output_features=num_features // 2)
 self.features.add_module('transition%d' %(i + 1), trans)
 num_features = num_features // 2
self.features.add_module('norm5', nn.BatchNorm2d(num_features))
self.classifier = nn.Linear(num_features, num_classes)
 for m in self.modules() :
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight)
 elif isinstance(m, nn.BatchNorm2d):
nn.init.constant_(m.weight, 1)
 nn.init.constant_(m.bias, 0)
 elif isinstance(m, nn.Linear):
nn.init.constant_(m.bias, 0)
 def forward(self, x):
features = self.features(x)
 out = F.relu(features, inplace=True)
 out = F.adaptive_avg_pool2d(out,(1, 1))
out = torch.flatten(out, 1)
 out = self.classifier(out)
 return out
def _load_state_dict(model, model_url, progress):
pattern = re.compile(
 r'^ (.*denselayer\d+\.( ?:norm|relu|conv)) \.((?:[12])\.( ?:weight|bias|running_mean|running_var)) $')
 state_dict = load_state_dict_from_url(model_url, progress=progress)
 for key in list(state_dict.keys()):
res = pattern.match(key)
 if res:
new_key = res.group(1)+ res.group(2)
 state_dict[new_key] = state_dict[key]
del state_dict[key]
model.load_state_dict(state_dict)
 def _densenet(arch, growth_rate, block_config, num_init_features, pretrained, progress,
**kwargs):
model = DenseNet(growth_rate, block_config, num_init_features, **kwargs)
 if pretrained:
_load_state_dict(model, model_urls[arch], progress)
 return model
def densenet121(pretrained=False, progress=True, **kwargs):
r
return _densenet('densenet121', 32,(6, 12, 24, 16), 64, pretrained, progress,
**kwargs )
!pip install -q efficientnet<import_modules>
def build_densenet_backbone(backbone_cfg, **kwargs):

 model = densenet121(pretrained=False)
 if backbone_cfg.get('pretrained_path'):
pretrained_path = backbone_cfg['pretrained_path']
state_dict = torch.load(pretrained_path, map_location='cpu')
 model.load_state_dict(state_dict, strict=False)
 return model
print("Tensorflow version " + tf.__version__ )<set_options>
model_cfg = {
'head_cfg': {
'head_name': 'simple_head',
'activation': 'leaky_relu',
'output_dims': [168, 11, 7],
'input_dims': 1000,
'hidden_dims': [512, 256],
'bn': True,
'dropout': -1
},
'backbone_cfg': {
}
}
AUTO = tf.data.experimental.AUTOTUNE
tpu = tf.distribute.cluster_resolver.TPUClusterResolver()
tf.config.experimental_connect_to_cluster(tpu)
 tf.tpu.experimental.initialize_tpu_system(tpu)
 strategy = tf.distribute.experimental.TPUStrategy(tpu)
 GCS_DS_PATH = KaggleDatasets().get_gcs_path()
IMAGE_SIZE = [512, 512]
EPOCHS = 20
BATCH_SIZE = 16 * strategy.num_replicas_in_sync<define_variables>
ACTIVATION_FN = {
'relu': F.relu,
'relu6': F.relu6,
'elu': F.elu,
'leaky_relu': F.leaky_relu,
None: None
}
class LinearLayer(nn.Module):
def __init__(self, input_dim, output_dim, activation, bn, dropout_rate = -1):
super(LinearLayer, self ).__init__()
self.input_dim = input_dim
self.output_dim = output_dim
self.linear = nn.Linear(input_dim, output_dim)
 self.activation_fn = ACTIVATION_FN[activation]
if bn:
self.bn = nn.BatchNorm1d(self.output_dim)
 else:
self.bn = None
if dropout_rate > 0:
self.dropout = nn.Dropout(p=dropout_rate)
 else:
self.dropout = None
def forward(self, x):
x = self.linear(x)
 if self.bn is not None:
x = self.bn(x)
 if self.activation_fn is not None:
x = self.activation_fn(x, inplace=True)
 if self.dropout is not None:
x = self.dropout(x)
 return x
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' )<define_variables>
def build_head(head_cfg):
return SimplePredictionHead(head_cfg)
 class SimplePredictionHead(nn.Module):
def __init__(self, head_cfg):
super(SimplePredictionHead, self ).__init__()
self.fc_layers = []
input_dim = head_cfg['input_dims']
for hidden_dim in head_cfg['hidden_dims']:
self.fc_layers.append(
 LinearLayer(input_dim, hidden_dim, bn=head_cfg['bn'], activation=head_cfg['activation'],
dropout_rate=head_cfg['dropout'])
)
 input_dim = hidden_dim
output_dims = head_cfg['output_dims']
self.fc_layers.append(
 LinearLayer(input_dim, sum(output_dims), bn=False, activation=None, dropout_rate=-1)
)
 self.fc_layers = nn.Sequential(*self.fc_layers)
 for m in self.modules() :
if isinstance(m, nn.BatchNorm1d):
nn.init.ones_(m.weight)
 nn.init.zeros_(m.bias)
 elif isinstance(m, nn.Linear):
nn.init.normal_(m.weight, 0, 0.01)
 nn.init.zeros_(m.bias)
 def forward(self, x):
return self.fc_layers(x )
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>
class BaselineModel(nn.Module):
def __init__(self, model_cfg):
super(BaselineModel, self ).__init__()
self.backbone = build_densenet_backbone(model_cfg['backbone_cfg'])
 self.head = build_head(model_cfg['head_cfg'])
 self.heads_dims = model_cfg['head_cfg']['output_dims']
def forward(self, x):
x = self.backbone(x)
 x = self.head(x)
 grapheme_logits, vowel_logits, consonant_logits = torch.split(x, self.heads_dims, dim=1)
 return grapheme_logits, vowel_logits, consonant_logits
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 data_augment(image, label, seed=2020):
image = tf.image.random_flip_left_right(image, seed=seed)
 return image, label
def get_training_dataset() :
dataset = load_dataset(TRAINING_FILENAMES, labeled=True)
 dataset = dataset.map(data_augment, 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_train_valid_datasets() :
dataset = load_dataset(TRAINING_FILENAMES + VALIDATION_FILENAMES, labeled=True)
 dataset = dataset.map(data_augment, num_parallel_calls=AUTO)
 dataset = dataset.repeat()
dataset = dataset.shuffle(2048)
 dataset = dataset.batch(BATCH_SIZE)
 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 )<choose_model_class>
model = BaselineModel(model_cfg)
 state_dict = torch.load(WEIGHTS_FILE, map_location='cpu')
 model.load_state_dict(state_dict['model_state'])
 model.to(device )
def lrfn(epoch):
LR_START = 0.00001
LR_MAX = 0.00005 * strategy.num_replicas_in_sync
LR_MIN = 0.00001
LR_RAMPUP_EPOCHS = 5
LR_SUSTAIN_EPOCHS = 0
LR_EXP_DECAY =.8
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<load_pretrained>
def test_eval() :
model.eval()
test_data = ['test_image_data_0.parquet','test_image_data_1.parquet','test_image_data_2.parquet','test_image_data_3.parquet']
row_id,target = [],[]
batch_size=1
for idx, fname in enumerate(test_data):
test_images = get_data('test', indices=[str(idx)])
 test_dataset = BengaliDataset(test_images, dataset_cfg, fname=fname)
 test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False,
num_workers=4)
 with torch.no_grad() :
for inputs, name in test_loader:
inputs = inputs.to(device)
 name = str(name ).strip("'() ,'")
 grapheme_logits, vowel_logits, consonant_logits = model(inputs.float())
 grapheme_logits = grapheme_logits.argmax(-1)
 vowel_logits = vowel_logits.argmax(-1)
 consonant_logits = consonant_logits.argmax(-1)
 row_id += [f'{name}_grapheme_root',f'{name}_vowel_diacritic',
f'{name}_consonant_diacritic']
target += [grapheme_logits.item() , vowel_logits.item() ,
consonant_logits.item() ]
del test_images, test_dataset, test_loader
gc.collect()
return pd.DataFrame({'row_id': row_id, 'target': target})
def freeze(model):
for layer in model.layers:
layer.trainable = False
def unfreeze(model):
for layer in model.layers:
layer.trainable = True<define_variables>
submission_df = test_eval()
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('Dataset: {} training images, {} validation images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))<choose_model_class>
submission_df.to_csv('submission.csv', index=False )