Kaggle competition: Petals to the Metal - Flower Classification on TPU
<SOS> metric: macrofscore Kaggle data source: petals-to-the-metal-flower-classification-on-tpu<import_modules>
!pip install efficientnet --quiet
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.model_selection import KFold
from lightgbm import LGBMClassifier
import lightgbm as lgb
import optuna<categorify>
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 )
all_data_one_hot = pd.get_dummies(all_data[['Survived','Pclass','Sex','Age','Fare','Embarked','family_size','Cabin_class',
'Ticket_first_letter','family_survival']],
columns=['Ticket_first_letter','Cabin_class','Sex','Pclass','Embarked'] )<choose_model_class>
GCS_DS_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started')
 print(GCS_DS_PATH )
def objective(trial):
params = {
'objective': 'binary',
'metric': 'binary_logloss',
'verbosity': -1,
'boosting_type': 'gbdt',
'learning_rate':trial.suggest_loguniform('learning_rate',0.01,0.05),
'num_leaves': trial.suggest_int('num_leaves', 2, 256),
'min_child_samples': trial.suggest_int('min_child_samples', 10, 60),
'max_depth':trial.suggest_int('max_depth',3,8)
 }
kf = KFold(n_splits=5,shuffle=True,random_state=1)
 accuracy_scores = []
for train_index,valid_index in kf.split(train):
X_train, X_valid = train.drop(columns='Survived' ).iloc[train_index],train.drop(columns='Survived' ).iloc[valid_index]
y_train, y_valid = train.Survived.iloc[train_index],train.Survived.iloc[valid_index]
lgb_train = lgb.Dataset(X_train,y_train)
 gbm = lgb.train(params,lgb_train)
 y_pred = np.round(gbm.predict(X_valid)).astype(int)
 accuracy_scores.append(accuracy_score(y_valid,y_pred))
return np.mean(accuracy_scores)
 study = optuna.create_study(direction='maximize',sampler=optuna.samplers.RandomSampler(seed=1))
optuna.logging.disable_default_handler()
study.optimize(objective, n_trials=100 )<find_best_params>
IMAGE_SIZE = [224, 224]
GCS_PATH = GCS_DS_PATH + '/tfrecords-jpeg-224x224'
AUTO = tf.data.experimental.AUTOTUNE
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')
 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']
print('Number of finished trials: {}'.format(len(study.trials)))
 print('Best trial:')
 trial = study.best_trial
print(' Value: {}'.format(trial.value))
print(' Params: ')
 for key, value in trial.params.items() :
