Kaggle competition: Kannada MNIST
<SOS> metric: CategorizationAccuracy Kaggle data source: kannada-mnist<install_modules>
plt.ion()
!pip install -q efficientnet 
<choose_model_class>
dataset_path = '/kaggle/input/Kannada-MNIST/'
output_path = '/kaggle/working/'
with strategy.scope() :
enet = efn.EfficientNetB7(
 input_shape=[*IMAGE_SIZE, 3],
weights='noisy-student',
include_top=False 
)
 enet.trainable = True
model = tf.keras.Sequential([
enet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model.compile(
 optimizer='adam',
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 model.summary()
models.append(model)
<train_model>
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
 print('Using %r' % device)
 batch_size = 1024
num_workers = 4
num_folds = 4
num_epochs = 50
history = model.fit(get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS,
validation_data=None if SKIP_VALIDATION else get_validation_dataset() ,
callbacks = [lr_callback] 
)
 histories.append(history )<predict_on_test>
csv_cache = {}
def read_csv(path):
if path in csv_cache:
return csv_cache[path]
else:
frame = pd.read_csv(path)
 csv_cache[path] = frame
return frame
class MNIST(torch.utils.data.Dataset):
def __init__(self, *paths, train=True, transform=None, split=None):
self.train = train
self.transform = transform
values = pd.concat(read_csv(path)for path in paths ).values
if train:
self.labels = values[:, 0].astype('int64')
 self.images = values[:, 1:].astype('float32' ).reshape(-1, 28, 28)
 else:
self.images = values.astype('float32')[:, 1:].reshape(-1, 28, 28)
 if split is not None:
if train:
self.labels = self.labels[split]
self.images = self.images[split]
def __len__(self):
return self.images.shape[0]
def __getitem__(self, key):
if torch.is_tensor(key):
key = tuple(key.tolist())
 if isinstance(key, tuple):
raise NotImplementedError
elif isinstance(key, slice):
image = self.images[key, :, :].copy()
if self.transform is not None:
for i in range(image.shape[0]):
image[i] = self.transform(image[i])
 elif isinstance(key, int):
image = self.images[key]
if self.transform is not None:
image = self.transform(image)
 if self.train:
label = self.labels[key]
return image, label
else:
return image
if not SKIP_VALIDATION:
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 = 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 )<compute_test_metric>
augmented_transform = transforms.Compose([
transforms.ToPILImage() ,
transforms.RandomAffine(degrees=10, translate=(0.25, 0.25),
scale=(0.9, 1.1), shear=10,
fillcolor=0),
transforms.ToTensor() ,
transforms.Normalize(mean=(128,), std=(128,)) ,
])
 transform = transforms.Compose([
transforms.ToTensor() ,
transforms.Normalize(mean=(128,), std=(128,)) ,
])
 trainsets = []
trainloaders = []
for i in range(num_folds):
trainset = MNIST(os.path.join(dataset_path, 'train.csv'), train=True,
transform=augmented_transform,
split=np.arange(i * 60000 // num_folds,(i + 1)* 60000 // num_folds))
trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size,
shuffle=True, num_workers=num_workers,
pin_memory=True)
 trainsets.append(trainset)
 trainloaders.append(trainloader)
 testset = MNIST(os.path.join(dataset_path, 'test.csv'), train=False,
transform=transform)
 testloader = torch.utils.data.DataLoader(testset, batch_size=4,
shuffle=False, num_workers=num_workers,
pin_memory=True)
 valset = MNIST(os.path.join(dataset_path, 'Dig-MNIST.csv'), train=True,
transform=transform)
 valloader = torch.utils.data.DataLoader(valset, batch_size=batch_size,
shuffle=False, num_workers=num_workers,
pin_memory=True )
if not SKIP_VALIDATION:
cmat = confusion_matrix(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)))
 score = f1_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
 precision = precision_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
 recall = 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, score, precision, recall)
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score, precision, recall))<save_to_csv>
class Model(nn.Module):
def __init__(self):
super(Model, self ).__init__()
self.conv1 = nn.Sequential(
 nn.Conv2d(1, 64, kernel_size=3, stride=1, padding=1),
nn.LeakyReLU(0.1),
nn.BatchNorm2d(64, eps=1e-5, momentum=0.1),
nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1),
nn.LeakyReLU(0.1),
nn.BatchNorm2d(64, eps=1e-5, momentum=0.1),
nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1),
nn.LeakyReLU(0.1),
nn.BatchNorm2d(64, eps=1e-5, momentum=0.1),
nn.MaxPool2d(kernel_size=2, stride=2),
nn.Dropout(0.2),
nn.Conv2d(64, 128, kernel_size=3, stride=1, padding=1),
nn.LeakyReLU(0.1),
nn.BatchNorm2d(128, eps=1e-5, momentum=0.1),
nn.Conv2d(128, 128, kernel_size=3, stride=1, padding=1),
nn.LeakyReLU(0.1),
nn.BatchNorm2d(128, eps=1e-5, momentum=0.1),
nn.Conv2d(128, 128, kernel_size=3, stride=1, padding=1),
nn.LeakyReLU(0.1),
nn.BatchNorm2d(128, eps=1e-5, momentum=0.1),
nn.MaxPool2d(kernel_size=2, stride=2),
nn.Dropout(0.2),
nn.Conv2d(128, 256, kernel_size=3, stride=1, padding=1),
nn.LeakyReLU(0.1),
nn.BatchNorm2d(256, eps=1e-5, momentum=0.1),
nn.Conv2d(256, 256, kernel_size=3, stride=1, padding=1),
nn.LeakyReLU(0.1),
nn.BatchNorm2d(256, eps=1e-5, momentum=0.1),
nn.MaxPool2d(kernel_size=2, stride=2),
nn.Dropout(0.2), 
)
 self.dense = nn.Sequential(
 nn.Linear(2304, 256),
nn.LeakyReLU(0.1),
nn.BatchNorm1d(256),
nn.Linear(256, 10), 
)
 def forward(self, x):
