Kaggle competition: Kannada MNIST
<SOS> metric: CategorizationAccuracy Kaggle data source: kannada-mnist<compute_train_metric>
%matplotlib inline
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()
cm_probabilities = dnet_model.predict(images_ds)
 cm_predictions = np.argmax(cm_probabilities, axis=-1)
 print("Correct labels: ", cm_correct_labels.shape, cm_correct_labels)
 print("Predicted labels: ", cm_predictions.shape, cm_predictions)
 cmat = confusion_matrix(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)))
 rscore = f1_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
 rprecision = precision_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
 rrecall = recall_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
 cmat =(cmat.T / cmat.sum(axis=1)).T
display_confusion_matrix(cmat, rscore, rprecision, rrecall)
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(rscore, rprecision, rrecall)) 
<predict_on_test>
config = tf.compat.v1.ConfigProto()
config.gpu_options.allow_growth = True
session = tf.compat.v1.Session(config=config )
test_ds = get_test_dataset(ordered=True)
 print('Computing predictions...')
 test_images_ds = test_ds.map(lambda image, idnum: image)
 dnet_probabilities = dnet_model.predict(test_images_ds)
 dnet_predictions = np.argmax(dnet_probabilities, axis=-1)
 print(dnet_predictions)
<prepare_output>
test = pd.read_csv("/kaggle/input/Kannada-MNIST/test.csv")
 train = pd.read_csv("/kaggle/input/Kannada-MNIST/train.csv")
 dig_mnist = pd.read_csv("/kaggle/input/Kannada-MNIST/Dig-MNIST.csv")
 sample_submission = pd.read_csv("/kaggle/input/Kannada-MNIST/sample_submission.csv" )
probabilities =(enet_probabilities + dnet_probabilities + irnet_probabilities + rnet_probabilities)/4
ensemble_predict = np.argmax(probabilities, axis=-1)
 print(ensemble_predict )<save_to_csv>
X_train = train.loc[:, train.columns!='label'].values.astype('uint8')
 print("X_train.shape", X_train.shape)
 y_train = train['label'].values
X_train = X_train.reshape(( X_train.shape[0],28,28))
print("X_train.shape", X_train.shape)
 print("y_train.shape",X_train.shape )
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, ensemble_predict]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')
 print('Submission Ensemble saved.....')
<install_modules>
X_train = X_train[:,:,:,None]
X_test = X_test[:,:,:,None]
!pip install -q efficientnet<import_modules>
batch_size = 32
num_epochs = 50
print('Tensorflow ver:',tf.__version__ )<set_options>
num_samples = X_train.shape[0]
num_classes = np.unique(y_train ).shape[0]
img_rows, img_cols = X_train[0,:,:,0].shape
classes = np.unique(y_train )
try:
tpu = tf.distribute.cluster_resolver.TPUClusterResolver()
tf.config.experimental_connect_to_cluster(tpu)
 tf.tpu.experimental.initialize_tpu_system(tpu)
 print('TPU configured, at',tpu.master())
 except ValueError:
tpu = None
print('TPUs not found! Using CPU')
 if tpu:
strategy = tf.distribute.experimental.TPUStrategy(tpu)
 else:
strategy = tf.distribute.get_strategy()
print('Succeed distributing TPUs!')
 print("REPLICAS: ", strategy.num_replicas_in_sync )<define_variables>
print("num_samples",num_samples)
 print("num_classes",num_classes)
 print("img_rows",img_rows)
 print("img_cols",img_cols)
 print("classes",classes )
AUTO = tf.data.experimental.AUTOTUNE
print('AUTO:',AUTO)
 BATCH_SIZE = 16 * strategy.num_replicas_in_sync
EPOCHS = 12
IMAGE_SIZE = [512,512]
WIDTH = IMAGE_SIZE[0]
HEIGHT = IMAGE_SIZE[1]
CHANNELS = 3
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'
]<define_variables>
y_train = np_utils.to_categorical(y_train, num_classes)
 y_train.shape
try:
BASE = KaggleDatasets().get_gcs_path('flower-classification-with-tpus')
 except ModuleNotFoundError:
BASE = "/Users/astzls/Downloads/flower"
PATH_SELECT = {
192: BASE + '/tfrecords-jpeg-192x192',
224: BASE + '/tfrecords-jpeg-224x224',
331: BASE + '/tfrecords-jpeg-331x331',
512: BASE + '/tfrecords-jpeg-512x512'
}
IMAGE_PATH = PATH_SELECT[IMAGE_SIZE[0]]
TRAINING_FILENAMES = tf.io.gfile.glob(IMAGE_PATH + '/train/*.tfrec')
 VALIDATION_FILENAMES = tf.io.gfile.glob(IMAGE_PATH + '/val/*.tfrec')
 TEST_FILENAMES = tf.io.gfile.glob(IMAGE_PATH + '/test/*.tfrec' )<create_dataframe>
