Kaggle competition: Petals to the Metal - Flower Classification on TPU
<SOS> metric: macrofscore Kaggle data source: petals-to-the-metal-flower-classification-on-tpu<count_unique_values>
import random, re, math, os
import numpy as np
import pandas as pd
import tensorflow as tf
import matplotlib.pyplot as plt
import tensorflow_addons as tfa
from kaggle_datasets import KaggleDatasets
from tensorflow.keras.mixed_precision import experimental as mixed_precision
from tensorflow.keras.applications import DenseNet201
import tensorflow.keras.backend as K
from sklearn.metrics import f1_score, precision_score, recall_score, confusion_matrix
import datetime
import tqdm
import json
from collections import Counter
import gc
unique_surname =(df['Surname'].value_counts().index)[ df['Surname'].value_counts() == 1 ]
unique_surname<feature_engineering>
IMAGE_SIZE = [512, 512]
EPOCHS = 16
SEED = 100
BATCH_SIZE = 16 * strategy.num_replicas_in_sync
single_passenger = df[df['Surname'].isin(unique_surname.to_list())]
single_woman = single_passenger['Surname'].loc[(single_passenger.Title=='woman')]
single_boy = single_passenger['Surname'].loc[(single_passenger.Title=='boy')]
df['Surname'] = df['Surname'].replace(single_woman, 'LivedPassenger')
 df['Surname'] = df['Surname'].replace(single_boy, 'DeadPassenger')
<count_values>
GCS_DS_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started')
 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' )
df['Surname'].value_counts()<count_values>
MIXED_PRECISION = False
XLA_ACCELERATE = False
if MIXED_PRECISION:
if tpu: policy = tf.keras.mixed_precision.experimental.Policy('mixed_bfloat16')
 else: policy = tf.keras.mixed_precision.experimental.Policy('mixed_float16')
 mixed_precision.set_policy(policy)
 print('Mixed precision enabled')
 if XLA_ACCELERATE:
tf.config.optimizer.set_jit(True)
 print('Accelerated Linear Algebra enabled' )
new_families = df.loc[(df.Surname != 'DeadMan')&(df.Surname != 'LivedPassenger')&(df.Surname != 'DeadPassenger')&(df.Surname != 'LivedFamily')&(df.Surname != 'DeadFamily')]
new_families_list =(df['Surname'].value_counts().index)[ df['Surname'].value_counts() < 5 ]
new_families<count_values>
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']
df['Surname'] = df['Surname'].replace('Billiard', 'DeadFamily')
 df['Surname'] = df['Surname'].replace(new_families_list, 'LivedFamily')
 df['Surname'].value_counts()<feature_engineering>
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), ', should 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()
df['SurnameSurvival'] = 0
df.loc[(df.Surname == 'LivedPassenger'), 'SurnameSurvival'] = 1
df.loc[(df.Surname == 'LivedFamily'), 'SurnameSurvival'] = 1<filter>
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
prediction = df['SurnameSurvival'].loc[test_index]
prediction<save_to_csv>
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_labeled_id_tfrecord(example):
LABELED_ID_TFREC_FORMAT = {
"image": tf.io.FixedLenFeature([], tf.string),
"class": tf.io.FixedLenFeature([], tf.int64),
"id": tf.io.FixedLenFeature([], tf.string),
}
example = tf.io.parse_single_example(example, LABELED_ID_TFREC_FORMAT)
 image = decode_image(example['image'])
 label = tf.cast(example['class'], tf.int32)
 idnum = example['id']
return image, label, idnum
submission_df = {"PassengerId": holdout_ids,
"Survived": prediction}
submission = pd.DataFrame(submission_df)
 submission.to_csv("submission.csv",index=False )<load_from_csv>
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
train = pd.read_csv("/kaggle/input/titanic/train.csv")
 test = pd.read_csv("/kaggle/input/titanic/test.csv" )<set_options>
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_id_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls=AUTO)
 return dataset
