Kaggle competition: Petals to the Metal - Flower Classification on TPU
pred_val_dense0 = model_dense_0.predict_classes(X_val )<compute_test_metric>
import re
import math
import numpy as np
import seaborn as sns
from kaggle_datasets import KaggleDatasets
from matplotlib import pyplot as plt
from sklearn.metrics import f1_score, precision_score, recall_score, confusion_matrix
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.callbacks import LearningRateScheduler
from tensorflow.keras.metrics import TruePositives, FalsePositives, FalseNegatives
acc_fc0 = print_validation_report(y_val, pred_val_dense0 )<choose_model_class>
!pip install efficientnet
def dense_model_1() :
model = Sequential()
model.add(Dense(100, input_dim=784, activation='relu'))
model.add(Dense(10, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
 return model<train_model>
AUTO = tf.data.experimental.AUTOTUNE
AUTO
history_dense_1 = model_dense_1.fit(X_train, y_train, validation_data=(X_val,y_val_10),
epochs=50, batch_size=batchsize )<compute_train_metric>
tpu = tf.distribute.cluster_resolver.TPUClusterResolver()
tf.config.experimental_connect_to_cluster(tpu)
 tf.tpu.experimental.initialize_tpu_system(tpu)
 strategy = tf.distribute.experimental.TPUStrategy(tpu )
pred_val_dense1 = model_dense_1.predict_classes(X_val)
 plot_confusion_matrix(y_val, pred_val_dense1)
 print(classification_report(y_val, pred_val_dense1))
acc_fc1 = accuracy_score(y_val, pred_val_dense1)
 print(acc_fc1 )<choose_model_class>
IMAGE_SIZE = [512, 512]
EPOCHS = 30
LEARNING_RATE = 1e-3
TTA_NUM = 5
BATCH_SIZE = 32 * strategy.num_replicas_in_sync
print("Batch size used: ", BATCH_SIZE)
def dense_model_2() :
model = Sequential()
model.add(Dense(100, input_dim=784, activation='relu'))
model.add(Dense(200, activation='relu'))
model.add(Dense(10, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
 return model<train_model>
GCS_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started')
 GCS_PATH_SELECT = {
192: GCS_PATH + '/tfrecords-jpeg-192x192',
224: GCS_PATH + '/tfrecords-jpeg-224x224',
331: GCS_PATH + '/tfrecords-jpeg-331x331',
512: GCS_PATH + '/tfrecords-jpeg-512x512'
}
GCS_FPATH = GCS_PATH_SELECT[IMAGE_SIZE[0]]
history_dense_2 = model_dense_2.fit(X_train, y_train, validation_data=(X_val,y_val_10),
epochs=50, batch_size=batchsize )<compute_train_metric>
TRAINING_FILENAMES = tf.io.gfile.glob(GCS_FPATH + '/train/*.tfrec')
 VALIDATION_FILENAMES = tf.io.gfile.glob(GCS_FPATH + '/val/*.tfrec')
 TEST_FILENAMES = tf.io.gfile.glob(GCS_FPATH + '/test/*.tfrec' )
pred_val_dense2 = model_dense_2.predict_classes(X_val)
 plot_confusion_matrix(y_val, pred_val_dense2)
 print(classification_report(y_val, pred_val_dense2))
acc_fc2 = accuracy_score(y_val, pred_val_dense2)
 print(acc_fc2 )<choose_model_class>
SKIP_VALIDATION = True
if SKIP_VALIDATION:
TRAINING_FILENAMES = TRAINING_FILENAMES + VALIDATION_FILENAMES
def dense_model_3() :
model = Sequential()
model.add(Dense(100, activation='relu', input_dim=784))
model.add(Dense(200, activation='relu'))
model.add(Dense(100, activation='relu'))
model.add(Dense(10, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
 return model<train_model>
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']
print(f"No of Flower classes in dataset: {len(CLASSES)}" )
history_dense_3 = model_dense_3.fit(X_train, y_train, validation_data=(X_val,y_val_10),
epochs=50, batch_size=batchsize )<compute_train_metric>
LR_START = 0.00001
LR_MAX = 0.00005 * strategy.num_replicas_in_sync
LR_MIN = 0.00001
LR_RAMPUP_EPOCHS = 5
LR_SUSTAIN_EPOCHS = 0
LR_EXP_DECAY =.7
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(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]))
pred_val_dense3 = model_dense_3.predict_classes(X_val)
 plot_confusion_matrix(y_val, pred_val_dense3)
 print(classification_report(y_val, pred_val_dense3))
acc_fc3 = accuracy_score(y_val, pred_val_dense3)
 print(acc_fc3 )<prepare_x_and_y>
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()
X_train = X_train.values.reshape(X_train.shape[0], img_rows, img_cols, 1)
 X_val = X_val.values.reshape(X_val.shape[0], img_rows, img_cols, 1)
 input_shape =(img_rows, img_cols, 1 )<define_variables>
def dataset_to_numpy_util(dataset, N):
dataset = dataset.unbatch().batch(N)
 for images, labels in dataset:
numpy_images = images.numpy()
numpy_labels = labels.numpy()
break;
return numpy_images, numpy_labels
batchsize = 128
epochs = 12<feature_engineering>
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 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_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 )
activation = 'relu'
adadelta = Adadelta()
loss = categorical_crossentropy<choose_model_class>
models = []
histories = []
def cnn_model_1(activation):
model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3), activation=activation, input_shape=input_shape))
model.add(Conv2D(64,(3, 3), activation=activation))
model.add(MaxPooling2D(pool_size=(2, 2)))
 model.add(Dropout(0.25))
