Kaggle competition: Bengali.AI Handwritten Grapheme Classification
def seed_everything(seed=0):
np.random.seed(seed)
 tf.random.set_seed(seed)
 os.environ['PYTHONHASHSEED'] = str(seed)
 os.environ['TF_DETERMINISSTIC_OPS'] = '1'
seed = 0
seed_everything(seed)
 warnings.filterwarnings("ignore" )<choose_model_class>
IMAGE_SIZE = 137, 236
class DatasetRetriever(Dataset):
def __init__(self, df):
self.image_ids = df.iloc[:, 0].tolist()
self.images = torch.from_numpy(255 - df[[str(x)for x in range(32332)]].values)
 def __len__(self):
return self.images.shape[0]
def __getitem__(self, idx):
img = self.images[idx]
img = img.view(*IMAGE_SIZE)
 img = img.to(torch.float32)/ 255.
 img = img.unsqueeze(0)
 img = img.repeat(3, 1, 1)
 img_id = self.image_ids[idx]
return img_id, img
class Predictor:
def __init__(self, model):
self.device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
 self.model = model.to(self.device, dtype=torch.float32);
self.model.eval()
print(f'Model prepared.Device is {self.device}')
 def predict(self, inputs):
inputs = inputs.to(self.device, dtype=torch.float32)
 with torch.no_grad() :
outputs = self.model(inputs)
 return outputs
def load(self, path):
checkpoint = torch.load(path, map_location=self.device)
 self.model.load_state_dict(checkpoint['model_state_dict'] )
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('RELICAS :', strategy.num_replicas_in_sync )<define_variables>
predictors = []
for i,(model_path, net, coef)in enumerate([ 
('/kaggle/input/ghostnetbengali/checkpoint.pt', ghost_net(num_classes=168+11+7), 0.5), 
('/kaggle/input/ghostnetbengali/densenet121-checkpoint.pt', densenet121(num_classes=168+11+7), 0.5),
]):
predictor = Predictor(net)
 predictor.load(model_path)
 predictors.append(( predictor, coef))
def predict_to_numpy(predict):
return torch.nn.functional.softmax(predict, dim=1 ).data.cpu().numpy().argmax(axis=1)
 def make_prediction(images):
outputs = 0
for predictor, coef in predictors:
outputs += predictor.predict(images)* coef
roots = predict_to_numpy(outputs[:,:168])
 vowels = predict_to_numpy(outputs[:,168:168+11])
 consonants = predict_to_numpy(outputs[:,168+11:])
 return roots, vowels, consonants
BATCH_SIZE = 16 * strategy.num_replicas_in_sync
WARMUP_EPOCHS = 3
WARMUP_LEARNING_RATE = 1e-4 * strategy.num_replicas_in_sync
EPOCHS = 20
LEARNING_RATE = 3e-5 * strategy.num_replicas_in_sync
HEIGHT = 512
WIDTH = 512
CHANNELS = 3
N_CLASSES = 104
ES_PATIENCE = 6
RLROP_PATIENCE = 3
DECAY_DROP = 0.3
model_path = 'DenseNet201_%sx%s.h5'%(HEIGHT, WIDTH)
 GCS_PATH = KaggleDatasets().get_gcs_path() + '/tfrecords-jpeg-%sx%s'%(HEIGHT, WIDTH)
 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>
%%time
target = []
row_id = []
for i in range(4):
data = pd.read_parquet(f'.. /input/bengaliai-cv19/test_image_data_{i}.parquet')
 dataset = DatasetRetriever(data)
 data_loader = DataLoader(dataset, batch_size=256, num_workers=4, shuffle=False, sampler=SequentialSampler(dataset))
for idx,(image_ids, images)in tqdm(enumerate(data_loader), total=len(data_loader)) :
roots, vowels, consonants = make_prediction(images)
 for image_id, root, vowel, consonant in zip(image_ids, roots, vowels, consonants):
row_id.append(image_id + '_consonant_diacritic')
 target.append(consonant)
 row_id.append(image_id + '_grapheme_root')
 target.append(root)
 row_id.append(image_id + '_vowel_diacritic')
 target.append(vowel )
<categorify><EOS> 
df_submission = pd.DataFrame(
 {
'row_id': row_id,
'target': target
},
columns=['row_id','target'] 
)
 df_submission.to_csv('submission.csv', index=False)
 df_submission.head(10 )