Kaggle competition: Petals to the Metal - Flower Classification on TPU
<SOS> metric: macrofscore Kaggle data source: petals-to-the-metal-flower-classification-on-tpu<drop_column>
!pip install efficientnet --quiet
sns.set()
<concatenate>
flower_categories = [
'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 flower categories:', len(flower_categories))
df = pd.concat(( train.loc[:,'Pclass':'Embarked'], test.loc[:,'Pclass':'Embarked'])).reset_index(drop=True)
<load_from_csv>
image_size =(224,224)
 data_gcs = KaggleDatasets().get_gcs_path('tpu-getting-started')
 ext_gcs = KaggleDatasets().get_gcs_path('tf-flower-photo-tfrec')
 data_dir_by_size = { 
(512, 512): '/tfrecords-jpeg-512x512', 
(331, 331): '/tfrecords-jpeg-331x331', 
(224, 224): '/tfrecords-jpeg-224x224', 
(192, 192): '/tfrecords-jpeg-192x192'
}
subdir = data_dir_by_size[image_size]
train_file_names = tf.io.gfile.glob(data_gcs + subdir+ '/train'+ '/*tfrec')
 val_file_names = tf.io.gfile.glob(data_gcs + subdir + '/val' + '/*tfrec')
 test_file_names = tf.io.gfile.glob(data_gcs + subdir + '/test' + '/*tfrec')
 imagenet_files = tf.io.gfile.glob(ext_gcs + '/imagenet' + subdir + '/*.tfrec')
 inaturelist_files = tf.io.gfile.glob(ext_gcs + '/inaturalist' + subdir + '/*.tfrec')
 openimage_files = tf.io.gfile.glob(ext_gcs + '/openimage' + subdir + '/*.tfrec')
 oxford_files = tf.io.gfile.glob(ext_gcs + '/oxford_102' + subdir + '/*.tfrec')
 tensorflow_files = tf.io.gfile.glob(ext_gcs + '/tf_flowers' + subdir + '/*.tfrec')
 train_file_names = train_file_names + imagenet_files + inaturelist_files + \
openimage_files + oxford_files + tensorflow_files
%pip install autoviz
AV = AutoViz_Class()
report_2 = AV.AutoViz("/kaggle/input/titanic/train.csv" )<feature_engineering>
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):

 example = tf.io.parse_single_example(
 serialized = example,
features = {
'image' : tf.io.FixedLenFeature([], tf.string),
'class' : tf.io.FixedLenFeature([], tf.int64)
 } 
)
 image = decode_image(example['image'])
 label = tf.cast(example['class'], tf.int32)
 return image, label
def read_unlabeled_tfrecord(example):

 example = tf.io.parse_single_example(
 serialized=example,
features={
'image': tf.io.FixedLenFeature([], tf.string),
'id': tf.io.FixedLenFeature([], tf.string),
} 
)
 image = decode_image(example['image'])
 idnum = example['id']
return image, idnum
def load_dataset(filenames, labeled = True, ordered= False):

 ignore_order = tf.data.Options()
ignore_order.experimental_deterministic = ordered
dataset = tf.data.TFRecordDataset(
 filenames, num_parallel_reads = tf.data.experimental.AUTOTUNE)
 dataset = dataset.with_options(ignore_order)
 dataset = dataset.map(
 read_labeled_tfrecord if labeled else read_unlabeled_tfrecord,
num_parallel_calls=tf.data.experimental.AUTOTUNE)
 return dataset
def count_data_items(filenames):

 return np.sum([
int(re.compile(r"-([0-9]*)\." ).search(filename ).group(1))
for filename in filenames])
 train_dataset = load_dataset(train_file_names, labeled=True, ordered=False)
 val_dataset = load_dataset(val_file_names, labeled=True, ordered=False)
 test_dataset = load_dataset(test_file_names, labeled=False, ordered=True)
 num_training_samples = count_data_items(train_file_names)
 num_validation_samples = count_data_items(val_file_names)
 num_testing_samples = count_data_items(test_file_names)
def basic_details(df):
b = pd.DataFrame()
b['Missing value, %'] = round(df.isnull().sum() /df.shape[0]*100)
 b['N unique value'] = df.nunique()
b['dtype'] = df.dtypes
return b
basic_details(df )<categorify>
print('Train samples:', num_training_samples, end=', ')
 print('Val samples:', num_validation_samples, end=', ')
 print('Test samples:', num_testing_samples )
