Kaggle competition: Kannada MNIST
preds_t,y_t = learner.TTA(n_aug=8,is_test=True)
 preds_t = np.stack(preds_t, axis=-1)
 pred_t = preds_t.mean(axis=-1 )<save_to_csv>
import tensorflow as tf
import keras
from keras.datasets import mnist
from keras import backend as K
import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from keras import layers, callbacks
from keras.layers import AveragePooling2D,Add, concatenate, Convolution2D, Conv2D, Input, MaxPooling2D, UpSampling2D, Activation, ZeroPadding2D,Dropout,Conv2DTranspose
from keras.layers.core import Reshape, Permute, Flatten
from keras.layers.normalization import BatchNormalization
from keras.layers import LeakyReLU, Dense, MaxPool2D
from keras.optimizers import RMSprop,SGD,Adam
from keras.models import Model
from keras.preprocessing.image import ImageDataGenerator
from keras.callbacks import ReduceLROnPlateau
from keras.models import Sequential
from sklearn import metrics
from keras.callbacks import LearningRateScheduler, ModelCheckpoint
from sklearn.utils import shuffle
def save_pred(pred, th=0.0, fname='protein_classification.csv'):
pred_list = []
for line in pred:
s = ' '.join(list([str(i)for i in np.nonzero(line>th)[0]]))
pred_list.append(s)
 df = pd.DataFrame({'Id':learner.data.test_ds.fnames,'Predicted':pred_list})
 df.sort_values(by='Id' ).to_csv(fname, header=True, index=False )<save_to_csv>
batch_size = 500
num_classes = 10
epochs = 300
img_rows, img_cols = 28,28
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")
 x_dig=Dig_MNIST.drop('label',axis=1 ).iloc[:,:].values
x_dig = x_dig.reshape(x_dig.shape[0], 28, 28,1)
 y_dig=Dig_MNIST.label
X=train.iloc[:,1:].values
Y=train.iloc[:,0].values
X = X.reshape(X.shape[0], 28, 28,1)
 Y = keras.utils.to_categorical(Y, 10)
 x_test=test.drop('id', axis=1 ).iloc[:,:].values
x_test = x_test.reshape(x_test.shape[0], 28, 28,1 )
save_pred(pred_t,th,'protein_classification_v.csv')
 save_pred(pred_t,0.0,'protein_classification_0.csv' )<define_variables>
X,Y = shuffle(X,Y)
 X_train, X_valid, Y_train, Y_valid = train_test_split(X, Y, test_size = 0.2, random_state=42)
 train_datagen = ImageDataGenerator(rescale = 1./255.,
rotation_range = 12,
width_shift_range = 0.25,
height_shift_range = 0.25,
zoom_range = 0.15,
horizontal_flip = False,
vertical_flip = False)
 valid_datagen = ImageDataGenerator(rescale=1./255 )
lb_prob = [
0.362397820,0.043841336,0.075268817,0.059322034,0.075268817,
0.075268817,0.043841336,0.075268817,0.010000000,0.010000000,
0.010000000,0.043841336,0.043841336,0.014198783,0.043841336,
0.010000000,0.028806584,0.014198783,0.028806584,0.059322034,
0.010000000,0.126126126,0.028806584,0.075268817,0.010000000,
0.222493880,0.028806584,0.010000000] 
<compute_test_metric>
initial_learningrate = 5e-3
batch_size = 128
epochs = 100
def lr_decay(epoch):
return initial_learningrate * 0.99 ** epoch
def Count_soft(preds,th=0.0,d=50.0):
preds = sigmoid_np(d*(preds - th))
return preds.mean(axis=0)
 def fit_test(x,y):
params = np.zeros(len(name_label_dict))
wd = 1e-5
error = lambda p: np.concatenate(( Count_soft(x,p)- y,
wd*p), axis=None)
 p, success = opt.leastsq(error, params)
 return p<train_model>
