Kaggle competition: Flower Classification with TPUs
<SOS> metric: MacroFScore Kaggle data source: flower-classification-with-tpus<categorify>
!pip install efficientnet tensorflow_addons==0.9.1 tensorflow==2.1.0
combined_train_test['Pclass_Fare_Category'] = combined_train_test.apply(pclass_fare_category, args=(Pclass_1_mean_fare, Pclass_2_mean_fare, Pclass_3_mean_fare), axis = 1)
 print(combined_train_test['Pclass_Fare_Category'].groupby(by = combined_train_test['Pclass_Fare_Category'] ).count().sort_values(ascending = False))
le_fare = LabelEncoder()
le_fare.fit(np.array(['Pclass_1_Low_Fare', 'Pclass_1_High_Fare', 'Pclass_2_Low_Fare', 'Pclass_2_High_Fare', 'Pclass_3_Low_Fare', 'Pclass_3_High_Fare']))
combined_train_test['Pclass_Fare_Category'] = le_fare.transform(combined_train_test['Pclass_Fare_Category'] )<groupby>
import math
import re
import random
import os
import tensorflow as tf
import tensorflow_addons as tfa
import numpy as np
import tensorflow.keras.backend as K
import efficientnet.tfkeras as efn
from matplotlib import pyplot as plt
from datetime import datetime
print(combined_train_test['Fare'].groupby(by = combined_train_test['Pclass'] ).mean().sort_values(ascending = True))
combined_train_test['Pclass'].replace([1, 2, 3],[Pclass_1_mean_fare, Pclass_2_mean_fare, Pclass_3_mean_fare], inplace = True )<categorify>
print(f'Numpy version : {np.__version__}')
 print(f'Tensorflow version {tf.__version__}')
 AUTO = tf.data.experimental.AUTOTUNE
START_TIME = datetime.now()
SEED = 42
os.environ['PYTHONHASHSEED']=str(SEED)
 random.seed(SEED)
 np.random.seed(SEED)
 tf.random.set_seed(SEED )
combined_train_test['Family_Size'] = combined_train_test['Parch'] + combined_train_test['SibSp'] + 1
print(combined_train_test['Family_Size'].groupby(by = combined_train_test['Family_Size'] ).count().sort_values(ascending = False))
combined_train_test['Family_Size_Category'] = combined_train_test['Family_Size'].map(family_size_category)
 print(combined_train_test['Family_Size_Category'].groupby(by = combined_train_test['Family_Size_Category'] ).count().sort_values(ascending = False))
print(combined_train_test.groupby(['Survived', 'Family_Size_Category'])['Survived'].count())
 le_family = LabelEncoder()
le_family.fit(np.array(['Single', 'Small_Family', 'Large_Family']))
combined_train_test['Family_Size_Category'] = le_family.transform(combined_train_test['Family_Size_Category'])
 fam_size_cat_dummies_df = pd.get_dummies(combined_train_test['Family_Size_Category'],
prefix = combined_train_test[['Family_Size_Category']].columns[0])
 combined_train_test = pd.concat([combined_train_test, fam_size_cat_dummies_df], axis = 1 )<sort_values>
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 )
print(combined_train_test['Age'].groupby(by = combined_train_test['Title'] ).mean().sort_values(ascending = True))<feature_engineering>
GCS_DS_PATH = KaggleDatasets().get_gcs_path()
GCS_DS_PATH
combined_train_test['Age_Null'] = combined_train_test['Age'].apply(lambda x: 1 if(pd.notnull(x)) else 0 )<categorify>
IMAGE_SIZE = [512, 512]
VALIDATE_WARMUP = False
EPOCHS_WARMUP = 3
DO_AUG_WARMUP = False
VALIDATE = False
EPOCHS = 30
DO_AUG = True
BATCH_SIZE = 16 * strategy.num_replicas_in_sync
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')
 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']
missing_age_df = pd.DataFrame(combined_train_test[['Age', 'Parch', 'Sex', 'SibSp', 'Family_Size', 'Family_Size_Category', 'Title', 'Fare']])
 missing_age_df = pd.get_dummies(missing_age_df, columns = ['Title', 'Family_Size_Category', 'Sex'])
 missing_age_df.shape