df['Title'] = df.Name.str.extract('([A-Za-z]+)\.', expand=False)
 df['Title'] = df['Title'].replace(['Lady', 'Countess','Capt', 'Col', 'Don', 'Dr', 'Major', 'Rev', 'Sir', 'Jonkheer', 'Dona'], 'Rare')
 df['Title'] = df['Title'].replace('Mlle', 'Miss')
 df['Title'] = df['Title'].replace('Ms', 'Miss')
 df['Title'] = df['Title'].replace('Mme', 'Mrs')
 title_mapping = {"Mr": 1, "Miss": 2, "Mrs": 3, "Master": 4, "Rare": 5}
df['Title'] = df['Title'].map(title_mapping)
 df['Title'] = df['Title'].fillna(0)
 df = df.drop(['Name'], axis=1)
 df["Sex"][df["Sex"] == "male"] = 0
df["Sex"][df["Sex"] == "female"] = 1
df["Sex"] = df["Sex"].astype(int)
 df['Age'] = df.groupby('Pclass')['Age'].transform(lambda x: x.fillna(x.median()))
df["Age"] = df["Age"].astype(int)
 df['Age_cat'] = pd.qcut(df['Age'],q=[0,.16,.33,.49,.66,.83, 1], labels=False, precision=1)
 tickets = []
for i in list(df.Ticket):
if not i.isdigit() :
tickets.append(i.replace(".","" ).replace("/","" ).strip().split(" ")[0])
 else:
tickets.append("x")
 df["Ticket"] = tickets
df = pd.get_dummies(df, columns= ["Ticket"], prefix = "T")
 df['Fare'] = df.groupby("Pclass")['Fare'].transform(lambda x: x.fillna(x.median()))
df['Zero_Fare'] = df['Fare'].map(lambda x: 1 if x == 0 else(0))
def fare_category(fr):
if fr <= 7.91:
return 1
elif fr <= 14.454 and fr > 7.91:
return 2
elif fr <= 31 and fr > 14.454:
return 3
return 4
df['Fare_cat'] = df['Fare'].apply(fare_category)
 df['Cabin'] = df['Cabin'].fillna('U')
 df['Cabin'] = df['Cabin'].map(lambda x: re.compile("([a-zA-Z]+)" ).search(x ).group())
 cabin_category = {'A':9, 'B':8, 'C':7, 'D':6, 'E':5, 'F':4, 'G':3, 'T':2, 'U':1}
df['Cabin'] = df['Cabin'].map(cabin_category)
 df["Embarked"] = df["Embarked"].fillna("C")
 df["Embarked"][df["Embarked"] == "S"] = 1
df["Embarked"][df["Embarked"] == "C"] = 2
df["Embarked"][df["Embarked"] == "Q"] = 3
df["Embarked"] = df["Embarked"].astype(int)
 df['FamilySize'] = df['SibSp'] + df['Parch'] + 1
df['FamilySize_cat'] = df['FamilySize'].map(lambda x: 1 if x == 1
else(2 if 5 > x >= 2
else(3 if 8 > x >= 5
else 4)
))
df['Alone'] = [1 if i == 1 else 0 for i in df['FamilySize']]
dummy_col=['Title', 'Sex', 'Age_cat', 'SibSp', 'Parch', 'Fare_cat', 'Cabin', 'Embarked', 'Pclass', 'FamilySize_cat']
dummy = pd.get_dummies(df[dummy_col], columns=dummy_col, drop_first=False)
 df = pd.concat([dummy, df], axis = 1)
 df['FareCat_Sex'] = df['Fare_cat']*df['Sex']
df['Pcl_Sex'] = df['Pclass']*df['Sex']
df['Pcl_Title'] = df['Pclass']*df['Title']
df['Age_cat_Sex'] = df['Age_cat']*df['Sex']
df['Age_cat_Pclass'] = df['Age_cat']*df['Pclass']
df['Title_Sex'] = df['Title']*df['Sex']
df['Age_Fare'] = df['Age_cat']*df['Fare_cat']
df['SmallF'] = df['FamilySize'].map(lambda s: 1 if s == 2 else 0)
 df['MedF'] = df['FamilySize'].map(lambda s: 1 if 3 <= s <= 4 else 0)
 df['LargeF'] = df['FamilySize'].map(lambda s: 1 if s >= 5 else 0)
 df['Senior'] = df['Age'].map(lambda s:1 if s>70 else 0)