learning_rate_reduction = ReduceLROnPlateau(monitor='loss',
patience=4,
verbose=1,
factor=0.5,
min_lr=0.00001 )
th_t = fit_test(pred_t,lb_prob)
 print('Thresholds: ',th_t)
 print('Fractions: ',(pred_t > th_t ).mean(axis=0))
print('Fractions(th = 0.0): ',(pred_t > 0.0 ).mean(axis=0))<save_to_csv>
def get_model(num_classes, input_shape):
model = Sequential()
model.add(Conv2D(filters = 32, kernel_size =(5,5),padding = 'Same',
activation ='relu', input_shape =(28,28,1)))
 model.add(Conv2D(filters = 32, kernel_size =(5,5),padding = 'Same',
activation ='relu'))
model.add(BatchNormalization())
 model.add(MaxPool2D(pool_size=(2,2)))
 model.add(Dropout(0.2))
model.add(Conv2D(filters = 64, kernel_size =(5,5),padding = 'Same',
activation ='relu'))
model.add(Conv2D(filters = 64, kernel_size =(3,3),padding = 'Same',
activation ='relu'))
model.add(Conv2D(filters = 64, kernel_size =(3,3),padding = 'Same',
activation ='relu'))
model.add(BatchNormalization())
 model.add(MaxPool2D(pool_size=(2,2), strides=(2,2)))
 model.add(Dropout(0.2))
model.add(Flatten())
 model.add(Dense(256, activation = "relu"))
model.add(BatchNormalization())
 model.add(Dropout(0.4))
model.add(Dense(84, activation = "relu"))
model.add(BatchNormalization())
 model.add(Dropout(0.4))
model.add(Dense(10, activation = "softmax"))
return model
save_pred(pred_t,th_t,'protein_classification_f.csv' )<prepare_output>
def lenet() :
model = Sequential()
model.add(Conv2D(filters=32, kernel_size=(5,5), padding='same', activation='relu', input_shape=(28, 28, 1)))
 model.add(MaxPool2D(strides=2))
model.add(Conv2D(filters=48, kernel_size=(5,5), padding='valid', activation='relu'))
model.add(MaxPool2D(strides=2))
model.add(Flatten())
 model.add(Dense(256, activation='relu'))
model.add(Dense(84, activation='relu'))
model.add(Dense(10, activation='softmax'))
return model
class_list = [8,9,10,15,20,24,27]
for i in class_list:
th_t[i] = th[i]
save_pred(pred_t,th_t,'protein_classification_c.csv' )<data_type_conversions>
input_shape =(28,28,1)
 model = get_model(num_classes, input_shape)
 optimizer = Adam(lr=initial_learningrate)
 model.compile(loss="categorical_crossentropy",
optimizer= optimizer,
metrics=['accuracy'] )
labels = pd.read_csv(LABELS ).set_index('Id')
 label_count = np.zeros(len(name_label_dict))
for label in labels['Target']:
l = [int(i)for i in label.split() ]
label_count += np.eye(len(name_label_dict)) [l].sum(axis=0)
 label_fraction = label_count.astype(np.float)/len(labels)
 label_count, label_fraction<train_model>
history = model.fit_generator(
 train_datagen.flow(X_train,Y_train, batch_size=batch_size),
steps_per_epoch=X_train.shape[0]//batch_size,
epochs=70,
callbacks=[learning_rate_reduction
],
validation_data=valid_datagen.flow(X_valid,Y_valid),
verbose=2
,class_weight = {0:2,1:1,2:1,3:1,4:1,5:1,6:2,7:2,8:1,9:1} )
th_t = fit_test(pred_t,label_fraction)
 print('Thresholds: ',th_t)
 print('Fractions: ',(pred_t > th_t ).mean(axis=0))
