Kaggle competition: Petals to the Metal - Flower Classification on TPU
df['Farecut']=pd.cut(df['Fare'], 5, labels=False )<feature_engineering>
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 )
column = 'mrms'
df[column] = df['Name'].str.extract('([A-Za-z]+)\.', expand = False)
 df[column] = df[column].replace(['Capt', 'Countess','Lady','Sir','Jonkheer', 'Don','Dona', 'Mlle','Mme','Major'], 'test_non')
 df[column] = df[column].replace(['Ms'], 'Miss')
 df[column] = df[column].replace(['Col','Dr', 'Rev'], 'Other' )<drop_column>
GCS_DS_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started')
 GCS_PATH = GCS_DS_PATH + '/tfrecords-jpeg-512x512'
column='Embarked'
df['Embarked'].fillna('S',inplace=True )<feature_engineering>
AUTO = tf.data.experimental.AUTOTUNE
IMAGE_SIZE = [512,512]
EPOCHS = 12
BATCH_SIZE = 16*strategy.num_replicas_in_sync
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' )
df.loc[df['Parch'] >= 3, 'Parch'] = 3
df.loc[df['SibSp'] >= 3, 'SibSp'] = 3<feature_engineering>
def count_data_items(filenames):
n = [int(re.compile(r"-([0-9]*)\." ).search(filename ).group(1)) for filename in filenames]
return np.sum(n)
df['Parch+SibSp']=df['Parch']+df['SibSp']<feature_engineering>
NUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)
 NUM_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES)
 NUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)
 print('Dataset: {} training images, {} validation images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))
df['Parch-SibSp']=df['Parch']-df['SibSp']<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
l=list(['Pclass','SibSp','Fare','Parch'])
 df['Agemedian'] = df['Age'].fillna(df.groupby(l)['Age'].transform('median'))
df['Agemedian'] = df['Agemedian'].fillna(df['Agemedian'].median())
 df['Agemedian'] = np.round(df['Agemedian'] )<feature_engineering>
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_saturation(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(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
column = 'Cabin'
df[column+'head'] = df[column].str.extract('([A-Za-z]+)', expand = False)
 labels, uniques = pd.factorize(df['Cabinhead'])
 df['Cabinhead']=labels
df['Cabinhead'].fillna(0,inplace=True)
 df['Cabinhead'].replace(-1,np.NaN,inplace=True)
 Ticket = df['Ticket'].str.extract(' (.*)\s (.*)')
 df['Ticket_head']=Ticket[0]
df['Ticket_num']=Ticket[1]
l = list(['Pclass','Farecut'])
 df['Cabinheadmedian'] = df['Cabinhead'].fillna(df.groupby(l)['Cabinhead'].transform('median'))
df['Cabinheadmedian'] = np.round(df['Cabinheadmedian'] )<categorify>
ds_train = get_training_dataset()
ds_val = get_validation_dataset()
ds_test = get_test_dataset()
print("Training", ds_train)
 print("Validation", ds_val)
 print("Test", ds_test)
l = list(['Farecut'])
 df['Cabinheadmedian'] = df['Cabinhead'].fillna(df.groupby(l)['Cabinhead'].transform('median'))<categorify>
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']
for column in ['mrms','Sex','Embarked','Ticket_head']:
labels, uniques = pd.factorize(df[column])
 df[column]=labels<drop_column>
print("Number of classes: {}".format(len(CLASSES)))
 print("First five classes, sorted alphabetically:")
 for name in sorted(CLASSES)[:5]:
print(name)
 print("number of training images: {}".format(NUM_TRAINING_IMAGES))
df = df.drop(['Name','Ticket','Cabin','Cabinhead','Age','Fare','Ticket_num'], axis=1 )<import_modules>
print("Training data shapes")
 for image,label in ds_train.take(3):
print(image.numpy().shape, label.numpy().shape)
 print("training data label examples:", label.numpy() )
import operator
import math
import random
from deap import gp
from deap import algorithms
from deap import base
from deap import creator
from deap import tools<define_variables>
print("Test data shapes")
 for image,idnum in ds_test.take(3):
print(image.numpy().shape, idnum.numpy().shape)
 print("test data IDs", idnum.numpy().astype('U'))
train=df<prepare_x_and_y>
one_batch = next(iter(ds_train.unbatch().batch(20)))
 display_batch_of_images(one_batch )
target = train['Survived']<define_search_model>
LR_START = 0.00001
LR_MAX = 0.00005 * strategy.num_replicas_in_sync
LR_MIN = LR_START
LR_RAMPUP_EPOCHS = 5
LR_SUSTAIN_EPOCHS = 0
LR_EXP_DECAY = 0.80
def lrfn(epoch):
if epoch < LR_RAMPUP_EPOCHS:
lr = LR_START +(epoch *(LR_MAX - LR_START)/ LR_RAMPUP_EPOCHS)
 elif epoch <(LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS):
lr = LR_MAX
else:
lr = LR_MIN +(LR_MAX - LR_MIN)* LR_EXP_DECAY **(epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS)
 return lr
lr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose = True)
 rng = [i for i in range(30)]
y = [lrfn(x)for x in rng]
plt.plot(rng, y )
def mydeap(mungedtrain):
inputs = mungedtrain.iloc[:,2:14].values.tolist()
outputs = mungedtrain['Survived'].values.tolist()
def protectedDiv(left, right):
try:
return left / right
except ZeroDivisionError:
return 1
pset = gp.PrimitiveSet("MAIN", 12)
 pset.addPrimitive(operator.add, 2)
 pset.addPrimitive(operator.sub, 2)
 pset.addPrimitive(operator.mul, 2)
 pset.addPrimitive(protectedDiv, 2)
 pset.addPrimitive(operator.neg, 1)
 pset.addPrimitive(math.cos, 1)
 pset.addPrimitive(math.sin, 1)
 pset.addPrimitive(max, 2)
 pset.addPrimitive(min, 2)
 pset.addEphemeralConstant("rand101", lambda: random.uniform(-10,10))
pset.renameArguments(ARG0='x1')
 pset.renameArguments(ARG1='x2')
 pset.renameArguments(ARG2='x3')
 pset.renameArguments(ARG3='x4')
 pset.renameArguments(ARG4='x5')
 pset.renameArguments(ARG5='x6')
 pset.renameArguments(ARG6='x7')
 pset.renameArguments(ARG7='x8')
 pset.renameArguments(ARG8='x9')
 pset.renameArguments(ARG9='x10')
 pset.renameArguments(ARG10='x11')
 pset.renameArguments(ARG11='x12')
 creator.create("FitnessMin", base.Fitness, weights=(1.0,))
creator.create("Individual", gp.PrimitiveTree, fitness=creator.FitnessMin)
 toolbox = base.Toolbox()
toolbox.register("expr", gp.genHalfAndHalf, pset=pset, min_=1, max_=3)
 toolbox.register("individual", tools.initIterate, creator.Individual, toolbox.expr)
 toolbox.register("population", tools.initRepeat, list, toolbox.individual)
 toolbox.register("compile", gp.compile, pset=pset)
 def evalSymbReg(individual):
func = toolbox.compile(expr=individual)
 return sum(round(1.-(1./(1.+numpy.exp(-func(*in_)))))== out for in_, out in zip(inputs, outputs)) /len(mungedtrain),
toolbox.register("evaluate", evalSymbReg)
 toolbox.register("select", tools.selTournament, tournsize=3)
 toolbox.register("mate", gp.cxOnePoint)
 toolbox.register("expr_mut", gp.genFull, min_=0, max_=2)
 toolbox.register("mutate", gp.mutUniform, expr=toolbox.expr_mut, pset=pset)
 toolbox.decorate("mate", gp.staticLimit(key=operator.attrgetter("height"), max_value=17))
toolbox.decorate("mutate", gp.staticLimit(key=operator.attrgetter("height"), max_value=17))
random.seed(318)
 pop = toolbox.population(n=300)
 hof = tools.HallOfFame(1)
 stats_fit = tools.Statistics(lambda ind: ind.fitness.values)
 stats_size = tools.Statistics(len)
 mstats = tools.MultiStatistics(fitness=stats_fit, size=stats_size)
 mstats.register("avg", numpy.mean)
 mstats.register("std", numpy.std)
 mstats.register("min", numpy.min)
 mstats.register("max", numpy.max)
 pop, log = algorithms.eaSimple(pop, toolbox, 0.5, 0.2, 1000, stats=mstats,
halloffame=hof, verbose=True)
 print(hof[0])
 func2 =toolbox.compile(expr=hof[0])
 return func2<save_to_csv>
early_stop = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=20, restore_best_weights = True )
if __name__ == "__main__":
mungedtrain = train[:df_train.shape[0]]
GeneticFunction = mydeap(mungedtrain)
 mytrain = mungedtrain.iloc[:,2:14].values.tolist()
trainPredictions = Outputs(np.array([GeneticFunction(*x)for x in mytrain]))
pdtrain = pd.DataFrame({'PassengerId': mungedtrain.PassengerId.astype(int),
'Predicted': trainPredictions.astype(int),
'Survived': mungedtrain.Survived.astype(int)})
 pdtrain.to_csv('MYgptrain.csv', index=False )<save_to_csv>
!pip install -q efficientnet
print(accuracy_score(df_train.Survived.astype(int),trainPredictions.astype(int)))
 mungedtest = train[df_train.shape[0]:]
mytest = mungedtest.iloc[:,2:14].values.tolist()
testPredictions = Outputs(np.array([GeneticFunction(*x)for x in mytest]))
pdtest = pd.DataFrame({'PassengerId': mungedtest.PassengerId.astype(int),
'Survived': testPredictions.astype(int)})
 pdtest.to_csv('gptest.csv', index=False )<train_model>
with strategy.scope() :
pretrained_model = efficientnet.EfficientNetB7(
 weights = 'noisy-student',
include_top = False,
input_shape = [*IMAGE_SIZE, 3] 
)
 pretrained_model.trainable = True
model = tf.keras.Sequential([
pretrained_model,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES),activation = 'softmax')
 ])
 model.compile(
 optimizer = 'adam',
loss = 'sparse_categorical_crossentropy',
metrics = ['sparse_categorical_accuracy'], 
)
 model.summary()
