Kaggle competition: Flower Classification with TPUs
<SOS> metric: MacroFScore Kaggle data source: flower-classification-with-tpus<feature_engineering>
import numpy as np
import pandas as pd
training.loc[training["n_new"] == 'Mr', 'Title'] = 1
training.loc[training["n_new"] == 'Miss', 'Title'] = 4
training.loc[training["n_new"] == 'Mrs', 'Title'] = 5
training.loc[training["n_new"] == 'Master', 'Title'] = 3
training.loc[training["n_new"] == 'Dr', 'Title'] = 2<define_variables>
!pip install -q efficientnet
print("Tensorflow version " + tf.__version__)
 AUTO = tf.data.experimental.AUTOTUNE
print("The number of traning examples(data points)= %i " % training.shape[0])
 print("The number of features we have = %i " % training.shape[1] )<count_unique_values>
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 )
unique, count= np.unique(training["Survived"], return_counts=True)
 print("The number of occurances of each class in the dataset = %s " % dict(zip(unique, count)) , "
" )<count_missing_values>
GCS_DS_PATH = KaggleDatasets().get_gcs_path()
training.isna().sum()<feature_engineering>
VALIDATION = False
if not VALIDATION:
TRAINING_FILENAMES = TRAINING_FILENAMES + VALIDATION_FILENAMES
C = training.Cabin[training.Cabin.isna() ]
C_not = training.Cabin[training.Cabin.notna() ]
C.values[:] = 0
C_not.values[:] = 1<concatenate>
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 display_confusion_matrix(cmat, score, precision, recall):
plt.figure(figsize=(15,15))
ax = plt.gca()
ax.matshow(cmat, cmap='Reds')
 ax.set_xticks(range(len(CLASSES)))
 ax.set_xticklabels(CLASSES, fontdict={'fontsize': 7})
 plt.setp(ax.get_xticklabels() , rotation=45, ha="left", rotation_mode="anchor")
 ax.set_yticks(range(len(CLASSES)))
 ax.set_yticklabels(CLASSES, fontdict={'fontsize': 7})
 plt.setp(ax.get_yticklabels() , rotation=45, ha="right", rotation_mode="anchor")
 titlestring = ""
if score is not None:
titlestring += 'f1 = {:.3f} '.format(score)
 if precision is not None:
titlestring += '
precision = {:.3f} '.format(precision)
 if recall is not None:
titlestring += '
recall = {:.3f} '.format(recall)
 if len(titlestring)> 0:
ax.text(101, 1, titlestring, fontdict={'fontsize': 18, 'horizontalalignment':'right', 'verticalalignment':'top', 'color':'
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.'] )
cabine_not = pd.concat([C, C_not] ).sort_index()<data_type_conversions>
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
def data_augment(image, label):
image = tf.image.random_flip_left_right(image)
 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_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)
 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))
np.random.seed(0)
 training['sp'] = training.SibSp + training['Parch']
training['cabine_n'] = cabine_not
training.cabine_n = training.cabine_n.astype(int)
 training.drop(["n_new", "Name" ,"Embarked", "PassengerId","Ticket","Cabin"], inplace = True, axis = 1 )<prepare_x_and_y>
print("Training data shapes:")
 for image, label in get_training_dataset().take(3):
print(image.numpy().shape, label.numpy().shape)
 print("Training data label examples:", label.numpy())
 print("Validation data shapes:")
 for image, label in get_validation_dataset().take(3):
print(image.numpy().shape, label.numpy().shape)
 print("Validation data label examples:", label.numpy())
 print("Test data shapes:")
 for image, idnum in get_test_dataset().take(3):
print(image.numpy().shape, idnum.numpy().shape)
 print("Test data IDs:", idnum.numpy().astype('U'))
x_train = training
repCol9 = {1 : 3 , 2 : 2 , 3 : 1 }
x_train['IsAlone'] = 1
x_train['IsAlone'].loc[x_train['sp'] > 0] = 0
x_train.replace({'Pclass': repCol9} , inplace = True)
 x_train = pd.get_dummies(x_train)
 y_train = x_train["Survived"]
x_train = x_train.drop(['Survived'], axis = 1)
 print(y_train.shape)
 y_train.head(20)
 x_train.head()<data_type_conversions>
training_dataset = get_training_dataset()
training_dataset = training_dataset.unbatch().batch(20)
 train_batch = iter(training_dataset )
imp = IterativeImputer(max_iter=10, random_state=0)
 x = imp.fit_transform(x_train)
 x_train = pd.DataFrame(x, columns = x_train.columns)
 x_train[[ 'Pclass', 'SibSp', 'Parch', 'Title', 'sp',
'cabine_n', 'IsAlone', 'Sex_female', 'Sex_male']] = x_train[[ 'Pclass', 'SibSp', 'Parch', 'Title', 'sp',
'cabine_n', 'IsAlone', 'Sex_female', 'Sex_male']].astype(int )<compute_test_metric>
display_batch_of_images(next(train_batch))
z = np.abs(stats.zscore(x_train))
zee =(np.where(z > 3)) [1]
print("number of data examples greater than 3 standard deviations = %i " % len(zee)) 
<feature_engineering>
test_dataset = get_test_dataset()
test_dataset = test_dataset.unbatch().batch(20)
 test_batch = iter(test_dataset )
