Kaggle competition: Kannada MNIST
print("Tensorflow version " + tf.__version__)
 AUTO = tf.data.experimental.AUTOTUNE<define_variables>
%reload_ext autoreload
%autoreload 2
%matplotlib inline
path = '/kaggle/input/Kannada-MNIST/'
print(os.listdir(path))
def random_seed(seed_value, use_cuda):
np.random.seed(seed_value)
 torch.manual_seed(seed_value)
 random.seed(seed_value)
 if use_cuda:
torch.cuda.manual_seed(seed_value)
 torch.cuda.manual_seed_all(seed_value)
 torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
random_seed(13,True )
GCS_DS_PATH = KaggleDatasets().get_gcs_path('flower-classification-with-tpus')
 IMAGE_SIZE = [512,512] 
<define_variables>
class CustomImageList(ImageList):
def open(self, fn):
if(fn.size == 785):
fn = fn[1:]
img = fn.reshape(28,28)
 img = np.stack(( img,)*3, axis=-1)
 return Image(pil2tensor(img, dtype=np.float32))
@classmethod
def from_csv_custom(cls, path:PathOrStr, csv_name:str, imgIdx:int=1, header:str='infer', **kwargs)->'ItemList':
df = pd.read_csv(Path(path)/csv_name, header=header)
 res = super().from_df(df, path=path, cols=0, **kwargs)
 res.items = df.iloc[:,imgIdx:].apply(lambda x: x.values / 255.0, axis=1 ).values
return res
@classmethod
def from_csv_custom_test(cls, path:PathOrStr, csv_name:str, imgIdx:int=1, header:str='infer', **kwargs)->'ItemList':
df = pd.read_csv(Path(path)/csv_name, header=header)
 res = super().from_df(df, path=path, cols=0, **kwargs)
 res.items = df.iloc[:,imgIdx:].apply(lambda x: x.values / 255.0, axis=1 ).values
print(res)
 return res
@classmethod
def from_df_custom(cls, path:PathOrStr, df:DataFrame, imgIdx:int=1, header:str='', **kwargs)->'ItemList':
res = super().from_df(df, path=path, cols=0, **kwargs)
 res.items = df.iloc[:,imgIdx:].apply(lambda x: x.values / 255.0, axis=1 ).values
return res
<define_variables>
test = CustomImageList.from_csv_custom_test(path=path, csv_name='test.csv', imgIdx=0 )
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')
 SKIP_VALIDATION = False
if SKIP_VALIDATION:
TRAINING_FILENAMES = TRAINING_FILENAMES + VALIDATION_FILENAMES 
<define_variables>
data =(CustomImageList.from_csv_custom(path=path, csv_name='train.csv', imgIdx=1)
.split_by_rand_pct (.02)
.label_from_df(cols='label')
.add_test(test, label=0)
.transform(get_transforms(do_flip=False,max_rotate=15,max_warp=0.4)) 
.databunch(bs=128, num_workers=0)
.normalize(imagenet_stats))
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']<set_options>
def conv2(ni,nf,stride=2,ks=5): return conv_layer(ni,nf,stride=stride,ks=ks)
MIXED_PRECISION = False
XLA_ACCELERATE = False
if MIXED_PRECISION:
if tpu: policy = tf.keras.mixed_precision.experimental.Policy('mixed_bfloat16')
 else: policy = tf.keras.mixed_precision.experimental.Policy('mixed_float16')
 mixed_precision.set_policy(policy)
 print('Mixed precision enabled')
 if XLA_ACCELERATE:
tf.config.optimizer.set_jit(True)
 print('Accelerated Linear Algebra enabled' )<set_options>
