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_values>
!pip install -q efficientnet
ktu.HardwareInfo.print_tf_version()
sns.set()
y_default = pd.Series([0] * train['Survived'].shape[0], name = 'Survived')
 print(y_default.value_counts() )<compute_test_metric>
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 )
print(confusion_matrix(y, y_default))
print()
print(accuracy_score(y, y_default)) 
<compute_train_metric>
image_size =(224, 224)
 data_gcs = KaggleDatasets().get_gcs_path('tpu-getting-started')
 ext_gcs = KaggleDatasets().get_gcs_path('tf-flower-photo-tfrec')
 data_dir_by_size = { 
(512, 512): '/tfrecords-jpeg-512x512', 
(331, 331): '/tfrecords-jpeg-331x331', 
(224, 224): '/tfrecords-jpeg-224x224', 
(192, 192): '/tfrecords-jpeg-192x192'
}
subdir = data_dir_by_size[image_size]
train_file_names = tf.io.gfile.glob(data_gcs + subdir + '/train' + '/*.tfrec')
 val_file_names = tf.io.gfile.glob(data_gcs + subdir + '/val' + '/*.tfrec')
 test_file_names = tf.io.gfile.glob(data_gcs + subdir + '/test' + '/*.tfrec')
 imagenet_files = tf.io.gfile.glob(ext_gcs + '/imagenet' + subdir + '/*.tfrec')
 inaturelist_files = tf.io.gfile.glob(ext_gcs + '/inaturalist' + subdir + '/*.tfrec')
 openimage_files = tf.io.gfile.glob(ext_gcs + '/openimage' + subdir + '/*.tfrec')
 oxford_files = tf.io.gfile.glob(ext_gcs + '/oxford_102' + subdir + '/*.tfrec')
 tensorflow_files = tf.io.gfile.glob(ext_gcs + '/tf_flowers' + subdir + '/*.tfrec')
 train_file_names = train_file_names + imagenet_files + inaturelist_files + \
openimage_files + oxford_files + tensorflow_files
classifier = LinearSVC(dual=False)
 classifier.fit(X_train, y_train)
 y_pred = classifier.predict(X_test)
 print(confusion_matrix(y_test, y_pred))
print(accuracy_score(y_test, y_pred))
scores = cross_val_score(classifier, X_train, y_train, cv=10, scoring='accuracy')
 print(scores.mean() )<compute_train_metric>
flower_categories = [
'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'
]
print('Number of flower categories:', len(flower_categories))
classifier = KNeighborsClassifier(n_neighbors = 2)
 classifier.fit(X_train, y_train)
 y_pred = classifier.predict(X_test)
 print(confusion_matrix(y_test, y_pred))
print(accuracy_score(y_test, y_pred))
scores = cross_val_score(classifier, X_train, y_train, cv=10, scoring='accuracy')
 print(scores.mean() )<find_best_model_class>
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):

 example = tf.io.parse_single_example(
 serialized=example,
features={
'image': tf.io.FixedLenFeature([], tf.string),
'class': tf.io.FixedLenFeature([], tf.int64),
} 
)
 image = decode_image(example['image'])
 label = tf.cast(example['class'], tf.int32)
 return image, label
def read_unlabeled_tfrecord(example):

 example = tf.io.parse_single_example(
 serialized=example,
features={
'image': tf.io.FixedLenFeature([], tf.string),
'id': tf.io.FixedLenFeature([], tf.string),
} 
)
 image = decode_image(example['image'])
 idnum = example['id']
return image, idnum
def load_dataset(filenames, labeled=True, ordered=False):

 ignore_order = tf.data.Options()
ignore_order.experimental_deterministic = ordered
dataset = tf.data.TFRecordDataset(
 filenames, num_parallel_reads=tf.data.experimental.AUTOTUNE)
 dataset = dataset.with_options(ignore_order)
 dataset = dataset.map(
 read_labeled_tfrecord if labeled else read_unlabeled_tfrecord,
num_parallel_calls=tf.data.experimental.AUTOTUNE)
 return dataset
def count_data_items(filenames):

 return np.sum([
int(re.compile(r"-([0-9]*)\." ).search(filename ).group(1))
for filename in filenames])
 train_dataset = load_dataset(train_file_names, labeled=True, ordered=False)
 val_dataset = load_dataset(val_file_names, labeled=True, ordered=False)
 test_dataset = load_dataset(test_file_names, labeled=False, ordered=True)
 num_training_samples = count_data_items(train_file_names)
 num_validation_samples = count_data_items(val_file_names)
 num_testing_samples = count_data_items(test_file_names )
print("AdaBoostClassifier")
 ada_boost_classifier = AdaBoostClassifier()
ada_boost_classifier.fit(X_train, y_train)
 y_pred = ada_boost_classifier.predict(X_test)
 print(confusion_matrix(y_test, y_pred))
print(accuracy_score(y_test, y_pred))
scores = cross_val_score(ada_boost_classifier, X_train, y_train, cv=10, scoring='accuracy')
 print(scores.mean())
 print("BaggingClassifier")
 bagging_classifier = BaggingClassifier()
bagging_classifier.fit(X_train, y_train)
 y_pred = bagging_classifier.predict(X_test)
 print(confusion_matrix(y_test, y_pred))
print(accuracy_score(y_test, y_pred))
scores = cross_val_score(bagging_classifier, X_train, y_train, cv=10, scoring='accuracy')
 print(scores.mean())
 print("ExtraTreesClassifier")
 extra_trees_classifier = ExtraTreesClassifier(n_estimators=100)
 extra_trees_classifier.fit(X_train, y_train)
 y_pred = extra_trees_classifier.predict(X_test)
 print(confusion_matrix(y_test, y_pred))