print(' {}: {}'.format(key, value))<init_hyperparams>
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
params = {
'objective': 'binary',
'metric': 'binary_logloss',
'verbosity': -1,
'boosting_type': 'gbdt'
}
params.update(trial.params )<train_model>
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))
def transform(image,label):
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
def get_training_dataset() :
dataset = load_dataset(TRAINING_FILENAMES, labeled=True)
 dataset = dataset.map(transform, 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
NUM_TRAINING_IMAGES = 12753
NUM_VALIDATION_IMAGES = 3712
NUM_TEST_IMAGES = 7382
kf = KFold(n_splits=5,shuffle=True,random_state=6)
 accuracy_scores = []
for train_index,valid_index in kf.split(train):
X_train, X_valid = train.drop(columns='Survived' ).iloc[train_index],train.drop(columns='Survived' ).iloc[valid_index]
y_train, y_valid = train.Survived.iloc[train_index],train.Survived.iloc[valid_index]
lgb_train = lgb.Dataset(X_train,y_train)
 gbm = lgb.train(params,lgb_train,num_boost_round=100)
 y_pred = np.round(gbm.predict(X_valid)).astype(int)
 accuracy_scores.append(accuracy_score(y_valid,y_pred))<create_dataframe>
BATCH_SIZE = 32 * strategy.num_replicas_in_sync
ds_train = get_training_dataset()
ds_valid = get_validation_dataset()
ds_test = get_test_dataset()
print("Training:", ds_train)
 print("Validation:", ds_valid)
 print("Test:", ds_test )
all_train_data = lgb.Dataset(train.drop(columns=['Survived']),label=train.Survived )<train_model>
with strategy.scope() :
pretrained_model1 = efficientnet.EfficientNetB7(
 weights='noisy-student',
include_top=False ,
input_shape=[*IMAGE_SIZE, 3])
 pretrained_model1.trainable = True
model1 = tf.keras.Sequential([
pretrained_model1,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 pretrained_model2 = tf.keras.applications.Xception(
 weights='imagenet',
include_top=False,
input_shape=[*IMAGE_SIZE,3])
 pretrained_model2.trainable = True
model2 = tf.keras.Sequential([
pretrained_model2,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 pretrained_model3 = tf.keras.applications.InceptionResNetV2(
 weights='imagenet',
include_top=False,
input_shape=[*IMAGE_SIZE,3])
 pretrained_model3.trainable = True
model3 = tf.keras.Sequential([
pretrained_model3,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 pretrained_model4 = tf.keras.applications.DenseNet201(
 weights='imagenet',
include_top=False,
input_shape=[*IMAGE_SIZE,3])
 pretrained_model4.trainable = True
model4 = tf.keras.Sequential([
pretrained_model4,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
gbm_final = lgb.train(train_set=all_train_data,
params = params,
num_boost_round=100
)<predict_on_test>
model1.compile(
 optimizer='adam',
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'], 
)
 model2.compile(
 optimizer='adam',
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'], 
)
 model3.compile(
 optimizer='adam',
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'], 
)
 model4.compile(
 optimizer='adam',
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'],
)
y_pred = np.round(gbm_final.predict(test.drop(columns=['Survived'])) ).astype(int )<load_from_csv>
def exponential_lr(epoch,
start_lr = 0.00001, min_lr = 0.00001, max_lr = 0.00005,
rampup_epochs = 5, sustain_epochs = 0,
exp_decay = 0.8):
def lr(epoch, start_lr, min_lr, max_lr, rampup_epochs, sustain_epochs, exp_decay):
if epoch < rampup_epochs:
lr =(( max_lr - start_lr)/ rampup_epochs * epoch + start_lr)
 elif epoch < rampup_epochs + sustain_epochs:
lr = max_lr
else:
lr =(( max_lr - min_lr)* exp_decay**(epoch - rampup_epochs - sustain_epochs)+ min_lr)
 return lr
return lr(epoch,start_lr,min_lr,max_lr,rampup_epochs,sustain_epochs,exp_decay)
 lr_callback = tf.keras.callbacks.LearningRateScheduler(exponential_lr, verbose=True )
submission_df = pd.read_csv('.. /input/titanic/gender_submission.csv' )<prepare_output>
EPOCHS = 15
STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE
history1 = model1.fit(
 ds_train,
validation_data=ds_valid,
epochs=EPOCHS,
steps_per_epoch=STEPS_PER_EPOCH,
callbacks=[lr_callback],
)
submission_df['Survived'] = y_pred<save_to_csv>
history2 = model2.fit(
 ds_train,
validation_data=ds_valid,
epochs=EPOCHS,
steps_per_epoch=STEPS_PER_EPOCH,
callbacks=[lr_callback],
)
JST = timezone(timedelta(hours=+9), 'JST')
 ts = datetime.now(JST ).strftime('%y%m%d%H%M')
 submission_df.to_csv(( ts+'lgb.csv'),index=False )<train_model>
history3 = model3.fit(
 ds_train,
validation_data=ds_valid,
epochs=EPOCHS,
steps_per_epoch=STEPS_PER_EPOCH,
callbacks=[lr_callback],
)
kf = KFold(n_splits=5,shuffle=True,random_state=6)
 mean_accuracy = {}
thresh_holds = np.arange(0.2,0.6,0.01)
 for thresh_hold in thresh_holds:
accuracy_scores = []
for train_index,valid_index in kf.split(train):
X_train, X_valid = train.drop(columns='Survived' ).iloc[train_index],train.drop(columns='Survived' ).iloc[valid_index]
y_train, y_valid = train.Survived.iloc[train_index],train.Survived.iloc[valid_index]
lgb_train = lgb.Dataset(X_train,y_train)
 gbm = lgb.train(params,lgb_train,num_boost_round=100)
 y_pred = np.where(gbm.predict(X_valid)<thresh_hold,0,1)
 accuracy_scores.append(accuracy_score(y_valid,y_pred))
mean_accuracy[thresh_hold] = np.mean(accuracy_scores )<install_modules>
history4 = model4.fit(
 ds_train,
validation_data=ds_valid,
epochs=EPOCHS,
steps_per_epoch=STEPS_PER_EPOCH,
callbacks=[lr_callback],
)
<load_from_url>
test_ds = get_test_dataset(ordered=True)
 print('Computing predictions...')
 test_images_ds = test_ds.map(lambda image, idnum: image)
 probabilities1 = model1.predict(test_images_ds)
 probabilities2 = model2.predict(test_images_ds)
 probabilities3 = model3.predict(test_images_ds)
 probabilities4 = model4.predict(test_images_ds)
 probabilities = probabilities1+probabilities2+probabilities3+probabilities4
predictions = np.argmax(probabilities, axis=-1)
 print(predictions )
<load_from_csv><EOS> 
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='', 
)
 !head submission.csv