Kaggle competition: Flower Classification with TPUs
<SOS> metric: MacroFScore Kaggle data source: flower-classification-with-tpus<drop_column>
!pip install -q efficientnet
train = dataset[:train_len]
test = dataset[train_len:]
test.drop(labels=['Survived'], axis=1, inplace=True )<prepare_x_and_y>
print("Tensorflow version " + tf.__version__)
train['Survived'] = train['Survived'].astype(int)
 Y_train = train['Survived']
X_train = train.drop(labels=['Survived'], axis=1 )<choose_model_class>
AUTO = tf.data.experimental.AUTOTUNE
tpu = tf.distribute.cluster_resolver.TPUClusterResolver()
tf.config.experimental_connect_to_cluster(tpu)
 tf.tpu.experimental.initialize_tpu_system(tpu)
 strategy = tf.distribute.experimental.TPUStrategy(tpu)
 GCS_DS_PATH = KaggleDatasets().get_gcs_path()
IMAGE_SIZE = [512, 512]
EPOCHS = 18
BATCH_SIZE = 16 * strategy.num_replicas_in_sync
kfold = StratifiedKFold(n_splits=10 )<choose_model_class>
LR_START = 0.00001
LR_MAX = 0.00005 * strategy.num_replicas_in_sync
LR_MIN = 0.00001
LR_RAMPUP_EPOCHS = 5
LR_SUSTAIN_EPOCHS = 0
LR_EXP_DECAY =.8
def lrfn(epoch):
if epoch < LR_RAMPUP_EPOCHS:
lr =(LR_MAX - LR_START)/ LR_RAMPUP_EPOCHS * epoch + LR_START
elif epoch < LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS:
lr = LR_MAX
else:
lr =(LR_MAX - LR_MIN)* LR_EXP_DECAY**(epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS)+ LR_MIN
return lr
lr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=True)
 rng = [i for i in range(EPOCHS)]
y = [lrfn(x)for x in rng]
plt.plot(rng, y)
 print("Learning rate schedule: {:.3g} to {:.3g} to {:.3g}".format(y[0], max(y), y[-1]))
random_state=3
classifiers = []
classifiers.append(SVC(random_state=random_state))
classifiers.append(DecisionTreeClassifier(random_state=random_state))
classifiers.append(AdaBoostClassifier(DecisionTreeClassifier(random_state=random_state), random_state=random_state, learning_rate=0.1))
classifiers.append(RandomForestClassifier(random_state=random_state))
classifiers.append(ExtraTreesClassifier(random_state=random_state))
classifiers.append(GradientBoostingClassifier(random_state=random_state))
classifiers.append(MLPClassifier(random_state=random_state))
classifiers.append(KNeighborsClassifier())
 classifiers.append(LogisticRegression(random_state=random_state))
classifiers.append(LinearDiscriminantAnalysis())
 classifiers.append(XGBClassifier(random_state=random_state))<choose_model_class>
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']
XGB = XGBClassifier(random_state=0)
 xgb_param_grid={'colsample_bylevel':[0.9],
'colsample_bytree' :[0.8],
'gamma' :[0.99],
'max_depth' :[4],
'min_child_weight' :[1],
'n_estimators' :[10],
'nthread' :[4],
'silent' :[True]}
gsXGB = GridSearchCV(XGB, param_grid=xgb_param_grid, cv=kfold, scoring='accuracy', n_jobs=4, verbose=1)
 gsXGB.fit(X_train, Y_train)
 XGBC_best = gsXGB.best_estimator_
gsXGB.best_score_<choose_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):
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
def data_augment(image, label):
image = tf.image.random_flip_left_right(image)
 image = tf.image.random_flip_up_down(image)
 image = tf.image.random_contrast(image,0,2)
 return image, label
def get_training_dataset() :
dataset = load_dataset(TRAINING_FILENAMES, labeled=True)
 dataset = dataset.map(data_augment, num_parallel_calls=AUTO)
 dataset = dataset.repeat()
dataset = dataset.shuffle(1024)
 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