print('end' )<import_modules>
BATCH_SIZE = 16*strategy.num_replicas_in_sync
EPOCHS = 11
STEPS_PER_EPOCH = NUM_TRAINING_IMAGES//BATCH_SIZE
history = model.fit(
 ds_train,
validation_data = ds_val,
epochs = EPOCHS,
steps_per_epoch = STEPS_PER_EPOCH,
callbacks = [lr_callback, early_stop] 
)
import numpy as np
import pandas as pd<load_from_csv>
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_probabilites = model.predict(images_ds)
 cm_predictions = np.argmax(cm_probabilites, axis = -1)
 labels = range(len(CLASSES))
cmat = confusion_matrix(
 cm_correct_labels,
cm_predictions,
labels = labels, 
)
 cmat =(cmat.T/cmat.sum(axis=1)).T
sample_submission = pd.read_csv('.. /input/titanic/gender_submission.csv')
 test = pd.read_csv('.. /input/titanic/test.csv')
 train = pd.read_csv('.. /input/titanic/train.csv' )<count_values>
score = f1_score(
 cm_correct_labels,
cm_predictions,
labels = labels,
average= 'macro', 
)
 precision = precision_score(
 	cm_correct_labels,
cm_predictions,
labels = labels,
average = 'macro', 
)
 recall = recall_score(
 	cm_correct_labels,
cm_predictions,
labels = labels,
average = 'macro', 
)
 display_confusion_matrix(cmat,score,precision,recall )
train['Survived'].value_counts(dropna=False )<split>
dataset = get_validation_dataset()
dataset = dataset.unbatch().batch(20)
 batch = iter(dataset)
kf = model_selection.StratifiedKFold(n_splits=5)
 x = list(kf.split(train, train['Survived'].values))<define_variables>
images,labels = next(batch)
 probabilites = model.predict(images)
 predictions = np.argmax(probabilites, axis = -1)
 display_batch_of_images(( images,labels), predictions )
[len(i)for i in x]<concatenate>
test_ds = get_test_dataset(ordered = True)
 print("Computing predictions for test set")
 test_images_ds = test_ds.map(lambda image,idnum: image)
 probabilities = model.predict(test_images_ds)
 predictions = np.argmax(probabilities, axis = -1)
 print(predictions)
all_data = train.append(test, sort=True ).fillna({'Survived': -1})
 len(train), len(test), len(all_data )<groupby>
print('Generating submision 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