Kaggle competition: Petals to the Metal - Flower Classification on TPU
<SOS> metric: macrofscore Kaggle data source: petals-to-the-metal-flower-classification-on-tpu<prepare_output>
print("Tensorflow version " + tf.__version__ )
result_data = {'ImageID': [i for i in range(1, len(results_classes)+1)],
'Label': results_classes
}
results_df = pd.DataFrame(result_data)
 results_df.head()<save_to_csv>
!pip install -q efficientnet
results_df.to_csv('MNIST_data_output_using_CNN_30_epochs.csv', index = False )<set_options>
%matplotlib inline<load_from_csv>
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 )
train_df = pd.read_csv('.. /input/train.csv')
 test_df = pd.read_csv('.. /input/test.csv' )<prepare_x_and_y>
GCS_DS_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started')
 print(GCS_DS_PATH )
x_train = train_df.drop('label', axis=1 ).values
y_train = train_df['label'].values
x_test = test_df.values<train_model>
IMAGE_SIZE = [224, 224]
GCS_PATH = GCS_DS_PATH + '/tfrecords-jpeg-224x224'
AUTO = tf.data.experimental.AUTOTUNE
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']
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
img_height, img_width = 28, 28
x_train = x_train.reshape(x_train.shape[0], img_height, img_width, 1)
 x_test = x_test.reshape(x_test.shape[0], img_height, img_width, 1 )<concatenate>
aug = tf.keras.Sequential([
tf.keras.layers.experimental.preprocessing.RandomFlip("horizontal"),
tf.keras.layers.experimental.preprocessing.RandomRotation(0.7),
tf.keras.layers.experimental.preprocessing.RandomTranslation(0.6,0.6),
tf.keras.layers.experimental.preprocessing.RandomContrast(( 0.5,1))
] )
num_classes = 10
y_train = np_utils.to_categorical(y_train, num_classes )<feature_engineering>
BATCH_SIZE = 16 * strategy.num_replicas_in_sync
ds_train = get_training_dataset()
ds_valid = get_validation_dataset()
ds_test = get_test_dataset()
print("Training:", ds_train)
 print("Validation:", ds_valid)
 print("Test:", ds_test )
x_test = x_test / 255.0
x_train = x_train / 255.0<choose_model_class>
np.set_printoptions(threshold=15, linewidth=80)
 print("Training data shapes:")
 for image, label in ds_train.take(3):
print(image.numpy().shape, label.numpy().shape)
 print("Training data label examples:", label.numpy() )
model = Sequential()
model.add(Conv2D(
 filters=32,
kernel_size=(5,5),
input_shape=(img_height, img_width, 1),
padding="Same",
activation="relu" 
))
model.add(Conv2D(
 filters=32,
kernel_size=(5,5),
input_shape=(img_height, img_width, 1),
padding="Same",
activation="relu" 
))
model.add(MaxPooling2D(pool_size=(2,2)))
 model.add(Dropout(0.25))
model.add(Conv2D(
 filters=64,
kernel_size=(3,3),
input_shape=(img_height, img_width, 1),
padding="Same",
activation="relu" 
))
model.add(Conv2D(
 filters=64,
kernel_size=(3,3),
input_shape=(img_height, img_width, 1),
padding="Same",
activation="relu" 
))
model.add(MaxPooling2D(pool_size=(2,2), strides=(2,2)))
 model.add(Dropout(0.25))
model.add(Flatten())
 model.add(Dense(256, activation="relu"))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation="softmax"))<choose_model_class>
print("Test data shapes:")
 for image, idnum in ds_test.take(3):
print(image.numpy().shape, idnum.numpy().shape)
 print("Test data IDs:", idnum.numpy().astype('U'))