missing_age_df.info()
missing_age_train = missing_age_df[missing_age_df['Age'].notnull() ]
missing_age_test = missing_age_df[missing_age_df['Age'].isnull() ]<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):
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 get_train_val_dataset(do_aug=True):
dataset = load_dataset(TRAINING_FILENAMES + VALIDATION_FILENAMES, labeled=True)
 if do_aug:
dataset = dataset.map(image_augmentation, num_parallel_calls=AUTO)
 dataset = dataset.repeat()
dataset = dataset.shuffle(2048)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.prefetch(AUTO)
 return dataset
def get_training_dataset(do_aug=True):
dataset = load_dataset(TRAINING_FILENAMES, labeled=True)
 if do_aug:
dataset = dataset.map(image_augmentation, 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
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 = count_data_items(VALIDATION_FILENAMES)
 NUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)
 STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE
print(f'Total training image: {NUM_TRAINING_IMAGES}')
 print(f'Total validation image: {NUM_VALIDATION_IMAGES}')
 print(f'Total test image: {NUM_TEST_IMAGES}')
 print(f'Steps per epoch : {STEPS_PER_EPOCH}' )
combined_train_test.loc[(combined_train_test.Age.isnull()), 'Age'] = fill_missing_age(missing_age_train, missing_age_test )<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 transform(image):
DIM = IMAGE_SIZE[0]
XDIM = DIM%2
if np.random.randint(0, 2)== 0:
rot = 17.* tf.random.normal([1],dtype='float32')
 else:
rot = tf.constant([0],dtype='float32')
 if np.random.randint(0, 2)== 0:
shr = 5.5 * tf.random.normal([1],dtype='float32')
 else:
shr = tf.constant([0],dtype='float32')
 if np.random.randint(0, 3)== 0:
h_zoom = tf.random.normal([1],dtype='float32')/8.5
if h_zoom > 0:
h_zoom = 1.0 + h_zoom * -1
else:
h_zoom = 1.0 + h_zoom
else:
h_zoom = tf.constant([1],dtype='float32')
 if np.random.randint(0, 3)== 0:
w_zoom = tf.random.normal([1],dtype='float32')/8.5
if w_zoom > 0:
w_zoom = 1.0 + w_zoom * -1
else:
w_zoom = 1.0 + w_zoom
else:
w_zoom = tf.constant([1],dtype='float32')
 if np.random.randint(0, 3)== 0:
h_shift = 18.* tf.random.normal([1],dtype='float32')
 else:
h_shift = tf.constant([0],dtype='float32')
 if np.random.randint(0, 3)== 0:
w_shift = 18.* tf.random.normal([1],dtype='float32')
 else:
w_shift = tf.constant([0],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] )
if(sum(n < 0 for n in combined_train_test.Age.values.flatten())> 0):
combined_train_test.loc[combined_train_test.Age < 0, 'Age'] = np.nan
combined_train_test['Age'] = combined_train_test[['Age']].fillna(combined_train_test.groupby('Title' ).transform('mean'))<sort_values>
def transform_grid_mark(image, inv_mat, image_shape):
h, w, c = image_shape
cx, cy = w//2, h//2
new_xs = tf.repeat(tf.range(-cx, cx, 1), h)
 new_ys = tf.tile(tf.range(-cy, cy, 1), [w])
 new_zs = tf.ones([h*w], dtype=tf.int32)
 old_coords = tf.matmul(inv_mat, tf.cast(tf.stack([new_xs, new_ys, new_zs]), tf.float32))