<feature_engineering>
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 descrictive_stat_feat(df):
df = pd.DataFrame(df)
 dcol= [c for c in df.columns if df[c].nunique() >=10]
d_median = df[dcol].median(axis=0)
 d_mean = df[dcol].mean(axis=0)
 q1 = df[dcol].apply(np.float32 ).quantile(0.25)
 q3 = df[dcol].apply(np.float32 ).quantile(0.75)
 for c in dcol:
df[c+str('_median_range')] =(df[c].astype(np.float32 ).values > d_median[c] ).astype(np.int8)
 df[c+str('_mean_range')] =(df[c].astype(np.float32 ).values > d_mean[c] ).astype(np.int8)
 df[c+str('_q1')] =(df[c].astype(np.float32 ).values < q1[c] ).astype(np.int8)
 df[c+str('_q3')] =(df[c].astype(np.float32 ).values > q3[c] ).astype(np.int8)
 return df
df = descrictive_stat_feat(df )<feature_engineering>
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 basic_details(df):
b = pd.DataFrame()
b['Missing value'] = df.isnull().sum()
b['N unique value'] = df.nunique()
b['dtype'] = df.dtypes
return b
basic_details(df )<prepare_x_and_y>
batch_size = 16 * strategy.num_replicas_in_sync
epochs = 25
batched_train_dataset = train_dataset.map(transform)
 batched_train_dataset = batched_train_dataset.repeat()
batched_train_dataset = batched_train_dataset.shuffle(buffer_size = 2048)
 batched_train_dataset = batched_train_dataset.batch(batch_size)
 batched_train_dataset = batched_train_dataset.prefetch(tf.data.experimental.AUTOTUNE)
 batched_val_dataset = val_dataset.batch(batch_size)
 batched_val_dataset = batched_val_dataset.cache()
batched_val_dataset = batched_val_dataset.prefetch(tf.data.experimental.AUTOTUNE)
 batched_test_dataset = test_dataset.batch(batch_size)
 batched_test_dataset = batched_test_dataset.prefetch(tf.data.experimental.AUTOTUNE)
 early_stopping = tf.keras.callbacks.EarlyStopping(monitor ='val_loss', patience= 3)
 save_checkpoints = tf.keras.callbacks.ModelCheckpoint('/kaggle/working/weights.{epoch:02d}-{val_loss:.2f}.hdf5',
save_freq='epoch', period=4)
 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_DECAY =.8
def lr_schedule(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_DECAY**(epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS)+ LR_MIN
return lr
lr_callback = tf.keras.callbacks.LearningRateScheduler(lr_schedule, verbose = True )
X_train = df[:train.shape[0]]
X_test_fin = df[train.shape[0]:]
y = train.Survived
X_train['Y'] = y
df = X_train
df.head(20)
 X = df.drop('Y', axis=1)
 y = df.Y<import_modules>
def get_model() :
with strategy.scope() :
feature_extractor = efficientnet.EfficientNetB7(
 weights = 'noisy-student', include_top = False, input_shape=[*image_size, 3])
 feature_extractor.trainable = True
model = tf.keras.Sequential([
feature_extractor,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(flower_categories), activation='softmax', dtype='float32')
 ])
 model.compile(optimizer='adam',
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 return model
from keras.models import Sequential
from keras.layers import Dense, Activation, Dropout
import keras
from keras.optimizers import SGD
import graphviz
import eli5
from eli5.sklearn import PermutationImportance<split>
history = model.fit(
 batched_train_dataset,
steps_per_epoch=num_training_samples // batch_size,
epochs=epochs,
callbacks=[lr_callback, early_stopping, save_checkpoints],
validation_data=batched_val_dataset,
verbose=2 )
<train_model><EOS> 
print("Creating submission")
 test_image_dataset = batched_test_dataset.map(lambda image,idnum: image)
 predictions = np.argmax(model.predict(test_image_dataset), axis = -1)
 test_ids_dataset = batched_test_dataset.map(lambda image, idnum: idnum ).unbatch()
test_ids = next(iter(test_ids_dataset.batch(num_testing_samples)) ).numpy().astype('U')
 np.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')
 print('Done!' )