save_pred(pred_t,th_t,'protein_classification_t.csv' )<import_modules>
predictions = model.predict(x_test/255.)
import numpy as np
import pandas as pd
import os<install_modules>
x2_train, x2_test, y2_train, y2_test = train_test_split(x_test, predictions, test_size=0.15)
 x_train_final = np.concatenate(( X,x2_train), axis=0)
 y_train_final = np.concatenate(( Y,y2_train), axis=0 )
!pip install -q efficientnet
!pip install -q pyyaml h5py
print("Tensorflow version " + tf.__version__)
 AUTO = tf.data.experimental.AUTOTUNE<set_options>
X_train, X_test, Y_train, Y_test = train_test_split(x_train_final, y_train_final, test_size=0.2 )
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>
keras.backend.clear_session()
GCS_DS_PATH = KaggleDatasets().get_gcs_path('flower-classification-with-tpus')
 IMAGE_SIZE = [512, 512]
BATCH_SIZE = 16 * strategy.num_replicas_in_sync
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]]
print("Selected Image files", GCS_PATH)
 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']<define_variables>
model2 = get_model(num_classes, input_shape )
VALIDATION = False
if not VALIDATION:
TRAINING_FILENAMES = TRAINING_FILENAMES+VALIDATION_FILENAMES<categorify>
learning_rate_reduction2 = ReduceLROnPlateau(monitor='loss', patience=4, verbose=1, factor=0.5, min_lr=0.00001)
 checkpoint2 = ModelCheckpoint("bestmodel.model", monitor='loss', verbose=1, save_best_only=True)
 model2.compile(loss='categorical_crossentropy', optimizer=Adam(lr=0.002), metrics=['acc'] )
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):
image = tf.image.random_flip_left_right(image)
 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_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)
 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>
history2 = model2.fit_generator(
 train_datagen.flow(X_train, Y_train, batch_size=128),
steps_per_epoch=X_train.shape[0] // 128,
epochs=70,
validation_data=valid_datagen.flow(X_test, Y_test),
validation_steps=X_test.shape[0] // 128,
callbacks=[checkpoint2, learning_rate_reduction2],
class_weight = {0:2,1:1,2:1,3:1,4:1,5:1,6:2,7:2,8:1,9:1} )
print("Training data shapes:")
 for image, label in get_training_dataset().take(3):
print(image.numpy().shape, label.numpy().shape)
 print("Training data label examples:", label.numpy())
 print("Validation data shapes:")
 for image, label in get_validation_dataset().take(3):
print(image.numpy().shape, label.numpy().shape)
 print("Validation data label examples:", label.numpy())
 print("Test data shapes:")
 for image, idnum in get_test_dataset().take(3):
print(image.numpy().shape, idnum.numpy().shape)
 print("Test data IDs:", idnum.numpy().astype('U'))<train_model>
model2.load_weights('bestmodel.model' )
training_dataset = get_training_dataset()
training_dataset = training_dataset.unbatch().batch(20)
 train_batch = iter(training_dataset )<categorify>
preds_dig=model2.predict(x_dig/255.)
preds_dig = np.argmax(preds_dig,axis=-1)
 print(metrics.accuracy_score(preds_dig, y_dig))
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='Reds')
 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.'] )<define_variables>
results=model2.predict(x_test/255.0)
 predictions=np.argmax(results, axis=-1)
 submission = pd.read_csv('/kaggle/input/Kannada-MNIST/sample_submission.csv')
 submission['label'] = predictions
submission.to_csv("submission.csv",index=False)
 print('Done' )
display_batch_of_images(next(train_batch))<define_variables>
misclassified = []
for i in range(len(preds_dig)) :
if preds_dig[i] != y_dig[i]:
misclassified.append(( preds_dig[i],y_dig[i]))
test_dataset = get_test_dataset()
test_dataset = test_dataset.unbatch().batch(20)
 test_batch = iter(test_dataset )<define_variables>
cnt = {}
for a,b in misclassified:
if b not in cnt:
cnt[b] = 0
cnt[b] += 1