Kaggle competition: Flower Classification with TPUs
<SOS> metric: MacroFScore Kaggle data source: flower-classification-with-tpus<concatenate>
!pip install -q efficientnet
sub = pd.concat([test.PassengerId, y_pred], axis=1 )<data_type_conversions>
import efficientnet.tfkeras as efn
from tensorflow.keras.applications import InceptionResNetV2
from tensorflow.keras.applications import ResNet152V2
from sklearn.metrics import f1_score, precision_score, recall_score, confusion_matrix
sub['Survived'].values[sub['Survived'].values > 0.5] = 1
sub['Survived'].values[sub['Survived'].values <= 0.5] = 0
sub['Survived'] = sub['Survived'].astype(int )<prepare_output>
import numpy as np
import pandas as pd
import os
sub = sub.set_index(['PassengerId'] )<save_to_csv>
from IPython.display import display
from IPython.core.interactiveshell import InteractiveShell
from sklearn.model_selection import KFold
sub.to_csv('titanic_keras_exp_1.csv' )<load_from_csv>
print("Tensorflow version " + tf.__version__)
 AUTO = tf.data.experimental.AUTOTUNE
def concat_df(train_data, test_data):
return pd.concat([train_data, test_data], sort=True ).reset_index(drop=True)
 def divide_df(all_data):
return all_data.loc[:890], all_data.loc[891:].drop(['Survived'], axis=1)
 df_train = pd.read_csv('/kaggle/input/titanic/train.csv')
 df_test = pd.read_csv('/kaggle/input/titanic/test.csv')
 df_all = concat_df(df_train, df_test)
 df_train.name = 'Training Set'
