Kaggle competition: Flower Classification with TPUs
<SOS> metric: MacroFScore Kaggle data source: flower-classification-with-tpus<feature_engineering>
!pip install -q efficientnet
num_col = ['LotFrontage', 'LotArea', '1stFlrSF', 'GrLivArea']
for col in num_col:
all_data[col] = np.log1p(all_data[col] )<feature_engineering>
print('Tensorflow ver:',tf.__version__ )
cat_col = [col for col in all_data.columns if all_data[col].dtypes == 'O']
for col in cat_col:
temp = all_data[col].value_counts() /len(all_data)
 temp_df = temp[temp>0.01].index
all_data[col] = np.where(all_data[col].isin(temp_df),all_data[col],'RareVar' )<split>
try:
tpu = tf.distribute.cluster_resolver.TPUClusterResolver()
tf.config.experimental_connect_to_cluster(tpu)
 tf.tpu.experimental.initialize_tpu_system(tpu)
 print('TPU configured, at',tpu.master())
 except ValueError:
tpu = None
print('TPUs not found! Using CPU')
 if tpu:
strategy = tf.distribute.experimental.TPUStrategy(tpu)
 else:
strategy = tf.distribute.get_strategy()
print('Succeed distributing TPUs!')
 print("REPLICAS: ", strategy.num_replicas_in_sync )
cat_train = all_data.iloc[:len(y), :]
cat_test = all_data.iloc[len(y):, :]<categorify>
AUTO = tf.data.experimental.AUTOTUNE
print('AUTO:',AUTO)
 BATCH_SIZE = 16 * strategy.num_replicas_in_sync
EPOCHS = 12
IMAGE_SIZE = [512,512]
WIDTH = IMAGE_SIZE[0]
HEIGHT = IMAGE_SIZE[1]
CHANNELS = 3
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'
]
all1 = pd.get_dummies(all_data,drop_first=True )<split>
try:
BASE = KaggleDatasets().get_gcs_path('flower-classification-with-tpus')
 except ModuleNotFoundError:
BASE = "/Users/astzls/Downloads/flower"
PATH_SELECT = {
192: BASE + '/tfrecords-jpeg-192x192',
224: BASE + '/tfrecords-jpeg-224x224',
331: BASE + '/tfrecords-jpeg-331x331',
512: BASE + '/tfrecords-jpeg-512x512'
}
IMAGE_PATH = PATH_SELECT[IMAGE_SIZE[0]]
TRAINING_FILENAMES = tf.io.gfile.glob(IMAGE_PATH + '/train/*.tfrec')
 VALIDATION_FILENAMES = tf.io.gfile.glob(IMAGE_PATH + '/val/*.tfrec')
 TEST_FILENAMES = tf.io.gfile.glob(IMAGE_PATH + '/test/*.tfrec' )
x_train = all1.iloc[:len(y), :]
x_test = all1.iloc[len(y):, :]<drop_column>
def get_training_dataset(do_aug=True):
dataset = load_dataset(TRAINING_FILENAMES, labeled=True)
 if do_aug:
dataset = dataset.map(data_augmentation, num_parallel_calls=AUTO)
 dataset = dataset.shuffle(2048)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.repeat()
dataset = dataset.prefetch(AUTO)
 return dataset
def get_validation_dataset(order=False):
dataset = load_dataset(VALIDATION_FILENAMES, labeled=True,ordered=order)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.cache()
dataset = dataset.prefetch(AUTO)
 return dataset
def get_test_dataset(order=False):
dataset = load_dataset(TEST_FILENAMES, labeled=False,ordered=order)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.prefetch(AUTO)
 return dataset
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_augmentation(image, label):
image = tf.image.random_flip_left_right(image)
 image = tf.image.random_flip_up_down(image)
 image = tf.image.random_brightness(image, 0.1)
 return image, label
def decode_image(image_data):
image = tf.image.decode_jpeg(image_data, channels=3)
 image = tf.cast(image, tf.float32)
 image /= 255.0
image = tf.reshape(image, [*IMAGE_SIZE, 3])
 return image
def read_labeled_tfrecord(example):
FEATURE = {
"image": tf.io.FixedLenFeature([], tf.string),
"class": tf.io.FixedLenFeature([], tf.int64)
 }
example = tf.io.parse_single_example(example, FEATURE)
 image = decode_image(example['image'])
 label = tf.cast(example['class'], tf.int32)
 return image, label
def read_unlabeled_tfrecord(example):
FEATURE = {
"image": tf.io.FixedLenFeature([], tf.string),
"id": tf.io.FixedLenFeature([], tf.string)
 }
example = tf.io.parse_single_example(example, FEATURE)
 image = decode_image(example['image'])
 idnum = example['id']
return image, idnum
x_train.drop('Id',axis = 1,inplace = True)
 x_test.drop('Id',axis = 1,inplace = True)
 cat_train.drop('Id',axis = 1,inplace = True)
 cat_test.drop('Id',axis = 1,inplace = True )<feature_engineering>
with strategy.scope() :
conv_base = efn.EfficientNetB7(
 input_shape=(512, 512, 3),
weights='imagenet',
include_top=False 
)
 set_trainable = False