model.compile(loss="categorical_crossentropy", optimizer="adam", metrics=["accuracy"])
 print(model.summary() )<choose_model_class>
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_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.'] )
checkpoint = ModelCheckpoint(
 'best_model.hdf5',
monitor='val_acc',
save_best_only=True,
verbose=1
)<choose_model_class>
ds_iter = iter(ds_train.unbatch().batch(20))
lr_reduction = ReduceLROnPlateau(
 monitor='val_acc',
patience=3,
factor=0.5,
min_lr=0.00001,
verbose=1
)<define_variables>
one_batch = next(ds_iter)
 display_batch_of_images(one_batch )
batch_size = 96
epochs = 40
validation_size = 0.3<train_model>
EPOCHS = 50
with strategy.scope() :
eb7 = enet.EfficientNetB7(input_shape=[*IMAGE_SIZE, 3], weights='noisy-student', include_top=False)
 eb7.trainable = True
model1 = tf.keras.Sequential([
eb7,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 for layer in model1.layers:
if isinstance(layer, tf.keras.layers.BatchNormalization):
layer.momentum = 0.9
model1.compile(
 optimizer=tf.keras.optimizers.Adam() ,
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'],
)
history = model.fit(
 x=x_train,
y=y_train,
batch_size=batch_size,
epochs=epochs,
verbose=1,
validation_split=validation_size,
callbacks=[checkpoint, lr_reduction]
)<load_pretrained>
def exponential_lr(epoch,
start_lr = 0.00001, min_lr = 0.00001, max_lr = 0.00005*strategy.num_replicas_in_sync,
rampup_epochs = 5, sustain_epochs = 0,
exp_decay = 0.8):
def lr(epoch, start_lr, min_lr, max_lr, rampup_epochs, sustain_epochs, exp_decay):
if epoch < rampup_epochs:
lr =(( max_lr - start_lr)/
rampup_epochs * epoch + start_lr)
 elif epoch < rampup_epochs + sustain_epochs:
lr = max_lr
else:
lr =(( max_lr - min_lr)*
exp_decay**(epoch - rampup_epochs - sustain_epochs)+
min_lr)
 return lr
return lr(epoch,
start_lr,
min_lr,
max_lr,
rampup_epochs,
sustain_epochs,
exp_decay)
 rng = [i for i in range(30)]
y = [exponential_lr(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]))
model.load_weights('best_model.hdf5' )<predict_on_test>
filepath="flower1.h5"
checkpoint = ModelCheckpoint(filepath, monitor='val_loss', verbose=1, save_best_only=True, mode='min')
 lr_callback = tf.keras.callbacks.LearningRateScheduler(exponential_lr, verbose=True)
 EPOCHS = 35
STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE
history = model1.fit(
 ds_train,
validation_data=ds_valid,
epochs=EPOCHS,
steps_per_epoch=STEPS_PER_EPOCH,
callbacks=[lr_callback, checkpoint],
)
probabilities = model.predict(x_test )<prepare_output>
model1 = tf.keras.models.load_model('./flower1.h5' )
predictions = np.argmax(probabilities, axis=1 )<create_dataframe>
EPOCHS = 50
with strategy.scope() :
pretrained_model = tf.keras.applications.InceptionResNetV2(
 include_top=False,
input_shape=[*IMAGE_SIZE, 3],
weights='imagenet', 
)
 for layer in pretrained_model.layers:
if isinstance(layer, tf.keras.layers.BatchNormalization):
layer.momentum = 0.9
model2 = tf.keras.Sequential([
pretrained_model,
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'],
)
submission = pd.DataFrame(data={
'ImageId': list(range(1, predictions.shape[0]+1)) ,
'Label': predictions
} )<save_to_csv>
filepath="flower2.h5"
checkpoint = ModelCheckpoint(filepath, monitor='val_loss', verbose=1, save_best_only=True, mode='min')
 lr_callback = tf.keras.callbacks.LearningRateScheduler(exponential_lr, verbose=True)
 EPOCHS = 35
STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE
history = model2.fit(
 ds_train,
validation_data=ds_valid,
epochs=EPOCHS,
steps_per_epoch=STEPS_PER_EPOCH,
callbacks=[lr_callback, checkpoint],
)
submission.to_csv('submission.csv', index=False )<save_to_csv>
model2 = tf.keras.models.load_model('./flower2.h5' )
submission.to_csv('submission.csv', index=False )<install_modules>
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()
cm1_probabilities = model1.predict(images_ds)
 cm2_probabilities = model2.predict(images_ds)
 scores = []
for alpha in np.linspace(0,1,100):
cm_probabilities = alpha*cm1_probabilities+(1-alpha)*cm2_probabilities
cm_predictions = np.argmax(cm_probabilities, axis=-1)
 scores.append(f1_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro'))
alpha = np.argmax(scores)/100
print('Best alpha: ' + str(alpha))
!git clone https://gitlab.com/YannBerthelot/kaggle_pystacknet.git
print(os.listdir("kaggle_pystacknet/pystacknet"))
!pip install "kaggle_pystacknet/pystacknet" 
<load_from_csv>
cm_probabilities = alpha*cm1_probabilities+(1-alpha)*cm2_probabilities
cm_predictions = np.argmax(cm_probabilities, axis=-1)
 labels = range(len(CLASSES))
cmat = confusion_matrix(
 cm_correct_labels,
cm_predictions,
labels=labels, 
)
 cmat =(cmat.T / cmat.sum(axis=1)).T
train=pd.read_csv(".. /input/train.csv")
 test=pd.read_csv(".. /input/test.csv" )<feature_engineering>
score = f1_score(
 cm_correct_labels,
cm_predictions,
labels=labels,
average='macro', 
)
 precision = precision_score(
 cm_correct_labels,
cm_predictions,
labels=labels,
average='macro', 
)
 recall = recall_score(
 cm_correct_labels,
cm_predictions,
labels=labels,
average='macro', 
)
 display_confusion_matrix(cmat, score, precision, recall )
def feature_engineering(df):
df["Cabin"]=df["Cabin"].fillna("C")
 deck = {"A": 1, "B": 2, "C": 3, "D": 4, "E": 5, "F": 6, "G": 7, "U": 8}
df['Deck'] = df['Cabin'].map(lambda x: re.compile("([a-zA-Z]+)" ).search(x ).group())
 mean = df["Age"].mean()
std = df["Age"].std()
is_null = df["Age"].isnull().sum()
rand_age = np.random.randint(mean - std, mean + std, size = is_null)
 age_slice = df["Age"].copy()
age_slice[np.isnan(age_slice)] = rand_age
df["Age"] = age_slice
df["Age"] = df["Age"].astype(int)
 df["Embarked"]=df['Embarked'].fillna("S")
 df["Siblings"]=df["SibSp"]+df["Parch"]
df=df.drop(["Name","Ticket","SibSp","Parch","PassengerId","Cabin","Fare"],axis=1)
 return(df)
 train=feature_engineering(train)
 test=feature_engineering(test )<prepare_x_and_y>
dataset = get_validation_dataset()
dataset = dataset.unbatch().batch(20)
 batch = iter(dataset )
X=train.drop("Survived",axis=1)
 Y=train["Survived"]<split>
images, labels = next(batch)
 probabilities1 = model1.predict(images)
 probabilities2 = model2.predict(images)
 probabilities = alpha*probabilities1+(1-alpha)*probabilities2
predictions = np.argmax(probabilities, axis=-1)
 display_batch_of_images(( images, labels), predictions )
x, x_test, y, y_test = train_test_split(X, Y, test_size=0.20, random_state=42,shuffle=True)
 X_oh=pd.get_dummies(X)
 test_oh=pd.get_dummies(test)
 test_oh["Deck_T"]=0<choose_model_class>
test_ds = get_test_dataset(ordered=True)
 print('Computing predictions...')
 test_images_ds = test_ds.map(lambda image, idnum: image)
 probabilities1 = model1.predict(test_images_ds)
 probabilities2 = model2.predict(test_images_ds)
 probabilities = alpha*probabilities1+(1-alpha)*probabilities2
predictions = np.argmax(probabilities, axis=-1)
 print(predictions )
<train_model><EOS> 
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