def mish(input):
return input * torch.tanh(F.softplus(input))
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>
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, in_planes, planes, stride=1):
super(BasicBlock, self ).__init__()
self.conv1 = nn.Conv2d(
 in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
 self.bn1 = nn.BatchNorm2d(planes)
 self.conv2 = nn.Conv2d(
 planes, planes, kernel_size=3, stride=1, padding=1, bias=False)
 self.bn2 = nn.BatchNorm2d(planes)
 self.shortcut = nn.Sequential()
if stride != 1 or in_planes != self.expansion * planes:
self.shortcut = nn.Sequential(
 nn.Conv2d(
 in_planes,
self.expansion * planes,
kernel_size=1,
stride=stride,
bias=False), nn.BatchNorm2d(self.expansion * planes))
def forward(self, x):
out = self.bn1(self.conv1(x))
out = mish(out)
 out = self.bn2(self.conv2(out))
out = mish(out)
 shrt = self.shortcut(x)
 out += mish(shrt)
 return out
class ResNet(nn.Module):
def __init__(self, block, num_blocks, num_classes=10):
super(ResNet, self ).__init__()
self.in_planes = 64
self.conv1 = nn.Conv2d(
 3, 64, kernel_size=3, stride=1, padding=1, bias=False)
 self.bn1 = nn.BatchNorm2d(64)
 self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1)
 self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2)
 self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2)
 self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2)
 self.linear = nn.Linear(512 * block.expansion, 200)
 self.linear2 = nn.Linear(200, num_classes)
 self.bn_1d_1 = nn.BatchNorm1d(num_features=200)
 self.dropout = nn.Dropout(p=0.2)
 def _make_layer(self, block, planes, num_blocks, stride):
strides = [stride] + [1] *(num_blocks - 1)
 layers = []
for stride in strides:
layers.append(block(self.in_planes, planes, stride))
self.in_planes = planes * block.expansion
return nn.Sequential(*layers)
 def forward(self, x):
out = self.bn1(self.conv1(x))
out = mish(out)
 out = self.layer1(out)
 out = self.layer2(out)
 out = self.layer3(out)
 out = self.layer4(out)
 out = F.avg_pool2d(out, 4)
 out = self.dropout(torch.flatten(out, 1))
out = self.linear(out)
 out = self.dropout(mish(self.bn_1d_1(out)))
 out = self.linear2(out)
 return F.log_softmax(out, dim=1)
 def ResNetCustom() :
return ResNet(BasicBlock, [4, 4, 4, 4] )
EPOCHS = 20<init_hyperparams>
model = ResNetCustom()
LR_START = 0.00001
LR_MAX = 0.00005 * strategy.num_replicas_in_sync
LR_MIN = 0.00001
LR_RAMPUP_EPOCHS = 4
LR_SUSTAIN_EPOCHS = 0
LR_EXP_DECAY =.8
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_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose = True)
 rng = [i for i in range(50 if EPOCHS<50 else EPOCHS)]
y = [lrfn(x)for x in rng]
plt.plot(rng, y)
 print("Learning rate schedule: {:.3g} to {:.3g} to {:.3g}".format(y[0], max(y), y[-1]))<categorify>
learn = Learner(data, model, loss_func = nn.CrossEntropyLoss() , metrics=[accuracy] )
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_training_dataset(dataset, do_aug=True):
dataset = dataset.map(data_augment, num_parallel_calls=AUTO)
 dataset = dataset.repeat()
dataset = dataset.batch(AUG_BATCH)
 if do_aug: dataset = dataset.map(transform, num_parallel_calls=AUTO)
 dataset = dataset.unbatch()
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 )<define_variables>
learn.fit_one_cycle(25 )
BATCH_SIZE = 8 * strategy.num_replicas_in_sync
AUG_BATCH = BATCH_SIZE
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)) 
<categorify>
learn.fit(1, 1e-5)
 learn.fit(1, 3e-6)
 learn.fit(1, 1e-6)
np.set_printoptions(threshold=15, linewidth=80)
 def batch_to_numpy_images_and_labels(data):