x_test['n_new']= x_test['Name'].apply(lambda x: x.split(',')[1].split('.')[0].strip() )<feature_engineering>
display_batch_of_images(next(test_batch))
x_test['Title'] = 0
x_test.loc[x_test["n_new"] == 'Mr', 'Title'] = 1
x_test.loc[x_test["n_new"] == 'Miss', 'Title'] = 4
x_test.loc[x_test["n_new"] == 'Mrs', 'Title'] = 5
x_test.loc[x_test["n_new"] == 'Master', "Title"] = 3
x_test.loc[x_test["n_new"] == 'Dr', 'Title'] = 2<categorify>
with strategy.scope() :
dn201 = tf.keras.applications.DenseNet201(weights='imagenet',
include_top=False,
input_shape=[*IMAGE_SIZE, 3])
 dn201.trainable = True
model1 = tf.keras.Sequential([
dn201,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model1.compile(
 optimizer = tf.keras.optimizers.Adam(learning_rate=0.001,
beta_1=0.9,
beta_2=0.999,
amsgrad=False),
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 model1.summary()
C = x_test.Cabin[x_test.Cabin.isna() ]
C_not = x_test.Cabin[x_test.Cabin.notna() ]
C.values[:] = 0
C_not.values[:] = 1
x_test['sp'] = x_test.SibSp + x_test['Parch']
x_test['cabine_n'] = cabine_not
x_test.cabine_n = x_test.cabine_n.astype(int)
 x_test['IsAlone'] = 1
x_test['IsAlone'].loc[x_test['sp'] > 0] = 0
x_test.drop(["Name", "Embarked", "Ticket", "n_new", "Cabin"], inplace = True, axis = 1)
 x_test.replace({'Pclass': repCol9} , inplace = True)
 x_test = pd.get_dummies(x_test)
 x_test.head()<count_values>
with strategy.scope() :
enb7 = efn.EfficientNetB7(weights = 'noisy-student',
include_top = False,
input_shape = [*IMAGE_SIZE, 3])
 enb7.trainable = True
model2 = tf.keras.Sequential([
enb7,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model2.compile(
 optimizer = tf.keras.optimizers.Adam(learning_rate = 0.001,
beta_1 = 0.9,
beta_2 = 0.999,
amsgrad = False),
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 model2.summary()
fact = y_train[y_train == 0].count() / y_train[y_train == 1].count()
class_weight = {1: fact, 0: 1.}<choose_model_class>
LR_START = 0.0001
LR_MAX = 0.00005 * strategy.num_replicas_in_sync
LR_MIN = 0.00001
LR_RAMPUP_EPOCHS = 4
LR_SUSTAIN_EPOCHS = 6
LR_EXP_DECAY =.8
def lrfn(epoch):
if epoch < LR_RAMPUP_EPOCHS:
lr = np.random.random_sample() * 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 )
InputDimension = 11
print(y_train.shape)
 model = Sequential()
model.add(Dense(25,input_dim=InputDimension, activation='relu'))
model.add(Dense(50, activation='relu'))
model.add(Dense(100, activation='relu'))
model.add(Dense(100, activation='relu'))
model.add(Dense(100, activation='relu'))
model.add(Dense(100, activation='relu'))
model.add(Dense(2, activation='softmax'))
earlystopping = callbacks.EarlyStopping(monitor='val_loss', min_delta=0, patience=30, verbose=0, mode='min')
 optimizer = optimizers.Adam(lr=0.001, decay=0.0001)
 model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['acc'])
 history = model.fit(x_train, pd.get_dummies(y_train), epochs=2000, batch_size=60, validation_split=0.2, verbose=1, callbacks=[earlystopping], class_weight = class_weight )<data_type_conversions>
es_callback = tf.keras.callbacks.EarlyStopping(min_delta = 0,
patience = 10,
verbose = 1,
mode = 'auto',
restore_best_weights = True )
id = x_test['PassengerId']
x_test.drop(['PassengerId'], inplace = True, axis = 1)
 imp = IterativeImputer(max_iter=10, random_state=0)
 x = imp.fit_transform(x_test)
 x_test = pd.DataFrame(x, columns = x_train.columns)
 x_test[[ 'Pclass', 'SibSp', 'Parch', 'Title', 'sp',
'cabine_n', 'IsAlone', 'Sex_female', 'Sex_male']] = x_test[['Pclass', 'SibSp', 'Parch', 'Title', 'sp',
'cabine_n', 'IsAlone', 'Sex_female', 'Sex_male']].astype(int )<predict_on_test>
if VALIDATION:
history1 = model1.fit(get_training_dataset() ,
steps_per_epoch = STEPS_PER_EPOCH,
epochs = 40,
validation_data = get_validation_dataset() ,
callbacks = [lr_callback, es_callback])
 else:
history1 = model1.fit(get_training_dataset() ,
steps_per_epoch = STEPS_PER_EPOCH,
epochs = 30,
callbacks = [lr_callback] )
predictions = model.predict(x_test )<prepare_output>
if VALIDATION:
history2 = model2.fit(get_training_dataset() ,
steps_per_epoch = STEPS_PER_EPOCH,
epochs = 40,
validation_data = get_validation_dataset() ,
callbacks = [lr_callback, es_callback])
 else:
history2 = model2.fit(get_training_dataset() ,
steps_per_epoch = STEPS_PER_EPOCH,
epochs = 30,
callbacks = [lr_callback] )
predictions = np.argmax(predictions, axis = 1 )<save_to_csv>
if 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 =(model1.predict(images_ds)*0.3)+model2.predict(images_ds)*0.7
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 )
id.reset_index(drop=True, inplace=True)
 out = pd.DataFrame({'PassengerId': id, "Survived": predictions})
 out.to_csv('titanic-predictions.csv', index = False)
 out.head(100 )<set_options>
if 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))
<load_from_csv><EOS> 
test_ds = get_test_dataset(ordered=True)
 print('Computing predictions...')
 test_images_ds = test_ds.map(lambda image, idnum: image)
 probabilities =(model1.predict(test_images_ds)+model2.predict(test_images_ds)) /2
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