for layer in conv_base.layers:
if layer.name == 'block2a_expand_conv':
set_trainable = True
if set_trainable:
layer.trainable = True
else:
layer.trainable = False
model = tf.keras.Sequential([
conv_base,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dropout(0.1),
tf.keras.layers.Dense(104, activation='softmax')
 ])
 model.compile(
 optimizer=tf.keras.optimizers.Adam() ,
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy']
)
y_transformed = np.log1p(y )<choose_model_class>
def lrfn(epoch):
LR_START = 2.5e-4
LR_MIN = 1e-5
lr = cos(epoch*pi/18)* LR_START
return lr if lr>LR_MIN else LR_MIN
def lrfn1(epoch):
lr_start = 2.5e-4
lr_min = 1e-5
lr = lr_start /(1 + e **(epoch - 5))
return lr if lr > lr_min else lr_min
callbacks_list = [
tf.keras.callbacks.EarlyStopping(
 monitor='val_loss',
patience=2 
),
tf.keras.callbacks.LearningRateScheduler(
 lrfn1,
verbose=1 
)
 ]
epochs=[x for x in range(12)]
lr_sigmoid=[lrfn1(x)for x in epochs]
plt.plot(epochs,lr_sigmoid,'b')
 plt.xlabel('Epoch')
 plt.ylabel('lr')
 plt.title('Sigmoid lr scheduler')
 plt.savefig('lr_sche.jpg')
 plt.show()
kf = KFold(n_splits=9, random_state=42, shuffle=True )<compute_test_metric>
nums_image = count_data_items(TRAINING_FILENAMES)
 STEPS_PER_EPOCH = nums_image // BATCH_SIZE
print('Total {} images will be training.. '.format(nums_image))
history = model.fit(get_training_dataset(do_aug=True),
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS,
validation_data=get_validation_dataset() ,
callbacks=callbacks_list,
verbose=2
)
def rmsle(y, y_pred):
return np.sqrt(mean_squared_error(y, y_pred))
def cv_rmse(model, X,y_true):
rmse = np.sqrt(-cross_val_score(model, X, y_true, scoring="neg_mean_squared_error", cv=kf))
return(rmse )<choose_model_class>
print('Model saving...')
 model.save_weights('my_weights.h5')
 show_acc_loss(history )
lasso_reg =make_pipeline(Min() ,Lasso(alpha=0.0005,random_state=44))<compute_test_metric>
print('Preparing test dataset...')
 test_ds = get_test_dataset(order=True)
 print('Predicting test dataset...')
 test_images = test_ds.map(lambda image, idnum: image)
 probabilities = model.predict(test_images)
 predictions = np.argmax(probabilities, axis=-1)
 print('Generating submission.csv file...')
 nums_test_images = count_data_items(TEST_FILENAMES)
 test_ids = test_ds.map(lambda image, idnum: idnum ).unbatch()
test_ids = next(iter(test_ids.batch(nums_test_images)) ).numpy().astype('U')
 np.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')
 print('Successfully generating csv submission file!')
scores = {}
score = cv_rmse(lasso_reg,x_train,y_transformed)
 print("Lasso: {:.4f}({:.4f})".format(score.mean() , score.std()))
scores['Lasso'] =(score.mean() , score.std() )<choose_model_class>
print('Preparing dataset...')
 dataset = get_validation_dataset(order=True)
 images = dataset.map(lambda image, label: image)
 labels = dataset.map(lambda image, label: label ).unbatch()
print('Predicting...')
 prediction_start = perf_counter()
output = model.predict(images)
 prediction_end = perf_counter()
print('In {:.1f}s compeleted!'.format(prediction_end - prediction_start))
prediction = np.argmax(output,axis=-1)
 nums_validation_images = count_data_items(VALIDATION_FILENAMES)
 correct_labels = next(iter(labels.batch(nums_validation_images)) ).numpy()
mistake = [0 for _ in range(len(CLASSES)) ]
print('Computing mistakes...')
 for i in range(nums_validation_images):
if prediction[i] != correct_labels[i]:
mistake[correct_labels[i]]+=1
with open('mistake.json','w')as f:
json.dump(mistake,f)
 classes = [x for x in range(104)]
plt.bar(classes,mistake)
 plt.xlabel('CLASSES')
 plt.ylabel('Mistake count')
 plt.title('Mistakes each class')
 plt.savefig('mistake.jpeg')
 plt.show()
<compute_test_metric><EOS> 
print('Spawning confusion matrix...')
 confusion_mat = confusion_matrix(correct_labels, prediction, labels=range(len(CLASSES)))
 score = f1_score(correct_labels, prediction, labels=range(len(CLASSES)) , average='macro')
 precision = precision_score(correct_labels, prediction, labels=range(len(CLASSES)) , average='macro')
 recall = recall_score(correct_labels, prediction, labels=range(len(CLASSES)) , average='macro')
 confusion_mat =(confusion_mat.T / confusion_mat.sum(axis=1)).T
display_confusion_matrix(confusion_mat, score, precision, recall)
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score, precision, recall))