Kaggle competition: Bengali.AI Handwritten Grapheme Classification
<SOS> metric: WeightedCategorizationAccuracy Kaggle data source: bengali.ai-handwritten-grapheme-classification<save_model>
!pip install.. /input/pretrainedmodels/pretrainedmodels-0.7.4/pretrainedmodels-0.7.4/ > /dev/null
monet_generator.save('monet_generator.h5')
 photo_generator.save('photo_generator.h5')
 monet_discriminator.save('monet_discriminator.h5')
 photo_discriminator.save('photo_discriminator.h5' )<install_modules>
HEIGHT = 137
WIDTH = 236
SIZE = 128
bs = 128
stats =(0.0692, 0.2051)
 arch = pretrainedmodels.__dict__['se_resnext50_32x4d']
MODEL = '.. /input/weights/seresnext.pth'
nworkers = 2
TEST = ['/kaggle/input/bengaliai-cv19/test_image_data_0.parquet',
'/kaggle/input/bengaliai-cv19/test_image_data_1.parquet',
'/kaggle/input/bengaliai-cv19/test_image_data_2.parquet',
'/kaggle/input/bengaliai-cv19/test_image_data_3.parquet']
LABELS = '.. /input/bengaliai-cv19/train.csv'
df = pd.read_csv(LABELS)
 nunique = list(df.nunique())[1:-1]
!pip install -q efficientnet<import_modules>
nunique
print("Tensorflow version " + tf.__version__ )<set_options>
class Head(nn.Module):
def __init__(self, nc, n, ps=0.5):
super().__init__()
layers = [AdaptiveConcatPool2d() , Mish() , Flatten() ] + \
bn_drop_lin(nc*2, 512, True, ps, Mish())+ \
bn_drop_lin(512, n, True, ps)
 self.fc = nn.Sequential(*layers)
 self._init_weight()
def _init_weight(self):
for m in self.modules() :
if isinstance(m, nn.Conv2d):
torch.nn.init.kaiming_normal_(m.weight)
 elif isinstance(m, nn.BatchNorm2d):
m.weight.data.fill_(1.0)
 m.bias.data.zero_()
def forward(self, x):
return self.fc(x)
 class Dnet_1ch(nn.Module):
def __init__(self, arch=arch, n=nunique, pre=True, ps=0.5):
super().__init__()
m = arch(pretrained='imagenet')if pre else arch(pretrained=None)
 conv = nn.Conv2d(1, 64, kernel_size=7, stride=2, padding=3, bias=False)
 w =(m.layer0.conv1.weight.sum(1)).unsqueeze(1)
 conv.weight = nn.Parameter(w)
 self.layer0 = nn.Sequential(conv, m.layer0.bn1, m.layer0.relu1, m.layer0.pool)
 self.layer1 = m.layer1
self.layer2 = m.layer2
self.layer3 = m.layer3
self.layer4 = nn.Sequential(m.layer4[0], m.layer4[1], m.layer4[2])
 nc = self.layer4[-1].se_module.fc2.out_channels
self.head1 = Head(nc,n[0])
 self.head2 = Head(nc,n[1])
 self.head3 = Head(nc,n[2])
 def forward(self, x):
x = self.layer0(x)
 x = self.layer1(x)
 x = self.layer2(x)
 x = self.layer3(x)
 x = self.layer4(x)
 x1 = self.head1(x)
 x2 = self.head2(x)
 x3 = self.head3(x)
 return x1,x2,x3
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>
model = Dnet_1ch(pre=False ).cuda()
model.load_state_dict(torch.load(MODEL, map_location=torch.device('cpu')));
model.eval() ;
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>
class GraphemeDataset(Dataset):
def __init__(self, fname):
self.df = pd.read_parquet(fname)
 self.data = 255 - self.df.iloc[:, 1:].values.reshape(-1, HEIGHT, WIDTH ).astype(np.uint8)
 def __len__(self):
return len(self.data)
 def __getitem__(self, idx):
name = self.df.iloc[idx,0]
img =(self.data[idx]*(255.0/self.data[idx].max())).astype(np.uint8)
 img = crop_resize(img)
 img =(img.astype(np.float32)/255.0 - stats[0])/stats[1]
return img, name
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>
EXP = -1.2
G_logits = []
V_logits = []
C_logits = []
G_preds = []
V_preds=[]
C_preds = []
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>
import scipy
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<choose_model_class>
row_id,target = [],[]
for fname in TEST:
ds = GraphemeDataset(fname)
 dl = DataLoader(ds, batch_size=bs, num_workers=nworkers, shuffle=False)
 with torch.no_grad() :
for x,y in tqdm(dl):
x = x.unsqueeze(1 ).cuda()
p1,p2,p3 = model(x)
 p1 = torch.nn.functional.softmax(p1)
 p2 = torch.nn.functional.softmax(p2)
 p3 = torch.nn.functional.softmax(p3)
 G_logits.append(p1.cpu())
 V_logits.append(p2.cpu())
 C_logits.append(p3.cpu())
 p1 = p1.argmax(-1 ).view(-1 ).cpu()
p2 = p2.argmax(-1 ).view(-1 ).cpu()
p3 = p3.argmax(-1 ).view(-1 ).cpu()
G_preds.append(p1)
 V_preds.append(p2)
 C_preds.append(p3)
with strategy.scope() :
enet = efn.EfficientNetB7(
 input_shape=(512, 512, 3),
weights='imagenet',
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() ,
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 model.summary()<load_pretrained>
G_preds = np.concatenate(G_preds)
 V_preds = np.concatenate(V_preds)
 C_preds = np.concatenate(C_preds )
def freeze(model):
for layer in model.layers:
layer.trainable = False
def unfreeze(model):
for layer in model.layers:
layer.trainable = True<define_variables>
s = pd.Series(G_preds)
 vc = s.value_counts().sort_index()
df = pd.DataFrame({'a':np.arange(168),'b':np.ones(168)})
 df.b = df.a.map(vc)
 df.fillna(df.b.min() ,inplace=True)
 mat1 = np.diag(df.b.astype('float32')**EXP)
 s = pd.Series(V_preds)
 vc = s.value_counts().sort_index()
df = pd.DataFrame({'a':np.arange(11),'b':np.ones(11)})
 df.b = df.a.map(vc)
 df.fillna(df.b.min() ,inplace=True)
 mat2 = np.diag(df.b.astype('float32')**EXP)
 s = pd.Series(C_preds)
 vc = s.value_counts().sort_index()
df = pd.DataFrame({'a':np.arange(7),'b':np.ones(7)})
 df.b = df.a.map(vc)
 df.fillna(df.b.min() ,inplace=True)
 mat3 = np.diag(df.b.astype('float32')**EXP)
 G_logits = np.concatenate(G_logits)
 V_logits = np.concatenate(V_logits)
 C_logits = np.concatenate(C_logits)
 G_pred = np.argmax(G_logits.dot(mat1), axis=1)
 V_pred = np.argmax(V_logits.dot(mat2), axis=1)
 C_pred = np.argmax(C_logits.dot(mat3), axis=1 )
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))<train_model>
all_list = [G_pred, V_pred, C_pred]
<save_to_csv><EOS> 
labels = ['grapheme_root', 'vowel_diacritic', 'consonant_diacritic']
sub = pd.DataFrame({'row_id': [f'Test_{i}_{j}' for i in range(len(G_pred)) for j in labels ],'target':[data[i].item() for i in range(len(G_pred)) for data in all_list]})
 sub.to_csv('submission.csv', index=False)
 sub