%matplotlib inline
train[num_features].hist(bins=8, figsize=(10,10))<count_values>
def get_training_dataset() :
train = load_dataset(TRAINING_FILENAMES, labeled = True)
 train = train.map(lambda image, label, idnum: [image, label])
 train = train.repeat()
train = train.shuffle(2048)
 train = train.batch(BATCH_SIZE)
 train = train.prefetch(AUTO)
 return train
def get_training_dataset_preview(ordered = True):
train = load_dataset(TRAINING_FILENAMES, labeled = True, ordered = ordered)
 train = train.batch(BATCH_SIZE)
 train = train.cache()
train = train.prefetch(AUTO)
 return train
num_passengers_in_train_set = 891
num_pass_without_child_or_parent = train.loc[train.Parch == 0]['Parch'].count()
percent_pass_without_child_or_parent = 100 * num_pass_without_child_or_parent / num_passengers_in_train_set
print("%2d passengers(%2d%%)travelled without a parent or child" %(num_pass_without_child_or_parent, percent_pass_without_child_or_parent))
num_pass_without_sib_or_spouse = train.loc[train.SibSp == 0]['SibSp'].count()
percent_pass_without_sib_or_spouse = 100 * num_pass_without_sib_or_spouse / num_passengers_in_train_set
print("%2d passengers(%2d%%)travelled without a sibling or spouse" %(num_pass_without_sib_or_spouse, percent_pass_without_sib_or_spouse))<filter>
def get_validation_dataset(ordered = False):
validation = load_dataset(VALIDATION_FILENAMES, labeled = True, ordered = ordered)
 validation = validation.map(lambda image, label, idnum: [image, label])
 validation = validation.batch(BATCH_SIZE)
 validation = validation.cache()
validation = validation.prefetch(AUTO)
 return validation
train.loc[train.Cabin == 'C23 C25 C27'][['Name', 'Ticket']].values<filter>
def get_test_dataset(ordered = False):
test = load_dataset(TEST_FILENAMES, labeled = False, ordered = ordered)
 test = test.batch(BATCH_SIZE)
 test = test.prefetch(AUTO)
 return test
train.loc[train.Ticket == '347082'][['Name', 'Ticket', 'Cabin', 'Fare', 'Pclass']].values<define_variables>
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_children = train.loc[train.Age <= 12].copy()
num_children = train_children.shape[0]
num_children_survived = train_children[train_children.Survived == 1].shape[0]
percent_children_survived = 100 * num_children_survived / num_children
num_children_in_pc1 = train_children.loc[train_children.Pclass == 1].shape[0]
num_children_in_pc2 = train_children.loc[train_children.Pclass == 2].shape[0]
num_children_in_pc3 = train_children.loc[train_children.Pclass == 3].shape[0]
print('%d(%d%%)of the %d children(<=12 years)survived' %(num_children_survived, percent_children_survived, num_children))
print('%d, %d and %d children travelled in 1st, 2nd and 3rd class respectively' %(num_children_in_pc1,num_children_in_pc2, num_children_in_pc3))
train_children[['Pclass', 'Survived']].groupby(['Pclass'], as_index=False ).mean().sort_values(by='Pclass', ascending=True )<sort_values>
train_dataset_aug = get_training_dataset()
display_batch_of_images(next(iter(train_dataset_aug.unbatch().batch(20))))
display_batch_of_images(next(iter(train_dataset_aug.unbatch().batch(20))))
display_batch_of_images(next(iter(train_dataset_aug.unbatch().batch(20))))
train[['Sex', 'Survived']].groupby(['Sex'], as_index=False ).mean().sort_values(by='Survived', ascending=False )<filter>
validation_dataset_aug = get_validation_dataset()
display_batch_of_images(next(iter(validation_dataset_aug.unbatch().batch(20))))
display_batch_of_images(next(iter(validation_dataset_aug.unbatch().batch(20))))
display_batch_of_images(next(iter(validation_dataset_aug.unbatch().batch(20))))
train.loc[pd.isnull(train.Embarked)]<filter>
test_dataset_aug = get_test_dataset()
display_batch_of_images(next(iter(test_dataset_aug.unbatch().batch(20))))
display_batch_of_images(next(iter(test_dataset_aug.unbatch().batch(20))))
display_batch_of_images(next(iter(test_dataset_aug.unbatch().batch(20))))
train.loc[train.Cabin == 'B28']<filter>
def lrfn(epoch):
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 =.8
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(25 if EPOCHS<25 else 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]))
train.loc[train.Ticket == '113572']<create_dataframe>
with strategy.scope() :
rnet = DenseNet201(
 input_shape =(512, 512, 3),
weights = 'imagenet',
include_top = False 
)
 rnet.trainable = True