df_test.name = 'Test Set'
df_all.name = 'All Set'
dfs = [df_train, df_test]
print('Number of Training Examples = {}'.format(df_train.shape[0]))
print('Number of Test Examples = {}
'.format(df_test.shape[0]))
print('Training X Shape = {}'.format(df_train.shape))
print('Training y Shape = {}
'.format(df_train['Survived'].shape[0]))
print('Test X Shape = {}'.format(df_test.shape))
print('Test y Shape = {}
'.format(df_test.shape[0]))
print(df_train.columns)
 print(df_test.columns )<feature_engineering>
GCS_DS_PATH = KaggleDatasets().get_gcs_path('flower-classification-with-tpus')
 IMAGE_SIZE = [512,512]
df_all['Fare'] = pd.qcut(df_all['Fare'], 13 )<feature_engineering>
df_all['Age'] = pd.qcut(df_all['Age'], 10 )<categorify>
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')
 SKIP_VALIDATION = False
if SKIP_VALIDATION:
TRAINING_FILENAMES = TRAINING_FILENAMES + VALIDATION_FILENAMES
df_all['Ticket_Frequency'] = df_all.groupby('Ticket')['Ticket'].transform('count' )<feature_engineering>
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']
df_all['Title'] = df_all['Name'].str.split(', ', expand=True)[1].str.split('.', expand=True)[0]
df_all['Is_Married'] = 0
df_all['Is_Married'].loc[df_all['Title'] == 'Mrs'] = 1<import_modules>
MIXED_PRECISION = False
XLA_ACCELERATE = False
if MIXED_PRECISION:
if tpu: policy = tf.keras.mixed_precision.experimental.Policy('mixed_bfloat16')
 else: policy = tf.keras.mixed_precision.experimental.Policy('mixed_float16')
 mixed_precision.set_policy(policy)
 print('Mixed precision enabled')
 if XLA_ACCELERATE:
tf.config.optimizer.set_jit(True)
 print('Accelerated Linear Algebra enabled' )
import string<string_transform>
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 )
def extract_surname(data):
families = []
for i in range(len(data)) :
name = data.iloc[i]
if '(' in name:
name_no_bracket = name.split('(')[0]
else:
name_no_bracket = name
family = name_no_bracket.split(',')[0]
title = name_no_bracket.split(',')[1].strip().split(' ')[0]
for c in string.punctuation:
family = family.replace(c, '' ).strip()
families.append(family)
 return families
df_all['Family'] = extract_surname(df_all['Name'])
 df_train = df_all.loc[:890]
df_test = df_all.loc[891:]
dfs = [df_train, df_test]<define_variables>
EPOCHS = 20
mean_survival_rate = np.mean(df_train['Survived'])
 train_family_survival_rate = []
train_family_survival_rate_NA = []
test_family_survival_rate = []
test_family_survival_rate_NA = []
for i in range(len(df_train)) :
if df_train['Family'][i] in family_rates:
train_family_survival_rate.append(family_rates[df_train['Family'][i]])
 train_family_survival_rate_NA.append(1)
 else:
train_family_survival_rate.append(mean_survival_rate)
 train_family_survival_rate_NA.append(0)
 for i in range(len(df_test)) :
if df_test['Family'].iloc[i] in family_rates:
test_family_survival_rate.append(family_rates[df_test['Family'].iloc[i]])
 test_family_survival_rate_NA.append(1)
 else:
test_family_survival_rate.append(mean_survival_rate)
 test_family_survival_rate_NA.append(0)
 df_train['Family_Survival_Rate'] = train_family_survival_rate
df_train['Family_Survival_Rate_NA'] = train_family_survival_rate_NA
df_test['Family_Survival_Rate'] = test_family_survival_rate
df_test['Family_Survival_Rate_NA'] = test_family_survival_rate_NA
train_ticket_survival_rate = []
train_ticket_survival_rate_NA = []
test_ticket_survival_rate = []
test_ticket_survival_rate_NA = []
for i in range(len(df_train)) :
if df_train['Ticket'][i] in ticket_rates:
train_ticket_survival_rate.append(ticket_rates[df_train['Ticket'][i]])
 train_ticket_survival_rate_NA.append(1)
 else:
train_ticket_survival_rate.append(mean_survival_rate)
 train_ticket_survival_rate_NA.append(0)
 for i in range(len(df_test)) :
if df_test['Ticket'].iloc[i] in ticket_rates:
test_ticket_survival_rate.append(ticket_rates[df_test['Ticket'].iloc[i]])
 test_ticket_survival_rate_NA.append(1)
 else:
test_ticket_survival_rate.append(mean_survival_rate)
 test_ticket_survival_rate_NA.append(0)
 df_train['Ticket_Survival_Rate'] = train_ticket_survival_rate
df_train['Ticket_Survival_Rate_NA'] = train_ticket_survival_rate_NA
df_test['Ticket_Survival_Rate'] = test_ticket_survival_rate
df_test['Ticket_Survival_Rate_NA'] = test_ticket_survival_rate_NA<load_from_csv>
LR_START = 0.00001
LR_MAX = 0.00005 * strategy.num_replicas_in_sync
LR_MIN = 0.00001
LR_RAMPUP_EPOCHS = 4
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(50 if EPOCHS<50 else 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]))
train_data=pd.read_csv('/kaggle/input/titanic/train.csv')
 test_data=pd.read_csv('/kaggle/input/titanic/test.csv' )<count_missing_values>
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, seed=2020):
image = tf.image.random_flip_left_right(image, seed=seed)
 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(2048)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.prefetch(AUTO)
 return dataset
def get_training_dataset(dataset, do_aug=True):
dataset = dataset.map(data_augment, num_parallel_calls=AUTO)
 dataset = dataset.repeat()
dataset = dataset.batch(AUG_BATCH)
 if do_aug: dataset = dataset.map(transform, num_parallel_calls=AUTO)
 dataset = dataset.unbatch()
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_train_valid_datasets() :
dataset = load_dataset(TRAINING_FILENAMES + VALIDATION_FILENAMES, labeled=True)
 dataset = dataset.map(data_augment, num_parallel_calls=AUTO)
 dataset = dataset.repeat()
