Kaggle competition: Petals to the Metal - Flower Classification on TPU
<SOS> metric: macrofscore Kaggle data source: petals-to-the-metal-flower-classification-on-tpu<choose_model_class>
print("Tensorflow version " + tf.__version__ )
lb = aml.leaderboard; lb<set_options>
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 )
aml.leader<predict_on_test>
GCS_DS_PATH = KaggleDatasets().get_gcs_path()
preds = aml.leader.predict(test )<save_to_csv>
IMAGE_SIZE = [512, 512, 3]
BATCH_SIZE = 16 * strategy.num_replicas_in_sync
NUM_TRAINING_IMAGES = 12753
NUM_TEST_IMAGES = 7382
STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE
TRAINING_FILENAMES = tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-%sx%s' %(IMAGE_SIZE[0], IMAGE_SIZE[1])+ '/train/*.tfrec')
 VALIDATION_FILENAMES = tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-%sx%s' %(IMAGE_SIZE[0], IMAGE_SIZE[1])+ '/val/*.tfrec')
 TEST_FILENAMES = tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-%sx%s' %(IMAGE_SIZE[0], IMAGE_SIZE[1])+ '/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']
WARMUP_EPOCHS = 20
WARMUP_LEARNING_RATE = 3e-3
TUNING_EPOCHS = 8
LR_MIN = 1e-10
LR_PEAK = 2e-4
LR_RAMPUP_EPOCHS = 4
LR_DECAY = 0.3
RE_PROBABILITY = 1
RE_S_LOW = 0.1
RE_S_HIGH = 0.6
RE_RATIO = 0.3
CROP_MIN = tf.cast(IMAGE_SIZE[0]*0.6, dtype=tf.int32)
 CROP_MAX = tf.cast(IMAGE_SIZE[0]*0.95, dtype=tf.int32 )
result = preds.expm1()
sub = test_id.cbind(result)
 sub.columns = ['Id','SalePrice']
sub = sub.as_data_frame()
sub.to_csv('submission.csv', index = False )<set_options>
fig, ax = plt.subplots()
blank = tf.constant(1, shape=(IMAGE_SIZE[0], IMAGE_SIZE[1], IMAGE_SIZE[2]), dtype=tf.float32)
 erasure = random_erasing(blank)
 ax.imshow(np.asarray(erasure.numpy()))
plt.show()
pd.set_option('display.expand_frame_repr', False)
 def ignore_warn(*args, **kwargs):
pass
warnings.warn = ignore_warn<import_modules>
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)
 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)
 dataset = dataset.with_options(ignore_order)
 dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord)
 return dataset
def get_training_dataset() :
dataset = load_dataset(TRAINING_FILENAMES, labeled=True)
 dataset = dataset.map(augment_dataset)
 dataset = dataset.repeat()
dataset = dataset.shuffle(2048)
 dataset = dataset.batch(BATCH_SIZE)
 return dataset
def get_training_dataset_preview(ordered=True):
dataset = load_dataset(TRAINING_FILENAMES, labeled=True, ordered=ordered)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.cache()
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()
return dataset
def get_test_dataset(ordered=False):
dataset = load_dataset(TEST_FILENAMES, labeled=False, ordered=ordered)
 dataset = dataset.batch(BATCH_SIZE)
 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)
 training_dataset = get_training_dataset()
validation_dataset = get_validation_dataset()
import matplotlib.pyplot as plt
import seaborn as sns<load_from_csv>
with strategy.scope() :
pretrained_model = tf.keras.applications.DenseNet201(
 weights = 'imagenet',
include_top = False,
input_shape = IMAGE_SIZE)
 pretrained_model.trainable = False
model = tf.keras.Sequential([
pretrained_model,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(104, activation = 'softmax')
 ])
 warmup_optimizer = tf.keras.optimizers.Adam(lr = WARMUP_LEARNING_RATE)
 model.compile(
 optimizer = warmup_optimizer,
loss = 'sparse_categorical_crossentropy',
metrics = ['sparse_categorical_accuracy'] 
)
 model.summary()
warmup_history = model.fit(
 training_dataset,
steps_per_epoch = STEPS_PER_EPOCH,
epochs = WARMUP_EPOCHS,
validation_data = validation_dataset )
train = pd.read_csv(".. /input/train.csv")
 validation = pd.read_csv(".. /input/test.csv" )<count_missing_values>
for layer in model.layers:
layer.trainable = True
tuning_optimizer = tf.keras.optimizers.Adam(lr = LR_PEAK)
 model.compile(
 optimizer = tuning_optimizer,
loss = 'sparse_categorical_crossentropy',
metrics = ['sparse_categorical_accuracy'] 
)
 model.summary()
lr_callback = tf.keras.callbacks.LearningRateScheduler(scheduler)
 tuning_history = model.fit(
 training_dataset,
steps_per_epoch = STEPS_PER_EPOCH,
epochs = TUNING_EPOCHS,
validation_data = validation_dataset,
callbacks = lr_callback )
<count_missing_values><EOS> 
test_ds = get_test_dataset(ordered=True)
 print('Computing predictions...')
 test_images_ds = test_ds.map(lambda image, idnum: image)
 probabilities = model.predict(test_images_ds)
 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='' )