model = tf.keras.Sequential([
rnet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation = 'softmax')
 ])
 model.compile(
 optimizer=tf.keras.optimizers.Adam() ,
loss = 'sparse_categorical_crossentropy',
metrics = ['sparse_categorical_accuracy'] 
)
 model.summary()
model.save('ML_finalproject.h5' )
test_passenger_ids = test['PassengerId']
for data in [train, test]:
data.drop(['Ticket', 'Cabin', 'PassengerId'], axis=1, inplace=True)
 for data in [train, test]:
imputer = SimpleImputer(strategy='median')
 data_trans = pd.DataFrame(imputer.fit_transform(data[['Fare']]), columns=['Fare'], index=data.index)
 data.update(data_trans)
 for data in [train, test]:
imputer = SimpleImputer(strategy='most_frequent')
 data_trans = pd.DataFrame(imputer.fit_transform(data[['Embarked']]), columns=['Embarked'], index=data.index)
 data.update(data_trans )<categorify>
gc.enable()
def get_training_dataset_raw() :
dataset = load_dataset(TRAINING_FILENAMES, labeled = True, ordered = False)
 return dataset
raw_training_dataset = get_training_dataset_raw()
label_counter = Counter()
for images, labels, id in raw_training_dataset:
label_counter.update([labels.numpy() ])
 del raw_training_dataset
TARGET_NUM_PER_CLASS = 122
def get_weight_for_class(class_id):
counting = label_counter[class_id]
weight = TARGET_NUM_PER_CLASS / counting
return weight
weight_per_class = {class_id: get_weight_for_class(class_id)for class_id in range(104)}
train_dummies = pd.get_dummies(train, columns=['Embarked'], prefix=['Embarked'])
 train = train_dummies
test_dummies = pd.get_dummies(test, columns=['Embarked'], prefix=['Embarked'])
 test = test_dummies
train['Sex'] = train['Sex'].apply(lambda x: 1 if x == 'male' else 0)
 test['Sex'] = test['Sex'].apply(lambda x: 1 if x == 'male' else 0)
<feature_engineering>
history = model.fit(
 get_training_dataset() ,
steps_per_epoch = STEPS_PER_EPOCH,
epochs = EPOCHS,
callbacks = [lr_callback],
validation_data = get_validation_dataset() ,
class_weight = weight_per_class
)
for data in [train, test]:
data['Title'] = data.Name.str.extract('([A-Za-z]+)\.', expand=False)
 pd.crosstab(train['Title'], train['Sex'] )<groupby>
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 )
for data in [train, test]:
data['Title'].replace('Mlle', 'Miss', inplace=True)
 data['Title'].replace('Ms', 'Miss', inplace=True)
 data['Title'].replace('Mme', 'Mrs', inplace=True)
 train[['Title', 'Survived']].groupby(['Title'], as_index=False ).count()<groupby>
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))
<categorify><EOS> 
test_ds = get_test_dataset(ordered = True)
 test_images_ds = test_ds.map(lambda image, idnum: image)
 probabilities = model.predict(test_images_ds)
 predictions = np.argmax(probabilities, axis = -1)
 print(predictions)
 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')
 test = pd.DataFrame({"id": test_ids, "label": predictions})
 print(test.head)
 test.to_csv("submission.csv",index = False )