Kaggle competition: Petals to the Metal - Flower Classification on TPU
<SOS> metric: macrofscore Kaggle data source: petals-to-the-metal-flower-classification-on-tpu<define_variables>
!pip install -q tensorflow==2.3.0
!pip install -q git+https://github.com/keras-team/keras-tuner@master
!pip install -q cloud-tpu-client
xgb_params = dict(
 gamma=0.2,
learning_rate=0.15,
n_estimators=100,
max_depth=11,
min_child_weight=1,
nthread=8,
objective="reg:squarederror")
 x_columns = [
'DayOfYear', 'cases_growth', 'death_growth',
'Cardiovascular diseases(%)', 'Cancers(%)',
'Diabetes, blood, & endocrine diseases(%)', 'Respiratory diseases(%)',
'Liver disease(%)', 'Diarrhea & common infectious diseases(%)',
'Musculoskeletal disorders(%)', 'HIV/AIDS and tuberculosis(%)',
'Malaria & neglected tropical diseases(%)',
'Nutritional deficiencies(%)', 'pneumonia-death-rates',
'Share of deaths from smoking(%)', 'alcoholic_beverages',
'animal_fats', 'animal_products', 'aquatic_products,_other',
'cereals_-_excluding_beer', 'eggs', 'fish,_seafood',
'fruits_-_excluding_wine', 'meat', 'milk_-_excluding_butter',
'miscellaneous', 'offals', 'oilcrops', 'pulses', 'spices',
'starchy_roots', 'stimulants', 'sugar_&_sweeteners', 'treenuts',
'vegetable_oils', 'vegetables', 'vegetal_products',
'hospital_beds_per10k', 'hospital_density', 'nbr_surgeons',
'nbr_obstetricians', 'nbr_anaesthesiologists', 'medical_doctors_per10k',
'bcg_coverage', 'bcg_year_delta', 'population',
'median age', 'population growth rate', 'birth rate', 'death rate',
'net migration rate', 'maternal mortality rate',
'infant mortality rate', 'life expectancy at birth',
'total fertility rate', 'obesity - adult prevalence rate',
'school_shutdown_1case', 'school_shutdown_10case',
'school_shutdown_50case', 'school_shutdown_1death', 'FF_DayOfYear',
'case1_DayOfYear', 'case10_DayOfYear', 'case50_DayOfYear', 'yhat_logistic_ConfirmedCases',
'yhat_logistic_Fatalities']
xgb_c_rmsle, xgb_c_fit = apply_xgb_model(
 train, x_columns, "ConfirmedCases", xgb_params)
 xgb_f_rmsle, xgb_f_fit = apply_xgb_model(
 train, x_columns, "Fatalities", xgb_params )<train_model>
print('Tensorflow version ' + tf.__version__)
def interpolate(alpha, x0, x1):
return x0 * alpha + x1 *(1 - alpha)
 def RMSLE_interpolate(alpha, y, x0, x1):
return RMSLE(y, interpolate(alpha, x0, x1))
def fit_hybrid(
 train: pd.DataFrame, y_cols: List[str] = ["ConfirmedCases", "Fatalities"] 
)-> pd.DataFrame:
def fit_one(y_col: str):
opt = least_squares(
 fun=RMSLE_interpolate,
args=(
 train[y_col],
train[f"yhat_logistic_{y_col}"],
train[f"yhat_xgb_{y_col}"], 
),
x0=(0.5,),
bounds=(( 0.0),(1.0,)) , 
)
 return {f"{y_col}_alpha": opt.x[0], f"{y_col}_cost": opt.cost}
result = {}
for y_col in y_cols:
result.update(fit_one(y_col))
return pd.DataFrame([result])
 def predict_hybrid(
 df: pd.DataFrame,
x_col: str = "DayOfYear",
y_cols: List[str] = ["ConfirmedCases", "Fatalities"], 
):
def predict_one(col):
df[f"yhat_hybrid_{col}"] = interpolate(
 df[f"{y_col}_alpha"].to_numpy() ,
df[f"yhat_logistic_{y_col}"].to_numpy() ,
df[f"yhat_xgb_{y_col}"].to_numpy() , 
)
 for y_col in y_cols:
predict_one(y_col )<merge>
try:
c = Client()
c.configure_tpu_version(tf.__version__, restart_type='ifNeeded')
 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.TPUStrategy(tpu)
 else:
strategy = tf.distribute.get_strategy()
print("REPLICAS: ", strategy.num_replicas_in_sync )
train = pd.merge(
 train,
train.groupby(["Country_Region"], observed=True, sort=False)
.apply(lambda x: fit_hybrid(x)) 
.reset_index() ,
on=["Country_Region"],
how="left",
)<predict_on_test>
IMAGE_SIZE = [331, 331]
EPOCHS_SEARCH = 10
EPOCHS_FINAL = 20
SEED = 123
BATCH_SIZE = 32 * strategy.num_replicas_in_sync
predict_hybrid(train )<compute_test_metric>
GCS_DS_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started')
 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 = GCS_PATH_SELECT[IMAGE_SIZE[0]]
TRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/train/*.tfrec')
 VALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec')
 TEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec' )
print(
 "Confirmed:
"
f'Logistic\t{RMSLE(train["ConfirmedCases"], train["yhat_logistic_ConfirmedCases"])}
'
f'XGBoost\t{RMSLE(train["ConfirmedCases"], train["yhat_xgb_ConfirmedCases"])}
'
f'Hybrid\t{RMSLE(train["ConfirmedCases"], train["yhat_hybrid_ConfirmedCases"])}
'
f"Fatalities:
"
f'Logistic\t{RMSLE(train["Fatalities"], train["yhat_logistic_Fatalities"])}
'
f'XGBoost\t{RMSLE(train["Fatalities"], train["yhat_xgb_Fatalities"])}
'
f'Hybrid\t{RMSLE(train["Fatalities"], train["yhat_hybrid_Fatalities"])}
'
)<merge>
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']
test = pd.merge(
 test,
train[["Country_Region"] +
['ConfirmedCases_p_0', 'ConfirmedCases_p_1', 'ConfirmedCases_p_2']+
['Fatalities_p_0','Fatalities_p_1', 'Fatalities_p_2'] +
["Fatalities_alpha"] +
["ConfirmedCases_alpha"]].groupby(['Country_Region'] ).head(1), on="Country_Region", how="left" )<predict_on_test>
def decode_image(image_data):
image = tf.image.decode_jpeg(image_data, channels=3)
 image = tf.cast(image, tf.float32)
 image = tf.ensure_shape(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 = AUTOTUNE)
 dataset = dataset.with_options(ignore_order)
 dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord,
num_parallel_calls = AUTOTUNE)
 return dataset
def one_hot_encoding(image, label, num_classes=len(CLASSES)) :
return image, tf.one_hot(label, num_classes)
 def get_training_dataset(dataset,do_aug=True):
dataset = dataset.map(one_hot_encoding, num_parallel_calls=AUTOTUNE)
 if do_aug: dataset = dataset.map(transform, num_parallel_calls=AUTOTUNE)
 dataset = dataset.repeat()
dataset = dataset.shuffle(2048)
 dataset = dataset.batch(BATCH_SIZE, drop_remainder=True)
 dataset = dataset.prefetch(AUTOTUNE)
 return dataset
def get_validation_dataset(dataset):
dataset = dataset.map(one_hot_encoding, num_parallel_calls=AUTOTUNE)
 dataset = dataset.batch(BATCH_SIZE, drop_remainder=True)
 dataset = dataset.cache()
dataset = dataset.prefetch(AUTOTUNE)
 return dataset
def get_test_dataset(ordered=False):
dataset = load_dataset(TEST_FILENAMES, labeled=False, ordered=ordered)
 dataset = dataset.batch(BATCH_SIZE, drop_remainder=False)
 dataset = dataset.prefetch(AUTOTUNE)
 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 )
predict_logistic(test)
 test["yhat_xgb_ConfirmedCases"] = xgb_c_fit.predict(test[x_columns].to_numpy())
 test["yhat_xgb_Fatalities"] = xgb_f_fit.predict(test[x_columns].to_numpy())
 predict_hybrid(test )<prepare_output>
def get_mat(rotation, shear, height_zoom, width_zoom, height_shift, width_shift):
rotation = math.pi * rotation / 180.
 shear = math.pi * shear / 180.
 c1 = tf.math.cos(rotation)
 s1 = tf.math.sin(rotation)
 one = tf.constant([1],dtype='float32')
 zero = tf.constant([0],dtype='float32')
 rotation_matrix = tf.reshape(tf.concat([c1,s1,zero, -s1,c1,zero, zero,zero,one],axis=0),[3,3])
 c2 = tf.math.cos(shear)
 s2 = tf.math.sin(shear)
 shear_matrix = tf.reshape(tf.concat([one,s2,zero, zero,c2,zero, zero,zero,one],axis=0),[3,3])
 zoom_matrix = tf.reshape(tf.concat([one/height_zoom,zero,zero, zero,one/width_zoom,zero, zero,zero,one],axis=0),[3,3])
 shift_matrix = tf.reshape(tf.concat([one,zero,height_shift, zero,one,width_shift, zero,zero,one],axis=0),[3,3])
 return K.dot(K.dot(rotation_matrix, shear_matrix), K.dot(zoom_matrix, shift_matrix))
submission = test[["ForecastId", "yhat_hybrid_ConfirmedCases", "yhat_hybrid_Fatalities"]].round().astype(int ).rename(
 columns={
"yhat_hybrid_ConfirmedCases": "ConfirmedCases",
"yhat_hybrid_Fatalities": "Fatalities",
} 
)
 submission["ConfirmedCases"] = np.maximum(0, submission["ConfirmedCases"])
 submission["Fatalities"] = np.maximum(0, submission["Fatalities"] )<save_to_csv>
def transform(image,label):
image = tf.image.random_flip_left_right(image)
 DIM = IMAGE_SIZE[0]
XDIM = DIM%2
rot = 15.* tf.random.normal([1],dtype='float32')
 shr = 5.* tf.random.normal([1],dtype='float32')
 h_zoom = 1.0 + tf.random.normal([1],dtype='float32')/10.
 w_zoom = 1.0 + tf.random.normal([1],dtype='float32')/10.
 h_shift = 16.* tf.random.normal([1],dtype='float32')
 w_shift = 16.* tf.random.normal([1],dtype='float32')
 m = get_mat(rot,shr,h_zoom,w_zoom,h_shift,w_shift)
 x = tf.repeat(tf.range(DIM//2,-DIM//2,-1), DIM)
 y = tf.tile(tf.range(-DIM//2,DIM//2),[DIM])
 z = tf.ones([DIM*DIM],dtype='int32')
 idx = tf.stack([x,y,z])
 idx2 = K.dot(m,tf.cast(idx,dtype='float32'))
idx2 = K.cast(idx2,dtype='int32')
 idx2 = K.clip(idx2,-DIM//2+XDIM+1,DIM//2)
 idx3 = tf.stack([DIM//2-idx2[0,], DIM//2-1+idx2[1,]])
 d = tf.gather_nd(image,tf.transpose(idx3))
return tf.reshape(d,[DIM,DIM,3]),label
submission.to_csv("submission.csv", index=False )<save_to_csv>
hm = HyperEfficientNet(input_shape=[IMAGE_SIZE[0], IMAGE_SIZE[1], 3] , classes=len(CLASSES))
hp = HyperParameters()
hp.Choice('version', ['B0', 'B1', 'B2', 'B3', 'B4'])
 tuner = kt.tuners.randomsearch.RandomSearch(
 hypermodel=hm,
objective='val_accuracy',
max_trials=5,
distribution_strategy=strategy,
directory='flower_classification',
project_name='randomsearch_efficientnet',
hyperparameters=hp, 
)
 tuner.search_space_summary()
submission.to_csv("submission.csv", index=False )<import_modules>
num_val_samples = count_data_items(VALIDATION_FILENAMES)
 num_train_samples = count_data_items(TRAINING_FILENAMES)
 train_ds = get_training_dataset(load_dataset(TRAINING_FILENAMES))
validation_ds = get_validation_dataset(load_dataset(VALIDATION_FILENAMES))
num_train_batches = num_train_samples // BATCH_SIZE
num_val_batches = num_val_samples // BATCH_SIZE
K.set_image_data_format('channels_last')
 print(os.listdir(".. /input")) 
<load_from_csv>
tuner.search(train_ds,
epochs=EPOCHS_SEARCH,
validation_data=validation_ds,
steps_per_epoch=num_train_batches,
verbose=2 )
train = pd.read_csv('.. /input/train.csv')
 test = pd.read_csv('.. /input/test.csv')
 df = train.copy()
df_test = test.copy()<train_model>
ds_all = get_training_dataset(load_dataset(TRAINING_FILENAMES + VALIDATION_FILENAMES))
model.fit(ds_all,
epochs=EPOCHS_FINAL,
steps_per_epoch=num_train_batches + num_val_batches,
callbacks=[tf.keras.callbacks.ReduceLROnPlateau() ],
verbose=2 )
print("Train: ", df.shape)
 print("Test: ", df_test.shape )<count_missing_values>
ds_test = get_test_dataset(ordered=True)
 print('Computing predictions...')
 predictions = []
for i,(test_img, test_id)in enumerate(ds_test):
print('Processing batch ', i)
 probabilities = model(test_img)
 prediction = np.argmax(probabilities, axis=-1)
 predictions.append(prediction)
 predictions = np.concatenate(predictions)
 print('Number of test examples predicted: ', predictions.shape )
<count_missing_values><EOS> 
ds_test_ids = ds_test.map(lambda image, idnum: idnum ).unbatch()
test_ids = next(iter(ds_test_ids.batch(np.iinfo(np.int64 ).max)) ).numpy().astype('U')
 np.savetxt(
 'submission.csv',
np.rec.fromarrays([test_ids, predictions]),
fmt=['%s', '%d'],
delimiter=',',
header='id,label',
comments='', 
)
 !head submission.csv