old_coords_x, old_coords_y = tf.round(old_coords[0, :] + w//2), tf.round(old_coords[1, :] + h//2)
 clip_mask_x = tf.logical_or(old_coords_x<0, old_coords_x>w-1)
 clip_mask_y = tf.logical_or(old_coords_y<0, old_coords_y>h-1)
 clip_mask = tf.logical_or(clip_mask_x, clip_mask_y)
 old_coords_x = tf.boolean_mask(old_coords_x, tf.logical_not(clip_mask))
old_coords_y = tf.boolean_mask(old_coords_y, tf.logical_not(clip_mask))
new_coords_x = tf.boolean_mask(new_xs+cx, tf.logical_not(clip_mask))
new_coords_y = tf.boolean_mask(new_ys+cy, tf.logical_not(clip_mask))
old_coords = tf.cast(tf.stack([old_coords_y, old_coords_x]), tf.int32)
 new_coords = tf.cast(tf.stack([new_coords_y, new_coords_x]), tf.int64)
 rotated_image_values = tf.gather_nd(image, tf.transpose(old_coords))
rotated_image_channel = list()
for i in range(c):
vals = rotated_image_values[:,i]
sparse_channel = tf.SparseTensor(tf.transpose(new_coords), vals, [h, w])
 rotated_image_channel.append(tf.sparse.to_dense(sparse_channel, default_value=0, validate_indices=False))
return tf.transpose(tf.stack(rotated_image_channel), [1,2,0])
 def random_rotate(image, angle, image_shape):
def get_rotation_mat_inv(angle):
angle = math.pi * angle / 180
cos_val = tf.math.cos(angle)
 sin_val = tf.math.sin(angle)
 one = tf.constant([1], tf.float32)
 zero = tf.constant([0], tf.float32)
 rot_mat_inv = tf.concat([cos_val, sin_val, zero,
-sin_val, cos_val, zero,
zero, zero, one], axis=0)
 rot_mat_inv = tf.reshape(rot_mat_inv, [3,3])
 return rot_mat_inv
angle = float(angle)* tf.random.normal([1],dtype='float32')
 rot_mat_inv = get_rotation_mat_inv(angle)
 return transform_grid_mark(image, rot_mat_inv, image_shape)
 def GridMask() :
h, w = IMAGE_SIZE[0], IMAGE_SIZE[1]
image_height, image_width =(h, w)
 d1 = 100
d2 = 160
rotate_angle = 45
ratio = 0.5
hh = int(np.ceil(np.sqrt(h*h+w*w)))
 hh = hh+1 if hh%2==1 else hh
d = tf.random.uniform(shape=[], minval=d1, maxval=d2, dtype=tf.int32)
 l = tf.cast(tf.cast(d,tf.float32)*ratio+0.5, tf.int32)
 st_h = tf.random.uniform(shape=[], minval=0, maxval=d, dtype=tf.int32)
 st_w = tf.random.uniform(shape=[], minval=0, maxval=d, dtype=tf.int32)
 y_ranges = tf.range(-1 * d + st_h, -1 * d + st_h + l)
 x_ranges = tf.range(-1 * d + st_w, -1 * d + st_w + l)
 for i in range(0, hh//d+1):
s1 = i * d + st_h
s2 = i * d + st_w
y_ranges = tf.concat([y_ranges, tf.range(s1,s1+l)], axis=0)
 x_ranges = tf.concat([x_ranges, tf.range(s2,s2+l)], axis=0)
 x_clip_mask = tf.logical_or(x_ranges <0 , x_ranges > hh-1)
 y_clip_mask = tf.logical_or(y_ranges <0 , y_ranges > hh-1)
 clip_mask = tf.logical_or(x_clip_mask, y_clip_mask)
 x_ranges = tf.boolean_mask(x_ranges, tf.logical_not(clip_mask))
y_ranges = tf.boolean_mask(y_ranges, tf.logical_not(clip_mask))
hh_ranges = tf.tile(tf.range(0,hh), [tf.cast(tf.reduce_sum(tf.ones_like(x_ranges)) , tf.int32)])
 x_ranges = tf.repeat(x_ranges, hh)
 y_ranges = tf.repeat(y_ranges, hh)
 y_hh_indices = tf.transpose(tf.stack([y_ranges, hh_ranges]))
x_hh_indices = tf.transpose(tf.stack([hh_ranges, x_ranges]))
y_mask_sparse = tf.SparseTensor(tf.cast(y_hh_indices, tf.int64), tf.zeros_like(y_ranges), [hh, hh])
 y_mask = tf.sparse.to_dense(y_mask_sparse, 1, False)
 x_mask_sparse = tf.SparseTensor(tf.cast(x_hh_indices, tf.int64), tf.zeros_like(x_ranges), [hh, hh])
 x_mask = tf.sparse.to_dense(x_mask_sparse, 1, False)
 mask = tf.expand_dims(tf.clip_by_value(x_mask + y_mask, 0, 1), axis=-1)
 mask = random_rotate(mask, rotate_angle, [hh, hh, 1])
 mask = tf.image.crop_to_bounding_box(mask,(hh-h)//2,(hh-w)//2, image_height, image_width)
 return mask
def apply_grid_mask(image):
mask = GridMask()
mask = tf.concat([mask, mask, mask], axis=-1)
 return image * tf.cast(mask, 'float32' )
print(combined_train_test['Age'].groupby(by = combined_train_test['Title'] ).mean().sort_values(ascending = True))<categorify>
def image_augmentation(image, label):
image = tf.image.random_flip_left_right(image)
 if np.random.randint(0, 2)== 0:
image = tf.image.random_brightness(image, 0.1)
 if np.random.randint(0, 2)== 0:
image = tf.image.random_contrast(image, 0.9, 1.1)
 if np.random.randint(0, 2)== 0:
image = tf.image.random_saturation(image, 0.9, 1.1)
 if np.random.randint(0, 2)== 0:
image = tf.image.random_hue(image, 0.05)
 image = transform(image)
 if np.random.randint(0, 2)== 0:
image = apply_grid_mask(image)
 return image, label
combined_train_test['Age_Category'] = combined_train_test['Age'].map(age_group_cat)
 le_age = LabelEncoder()
le_age.fit(np.array(['Baby', 'Toddler', 'Child', 'Teenager', 'Adult', 'Middle_Aged', 'Senior_Citizen', 'Old']))
combined_train_test['Age_Category'] = le_age.transform(combined_train_test['Age_Category'])
 age_cat_dummies_df = pd.get_dummies(combined_train_test['Age_Category'],
prefix = combined_train_test[['Age_Category']].columns[0])
 combined_train_test = pd.concat([combined_train_test, age_cat_dummies_df], axis = 1 )<categorify>
from tensorflow.keras.models import Model, Sequential
from tensorflow.keras.layers import Input, Flatten, Dense, Dropout, AveragePooling2D, GlobalAveragePooling2D, SpatialDropout2D
combined_train_test['Ticket_Letter'] = combined_train_test['Ticket'].str.split().str[0]
combined_train_test['Ticket_Letter'] = combined_train_test['Ticket_Letter'].apply(lambda x: np.NaN if x.isnumeric() else x)
 combined_train_test['Ticket_Number'] = combined_train_test['Ticket'].apply(lambda x: pd.to_numeric(x, errors='coerce'))
combined_train_test['Ticket_Number'].fillna(0, inplace = True)
 combined_train_test = pd.get_dummies(combined_train_test, columns = ['Ticket', 'Ticket_Letter'])
 combined_train_test.shape<categorify>
es_val_acc = tf.keras.callbacks.EarlyStopping(
 monitor='val_sparse_categorical_accuracy', min_delta=0.001, patience=5, verbose=1, mode='auto',
baseline=None, restore_best_weights=True 
)
 es_val_loss = tf.keras.callbacks.EarlyStopping(
 monitor='val_loss', min_delta=0.001, patience=5, verbose=1, mode='auto',
baseline=None, restore_best_weights=True 
)
 es_acc = tf.keras.callbacks.EarlyStopping(
 monitor='sparse_categorical_accuracy', min_delta=0.001, patience=5, verbose=1, mode='auto',
baseline=None, restore_best_weights=False 
)
 es_loss = tf.keras.callbacks.EarlyStopping(
 monitor='loss', min_delta=0.001, patience=5, verbose=1, mode='auto',
baseline=None, restore_best_weights=False
)
combined_train_test['Cabin_Letter'] = combined_train_test['Cabin'].apply(lambda x: str(x)[0] if(pd.notnull(x)) else x)
 combined_train_test = pd.get_dummies(combined_train_test, columns = ['Cabin', 'Cabin_Letter'])
 combined_train_test.shape<normalization>
with strategy.scope() :
efn7 = efn.EfficientNetB7(weights='noisy-student', include_top=False, input_shape=(IMAGE_SIZE[0], IMAGE_SIZE[1], 3))
for layer in efn7.layers[:745]:
layer.trainable = False
for layer in efn7.layers[745:]:
layer.trainable = True
model = Sequential([
efn7,
GlobalAveragePooling2D() ,
Dense(len(CLASSES), activation='softmax')
 ], name='b7-flower')
 densenet201 = DenseNet201(weights='imagenet', include_top=False, input_shape=(IMAGE_SIZE[0], IMAGE_SIZE[1], 3))
model.compile(optimizer=tfa.optimizers.LAMB() , loss='sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy'])
 model.summary()
scale_age_fare = preprocessing.StandardScaler().fit(combined_train_test[['Age', 'Fare']])
 combined_train_test[['Age', 'Fare']] = scale_age_fare.transform(combined_train_test[['Age', 'Fare']] )<drop_column>
with strategy.scope() :
densenet201 = tf.keras.applications.densenet.DenseNet201(weights='imagenet', include_top=False, input_shape=(IMAGE_SIZE[0], IMAGE_SIZE[1], 3))
for layer in densenet201.layers[:481]:
layer.trainable = False
for layer in densenet201.layers[481:]:
layer.trainable = True
model2 = Sequential([
densenet201,
GlobalAveragePooling2D() ,
Dense(len(CLASSES), activation='softmax')
 ], name='dn201-flower')
 model2.compile(optimizer=tfa.optimizers.LAMB() , loss='sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy'])
 model2.summary()
combined_train_test.drop(['Name', 'PassengerId', 'Embarked', 'Sex', 'Title', 'Fare_Category', 'Family_Size_Category', 'Age_Category', 'First_Name', 'Last_Name', 'Original_Name', 'Name_Length_Category'], axis = 1, inplace = True )<prepare_x_and_y>
def lrfn(epoch):
initial_lr = 0.0001
current_lr = initial_lr + 0.00015 * epoch
return current_lr
lr_schedule = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose = True)
 plt_lr(EPOCHS_WARMUP )
