Kaggle competition: Flower Classification with TPUs
<SOS> metric: MacroFScore Kaggle data source: flower-classification-with-tpus<data_type_conversions>
!pip install -q efficientnet
col_convert = ['Survived']
df_ticket[col_convert] = df_ticket[col_convert].astype(float )<data_type_conversions>
print("Tensorflow version " + tf.__version__)
df_ticket['Together'] = df_ticket['Survived'].apply(lambda x: 1 if x == 0 or x == 1 else 0 ).astype('object' )<merge>
AUTO = tf.data.experimental.AUTOTUNE
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)
 GCS_DS_PATH = KaggleDatasets().get_gcs_path('flower-classification')
 GCS_DS_PATH2 = KaggleDatasets().get_gcs_path('tf-flower-photo-tfrec')
 img_size=512
IMAGE_SIZE = [img_size, img_size]
EPOCHS = 25
BATCH_SIZE = 16 * strategy.num_replicas_in_sync
df_data = pd.merge(df_data, df_ticket[['Ticket', 'Sex_male', 'Sex_female', 'Title_Crew', 'Title_Dr', 'Title_Master', 'Title_Miss', 'Title_Mr', 'Title_Mrs', 'Title_Royal']], how='left', left_on='Ticket', right_on='Ticket' ).rename(columns={
'Sex_male': 'WithSexMale', 'Sex_female': 'WithSexFemale',
'Title_Crew': 'WithTitleCrew', 'Title_Dr': 'WithTitleDr', 'Title_Master': 'WithTitleMaster', 'Title_Miss': 'WithTitleMiss', 'Title_Mr': 'WithTitleMr', 'Title_Mrs': 'WithTitleMrs', 'Title_Royal': 'WithTitleRoyal'
})
 col_fillnas = ['WithSexMale', 'WithSexFemale', 'WithTitleCrew', 'WithTitleDr', 'WithTitleMaster', 'WithTitleMiss', 'WithTitleMr', 'WithTitleMrs', 'WithTitleRoyal']
