Kaggle competition: Petals to the Metal - Flower Classification on TPU
<SOS> metric: macrofscore Kaggle data source: petals-to-the-metal-flower-classification-on-tpu<define_variables>
def seed_everything(seed=0):
np.random.seed(seed)
 tf.random.set_seed(seed)
 os.environ['PYTHONHASHSEED'] = str(seed)
 os.environ['TF_DETERMINISSTIC_OPS'] = '1'
seed = 0
seed_everything(seed)
 warnings.filterwarnings("ignore" )
li_idxs = []
for i in range(10):
for nr in range(10):
ix = y[y==nr].index[i]
li_idxs.append(ix )<train_on_grid>
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('RELICAS :', strategy.num_replicas_in_sync )
clf_Perceptron = Perceptron(random_state=0)
 param_grid = { 'penalty': ['l1','l2'], 'tol': [0.05, 0.1] }
GridCV_Perceptron = GridSearchCV(clf_Perceptron, param_grid, verbose=1, cv=5)
 GridCV_Perceptron.fit(X_train,y_train)
 score_grid_Perceptron = get_best_score(GridCV_Perceptron )<predict_on_test>
BATCH_SIZE = 16 * strategy.num_replicas_in_sync
WARMUP_EPOCHS = 3
WARMUP_LEARNING_RATE = 1e-4 * strategy.num_replicas_in_sync
EPOCHS = 20
LEARNING_RATE = 3e-5 * strategy.num_replicas_in_sync
HEIGHT = 512
WIDTH = 512
CHANNELS = 3
N_CLASSES = 104
ES_PATIENCE = 6
RLROP_PATIENCE = 3
DECAY_DROP = 0.3
model_path = 'DenseNet201_%sx%s.h5'%(HEIGHT, WIDTH)
 GCS_PATH = KaggleDatasets().get_gcs_path() + '/tfrecords-jpeg-%sx%s'%(HEIGHT, WIDTH)
 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']
pred_val_perc = GridCV_Perceptron.predict(X_val )<compute_test_metric>
AUTO = tf.data.experimental.AUTOTUNE
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, [HEIGHT, WIDTH, 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, seed=seed)
 image = tf.image.random_flip_up_down(image, seed=seed)
 image = tf.image.random_saturation(image, lower=0, upper=2, seed=seed)
 image = tf.image.random_crop(image, size=[int(HEIGHT*.8), int(WIDTH*.8), CHANNELS], 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_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
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 )
acc_perc = print_validation_report(y_val, pred_val_perc )<train_on_grid>
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 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
def title_from_label_and_target(label, correct_label):
label = np.argmax(label, axis=-1)
 correct =(label == correct_label)
 return "{} [{}{}{}]".format(CLASSES[label], str(correct), ', shoud be ' if not correct else '',
CLASSES[correct_label] if not correct else ''), correct
def display_one_flower_eval(image, title, subplot, red=False):
plt.subplot(subplot)
 plt.axis('off')
 plt.imshow(image)
 plt.title(title, fontsize=14, color='red' if red else 'black')
 return subplot+1
def display_9_images_with_predictions(images, predictions, labels):
subplot=331
plt.figure(figsize=(13,13))
for i, image in enumerate(images):
title, correct = title_from_label_and_target(predictions[i], labels[i])
 subplot = display_one_flower_eval(image, title, subplot, not correct)
 if i >= 8:
break;
plt.tight_layout()
plt.subplots_adjust(wspace=0.1, hspace=0.1)
 plt.show()
clf_LR = LogisticRegression(random_state=0)
 param_grid = {'C': [0.014,0.012], 'multi_class': ['multinomial'],
'penalty': ['l1'],'solver': ['saga'], 'tol': [0.1] }
GridCV_LR = GridSearchCV(clf_LR, param_grid, verbose=1, cv=5)
 GridCV_LR.fit(X_train,y_train)
 score_grid_LR = get_best_score(GridCV_LR )<predict_on_test>
NUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)
 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)
 NUM_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES)
 valid_dataset = get_validation_dataset(ordered=True)
 y_valid = next(iter(valid_dataset.unbatch().map(lambda image, label: label ).batch(NUM_VALIDATION_IMAGES)) ).numpy()
print('Number of validation images %d' % NUM_VALIDATION_IMAGES)
 NUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)
 print('Number of test images %d' % NUM_TEST_IMAGES)
 test_dataset = get_test_dataset(ordered=True )
pred_val_lr = GridCV_LR.predict(X_val)
 acc_lr = print_validation_report(y_val, pred_val_lr )<train_model>
display_batch_of_images(next(iter(train_dataset.unbatch().batch(20))))
clf_knn = KNeighborsClassifier(n_neighbors=10)
 clf_knn.fit(X_train,y_train )<predict_on_test>
display_batch_of_images(next(iter(valid_dataset.unbatch().batch(20))))
pred_val_knn = clf_knn.predict(X_val)
 acc_knn = print_validation_report(y_val, pred_val_knn )<train_on_grid>
display_batch_of_images(next(iter(test_dataset.unbatch().batch(20))))
clf_RF = RandomForestClassifier(random_state=0)
 param_grid = {'max_depth': [15], 'max_features': [100],
'min_samples_split': [5],'n_estimators' : [50] }
GridCV_RF = GridSearchCV(clf_RF, param_grid, verbose=1, cv=5)
 GridCV_RF.fit(X_train,y_train)
 score_grid_RF = get_best_score(GridCV_RF )<predict_on_test>