train_data = combined_train_test[:891]
test_data = combined_train_test[891:]
titanic_train_data_X = train_data.drop(['Survived'], axis = 1)
 titanic_train_data_y = train_data['Survived']
titanic_test_data_X = test_data.drop(['Survived'], axis = 1 )<choose_model_class>
if VALIDATE_WARMUP:
model.fit(
 get_training_dataset(do_aug=DO_AUG_WARMUP), steps_per_epoch=STEPS_PER_EPOCH, epochs=EPOCHS_WARMUP,
validation_data=get_validation_dataset() , callbacks=[lr_schedule], verbose=1 
)
 else:
model.fit(
 get_train_val_dataset(do_aug=DO_AUG_WARMUP), steps_per_epoch=STEPS_PER_EPOCH, epochs=EPOCHS_WARMUP,
callbacks=[lr_schedule], verbose=1
)
rf_est = ensemble.RandomForestClassifier(n_estimators = 750, criterion = 'gini', max_features = 'sqrt', max_depth = 3, min_samples_split = 4, min_samples_leaf = 2, n_jobs = 50, random_state = 42, verbose = 1)
 gbm_est = ensemble.GradientBoostingClassifier(n_estimators = 900, learning_rate = 0.0008, loss = 'exponential', min_samples_split = 3, min_samples_leaf = 2, max_features ='sqrt', max_depth = 3, random_state = 42, verbose = 1)
 et_est = ensemble.ExtraTreesClassifier(n_estimators = 750, max_features = 'sqrt', max_depth = 35, n_jobs = 50, criterion = 'entropy', random_state = 42, verbose = 1)
 voting_est = ensemble.VotingClassifier(estimators = [('rf', rf_est),('gbm', gbm_est),('et', et_est)],
voting = 'soft', weights = [3,5,2],
n_jobs = 50)
 voting_est.fit(titanic_train_data_X, titanic_train_data_y)
 print("VotingClassifier Score: " + str(voting_est.score(titanic_train_data_X, titanic_train_data_y)))
 print("VotingClassifier Estimators: " + str(voting_est.estimators_))<predict_on_test>