x = self.conv1(x)
 x = x.flatten(start_dim=1)
 x = self.dense(x)
 return x
test_ds = get_test_dataset(ordered=True)
 print('Computing predictions...')
 test_images_ds = test_ds.map(lambda image, idnum: image)
 probabilities = model.predict(test_images_ds)
 predictions = np.argmax(probabilities, axis=-1)
 print(predictions)
 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, predictions]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')
 !head submission.csv<load_pretrained>
models = []
for _ in range(num_folds):
model = Model().to(device)
 print(model(iter(trainloader ).next() [0].to(device)).argmax(1 ).tolist())
 models.append(model)
 models
model_json = model.to_json()
with open("Flower_model.json", "w")as json_file:
json_file.write(model_json)
 model.save_weights("Flower_model.h5")
 print("Saved model to disk" )<install_modules>
criterion = nn.CrossEntropyLoss()
optimizers = [torch.optim.RMSprop(model.parameters() , lr=0.002,
alpha=0.9, momentum=0.1,
eps=1e-7, centered=True)
 for model in models]
schedulers = [torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min',
factor=0.25, patience=2,
verbose=True, min_lr=0.00001)
 for optimizer in optimizers]
!pip install -q efficientnet<set_options>
histories = []
for k,(optimizer, model)in enumerate(zip(optimizers, models)) :
schedulers[k]
histories.append([])
 if k > 0:
print()
print()
print()
print(f'Model fold {k + 1}')
 trainsets[k].transform = transform
for epoch in range(num_epochs):
sample = 0
running_total = running_errors = running_loss = 0
epoch_total = epoch_errors = epoch_loss = 0
model.train()
for i, trainloader in enumerate(trainloaders):
if i == k:
continue
for images, labels in trainloader:
optimizer.zero_grad()
outputs = model(images.to(device))
loss = criterion(outputs, labels.to(device))
loss.backward()
optimizer.step()
total = labels.size(0)
 errors =(outputs.argmax(1 ).cpu() != labels ).sum().item()