X_train_norm = X_train.astype('float32')
 X_test_norm = X_test.astype('float32')
 X_train_norm /= 255
X_test_norm /= 255
def get_training_dataset(do_aug=True):
dataset = load_dataset(TRAINING_FILENAMES, labeled=True)
 if do_aug:
dataset = dataset.map(data_augmentation, num_parallel_calls=AUTO)
 dataset = dataset.shuffle(2048)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.repeat()
dataset = dataset.prefetch(AUTO)
 return dataset
def get_validation_dataset(order=False):
dataset = load_dataset(VALIDATION_FILENAMES, labeled=True,ordered=order)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.cache()
dataset = dataset.prefetch(AUTO)
 return dataset
def get_test_dataset(order=False):
dataset = load_dataset(TEST_FILENAMES, labeled=False,ordered=order)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.prefetch(AUTO)
 return dataset
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_augmentation(image, label):
image = tf.image.random_flip_left_right(image)
 image = tf.image.random_flip_up_down(image)
 image = tf.image.random_brightness(image, 0.1)
 return image, label
def decode_image(image_data):
image = tf.image.decode_jpeg(image_data, channels=3)
 image = tf.cast(image, tf.float32)
 image /= 255.0
image = tf.reshape(image, [*IMAGE_SIZE, 3])
 return image
def read_labeled_tfrecord(example):
FEATURE = {
"image": tf.io.FixedLenFeature([], tf.string),
"class": tf.io.FixedLenFeature([], tf.int64)
 }
example = tf.io.parse_single_example(example, FEATURE)
 image = decode_image(example['image'])
 label = tf.cast(example['class'], tf.int32)
 return image, label
def read_unlabeled_tfrecord(example):
FEATURE = {
"image": tf.io.FixedLenFeature([], tf.string),
"id": tf.io.FixedLenFeature([], tf.string)
 }
example = tf.io.parse_single_example(example, FEATURE)
 image = decode_image(example['image'])
 idnum = example['id']
return image, idnum 
<choose_model_class>
learning_rate_reduction=ReduceLROnPlateau(monitor='val_loss',
patience=5,
verbose=1,
factor=0.2
)
with strategy.scope() :
conv_base = efn.EfficientNetB7(
 input_shape=(512, 512, 3),
weights='imagenet',
include_top=False 
)
 set_trainable = False
for layer in conv_base.layers:
if layer.name == 'block2a_expand_conv':
set_trainable = True
if set_trainable:
layer.trainable = True
else:
layer.trainable = False
model = tf.keras.Sequential([
conv_base,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dropout(0.1),
tf.keras.layers.Dense(104, activation='softmax')
 ])
 model.compile(
 optimizer=tf.keras.optimizers.Adam() ,
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy']
)<choose_model_class>
early_stopping = EarlyStopping(monitor='val_loss',
mode='min',
verbose=1,
patience=10
)
def lrfn(epoch):
LR_START = 2.5e-4
LR_MIN = 1e-5
lr = cos(epoch*pi/18)* LR_START
return lr if lr>LR_MIN else LR_MIN
def lrfn1(epoch):
lr_start = 2.5e-4
lr_min = 1e-5
lr = lr_start /(1 + e **(epoch - 5))
return lr if lr > lr_min else lr_min
callbacks_list = [
tf.keras.callbacks.EarlyStopping(
 monitor='val_loss',
patience=2 
),
tf.keras.callbacks.LearningRateScheduler(
 lrfn1,
verbose=1 
)
 ]
epochs=[x for x in range(12)]
lr_sigmoid=[lrfn1(x)for x in epochs]
plt.plot(epochs,lr_sigmoid,'b')
 plt.xlabel('Epoch')
 plt.ylabel('lr')
 plt.title('Sigmoid lr scheduler')
 plt.savefig('lr_sche.jpg')
 plt.show()<define_variables>