def count_data_items(filenames):
n = [int(re.compile(r"-([0-9]*)\." ).search(filename ).group(1)) for filename in filenames]
return np.sum(n)
 NUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)
 NUM_VALIDATION_IMAGES =(1 - SKIP_VALIDATION)* count_data_items(VALIDATION_FILENAMES)
 NUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)
 STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE
print('Dataset: {} training images, {} validation images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))
DTC = DecisionTreeClassifier(max_depth=1)
 adaDTC = AdaBoostClassifier(DTC, random_state=0)
 ada_param_grid = {'base_estimator__criterion':['gini', 'entropy'],
'base_estimator__splitter' :['best', 'random'],
'algorithm' :['SAMME', 'SAMME.R'],
'n_estimators' :[100],
'learning_rate' :[0.0001, 0.001, 0.01, 0.1, 1, 5, 10]}
gsadaDTC = GridSearchCV(adaDTC, param_grid=ada_param_grid, cv=kfold, scoring='accuracy', n_jobs=4, verbose=1)
 gsadaDTC.fit(X_train,Y_train)
 ada_best = gsadaDTC.best_estimator_
gsadaDTC.best_score_<choose_model_class>
with strategy.scope() :
enet = efn.EfficientNetB7(
 input_shape=(512, 512, 3),
weights='imagenet',
include_top=False 
)
 model = tf.keras.Sequential([
enet,
tf.keras.layers.GlobalMaxPooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model.compile(
 optimizer=tf.keras.optimizers.Adam(lr=0.0001),
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 model.summary()
ExtC = ExtraTreesClassifier(random_state=0)
 ex_param_grid = {'max_depth' :[4],
'max_features' :[7],
'min_samples_split':[8],
'min_samples_leaf' :[4],
'bootstrap' :[False],
'n_estimators' :[100],
'criterion' :['gini']}
gsExtC = GridSearchCV(ExtC, param_grid=ex_param_grid, cv=kfold, scoring='accuracy', n_jobs=4, verbose=1)
 gsExtC.fit(X_train, Y_train)
 ExtC_best = gsExtC.best_estimator_
gsExtC.best_score_<train_on_grid>
history = model.fit(
 get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS,
callbacks=[lr_callback],
validation_data=None if SKIP_VALIDATION else get_validation_dataset()
)
RFC = RandomForestClassifier(random_state=0)
 rf_param_grid = {'max_depth' :[6],
'max_features' :[10],
'min_samples_split':[10],
'bootstrap' :[False],
'n_estimators' :[100],
'criterion' :['gini']}
gsRFC = GridSearchCV(RFC, param_grid=rf_param_grid, cv=kfold, scoring='accuracy', n_jobs=4, verbose=1)
 gsRFC.fit(X_train, Y_train)
 RFC_best = gsRFC.best_estimator_
gsRFC.best_score_<choose_model_class>
with strategy.scope() :
res = ResNet152V2(
 input_shape=(512, 512, 3),
weights='imagenet',
include_top=False 
)
 model2 = tf.keras.Sequential([
res,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model2.compile(
 optimizer=tf.keras.optimizers.Adam(lr=0.0001),
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 model2.summary()
GBC = GradientBoostingClassifier(random_state=0)
 gb_param_grid = {'loss' :['deviance'],
'n_estimators' :[10],
'learning_rate' :[0.001, 0.01, 0.1, 1, 10, 100],
'max_depth' :[4],
'min_samples_leaf':[8],
'max_features' :[0.3, 0.1]
}
gsGBC = GridSearchCV(GBC, param_grid=gb_param_grid, cv=kfold, scoring='accuracy',n_jobs=4, verbose=1)
 gsGBC.fit(X_train, Y_train)
 GBC_best = gsGBC.best_estimator_
gsGBC.best_score_<train_on_grid>
history2 = model2.fit(
 get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS,
callbacks=[lr_callback],
validation_data=None if SKIP_VALIDATION else get_validation_dataset()
)
SVMC = SVC(probability=True)
 svc_param_grid = {'kernel':['rbf'],
'gamma' :[0.01,0.1,1,10,100],
'C' :[0.01,0.1,1,10,100]}
gsSVMC = GridSearchCV(SVMC, param_grid=svc_param_grid, cv=kfold, scoring='accuracy', n_jobs=4, verbose=1)
 gsSVMC.fit(X_train, Y_train)
 SVMC_best = gsSVMC.best_estimator_
gsSVMC.best_score_<train_on_grid>
with strategy.scope() :
Inct=InceptionResNetV2(
 input_shape=(512, 512, 3),
weights='imagenet',
include_top=False 
)
 model3 = tf.keras.Sequential([
Inct,
tf.keras.layers.GlobalMaxPooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model3.compile(
 optimizer=tf.keras.optimizers.Adam(lr=0.0001),
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 model3.summary()
parameters = {'solver':['adam'], 'max_iter':[800], 'alpha':10.0**-np.arange(1,10), 'hidden_layer_sizes':[40,20,10], 'random_state':[0,1] }
gsMLPC=GridSearchCV(MLPClassifier() , parameters, n_jobs=-1)
 gsMLPC.fit(X_train, Y_train)
 MLPC_best = gsMLPC.best_estimator_
gsMLPC.best_score_<save_to_csv>
history3 = model3.fit(
 get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS,
callbacks=[lr_callback],
validation_data=None if SKIP_VALIDATION else get_validation_dataset()
)
test_Survived = gsExtC.predict(test)
 submission = pd.DataFrame({
'PassengerId' : IDtest,
'Survived' : test_Survived
})
 submission.to_csv('ExtC_55th.csv', index=False )<save_to_csv>
with strategy.scope() :
den=DenseNet201(
 input_shape=(512, 512, 3),
weights='imagenet',
include_top=False 
)
 model4 = tf.keras.Sequential([
den,
tf.keras.layers.GlobalMaxPooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model4.compile(
 optimizer=tf.keras.optimizers.Adam(lr=0.0001),
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 model4.summary()
test_Survived = gsXGB.predict(test)
 submission = pd.DataFrame({
'PassengerId' : IDtest,
'Survived' : test_Survived
})
 submission.to_csv('XGB_55th.csv', index=False )<save_to_csv>
history4 = model4.fit(
 get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS,
callbacks=[lr_callback],
validation_data=None if SKIP_VALIDATION else get_validation_dataset()
)
test_Survived = gsGBC.predict(test)
 submission = pd.DataFrame({
'PassengerId' : IDtest,
'Survived' : test_Survived
})
 submission.to_csv('GBC_55th.csv', index=False )<save_to_csv>
if not SKIP_VALIDATION:
cmdataset = get_validation_dataset(ordered=True)
 images_ds = cmdataset.map(lambda image, label: image)
 labels_ds = cmdataset.map(lambda image, label: label ).unbatch()
cm_correct_labels = next(iter(labels_ds.batch(NUM_VALIDATION_IMAGES)) ).numpy()
m = model.predict(images_ds)
 m2 = model2.predict(images_ds)
 m3 = model3.predict(images_ds)
 scores = []
best_score,best_alpha,best_beta=0,0,0
for alpha in np.linspace(0,1,100):
for beta in np.linspace(0,1,100):
cm_probabilities = alpha*m+(beta)*m2+(1-alpha-beta)*m3
cm_predictions = np.argmax(cm_probabilities, axis=-1)
 score = f1_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
 if(score > best_score):
best_alpha = alpha
best_beta = beta
best_score = score
scores.append(best_score)
 plt.plot(scores)
 print("best_alha:",best_alpha,"best_beta:",best_beta)
 cm_probabilities = best_alpha*m+best_beta*m2+(1-best_alpha)*m3
cm_predictions = np.argmax(cm_probabilities, axis=-1)
 else:
best_alpha = 0.505
best_beta = 0.303
test_Survived = gsSVMC.predict(test)
 submission = pd.DataFrame({
'PassengerId' : IDtest,
'Survived' : test_Survived
})
 submission.to_csv('SVMC_55th.csv', index=False )<set_options>
if not SKIP_VALIDATION:
cmat = confusion_matrix(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)))
 score = f1_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
 precision = precision_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
 recall = recall_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
 display_confusion_matrix(cmat, score, precision, recall)
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score, precision, recall))
<load_from_csv><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)+ model2.predict(test_images_ds)+model3.predict(test_images_ds)+model4.predict(test_images_ds)) /4
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='' )