print(accuracy_score(y_test, y_pred))
scores = cross_val_score(extra_trees_classifier, X_train, y_train, cv=10, scoring='accuracy')
 print(scores.mean())
 print("GradientBoostingClassifier")
 gradient_boosting_classifier = GradientBoostingClassifier()
gradient_boosting_classifier.fit(X_train, y_train)
 y_pred = gradient_boosting_classifier.predict(X_test)
 print(confusion_matrix(y_test, y_pred))
print(accuracy_score(y_test, y_pred))
scores = cross_val_score(gradient_boosting_classifier, X_train, y_train, cv=10, scoring='accuracy')
 print(scores.mean())
 print("RandomForestClassifier")
 random_forest_classifier = RandomForestClassifier(n_estimators=100)
 random_forest_classifier.fit(X_train, y_train)
 y_pred = random_forest_classifier.predict(X_test)
 print(confusion_matrix(y_test, y_pred))
print(accuracy_score(y_test, y_pred))
scores = cross_val_score(random_forest_classifier, X_train, y_train, cv=10, scoring='accuracy')
 print(scores.mean() )<compute_train_metric>
print('Train samples:', num_training_samples, end=', ')
 print('Val samples:', num_validation_samples, end=', ')
 print('Test samples:', num_testing_samples )
xgboost_classifier = XGBClassifier()
xgboost_classifier.fit(X_train, y_train)
 y_pred = xgboost_classifier.predict(X_test)
 print(confusion_matrix(y_test, y_pred))
print(accuracy_score(y_test, y_pred))
scores = cross_val_score(xgboost_classifier, X_train, y_train, cv=10, scoring='accuracy')
 print(scores.mean() )<predict_on_test>
transformer = ktu.TFImageTransform(
 image_size,
horizontal_flip=True,
vertical_flip=True,
brightness_adjustments=True,
rotation_range=15.,
shear_range=5.,
zoom_range=(0.1, 0.1),
shift_range=(16., 16.) 
)
 def augmentation(image, label):
return transformer.transform(image), label
X_validation = validation[['Age', 'Fare', 'Pclass_2', 'Pclass_3', 'Sex_female', 'Embarked_C',
'Embarked_S', 'HasCabin', 'FamilySize', 'Title_Master', 'Title_Mr',
'Title_Mrs', 'Title_Special']]
y_valid = xgboost_classifier.predict(X_validation )<count_values>
batch_size = 16 * strategy.num_replicas_in_sync
epochs = 25
batched_train_dataset = train_dataset.map(augmentation)
 batched_train_dataset = batched_train_dataset.repeat()
batched_train_dataset = batched_train_dataset.shuffle(buffer_size=2048)
 batched_train_dataset = batched_train_dataset.batch(batch_size)
 batched_train_dataset = batched_train_dataset.prefetch(tf.data.experimental.AUTOTUNE)
 batched_val_dataset = val_dataset.batch(batch_size)
 batched_val_dataset = batched_val_dataset.cache()
batched_val_dataset = batched_val_dataset.prefetch(tf.data.experimental.AUTOTUNE)
 batched_test_dataset = test_dataset.batch(batch_size)
 batched_test_dataset = batched_test_dataset.prefetch(tf.data.experimental.AUTOTUNE)
 early_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=3)
 save_checkpoints = tf.keras.callbacks.ModelCheckpoint(
 '/kaggle/working/weights.{epoch:02d}-{val_loss:.2f}.hdf5',
save_freq='epoch', period=4)
 lr_callback = ktu.LRSchedulers.FineTuningLR(
 lr_start=1e-5, lr_max=5e-5 * strategy.num_replicas_in_sync, lr_min=1e-5,
lr_rampup_epochs=5, lr_sustain_epochs=0, lr_exp_decay=0.8, verbose=1 )
validation_pId = validation.loc[:, 'PassengerId']
my_submission = pd.DataFrame(data={'PassengerId':validation_pId, 'Survived':y_valid})
 print(my_submission['Survived'].value_counts() )<save_to_csv>
plt.figure(figsize=(8, 5))
lr_callback.visualize(steps_per_epoch=num_training_samples // batch_size, epochs=epochs )
my_submission.to_csv('submission.csv', index = False )<load_from_csv>
def get_model() :
with strategy.scope() :
feature_extractor= efficientnet.EfficientNetB7(
 weights='noisy-student', include_top=False, input_shape=[*image_size, 3])
 feature_extractor.trainable = True
model = tf.keras.Sequential([
feature_extractor,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(flower_categories), activation='softmax', dtype='float32')
 ])
 model.compile(
 optimizer='adam',
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'])
 return model
model = get_model()
model.summary()
history = model.fit(
 batched_train_dataset,
steps_per_epoch=num_training_samples // batch_size,
epochs=epochs,
callbacks=[lr_callback, early_stopping, save_checkpoints],
validation_data=batched_val_dataset,
verbose=2 )
<count_unique_values><EOS> 
print('Generating Submission file...', end=' ')
 test_images_dataset = batched_test_dataset.map(lambda image, idnum: image)
 predictions = np.argmax(model.predict(test_images_dataset), axis=-1)
 test_ids_dataset = batched_test_dataset.map(lambda image, idnum: idnum ).unbatch()
test_ids = next(iter(test_ids_dataset.batch(num_testing_samples)) ).numpy().astype('U')
 np.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')
 print('Done!' )