model.add(Flatten())
 model.add(Dense(128, activation=activation))
model.add(Dropout(0.5))
model.add(Dense(10, activation='softmax'))
model.compile(loss=loss, optimizer=adadelta, metrics=['accuracy'])
 return model<find_best_params>
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 + NUM_VALIDATION_IMAGES)// BATCH_SIZE
print('Dataset: {} training images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES+NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))
model_cnn_1 = cnn_model_1(activation)
 model_cnn_1.summary()<train_model>
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 get_training_dataset_preview(ordered=True):
dataset = load_dataset(TRAINING_FILENAMES, labeled=True, ordered=ordered)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.cache()
dataset = dataset.prefetch(AUTO)
 return dataset
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 dataset_to_numpy_util(dataset, N):
dataset = dataset.unbatch().batch(N)
 for images, labels in dataset:
numpy_images = images.numpy()
numpy_labels = labels.numpy()
break;
return numpy_images, numpy_labels
history_cnn_1 = model_cnn_1.fit(X_train, y_train, validation_data=(X_val,y_val_10),
epochs=epochs, batch_size=batchsize, verbose=1 )<compute_train_metric>
train_dataset = get_training_dataset_preview(ordered=True)
 y_train = next(iter(train_dataset.unbatch().map(lambda image, label: label ).batch(NUM_TRAINING_IMAGES)) ).numpy()
print('Number of training images %d' % NUM_TRAINING_IMAGES )
pred_val_cnn1 = model_cnn_1.predict_classes(X_val)
 plot_confusion_matrix(y_val, pred_val_cnn1)
 print(classification_report(y_val, pred_val_cnn1))
acc_cnn1 = accuracy_score(y_val, pred_val_cnn1)
 print(acc_cnn1)
<define_variables>
display_batch_of_images(next(iter(train_dataset.unbatch().batch(20))))
batch_size=90
epochs=30 
<choose_model_class>
test_dataset = get_test_dataset()
test_dataset = test_dataset.unbatch().batch(20)
 test_batch = iter(test_dataset )
def cnn_model_2(optimizer,loss):
model = Sequential()
model.add(Conv2D(32,(3, 3), padding = 'Same', activation="relu", input_shape=input_shape))
model.add(MaxPooling2D(pool_size =(2, 2)))
 model.add(Conv2D(32,(3, 3), activation="relu"))
model.add(MaxPooling2D(pool_size =(2, 2)))
 model.add(Flatten())
 model.add(Dense(256, activation=activation))
model.add(Dense(10, activation='softmax'))
model.compile(optimizer = optimizer, loss = loss, metrics = ['accuracy'])
 return model<compute_train_metric>
display_batch_of_images(next(test_batch))
model_cnn_2 = cnn_model_2(adadelta, categorical_crossentropy)
 model_cnn_2.summary()<train_model>
def get_mat(rotation, shear, height_zoom, width_zoom, height_shift, width_shift):
rotation = math.pi * rotation / 180.
 shear = math.pi * shear/ 180.
 c1 = tf.math.cos(rotation)
 c2 = tf.math.sin(rotation)
 one = tf.constant([1], dtype='float32')
 zero = tf.constant([0], dtype='float32')
 rotation_mat = tf.reshape(tf.concat([c1, s1, zero, -s1, c1, zero, \
zero, zero, one], axis=0), [3,3])
 c2 = tf.math.cos(shear)
 s2 = tf.math.sin(shear)
 shear_mat = tf.reshape(tf.concat([one, s2, zero, zero, c2, \
zero, zero, zero, one], axis=0), [3,3])
 zoom_mat = tf.reshape(tf.concat([one/height_zoom, zero, zero, zero, \
oneb/width_zoom, zero, zero, zero, one], axis=0), [3,3])
 shift_mat = tf.reshape(tf.concat([one_zero, height_shift, zero, one, width_shift, zero, \
zero, one], axis=0), [3,3])
 return K.dot(K.dot(rotation_mat, shear_mat), K.dot(zoom_mat, shift_mat))
history_cnn_2 = model_cnn_2.fit(X_train, y_train, validation_data=(X_val,y_val_10),
epochs=epochs, batch_size=batchsize, verbose=1 )<compute_train_metric>
def transform(image, label):
DIM = 512
XIM = DIM%2
rot = 15.* tf.random.normal([1], dtype='float32')
 shr = 5.*tf.random.normal([1], dtype='float32')
 h_zoom = 1.0 + tf.random.normal([1], dtype='float32')/ 1.0
w_zoom = 1.0 + tf.random.normal([1], dtype='float32')/1.0
h_shift = 16.* tf.random.normal([1],dtype='float32')
 w_shift = 16.* tf.random.normal([1],dtype='float32')
 m = get_mat(rot,shr,h_zoom,w_zoom,h_shift,w_shift)
 x = tf.repeat(tf.range(DIM//2,-DIM//2,-1), DIM)
 y = tf.tile(tf.range(-DIM//2,DIM//2),[DIM])
 z = tf.ones([DIM*DIM],dtype='int32')
 idx = tf.stack([x,y,z])
 idx2 = K.dot(m,tf.cast(idx,dtype='float32'))
idx2 = K.cast(idx2,dtype='int32')
 idx2 = K.clip(idx2,-DIM//2+XDIM+1,DIM//2)
 idx3 = tf.stack([DIM//2-idx2[0,], DIM//2-1+idx2[1,]])
 d = tf.gather_nd(image,tf.transpose(idx3))
return tf.reshape(d,[DIM,DIM,3]), label
pred_val_cnn2 = model_cnn_2.predict_classes(X_val)
 plot_confusion_matrix(y_val, pred_val_cnn2)
 print(classification_report(y_val, pred_val_cnn2))
acc_cnn2 = accuracy_score(y_val, pred_val_cnn2)
 print(acc_cnn2 )<load_from_csv>
with strategy.scope() :
enet = efn.EfficientNetB3(
 input_shape=(IMAGE_SIZE[0], IMAGE_SIZE[1], 3),
weights='imagenet',
include_top=False 
)
 enet.trainable = True
model1 = tf.keras.Sequential([
enet,
tf.keras.layers.GlobalMaxPooling2D(name="Layer1"),
tf.keras.layers.Dropout(0.) ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model1.compile(
 optimizer=tf.keras.optimizers.Adam(lr=0.0001),
loss = 'sparse_categorical_crossentropy',
metrics = "sparse_categorical_accuracy" 
)
 model1.summary()
models.append(model1 )
sample_submission = pd.read_csv('.. /input/sample_submission.csv')
 if mode == "edit" :
X = X[:nr_samples//2]
y = y[:nr_samples//2]
X_test = X_test[:nr_samples//2]
sample_submission = sample_submission[:nr_samples//2]<train_on_grid>
tf.keras.utils.plot_model(
 model1, to_file='model.png', show_shapes=True, show_layer_names=True, 
)
print(GridCV_Perceptron.best_params_)
 GridCV_Perceptron.best_estimator_.fit(X,y )<save_to_csv>
Checkpoint=tf.keras.callbacks.ModelCheckpoint(f"Enet_model.h5", monitor='val_accuracy', verbose=1, save_best_only=True,
save_weights_only=True,mode='max')
 train_history1 = model1.fit(
 get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS,
callbacks=[lr_callback, Checkpoint, keras.callbacks.EarlyStopping(
 monitor="val_loss",
min_delta=1e-2,
patience=2,
verbose=1, 
)], 
)
 histories.append(train_history1)
pred_test_perc = GridCV_Perceptron.best_estimator_.predict(X_test)
 result_perc = pd.DataFrame({'ImageId':sample_submission.ImageId, 'Label':pred_test_perc})
 result_perc.to_csv("subm_perc.csv",index=False )<train_on_grid>
with strategy.scope() :
densenet = tf.keras.applications.DenseNet201(input_shape=[*IMAGE_SIZE, 3], weights='imagenet', include_top=False)
 densenet.trainable = True
model2 = tf.keras.Sequential([
densenet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model2.compile(
 optimizer=tf.keras.optimizers.Adam() ,
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 model2.summary()
print(GridCV_LR.best_params_)
 GridCV_LR.best_estimator_.fit(X,y )<save_to_csv>
tf.keras.utils.plot_model(
 model1, to_file='model.png', show_shapes=True, show_layer_names=True,
)
pred_test_lr = GridCV_LR.best_estimator_.predict(X_test)
 result_lr = pd.DataFrame({'ImageId':sample_submission.ImageId, 'Label':pred_test_lr})
 result_lr.to_csv("subm_lr.csv",index=False )<train_model>
Checkpoint=tf.keras.callbacks.ModelCheckpoint(f"Dnet_model.h5", monitor='val_accuracy', verbose=1, save_best_only=True,
save_weights_only=True,mode='max')
 train_history2 = model2.fit(get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
epochs=30,
callbacks = [lr_callback, Checkpoint, keras.callbacks.EarlyStopping(
 monitor="val_loss",
min_delta=1e-2,
patience=2,
verbose=1, 
)])
 histories.append(train_history2 )
clf_knn.fit(X,y )<save_to_csv>
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()
m1 = model1.predict(images_ds)
 m2 = model2.predict(images_ds)
 scores = []
for alpha in np.linspace(0,1,100):
cm_probabilities = alpha*m1+(1-alpha)*m2
cm_predictions = np.argmax(cm_probabilities, axis=-1)
 scores.append(f1_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro'))
best_alpha = np.argmax(scores)/100
print('Best alpha: ' + str(best_alpha))
pred_test_knn = clf_knn.predict(X_test)
 result_knn = pd.DataFrame({'ImageId':sample_submission.ImageId, 'Label':pred_test_knn})
 result_knn.to_csv("subm_knn.csv",index=False )<train_on_grid>
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')
 display_confusion_matrix(cmat, score, precision, recall)
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score, precision, recall))
print(GridCV_RF.best_params_)
 GridCV_RF.best_estimator_.fit(X,y )<save_to_csv>
def predict_tta(model, n_iter):
probs = []
for i in range(n_iter):
test_ds = get_test_dataset(ordered=True)
 test_images_ds = test_ds.map(lambda image, idnum: image)
 probs.append(model.predict(test_images_ds,verbose=0))
return probs
pred_test_rf = GridCV_RF.best_estimator_.predict(X_test)
 result_rf = pd.DataFrame({'ImageId':sample_submission.ImageId, 'Label':pred_test_rf})
 result_rf.to_csv("subm_rf.csv",index=False )<train_model>
test_ds = get_test_dataset(ordered=True)
 print('Calculating predictions...')
 test_images_ds = test_ds.map(lambda image, idnum: image)
 probs1 = np.mean(predict_tta(model1, TTA_NUM), axis=0)
 probs2 = np.mean(predict_tta(model2, TTA_NUM), axis=0)
 probabilities = best_alpha*probs1 +(1-best_alpha)*probs2
predictions = np.argmax(probabilities, axis=-1 )
<save_to_csv><EOS> 
print('Generating submission 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='')