def create_model(input_shape, N_CLASSES):
base_model = applications.DenseNet201(weights='imagenet',
include_top=False,
input_shape=input_shape)
 base_model.trainable = False
model = tf.keras.Sequential([
base_model,
layers.GlobalAveragePooling2D() ,
layers.Dense(N_CLASSES, activation='softmax')
 ])
 return model
pred_val_rf = GridCV_RF.predict(X_val )<compute_test_metric>
with strategy.scope() :
model = create_model(( None, None, CHANNELS), N_CLASSES)
 metric_list = ['sparse_categorical_accuracy']
optimizer = optimizers.Adam(lr=WARMUP_LEARNING_RATE)
 model.compile(optimizer=optimizer,
loss = 'sparse_categorical_crossentropy',
metrics=metric_list)
 model.summary()
acc_rf = print_validation_report(y_val, pred_val_rf )<train_model>
STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE
warmup_history = model.fit(x=get_training_dataset() ,
steps_per_epoch = STEPS_PER_EPOCH,
validation_data = get_validation_dataset() ,
epochs=WARMUP_EPOCHS,
verbose=2 ).history
clf_svm = SVC(C=5, gamma=0.05, kernel='rbf', random_state=0)
 clf_svm.fit(X_train,y_train )<predict_on_test>
LR_START = 0.00000001
LR_MIN = 0.000001
LR_MAX = LEARNING_RATE
LR_RAMPUP_EPOCHS = 3
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
rng = [i for i in range(EPOCHS)]
y = [lrfn(x)for x in rng]
sns.set(style='whitegrid')
 fig, ax = plt.subplots(figsize=(20, 6))
plt.plot(rng, y)
 print("Learning rate shcedule: {:.3g} to {:.3g} to {:.3g}".format(y[0], max(y), y[-1]))
pred_val_svm = clf_svm.predict(X_val)
 acc_svm = print_validation_report(y_val, pred_val_svm )<define_variables>
for layer in model.layers:
layer.trainable = True
checkpoint = ModelCheckpoint(model_path, monitor='val_loss', mode='min', save_best_only=True)
 es = EarlyStopping(monitor='val_loss', mode='min', patience=ES_PATIENCE,
restore_best_weights=True, verbose=1)
 lr_callback = LearningRateScheduler(lrfn, verbose=1)
 callback_list = [checkpoint, es, lr_callback]
optimizer = optimizers.Adam(lr=LEARNING_RATE)
 model.compile(optimizer=optimizer, loss='sparse_categorical_crossentropy', metrics=metric_list)
 model.summary()
batchsize = int(nr_samples/15 )<train_on_grid>
history = model.fit(x=get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
validation_data=get_validation_dataset() ,
callbacks=callback_list,
epochs=EPOCHS,
verbose=2 ).history
clf_mlp = MLPClassifier(activation = "logistic", hidden_layer_sizes=(200,), random_state=0)
 param_grid = { 'batch_size' : [batchsize] , 'max_iter': [600], 'alpha': [1e-4],
'solver': ['sgd'], 'learning_rate_init': [0.05,0.06],'tol': [1e-4] }
GridCV_MLP = GridSearchCV(clf_mlp, param_grid, verbose=1, cv=3)
 GridCV_MLP.fit(X_train,y_train)
 score_grid_MLP = get_best_score(GridCV_MLP )<predict_on_test>
x_train = train_dataset.map(lambda image, label : image)
 train_preds = model.predict(x_train)
 train_preds = np.argmax(train_preds, axis=-1)
 print(classification_report(y_train, train_preds, target_names=CLASSES))
pred_val_mlp = GridCV_MLP.predict(X_val )<compute_test_metric>
x_valid = valid_dataset.map(lambda image, label : image)
 valid_preds = model.predict(x_valid)
 valid_preds = np.argmax(valid_preds, axis=-1)
 print(classification_report(y_valid, valid_preds, target_names=CLASSES))
acc_mlp = print_validation_report(y_val, pred_val_mlp )<categorify>
x_train_samp, y_train_samp = dataset_to_numpy_util(train_dataset, 9)
 train_samp_preds = model.predict(x_train_samp, batch_size=9)
 display_9_images_with_predictions(x_train_samp, train_samp_preds, y_train_samp )
y_train = to_categorical(y_train, 10)
 y_val_10 = to_categorical(y_val, 10 )<choose_model_class>
x_valid_samp, y_valid_samp = dataset_to_numpy_util(valid_dataset, 9)
 valid_samp_preds = model.predict(x_valid_samp, batch_size=9)
 display_9_images_with_predictions(x_valid_samp, valid_samp_preds, y_valid_samp )
def dense_model_0() :
model = Sequential()
model.add(Dense(10, input_dim=784, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
 return model<train_model>
x_test = test_dataset.map(lambda image, idnum: image)
 test_preds = model.predict(x_test)
 test_preds = np.argmax(test_preds, axis=-1 )
model_dense_0.fit(X_train, y_train, epochs=50, batch_size=batchsize )<predict_on_test>
test_ids_ds = test_dataset.map(lambda image, idnum:idnum ).unbatch()
test_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES)) ).numpy().astype('U')
 submission = pd.DataFrame(test_ids, columns=['id'])
 submission['label'] = test_preds
submission.to_csv('submission.csv', index=False)
 display(submission.head(10))