loss = loss.item()
running_total += total
running_errors += errors
running_loss += loss
epoch_total += total
epoch_errors += errors
epoch_loss += loss
if sample % 10 == 9:
print(f'\rEpoch {epoch + 1}, sample {(sample + 1)* batch_size:6d}, '
f'loss {running_loss / running_total:.5f}, '
f'acc {(1 - running_errors / running_total)* 100:3.2f}',
end='')
 running_total = running_errors = running_loss = 0
sample += 1
model.eval()
total = 0
corrects = 0
for i,(images, labels)in enumerate(trainloaders[k]):
total += labels.size(0)
 corrects +=(model(images.to(device)).argmax(1)== labels.to(device)).sum().cpu().item()
print(f'\r{total} / {len(valset)} inferred', end='')
 print('\r', end='')
 print(f'Epoch {epoch + 1} ')
 print(f'- Val acc: {100 * corrects / total:3.2f}%')
 print(f'- Train acc: {100 *(1 - epoch_errors / epoch_total):3.2f}%, '
f'loss: {epoch_loss:.5f}')
 histories[k].append(( corrects / total, 1 - epoch_errors / epoch_total))
schedulers[k].step(epoch_loss)
 trainsets[k].transform = augmented_transform
print('TensorFlow version', tf.__version__)
 AUTO = tf.data.experimental.AUTOTUNE<define_variables>
for i, model in enumerate(models):
torch.save(model.state_dict() , os.path.join(output_path, f'model-{i + 1}.pt'))
start_time = datetime.now()
print('Time now is', start_time)
 end_training_by_tdelta = timedelta(seconds=8400)
 this_run_file_prefix = start_time.strftime('%Y%m%d_%H%M_')
 print(this_run_file_prefix)
 IMAGE_SIZE = [224, 224]
EPOCHS = 12
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]]
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')
 MOREIMAGES_PATH_SELECT = {
192: '/tfrecords-jpeg-192x192',
224: '/tfrecords-jpeg-224x224',
331: '/tfrecords-jpeg-331x331',
512: '/tfrecords-jpeg-512x512'
}
MOREIMAGES_PATH = MOREIMAGES_PATH_SELECT[IMAGE_SIZE[0]]
IMAGENET_FILES = tf.io.gfile.glob(MORE_IMAGES_GCS_DS_PATH + '/imagenet' + MOREIMAGES_PATH + '/*.tfrec')
 INATURELIST_FILES = tf.io.gfile.glob(MORE_IMAGES_GCS_DS_PATH + '/inaturalist' + MOREIMAGES_PATH + '/*.tfrec')
 OPENIMAGE_FILES = tf.io.gfile.glob(MORE_IMAGES_GCS_DS_PATH + '/openimage' + MOREIMAGES_PATH + '/*.tfrec')
 OXFORD_FILES = tf.io.gfile.glob(MORE_IMAGES_GCS_DS_PATH + '/oxford_102' + MOREIMAGES_PATH + '/*.tfrec')
 TENSORFLOW_FILES = tf.io.gfile.glob(MORE_IMAGES_GCS_DS_PATH + '/tf_flowers' + MOREIMAGES_PATH + '/*.tfrec')
 ADDITIONAL_TRAINING_FILENAMES = IMAGENET_FILES + INATURELIST_FILES + OPENIMAGE_FILES + OXFORD_FILES + TENSORFLOW_FILES
print('----')
 TRAINING_FILENAMES = TRAINING_FILENAMES + ADDITIONAL_TRAINING_FILENAMES
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']<choose_model_class>
submission = []
for images in testloader:
predictions = sum(model(images.to(device)) for model in models)
 submission.extend(predictions.argmax(1 ).tolist())
 len(submission )
<categorify><EOS> 
df = pd.DataFrame.from_records(np.array(submission ).reshape(-1, 1))
df.to_csv(os.path.join(output_path, 'submission.csv'),
index_label='id', header=['label'] )