dataset = dataset.shuffle(2048)
 dataset = dataset.batch(BATCH_SIZE)
 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 )
train_data.isnull().sum()<count_missing_values>
BATCH_SIZE = 8 * strategy.num_replicas_in_sync
AUG_BATCH = BATCH_SIZE
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('Dataset: {} training images, {} validation images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))
test_data.isnull().sum()<feature_engineering>
np.set_printoptions(threshold=15, linewidth=80)
 def batch_to_numpy_images_and_labels(data):
images, labels = data
numpy_images = images.numpy()
numpy_labels = labels.numpy()
if numpy_labels.dtype == object:
numpy_labels = [None for _ in enumerate(numpy_images)]
return numpy_images, numpy_labels
def title_from_label_and_target(label, correct_label):
if correct_label is None:
return CLASSES[label], True
correct =(label == correct_label)
 return "{} [{}{}{}]".format(CLASSES[label], 'OK' if correct else 'NO', u"\u2192" if not correct else '',
CLASSES[correct_label] if not correct else ''), correct
def display_one_flower(image, title, subplot, red=False, titlesize=16):
plt.subplot(*subplot)
 plt.axis('off')
 plt.imshow(image)
 if len(title)> 0:
plt.title(title, fontsize=int(titlesize)if not red else int(titlesize/1.2), color='red' if red else 'black', fontdict={'verticalalignment':'center'}, pad=int(titlesize/1.5))
return(subplot[0], subplot[1], subplot[2]+1)
 def display_batch_of_images(databatch, predictions=None):

 images, labels = batch_to_numpy_images_and_labels(databatch)
 if labels is None:
labels = [None for _ in enumerate(images)]
rows = int(math.sqrt(len(images)))
 cols = len(images)//rows
FIGSIZE = 13.0
SPACING = 0.1
subplot=(rows,cols,1)
 if rows < cols:
plt.figure(figsize=(FIGSIZE,FIGSIZE/cols*rows))
else:
plt.figure(figsize=(FIGSIZE/rows*cols,FIGSIZE))
for i,(image, label)in enumerate(zip(images[:rows*cols], labels[:rows*cols])) :
title = '' if label is None else CLASSES[label]
correct = True
if predictions is not None:
title, correct = title_from_label_and_target(predictions[i], label)
 dynamic_titlesize = FIGSIZE*SPACING/max(rows,cols)*40+3
subplot = display_one_flower(image, title, subplot, not correct, titlesize=dynamic_titlesize)
 plt.tight_layout()
if label is None and predictions is None:
plt.subplots_adjust(wspace=0, hspace=0)
 else:
plt.subplots_adjust(wspace=SPACING, hspace=SPACING)
 plt.show()
def display_confusion_matrix(cmat, score, precision, recall):
plt.figure(figsize=(15,15))
ax = plt.gca()
ax.matshow(cmat, cmap='BuPu')
 ax.set_xticks(range(len(CLASSES)))
 ax.set_xticklabels(CLASSES, fontdict={'fontsize': 7})
 plt.setp(ax.get_xticklabels() , rotation=45, ha="left", rotation_mode="anchor")
 ax.set_yticks(range(len(CLASSES)))
 ax.set_yticklabels(CLASSES, fontdict={'fontsize': 7})
 plt.setp(ax.get_yticklabels() , rotation=45, ha="right", rotation_mode="anchor")
 titlestring = ""
if score is not None:
titlestring += 'f1 = {:.3f} '.format(score)
 if precision is not None:
titlestring += '
precision = {:.3f} '.format(precision)
 if recall is not None:
titlestring += '
recall = {:.3f} '.format(recall)
 if len(titlestring)> 0:
ax.text(101, 1, titlestring, fontdict={'fontsize': 18, 'horizontalalignment':'right', 'verticalalignment':'top', 'color':'
plt.show()
def display_training_curves(training, validation, title, subplot):
if subplot%10==1:
plt.subplots(figsize=(10,10), facecolor='
plt.tight_layout()
ax = plt.subplot(subplot)
 ax.set_facecolor('
ax.plot(training)
 ax.plot(validation)
 ax.set_title('model '+ title)
 ax.set_ylabel(title)
 ax.set_xlabel('epoch')
 ax.legend(['train', 'valid.'] )
train_data['Age'] = train_data['Age'].fillna(30 )<drop_column>
dataset = load_dataset(TRAINING_FILENAMES, labeled=True)
 training_dataset = get_training_dataset(dataset, do_aug=False)
 training_dataset = training_dataset.unbatch().batch(20)
 train_batch = iter(training_dataset )
train_data = train_data.drop(['Cabin'],axis=1)
 test_data = test_data.drop(['Cabin'],axis=1 )<count_values>
print("Training data shapes:")
 for image, label in get_training_dataset(dataset, do_aug=False ).take(2):
print(image.numpy().shape, label.numpy().shape)
 train_image = image.numpy()
train_label = label.numpy()
print("Training data label examples:", label.numpy())
 print("Validation data shapes:")
 for image, label in get_validation_dataset().take(2):
print(image.numpy().shape, label.numpy().shape)
 print("Validation data label examples:", label.numpy())
 print("Test data shapes:")
 for image, idnum in get_test_dataset().take(2):
print(image.numpy().shape, idnum.numpy().shape)
 print("Test data IDs:", idnum.numpy().astype('U'))
train_data['Embarked'].value_counts()<feature_engineering>
valid_dataset = get_validation_dataset()
valid_dataset = valid_dataset.unbatch().batch(20)
 val_batch = iter(valid_dataset )
train_data['Embarked']=train_data['Embarked'].fillna('S' )<categorify>
display_batch_of_images(next(train_batch))
train_data['Sex'] = pd.get_dummies(train_data['Sex'])
 test_data['Sex'] = pd.get_dummies(test_data['Sex'])
 train_data['Fare']=train_data['Fare'].astype('int32')
 train_data['Embarked'] = pd.factorize(train_data['Embarked'])[0]
test_data['Embarked'] = pd.factorize(test_data['Embarked'])[0]
test_data['Fare']=test_data['Fare'].fillna(test_data['Fare'].mean())
 test_data['Fare']=test_data['Fare'].astype('int32' )<categorify>
display_batch_of_images(next(val_batch))
for i in range(0,len(train_data)) :
if train_data['Age'][i] <= 15:
train_data['Age'][i] = 0
elif(train_data['Age'][i] > 15)&(train_data['Age'][i] <=35):
train_data['Age'][i]=1
elif(train_data['Age'][i] > 35)&(train_data['Age'][i] <=55):
train_data['Age'][i]=2
elif(train_data['Age'][i] > 55)&(train_data['Age'][i] <=75):
train_data['Age'][i]=3
else:
train_data['Age'][i]=4<categorify>
test_dataset = get_test_dataset()
test_dataset = test_dataset.unbatch().batch(20)
 test_batch = iter(test_dataset )
for i in range(0,len(test_data)) :
if test_data['Age'][i] <= 15:
test_data['Age'][i] = 0
elif(test_data['Age'][i] > 15)&(test_data['Age'][i] <=26):
test_data['Age'][i]=1
elif(test_data['Age'][i] > 35)&(test_data['Age'][i] <=55):
test_data['Age'][i]=2
elif(test_data['Age'][i] > 55)&(test_data['Age'][i] <=75):
test_data['Age'][i]=3
else:
test_data['Age'][i]=4<feature_engineering>
display_batch_of_images(next(test_batch))
for i in range(0,len(train_data)) :
if train_data['Fare'][i] <= 50:
train_data['Fare'][i] = 3
elif(train_data['Fare'][i] > 50)&(train_data['Fare'][i] <=150):
train_data['Fare'][i]=2
else:
train_data['Fare'][i]=1<feature_engineering>
def onehot(image,label):
CLASSES = 104
return image,tf.one_hot(label,CLASSES )
for i in range(0,len(test_data)) :
if test_data['Fare'][i] <= 50:
test_data['Fare'][i] = 3
elif(test_data['Fare'][i] > 50)&(test_data['Fare'][i] <=150):
test_data['Fare'][i]=2
else:
test_data['Fare'][i]=1<feature_engineering>
def cutmix(image, label, PROBABILITY = 1.0):
DIM = IMAGE_SIZE[0]
CLASSES = 104
imgs = []; labs = []
for j in range(AUG_BATCH):
P = tf.cast(tf.random.uniform([],0,1)<=PROBABILITY, tf.int32)
 k = tf.cast(tf.random.uniform([],0,AUG_BATCH),tf.int32)
 x = tf.cast(tf.random.uniform([],0,DIM),tf.int32)
 y = tf.cast(tf.random.uniform([],0,DIM),tf.int32)
 b = tf.random.uniform([],0,1)
 WIDTH = tf.cast(DIM * tf.math.sqrt(1-b),tf.int32)* P
ya = tf.math.maximum(0,y-WIDTH//2)
 yb = tf.math.minimum(DIM,y+WIDTH//2)
 xa = tf.math.maximum(0,x-WIDTH//2)
 xb = tf.math.minimum(DIM,x+WIDTH//2)
 one = image[j,ya:yb,0:xa,:]
two = image[k,ya:yb,xa:xb,:]
three = image[j,ya:yb,xb:DIM,:]
middle = tf.concat([one,two,three],axis=1)
 img = tf.concat([image[j,0:ya,:,:],middle,image[j,yb:DIM,:,:]],axis=0)
 imgs.append(img)
 a = tf.cast(WIDTH*WIDTH/DIM/DIM,tf.float32)
 if len(label.shape)==1:
lab1 = tf.one_hot(label[j],CLASSES)
 lab2 = tf.one_hot(label[k],CLASSES)
 else:
lab1 = label[j,]
lab2 = label[k,]
labs.append(( 1-a)*lab1 + a*lab2)
 image2 = tf.reshape(tf.stack(imgs),(AUG_BATCH,DIM,DIM,3))
label2 = tf.reshape(tf.stack(labs),(AUG_BATCH,CLASSES))
return image2,label2
train_data['Fam'] = train_data['Parch'] + train_data['SibSp']
test_data['Fam'] = test_data['Parch'] + test_data['SibSp']<categorify>
def mixup(image, label, PROBABILITY = 1.0):
DIM = IMAGE_SIZE[0]
CLASSES = 104
imgs = []; labs = []
for j in range(AUG_BATCH):
P = tf.cast(tf.random.uniform([],0,1)<=PROBABILITY, tf.float32)
 k = tf.cast(tf.random.uniform([],0,AUG_BATCH),tf.int32)
 a = tf.random.uniform([],0,1)*P
img1 = image[j,]
img2 = image[k,]
imgs.append(( 1-a)*img1 + a*img2)
 if len(label.shape)==1:
lab1 = tf.one_hot(label[j],CLASSES)
 lab2 = tf.one_hot(label[k],CLASSES)
 else:
lab1 = label[j,]
lab2 = label[k,]
labs.append(( 1-a)*lab1 + a*lab2)
 image2 = tf.reshape(tf.stack(imgs),(AUG_BATCH,DIM,DIM,3))
label2 = tf.reshape(tf.stack(labs),(AUG_BATCH,CLASSES))
return image2,label2
for i in range(0,len(train_data)) :
if train_data['Fam'][i] == 0:
train_data['Fam'][i] = 0
elif(train_data['Fam'][i] >= 1)&(train_data['Fam'][i] <=3):
train_data['Fam'][i]=1
elif(train_data['Fam'][i] >= 4)&(train_data['Fam'][i] <=6):
train_data['Fam'][i]=2
elif(train_data['Fam'][i] >= 7)&(train_data['Fam'][i] <=9):
train_data['Fam'][i]=3
else:
train_data['Fam'][i]=4<categorify>
def transform(image,label):
DIM = IMAGE_SIZE[0]
CLASSES = 104
SWITCH = 0.5
CUTMIX_PROB = 0.666
MIXUP_PROB = 0.666
image2, label2 = cutmix(image, label, CUTMIX_PROB)
 image3, label3 = mixup(image, label, MIXUP_PROB)
 imgs = []; labs = []
for j in range(AUG_BATCH):
P = tf.cast(tf.random.uniform([],0,1)<=SWITCH, tf.float32)
 imgs.append(P*image2[j,]+(1-P)*image3[j,])
 labs.append(P*label2[j,]+(1-P)*label3[j,])
 image4 = tf.reshape(tf.stack(imgs),(AUG_BATCH,DIM,DIM,3))
label4 = tf.reshape(tf.stack(labs),(AUG_BATCH,CLASSES))
return image4,label4
for i in range(0,len(test_data)) :
if test_data['Fam'][i] == 0:
test_data['Fam'][i] = 0
elif(test_data['Fam'][i] >= 1)&(test_data['Fam'][i] <=3):
test_data['Fam'][i]=1
elif(test_data['Fam'][i] >= 4)&(test_data['Fam'][i] <=6):
test_data['Fam'][i]=2
elif(test_data['Fam'][i] >= 7)&(test_data['Fam'][i] <=9):
test_data['Fam'][i]=3
else:
test_data['Fam'][i]=4<split>
X = train_data[['Sex','Pclass','Age','Parch','Fam','Fare','Embarked']]
y = train_data[['Survived']]
X_test = test_data[['Sex','Pclass','Age','Parch','Fam','Fare','Embarked']]
train_X , test_X , train_y , test_y = train_test_split(X,y,test_size = 0.2,random_state=0 )<train_model>
def call_model_efn() :
enet = efn.EfficientNetB7(
 input_shape=(512, 512, 3),
weights = 'noisy-student',
include_top=False 
)
 enet.trainable = True
model = tf.keras.Sequential([
enet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model.compile(
 optimizer='adam',
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 return model
classifier = RandomForestClassifier(n_estimators=500,max_depth=3)
 classifier.fit(train_X,train_y)
 classifier.score(test_X,test_y )<train_model>
with strategy.scope() :
enet_model = call_model_efn()
enet_model.summary()
history_enet = enet_model.fit(
 get_training_dataset(load_dataset(TRAINING_FILENAMES),do_aug=False),
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS,
callbacks = [lr_callback],
validation_data = get_validation_dataset() ,
verbose=2 
)
xgb_model = xb.XGBClassifier(base_score=0.5,n_estimators=1000, learning_rate=0.05)
 xgb_model.fit(train_X, train_y, early_stopping_rounds=5,
eval_set=[(test_X, test_y)], verbose=False)
 xgb_model.score(test_X,test_y )<train_on_grid>
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()
cm_probabilities = enet_model.predict(images_ds)
 cm_predictions = np.argmax(cm_probabilities, axis=-1)
 print("Correct labels: ", cm_correct_labels.shape, cm_correct_labels)
 print("Predicted labels: ", cm_predictions.shape, cm_predictions)
 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')
 cmat =(cmat.T / cmat.sum(axis=1)).T
display_confusion_matrix(cmat, score, precision, recall)
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score, precision, recall))
log_reg = LogisticRegression()
log_reg.fit(train_X,train_y)
 log_reg.score(test_X,test_y )<predict_on_test>
test_ds = get_test_dataset(ordered=True)
 print('Computing predictions...')
 test_images_ds = test_ds.map(lambda image, idnum: image)
 enet_probabilities = enet_model.predict(test_images_ds)
 enet_predictions = np.argmax(enet_probabilities, axis=-1)
 print(enet_predictions)
predictions = xgb_model.predict(X_test )<save_to_csv>
output = pd.DataFrame({'PassengerId': test_data.PassengerId, 'Survived': predictions})
 output.to_csv('submission.csv', index=False )<set_options>
def call_model_rn152v2() :
rnet = ResNet152V2(
 input_shape=(512,512,3),
weights = 'imagenet',
include_top=False 
)
 rnet.trainable = True
model = tf.keras.Sequential([
rnet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model.compile(
 optimizer = 'adam',
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 return model
%matplotlib inline<load_from_csv>
with strategy.scope() :
rnet_model = call_model_rn152v2()
rnet_model.summary()
history_resnet = rnet_model.fit(
 get_training_dataset(load_dataset(TRAINING_FILENAMES),do_aug=False),
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS,
callbacks = [lr_callback],
validation_data = get_validation_dataset() ,
verbose=2 
)
train = pd.read_csv('/kaggle/input/house-prices-advanced-regression-techniques/train.csv')
 test = pd.read_csv('/kaggle/input/house-prices-advanced-regression-techniques/test.csv')
 print(train.shape,test.shape )<count_missing_values>
cmdataset = get_validation_dataset(ordered=True)
 images_ds = cmdataset.map(lambda image, label: image)
 labels_ds = cmdataset.map(lambda image, label: label ).unbatch()
rm_correct_labels = next(iter(labels_ds.batch(NUM_VALIDATION_IMAGES)) ).numpy()
rm_probabilities = rnet_model.predict(images_ds)
 rm_predictions = np.argmax(rm_probabilities, axis=-1)
 print("Correct labels: ", rm_correct_labels.shape, cm_correct_labels)
 print("Predicted labels: ", rm_predictions.shape, cm_predictions)
 rmat = confusion_matrix(rm_correct_labels, rm_predictions, labels=range(len(CLASSES)))
 score = f1_score(rm_correct_labels, rm_predictions, labels=range(len(CLASSES)) , average='macro')
 precision = precision_score(rm_correct_labels, rm_predictions, labels=range(len(CLASSES)) , average='macro')
 recall = recall_score(rm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
 rmat =(rmat.T / rmat.sum(axis=1)).T
display_confusion_matrix(rmat, score, precision, recall)
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score, precision, recall))
na_columns = [col for col in train.columns if train[col].isna().sum() >=1]
for col in na_columns:
print(col,np.round(train[col].isna().mean() ,4))<define_variables>
test_ds = get_test_dataset(ordered=True)
 print('Computing predictions...')
 test_images_ds = test_ds.map(lambda image, idnum: image)
 rnet_probabilities = rnet_model.predict(test_images_ds)
 rnet_predictions = np.argmax(rnet_probabilities, axis=-1)
 print(rnet_predictions)
numerical_col = [col for col in train.columns if train[col].dtypes !='O']
print(numerical_col)
 print(len(numerical_col))<count_unique_values>
def call_model_IRv2() :
irnet = InceptionResNetV2(
 input_shape=(512,512,3),
weights = 'imagenet',
include_top=False 
)
 irnet.trainable = True
model = tf.keras.Sequential([
irnet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model.compile(
 optimizer = 'adam',
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 return model
descrete_col = [col for col in numerical_col if len(train[col].unique())<25 and col not in year_col]
len(descrete_col )<define_variables>
with strategy.scope() :
irnet_model = call_model_IRv2()
irnet_model.summary()
history_incepresnet = irnet_model.fit(
 get_training_dataset(load_dataset(TRAINING_FILENAMES),do_aug=False),
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS,
callbacks = [lr_callback],
validation_data = get_validation_dataset() ,
verbose=2 
)
conti_col = [col for col in numerical_col if col not in descrete_col+year_col+['Id']]
print(len(conti_col),'continuous features')
 print(conti_col )<define_variables>
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()
cm_probabilities = irnet_model.predict(images_ds)
 cm_predictions = np.argmax(cm_probabilities, axis=-1)
 print("Correct labels: ", cm_correct_labels.shape, cm_correct_labels)
 print("Predicted labels: ", cm_predictions.shape, cm_predictions)
 cmat = confusion_matrix(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)))
 rscore = f1_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
 rprecision = precision_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
 rrecall = recall_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
 cmat =(cmat.T / cmat.sum(axis=1)).T
display_confusion_matrix(cmat, rscore, rprecision, rrecall)
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(rscore, rprecision, rrecall))
cat_col = [col for col in train.columns if train[col].dtypes == 'O']
print(cat_col)
 print('We have {} categorical features'.format(len(cat_col)) )<count_unique_values>
test_ds = get_test_dataset(ordered=True)
 print('Computing predictions...')
 test_images_ds = test_ds.map(lambda image, idnum: image)
 irnet_probabilities = irnet_model.predict(test_images_ds)
 irnet_predictions = np.argmax(irnet_probabilities, axis=-1)
 print(irnet_predictions)
for col in cat_col:
print(col,': {}'.format(train[col].nunique()))<prepare_x_and_y>
from tensorflow.keras.applications import DenseNet201
y = train['SalePrice'].reset_index(drop=True)
 previous_train = train.copy()<concatenate>
def call_model_Dnet201() :
dnet = DenseNet201(
 input_shape=(512,512,3),
weights='imagenet',
include_top=False 
)
 dnet.trainable = True
model = tf.keras.Sequential([
dnet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model.compile(
 optimizer = 'adam',
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 return model
all_data = pd.concat(( train, test)).reset_index(drop=True)
 all_data.drop(['SalePrice'], axis=1, inplace=True )<count_missing_values>
with strategy.scope() :
dnet_model = call_model_Dnet201()
dnet_model.summary()
history_dnet = dnet_model.fit(
 get_training_dataset(load_dataset(TRAINING_FILENAMES),do_aug=False),
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS,
callbacks = [lr_callback],
validation_data = get_validation_dataset() ,
verbose=2 
)
nan_feature = [col for col in all_data.columns if all_data[col].isnull().sum() >=1 and all_data[col].dtypes == 'O']
print(len(nan_feature))
for feture in nan_feature:
print('{} has {} % missing values'.format(feture,np.round(all_data[feture].isnull().mean() ,4)) )<categorify>
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()
cm_probabilities = dnet_model.predict(images_ds)
 cm_predictions = np.argmax(cm_probabilities, axis=-1)
 print("Correct labels: ", cm_correct_labels.shape, cm_correct_labels)
 print("Predicted labels: ", cm_predictions.shape, cm_predictions)
 cmat = confusion_matrix(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)))
 rscore = f1_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
 rprecision = precision_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
 rrecall = recall_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
 cmat =(cmat.T / cmat.sum(axis=1)).T
display_confusion_matrix(cmat, rscore, rprecision, rrecall)
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(rscore, rprecision, rrecall))
def replace_missing(data,missing_feature):
df = data.copy()
df[missing_feature] = df[missing_feature].fillna('missing')
 return df
all_data = replace_missing(all_data,nan_feature)
 all_data[nan_feature].isnull().sum()<count_missing_values>
test_ds = get_test_dataset(ordered=True)
 print('Computing predictions...')
 test_images_ds = test_ds.map(lambda image, idnum: image)
 dnet_probabilities = dnet_model.predict(test_images_ds)
 dnet_predictions = np.argmax(dnet_probabilities, axis=-1)
 print(dnet_predictions)
num_na_col = [col for col in all_data.columns if all_data[col].isnull().sum() >=1 and all_data[col].dtypes != 'O']
for col in num_na_col:
print('{} has {}% null values'.format(col,np.round(all_data[col].isnull().mean() ,4)) )<feature_engineering>
probabilities =(enet_probabilities + dnet_probabilities + irnet_probabilities + rnet_probabilities)/4
ensemble_predict = np.argmax(probabilities, axis=-1)
 print(ensemble_predict )
<feature_engineering><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, ensemble_predict]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')
 print('Submission Ensemble saved.....')