images, labels = data
numpy_images = images.numpy()
numpy_labels = labels.numpy()
if numpy_labels.dtype == object:
numpy_labels = [None for _ in enumerate(numpy_images)]
return numpy_images, numpy_labels
def title_from_label_and_target(label, correct_label):
if correct_label is None:
return CLASSES[label], True
correct =(label == correct_label)
 return "{} [{}{}{}]".format(CLASSES[label], 'OK' if correct else 'NO', u"\u2192" if not correct else '',
CLASSES[correct_label] if not correct else ''), correct
def display_one_flower(image, title, subplot, red=False, titlesize=16):
plt.subplot(*subplot)
 plt.axis('off')
 plt.imshow(image)
 if len(title)> 0:
plt.title(title, fontsize=int(titlesize)if not red else int(titlesize/1.2), color='red' if red else 'black', fontdict={'verticalalignment':'center'}, pad=int(titlesize/1.5))
return(subplot[0], subplot[1], subplot[2]+1)
 def display_batch_of_images(databatch, predictions=None):

 images, labels = batch_to_numpy_images_and_labels(databatch)
 if labels is None:
labels = [None for _ in enumerate(images)]
rows = int(math.sqrt(len(images)))
 cols = len(images)//rows
FIGSIZE = 13.0
SPACING = 0.1
subplot=(rows,cols,1)
 if rows < cols:
plt.figure(figsize=(FIGSIZE,FIGSIZE/cols*rows))
else:
plt.figure(figsize=(FIGSIZE/rows*cols,FIGSIZE))
for i,(image, label)in enumerate(zip(images[:rows*cols], labels[:rows*cols])) :
title = '' if label is None else CLASSES[label]
correct = True
if predictions is not None:
title, correct = title_from_label_and_target(predictions[i], label)
 dynamic_titlesize = FIGSIZE*SPACING/max(rows,cols)*40+3
subplot = display_one_flower(image, title, subplot, not correct, titlesize=dynamic_titlesize)
 plt.tight_layout()
if label is None and predictions is None:
plt.subplots_adjust(wspace=0, hspace=0)
 else:
plt.subplots_adjust(wspace=SPACING, hspace=SPACING)
 plt.show()
def display_confusion_matrix(cmat, score, precision, recall):
plt.figure(figsize=(15,15))
ax = plt.gca()
ax.matshow(cmat, cmap='BuPu')
 ax.set_xticks(range(len(CLASSES)))
 ax.set_xticklabels(CLASSES, fontdict={'fontsize': 7})
 plt.setp(ax.get_xticklabels() , rotation=45, ha="left", rotation_mode="anchor")
 ax.set_yticks(range(len(CLASSES)))
 ax.set_yticklabels(CLASSES, fontdict={'fontsize': 7})
 plt.setp(ax.get_yticklabels() , rotation=45, ha="right", rotation_mode="anchor")
 titlestring = ""
if score is not None:
titlestring += 'f1 = {:.3f} '.format(score)
 if precision is not None:
titlestring += '
precision = {:.3f} '.format(precision)
 if recall is not None:
titlestring += '
recall = {:.3f} '.format(recall)
 if len(titlestring)> 0:
ax.text(101, 1, titlestring, fontdict={'fontsize': 18, 'horizontalalignment':'right', 'verticalalignment':'top', 'color':'
plt.show()
def display_training_curves(training, validation, title, subplot):
if subplot%10==1:
plt.subplots(figsize=(10,10), facecolor='
plt.tight_layout()
ax = plt.subplot(subplot)
 ax.set_facecolor('
ax.plot(training)
 ax.plot(validation)
 ax.set_title('model '+ title)
 ax.set_ylabel(title)
 ax.set_xlabel('epoch')
 ax.legend(['train', 'valid.'] )<train_model>
predictions, *_ = learn.get_preds(DatasetType.Test)
 labels = np.argmax(predictions, 1)
 submission_df = pd.DataFrame({'id': list(range(0,len(labels))), 'label': labels})
 submission_df.to_csv(f'submission.csv', index=False )
<train_model><EOS> 
interp = ClassificationInterpretation.from_learner(learn )