Kaggle competition: Petals to the Metal - Flower Classification on TPU
<SOS> metric: macrofscore Kaggle data source: petals-to-the-metal-flower-classification-on-tpu<compute_test_metric>
!pip install -q efficientnet
logloss_rf = log_loss(y_val,rf_clf.predict_proba(X_val_onehot))
print('logloss_rf:',logloss_rf )<train_model>
import numpy as np
import pandas as pd
import re
import os
import efficientnet.tfkeras as efn
import tensorflow as tf
from tensorflow.keras.layers import Input, Dense
from tensorflow.keras.layers import GlobalAveragePooling2D
from tensorflow.keras.models import Sequential
from tensorflow.keras.callbacks import LearningRateScheduler
from kaggle_datasets import KaggleDatasets
from sklearn.metrics import confusion_matrix, f1_score
from sklearn.metrics import precision_score, recall_score
import seaborn as sea
import matplotlib.pyplot as plt
xgb_clf = xgb.XGBClassifier(n_estimators=100,n_jobs=-1,max_depth=15,
min_child_weight=3,objective='binary:logistic'
,colsample_bytree=0.4)
 xgb_clf.fit(X_train_onehot, y_train)
 xgb_predictions = xgb_clf.predict(X_val_onehot)
 print('accuracy score: ',accuracy_score(xgb_predictions,y_val))
print(classification_report(y_val, xgb_predictions))<compute_test_metric>
sea.set_style("darkgrid")
 np.random.seed(3)
 tf.random.set_seed(6 )
logloss_xgb = log_loss(y_val,xgb_clf.predict_proba(X_val_onehot))
print('logloss_rf:',logloss_xgb )<choose_model_class>
gcs_path = KaggleDatasets().get_gcs_path("tpu-getting-started")
 data_path = os.path.join(gcs_path, "tfrecords-jpeg-512x512/")
 train_path = os.path.join(gcs_path, "tfrecords-jpeg-512x512/train/")
 val_path = os.path.join(gcs_path, "tfrecords-jpeg-512x512/val/")
 test_path = os.path.join(gcs_path, "tfrecords-jpeg-512x512/test/" )
model = Sequential()
model.add(Dense(512, activation='relu', input_dim=np.shape(X_train_onehot)[1],
kernel_regularizer=regularizers.l2(0.01),
activity_regularizer=regularizers.l1(0.01)))
 model.add(BatchNormalization())
 model.add(Dropout(0.5))
model.add(Dense(256, activation='relu'))
model.add(BatchNormalization())
 model.add(Dropout(0.6))
model.add(Dense(64, activation='relu'))
model.add(BatchNormalization())
 model.add(Dropout(0.5))
model.add(Dense(1, activation='sigmoid'))
adam = Adam(lr=1e-4, beta_1=0.9, beta_2=0.999, epsilon=10**-8, decay=0.0001, amsgrad=False)
 model.compile(optimizer= adam,
loss='binary_crossentropy',
metrics=['accuracy'])
 print(model.summary())
 hist = model.fit(X_train_onehot, y_train,validation_data =(X_val_onehot,y_val), epochs=20, batch_size=16 )<predict_on_test>
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']
dnn_pred = model.predict_classes(X_val_onehot )<compute_test_metric>
def read_record(example):
features = {
"image": tf.io.FixedLenFeature([], tf.string),
"class": tf.io.FixedLenFeature([], tf.int64),
}
example = tf.io.parse_single_example(example, features)
 image = tf.image.decode_jpeg(example["image"], channels=3)
 image = tf.cast(image, tf.float32)/ 255.0
image = tf.reshape(image, [512,512,3])
 label = tf.cast(example["class"], tf.int32)
 return image, label
def read_record_test(example):
features = {
"image": tf.io.FixedLenFeature([], tf.string),
"id": tf.io.FixedLenFeature([], tf.string),
}
example = tf.io.parse_single_example(example, features)
 image = tf.image.decode_jpeg(example["image"], channels=3)
 image = tf.cast(image, tf.float32)/ 255.0
image = tf.reshape(image, [512,512,3])
 image_id = example["id"]
return image, image_id
print('accuracy score: ',accuracy_score(dnn_pred,y_val))
print(classification_report(y_val, dnn_pred))<compute_test_metric>
AUTO = tf.data.experimental.AUTOTUNE
def get_size(filenames):
data_size = 0
for i in range(len(filenames)) :
count = re.search(r"-[0-9][0-9][0-9]\.", filenames[i] ).group()
data_size = data_size + int(count[1:4])
 return data_size
def prepare_dataset(flag, order = False):
filenames = tf.io.gfile.glob(os.path.join(data_path, flag)+"/*.tfrec")
 data_size = get_size(filenames)
 dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO)
 ignore_order = tf.data.Options()
if order == False:
ignore_order.experimental_deterministic = False
else:
ignore_order.experimental_deterministic = True
dataset = dataset.with_options(ignore_order)
 if flag == "test":
dataset = dataset.map(read_record_test, num_parallel_calls=AUTO)
 else:
dataset = dataset.map(read_record, num_parallel_calls=AUTO)
 return dataset, data_size