h = model.history
plt_acc(h)
 plt_loss(h )
titanic_test_data_X['Survived'] = voting_est.predict(titanic_test_data_X )<save_to_csv>
if VALIDATE_WARMUP:
model2.fit(
 get_training_dataset(do_aug=DO_AUG_WARMUP), steps_per_epoch=STEPS_PER_EPOCH, epochs=EPOCHS_WARMUP,
validation_data=get_validation_dataset() , callbacks=[lr_schedule], verbose=1 
)
 else:
model2.fit(
 get_train_val_dataset(do_aug=DO_AUG_WARMUP), steps_per_epoch=STEPS_PER_EPOCH, epochs=EPOCHS_WARMUP,
callbacks=[lr_schedule], verbose=1
)
submission = pd.DataFrame({'PassengerId': test_data_orig.loc[:, 'PassengerId'],
'Survived': titanic_test_data_X.loc[:, 'Survived']})
 submission.to_csv(".. /working/submission.csv", index = False )<import_modules>
LR_START = 0.0006
LR_MAX = 0.003
LR_MIN = 0.0003
LR_RAMPUP_EPOCHS = 4
LR_SUSTAIN_EPOCHS = 0
LR_EXP_DECAY = 0.91
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_schedule = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose = True)
 plt_lr(EPOCHS )