def build_model() :
model = Sequential()
x_in = layers.Input(shape=(28, 28, 1))
x = layers.Conv2D(64, kernel_size=(3, 3), activation='relu' )(x_in)
 x = layers.BatchNormalization()(x)
 x = layers.Conv2D(128, kernel_size=(3, 3), activation='relu' )(x)
 x = layers.BatchNormalization()(x)
 x = layers.MaxPooling2D(pool_size=(2, 2))(x)
 x = layers.Dropout(0.25 )(x)
 x = layers.Conv2D(256, kernel_size=(3, 3), activation='relu' )(x)
 x = layers.BatchNormalization()(x)
 x = layers.Conv2D(512, kernel_size=(3, 3), activation='relu' )(x)
 x = layers.BatchNormalization()(x)
 x = layers.MaxPooling2D(pool_size=(2, 2))(x)
 x = layers.Dropout(0.25 )(x)
 x = layers.Flatten()(x)
 x = layers.Dense(512 )(x)
 x = layers.BatchNormalization()(x)
 x = layers.Dense(256 )(x)
 x = layers.BatchNormalization()(x)
 x = layers.Dense(128 )(x)
 x = layers.BatchNormalization()(x)
 classes = layers.Dense(num_classes, activation='softmax' )(x)
 model = Model(inputs=x_in, outputs=classes)
 model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
 return model
nums_image = count_data_items(TRAINING_FILENAMES)
 STEPS_PER_EPOCH = nums_image // BATCH_SIZE
print('Total {} images will be training.. '.format(nums_image))
history = model.fit(get_training_dataset(do_aug=True),
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS,
validation_data=get_validation_dataset() ,
callbacks=callbacks_list,
verbose=2
)<load_pretrained>
model = build_model()
print('Model saving...')
 model.save_weights('my_weights.h5')
 show_acc_loss(history )<save_to_csv>
history = model.fit(X_train_norm,
y_train,
batch_size = batch_size,
epochs = num_epochs,
validation_split = 0.1,
shuffle = True,
callbacks = [learning_rate_reduction, early_stopping]
)
print('Preparing test dataset...')
 test_ds = get_test_dataset(order=True)
 print('Predicting test dataset...')
 test_images = test_ds.map(lambda image, idnum: image)
 probabilities = model.predict(test_images)
 predictions = np.argmax(probabilities, axis=-1)
 print('Generating submission.csv file...')
 nums_test_images = count_data_items(TEST_FILENAMES)
 test_ids = test_ds.map(lambda image, idnum: idnum ).unbatch()
test_ids = next(iter(test_ids.batch(nums_test_images)) ).numpy().astype('U')
 np.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')
 print('Successfully generating csv submission file!')
<predict_on_test>
model.save('model.h5' )
print('Preparing dataset...')
 dataset = get_validation_dataset(order=True)
 images = dataset.map(lambda image, label: image)
 labels = dataset.map(lambda image, label: label ).unbatch()
print('Predicting...')
 prediction_start = perf_counter()
output = model.predict(images)
 prediction_end = perf_counter()
print('In {:.1f}s compeleted!'.format(prediction_end - prediction_start))
prediction = np.argmax(output,axis=-1)
 nums_validation_images = count_data_items(VALIDATION_FILENAMES)
 correct_labels = next(iter(labels.batch(nums_validation_images)) ).numpy()
mistake = [0 for _ in range(len(CLASSES)) ]
print('Computing mistakes...')
 for i in range(nums_validation_images):
if prediction[i] != correct_labels[i]:
mistake[correct_labels[i]]+=1
with open('mistake.json','w')as f:
json.dump(mistake,f)
 classes = [x for x in range(104)]
plt.bar(classes,mistake)
 plt.xlabel('CLASSES')
 plt.ylabel('Mistake count')
 plt.title('Mistakes each class')
 plt.savefig('mistake.jpeg')
 plt.show()<compute_test_metric>
pred = model.predict(X_test_norm )
print('Spawning confusion matrix...')
 confusion_mat = confusion_matrix(correct_labels, prediction, labels=range(len(CLASSES)))
 score = f1_score(correct_labels, prediction, labels=range(len(CLASSES)) , average='macro')
 precision = precision_score(correct_labels, prediction, labels=range(len(CLASSES)) , average='macro')
 recall = recall_score(correct_labels, prediction, labels=range(len(CLASSES)) , average='macro')
 confusion_mat =(confusion_mat.T / confusion_mat.sum(axis=1)).T
display_confusion_matrix(confusion_mat, score, precision, recall)
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score, precision, recall)) 
<set_options>
pred=np.argmax(pred, axis=1 )
print("Tensorflow version " + tf.__version__)
 AUTO = tf.data.experimental.AUTOTUNE<set_options>
sample_submission['label'] = pred
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>
sample_submission.to_csv("submission.csv", index=False )