train_dataset, train_size = prepare_dataset("train")
 val_dataset, val_size = prepare_dataset("val")
 test_dataset, test_size = prepare_dataset("test")
 print("Size of Training Dataset\t: ", train_size)
 print("Size of Validation Dataset\t: ", val_size)
 print("Size of Test Dataset\t\t: ", test_size )
logloss_dnn = log_loss(y_val,model.predict_proba(X_val_onehot))
print('logloss_dnn:',logloss_dnn )<predict_on_test>
def augment(image, label):
cont_low = 0.8
cont_high = 1.2
cont_factor = tf.random.uniform([], minval=cont_low,
maxval=cont_high,
dtype=tf.float32)
 trn_image = tf.image.adjust_contrast(image, cont_factor)
 return trn_image, label
lr_predictions_val = lr_clf.predict_proba(X_val_onehot)
 mnb_predictions_val = mnb_clf.predict_proba(X_val_onehot)
 xgb_predictions_val = xgb_clf.predict_proba(X_val_onehot)
<define_variables>
batch_size = 16 * tpu_strategy.num_replicas_in_sync
train_dataset = train_dataset.map(augment,
num_parallel_calls = AUTO)
 train_dataset = train_dataset.repeat().shuffle(3000)\ 
.batch(batch_size ).prefetch(AUTO)
 val_dataset = val_dataset.batch(batch_size ).prefetch(AUTO)
 test_dataset = test_dataset.batch(batch_size ).prefetch(AUTO )
predictions_val = 1/3*lr_predictions_val[:,1]+1/3*mnb_predictions_val[:,1] \
+1/3*xgb_predictions_val[:,1]
predictions_val = np.where(predictions_val>0.5, 1, 0 )<compute_test_metric>
with tpu_strategy.scope() :
base_model = efn.EfficientNetB5(include_top=False,
input_shape=(512,512,3),
weights='imagenet')
 base_model.trainable = True
model = Sequential(name="Flower_Detector")
 model.add(base_model)
 model.add(GlobalAveragePooling2D(name="GAP"))
model.add(Dense(104, activation="softmax", name="Probs"))
model.compile(optimizer=tf.keras.optimizers.Adam() ,
loss="sparse_categorical_crossentropy",
metrics=["sparse_categorical_accuracy"])
 model.summary()
print('accuracy score: ',accuracy_score(predictions_val,y_val))
print(classification_report(y_val, predictions_val))<load_from_csv>
step_per_epoch = train_size // batch_size
history = model.fit(train_dataset,
validation_data=val_dataset,
steps_per_epoch=step_per_epoch,
epochs=epoch,
callbacks=[lrs] )
df_test = pd.read_csv('.. /input/nlp-getting-started/test.csv' )<feature_engineering>
val_dataset, val_size = prepare_dataset("val", True)
 val_dataset = val_dataset.batch(batch_size ).prefetch(AUTO)
 val_image_dataset = val_dataset.map(lambda image,label: image)
 val_label_dataset = val_dataset.map(lambda image,label: label ).unbatch()
val_labels = next(iter(val_label_dataset.batch(val_size)) ).numpy()
val_probs = model.predict(val_image_dataset)
 val_preds = np.argmax(val_probs, axis=-1 )
df_test['text_processed'] = df_test['text'].apply(text_preprocessing )<categorify>
con_mat = confusion_matrix(val_labels, val_preds,
labels=range(len(classes)))
 prec = precision_score(val_labels, val_preds,
labels=range(len(classes)) ,
average='macro')
 rec = recall_score(val_labels, val_preds,
labels=range(len(classes)) ,
average='macro')
 f1 = f1_score(val_labels, val_preds,
labels=range(len(classes)) ,
average='macro')
 plt.figure(figsize=(10,10))
ax = plt.gca()
ax.matshow(con_mat, cmap='Greens')
 ax.set_xticks(range(len(classes)))
 ax.set_xticklabels(classes, fontdict={'fontsize': 6})
 plt.setp(ax.get_xticklabels() , rotation=65, ha="left",
rotation_mode="anchor")
 ax.set_yticks(range(len(classes)))
 ax.set_yticklabels(classes, fontdict={'fontsize': 6})
 plt.setp(ax.get_yticklabels() , rotation=25, ha="right",
rotation_mode="anchor")
 plt.show()
print('Precision \t: {:.4f}'.format(prec))
print('Recall \t\t: {:.4f}'.format(rec))
print('F1 score \t: {:.4f}'.format(f1))
X_test = df_test['text_processed']
X_test_onehot = vectorizer.transform(X_test ).todense()<predict_on_test>
test_dataset, test_size = prepare_dataset("test", True)
 test_dataset = test_dataset.batch(batch_size ).prefetch(AUTO)
 test_image_dataset = test_dataset.map(lambda image,idnum: image)
 test_id_dataset = test_dataset.map(lambda image,idnum: idnum ).unbatch()
test_ids = next(iter(test_id_dataset.batch(test_size)) ).numpy().astype('U')
 test_probs = model.predict(test_image_dataset)
 test_preds = np.argmax(test_probs, axis=-1 )