for col_fillna in col_fillnas: df_data[col_fillna] = df_data[col_fillna].fillna(0 )<data_type_conversions>
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
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]))
df_temp = df_data.copy(deep=True)
 df_temp['Survived'] = df_temp['Survived'].astype(float)
 df_ticket_self = df_temp.groupby(['Ticket'], as_index=True)
 count = df_ticket_self['Survived'].transform('count')
 mean = df_ticket_self['Survived'].transform('mean')
 df_data['SurvivedPeer'] =(mean * count - df_data['Survived'].astype(float)) /(count - 1)
 df_data['SurvivedPeer'] = df_data['SurvivedPeer'].astype(float ).fillna(-1 )<categorify>
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_SELECT2 = {
192: GCS_DS_PATH2 + '/oxford102/tfrecords-jpeg-192x192',
224: GCS_DS_PATH2 + '/oxford102/tfrecords-jpeg-224x224',
331: GCS_DS_PATH2 + '/oxford102/tfrecords-jpeg-331x331',
512: GCS_DS_PATH2 + '/oxford102/tfrecords-jpeg-512x512'
}
GCS_PATH_SELECT3 = {
192: GCS_DS_PATH2 + '/imagenet/tfrecords-jpeg-192x192',
224: GCS_DS_PATH2 + '/imagenet/tfrecords-jpeg-224x224',
331: GCS_DS_PATH2 + '/imagenet/tfrecords-jpeg-331x331',
512: GCS_DS_PATH2 + '/imagenet/tfrecords-jpeg-512x512'
}
GCS_PATH_SELECT4 = {
192: GCS_DS_PATH2 + '/inaturalist/tfrecords-jpeg-192x192',
224: GCS_DS_PATH2 + '/inaturalist/tfrecords-jpeg-224x224',
331: GCS_DS_PATH2 + '/inaturalist/tfrecords-jpeg-331x331',
512: GCS_DS_PATH2 + '/inaturalist/tfrecords-jpeg-512x512'
}
GCS_PATH_SELECT5 = {
192: GCS_DS_PATH2 + '/inaturalist_1/tfrecords-jpeg-192x192',
224: GCS_DS_PATH2 + '/inaturalist_1/tfrecords-jpeg-224x224',
331: GCS_DS_PATH2 + '/inaturalist_1/tfrecords-jpeg-331x331',
512: GCS_DS_PATH2 + '/inaturalist_1/tfrecords-jpeg-512x512'
}
GCS_PATH_SELECT6 = {
192: GCS_DS_PATH2 + '/tf_flowers/tfrecords-jpeg-192x192',
224: GCS_DS_PATH2 + '/tf_flowers/tfrecords-jpeg-224x224',
331: GCS_DS_PATH2 + '/tf_flowers/tfrecords-jpeg-331x331',
512: GCS_DS_PATH2 + '/tf_flowers/tfrecords-jpeg-512x512'
}
GCS_PATH_SELECT7 = {
192: GCS_DS_PATH2 + '/openimage/tfrecords-jpeg-192x192',
224: GCS_DS_PATH2 + '/openimage/tfrecords-jpeg-224x224',
331: GCS_DS_PATH2 + '/openimage/tfrecords-jpeg-331x331',
512: GCS_DS_PATH2 + '/openimage/tfrecords-jpeg-512x512'
}
GCS_PATH = GCS_PATH_SELECT[IMAGE_SIZE[0]]
GCS_PATH2 = GCS_PATH_SELECT2[IMAGE_SIZE[0]]
GCS_PATH3 = GCS_PATH_SELECT3[IMAGE_SIZE[0]]
GCS_PATH4 = GCS_PATH_SELECT4[IMAGE_SIZE[0]]
GCS_PATH5 = GCS_PATH_SELECT5[IMAGE_SIZE[0]]
GCS_PATH6 = GCS_PATH_SELECT6[IMAGE_SIZE[0]]
GCS_PATH7 = GCS_PATH_SELECT7[IMAGE_SIZE[0]]
TRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/train/*.tfrec')
 TRAINING_FILENAMES2 = tf.io.gfile.glob(GCS_PATH2 + '/*.tfrec')
 TRAINING_FILENAMES3 = tf.io.gfile.glob(GCS_PATH3 + '/*.tfrec')
 TRAINING_FILENAMES4 = tf.io.gfile.glob(GCS_PATH4 + '/*.tfrec')
 TRAINING_FILENAMES5 = tf.io.gfile.glob(GCS_PATH5 + '/*.tfrec')
 TRAINING_FILENAMES6 = tf.io.gfile.glob(GCS_PATH6 + '/*.tfrec')
 TRAINING_FILENAMES7 = tf.io.gfile.glob(GCS_PATH7 + '/*.tfrec')
 TRAINING_FILENAMES=TRAINING_FILENAMES+TRAINING_FILENAMES2+TRAINING_FILENAMES3+TRAINING_FILENAMES5+TRAINING_FILENAMES6+TRAINING_FILENAMES7
VALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec')
 TEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec')
 SKIP_VALIDATION = True
if SKIP_VALIDATION:
TRAINING_FILENAMES = TRAINING_FILENAMES + VALIDATION_FILENAMES
df_temp = df_data.copy(deep=True)
 df_temp['Survived'] = df_temp['Survived'].astype(float)
 col_revises = ['Crew', 'Dr', 'Master', 'Miss', 'Mr', 'Mrs', 'Royal']
for col_revise in col_revises:
df_temp['Survived' + col_revise] = df_temp['Survived']
df_temp.loc[df_temp['Title'] != col_revise, 'Survived' + col_revise] = np.nan
df_ticket_title = df_temp.groupby(['Ticket'], as_index=True)
 for col_revise in col_revises:
count = df_ticket_title['Survived' + col_revise].transform('count')
 mean = df_ticket_title['Survived' + col_revise].transform('mean')
 df_data['SurvivedPeer' + col_revise] =(mean * count - df_temp['Survived' + col_revise].astype(float)) /(count - 1)
 df_data['SurvivedPeer' + col_revise] = df_data['SurvivedPeer' + col_revise].astype(float ).fillna(-1 )<feature_engineering>
MIXED_PRECISION = True
XLA_ACCELERATE = True
if MIXED_PRECISION:
if tpu: policy = tf.keras.mixed_precision.experimental.Policy('mixed_bfloat16')
 else: policy = tf.keras.mixed_precision.experimental.Policy('float32')
 mixed_precision.set_policy(policy)
 print('Mixed precision enabled')
 if XLA_ACCELERATE:
tf.config.optimizer.set_jit(True)
 print('Accelerated Linear Algebra enabled' )
df_data['Survived'] = df_data['Survived'].fillna(-1 )<categorify>
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_data = pd.get_dummies(df_data, columns=['Pclass', 'Sex', 'Embarked', 'DataType', 'Title', 'TicketString', 'HasTicketString', 'CabinString', 'HasCabin'], drop_first=True )<data_type_conversions>
def random_blockout(img, sl=0.1, sh=0.2, rl=0.4):
h, w, c = img_size, img_size, 3
origin_area = tf.cast(h*w, tf.float32)
 e_size_l = tf.cast(tf.round(tf.sqrt(origin_area * sl * rl)) , tf.int32)
 e_size_h = tf.cast(tf.round(tf.sqrt(origin_area * sh / rl)) , tf.int32)
 e_height_h = tf.minimum(e_size_h, h)
 e_width_h = tf.minimum(e_size_h, w)
 erase_height = tf.random.uniform(shape=[], minval=e_size_l, maxval=e_height_h, dtype=tf.int32)
 erase_width = tf.random.uniform(shape=[], minval=e_size_l, maxval=e_width_h, dtype=tf.int32)
 erase_area = tf.zeros(shape=[erase_height, erase_width, c])
 erase_area = tf.cast(erase_area, tf.uint8)
 pad_h = h - erase_height
pad_top = tf.random.uniform(shape=[], minval=0, maxval=pad_h, dtype=tf.int32)
 pad_bottom = pad_h - pad_top
pad_w = w - erase_width
pad_left = tf.random.uniform(shape=[], minval=0, maxval=pad_w, dtype=tf.int32)
 pad_right = pad_w - pad_left
erase_mask = tf.pad([erase_area], [[0,0],[pad_top, pad_bottom], [pad_left, pad_right], [0,0]], constant_values=1)
 erase_mask = tf.squeeze(erase_mask, axis=0)
 erased_img = tf.multiply(tf.cast(img,tf.float32), tf.cast(erase_mask, tf.float32))
return tf.cast(erased_img, img.dtype )
col_convert = ['Survived', 'SibSp', 'Parch', 'FamilySize']
df_data[col_convert] = df_data[col_convert].astype(int )<prepare_x_and_y>
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 =(1 - SKIP_VALIDATION)* 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))
x = df_data[df_data['DataType_training'] == 1].drop(['PassengerId', 'Survived', 'Name', 'Ticket', 'Cabin', 'Surname', 'FamilySize', 'DataType_training', 'SurvivedPeerCrew', 'SurvivedPeerDr', 'SurvivedPeerMaster', 'SurvivedPeerMiss', 'SurvivedPeerMr', 'SurvivedPeerMrs', 'SurvivedPeerRoyal'], axis=1)
 y = df_data.loc[df_data['DataType_training'] == 1, 'Survived']<train_model>
forestclf = RandomForestClassifier(n_estimators=100, random_state=58 ).fit(x, y)
 feat = pd.DataFrame(data=forestclf.feature_importances_, index=x.columns, columns=['FeatureImportances'] ).sort_values(['FeatureImportances'], ascending=False )<features_selection>
model_feat = feat[feat['FeatureImportances'] > 0.005].index<prepare_x_and_y>
x = df_data.loc[df_data['DataType_training'] == 1, model_feat]
y = df_data.loc[df_data['DataType_training'] == 1, 'Survived']<split>
x_train, x_validate, y_train, y_validate = train_test_split(x, y, test_size=0.25, random_state=58 )<compute_train_metric>
with strategy.scope() :
net=MobileNetV2(
 input_shape=(512, 512, 3),
weights='imagenet',
include_top=False 
)
 model = tf.keras.Sequential([
net,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax',dtype=tf.float32)
 ])
 model.compile(
 optimizer=tf.keras.optimizers.Adam(lr=0.0001),
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 model.summary()
<find_best_model_class><EOS> 
history = model.fit(
 get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS,
callbacks=[lr_callback],
validation_data=None if SKIP_VALIDATION else get_validation_dataset() 
)
 model.save_weights("model.h5")
 test_ds = get_test_dataset(ordered=True)
 print('Computing predictions...')
 test_images_ds = test_ds.map(lambda image, idnum: image)
 preds1=model.predict(test_images_ds)
 del model
gc.collect()
tf.tpu.experimental.initialize_tpu_system(tpu )