import re
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, auc, classification_report, confusion_matrix, f1_score, fbeta_score, precision_recall_curve, precision_score, recall_score, roc_auc_score, roc_curve<load_from_csv>
for layer in model.layers:
layer.trainable = True
model.compile(optimizer=tfa.optimizers.LAMB() , loss='sparse_categorical_crossentropy', metrics=['sparse_categorical_accuracy'])
 model.summary()
df_train = pd.read_csv('.. /input/train.csv')
 df_test = pd.read_csv('.. /input/test.csv' )<concatenate>
if VALIDATE:
model.fit(
 get_training_dataset(do_aug=DO_AUG), steps_per_epoch=STEPS_PER_EPOCH, epochs=35,
validation_data=get_validation_dataset() , callbacks=[es_acc, lr_schedule], verbose=1 
)
 else:
model.fit(
 get_train_val_dataset(do_aug=DO_AUG), steps_per_epoch=STEPS_PER_EPOCH, epochs=35,
callbacks=[es_val_acc, lr_schedule], verbose=1
)
df_train['DataType'], df_test['DataType'] = 'training', 'testing'
df_test.insert(1, 'Survived', np.nan)
 df_data = pd.concat([df_train, df_test], ignore_index=True )<data_type_conversions>
h = model.history
plt_acc(h)
 plt_loss(h )
col_convert = ['Survived', 'Pclass', 'SibSp', 'Parch']
df_data[col_convert] = df_data[col_convert].astype('object' )<feature_engineering>
if VALIDATE:
model2.fit(
 get_training_dataset(do_aug=DO_AUG), steps_per_epoch=STEPS_PER_EPOCH, epochs=30,
validation_data=get_validation_dataset() , callbacks=[es_acc, lr_schedule], verbose=1 
)
 else:
model2.fit(
 get_train_val_dataset(do_aug=DO_AUG), steps_per_epoch=STEPS_PER_EPOCH, epochs=30,
callbacks=[es_val_acc, lr_schedule], verbose=1
)
df_data['Surname'] = df_data['Name'].str.extract(r'([A-Za-z]+),', expand=False )<feature_engineering>
POST_TRAINING_TIME_START = datetime.now()
df_data['Title'] = df_data['Name'].str.extract(r'([A-Za-z]+)\.', expand=False)
 df_data['Title'] = df_data['Title'].replace(['Capt', 'Rev'], 'Crew')
 df_data['Title'] = df_data['Title'].replace('Ms', 'Miss')
 df_data['Title'] = df_data['Title'].replace(['Col', 'Countess', 'Don', 'Dona', 'Jonkheer', 'Lady', 'Major', 'Mlle', 'Mme', 'Sir'], 'Royal')
 df_data['Title'].value_counts()<data_type_conversions>
if VALIDATE:
cmat, score, precision, recall, acc = evaluate(model )
df_data['Age'] = df_data['Age'].fillna(df_data.groupby(['Title'], as_index=True)['Age'].transform('mean'))<feature_engineering>
if VALIDATE:
display_confusion_matrix(cmat, score, precision, recall, acc )
df_data['FamilySize'] = df_data['SibSp'] + df_data['Parch'] + 1<count_values>
if VALIDATE:
cmat, score, precision, recall, acc = evaluate(model2 )
df_data['TicketString'] = df_data['Ticket'].apply(lambda x: ''.join(re.findall(r'[a-zA-Z]+', x)))
 df_data['TicketString'] = df_data['TicketString'].replace(['CASOTON', 'SOTONO', 'STONO', 'STONOQ'], 'SOTONOQ')
 df_data['TicketString'] = df_data['TicketString'].replace(['SC', 'SCParis'], 'SCPARIS')
 df_data['TicketString'] = df_data['TicketString'].replace('FCC', 'FC')
 df_data['TicketString'] = df_data['TicketString'].replace(df_data['TicketString'].value_counts() [df_data['TicketString'].value_counts() < 10].index.tolist() , 'OTHER')
 df_data['TicketString'].value_counts()<data_type_conversions>
if VALIDATE:
display_confusion_matrix(cmat, score, precision, recall, acc )
df_data['HasTicketString'] = df_data['TicketString'].apply(lambda x: 1 if x else 0 ).astype('object' )<categorify>
if VALIDATE:
cmat, score, precision, recall, acc = evaluate([model, model2] )
df_data['Fare'] = df_data['Fare'].fillna(df_data.groupby(['Pclass'], as_index=True)['Fare'].transform('mean'))<feature_engineering>
if VALIDATE:
display_confusion_matrix(cmat, score, precision, recall, acc )
df_data['Cabin'] = df_data['Cabin'].fillna(0 )<feature_engineering>
def show_predict_val(m):
row, col = 3, 5
dataset = get_validation_dataset()
dataset = dataset.unbatch().batch(row * col)
 images, labels = next(iter(dataset))
probabilities = m.predict(images)
 predictions = np.argmax(probabilities, axis=-1)
 plt.figure(figsize=(15,int(15*row/col)))
 for i in range(row*col):
plt.subplot(row,col,i+1)
 pred = CLASSES[predictions[i]]
real = CLASSES[labels[i]]
if pred == real:
plt.title(f'{pred} [OK]')
 else:
plt.title(f'{pred} [NO -> {real}]', color='red')
 plt.axis('off')
 plt.imshow(images[i,])
 plt.show()
df_data['CabinString'] = df_data['Cabin'].str.extract(r'([A-Za-z]+)', expand=False )<data_type_conversions>
if VALIDATE:
show_predict_val(model )
df_data['HasCabin'] = df_data['CabinString'].apply(lambda x: 0 if pd.isnull(x)else 1 ).astype('object' )<count_values>
if VALIDATE:
show_predict_val(model2 )
df_data['Embarked'] = df_data['Embarked'].fillna(df_data['Embarked'].value_counts().idxmax() )<categorify>
test_ds = get_test_dataset(ordered=True)
 print('Computing predictions...')
 test_images_ds = test_ds.map(lambda image, idnum: image)
 model_pred = model.predict(test_images_ds)
 model2_pred = model2.predict(test_images_ds)
 probabilities =(model_pred * 0.56)+(model2_pred * 0.44)
 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='')
 !head submission.csv
<data_type_conversions><EOS> 
print(f'Post training time : {(datetime.now() - POST_TRAINING_TIME_START ).total_seconds() } seconds' )