Kaggle competition: Flower Classification with TPUs
<SOS> metric: MacroFScore Kaggle data source: flower-classification-with-tpus<load_from_csv>
!pip install -q efficientnet
train = pd.read_csv('.. /input/train.csv')
 test = pd.read_csv('.. /input/test.csv')
 print('Train Shape: {}, Train ID Range {} to {}'.format(train.shape,train.Id.min() , train.Id.max()))
print('Test Shape: {}, Test ID Range {} to {}'.format(test.shape,test.Id.min() , test.Id.max()))<concatenate>
print("Tensorflow version " + tf.__version__)
 AUTO = tf.data.experimental.AUTOTUNE
all_data = train.append(test,sort = False)
 print(all_data.shape)
 all_data.head(3 )<groupby>
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 )
all_data.dtypes.groupby(all_data.dtypes ).count()<sort_values>
GCS_DS_PATH = KaggleDatasets().get_gcs_path('flower-classification' )
skew_calcs = all_data[numerics].skew().sort_values()
skew_calcs = skew_calcs[skew_calcs >.75]
print(skew_calcs)
 skew_feats = skew_calcs.index 
<feature_engineering>
EXT_DS_PATH = KaggleDatasets().get_gcs_path('tf-flower-photo-tfrec' )
all_data[skew_feats] = np.log1p(all_data[skew_feats] )<categorify>
USE_EXTERNAL = False
SKIP_VALIDATION = True
if tpu:
SIZE = 512
else:
SIZE = 192
IMAGE_SIZE = [SIZE, SIZE]
EPOCHS = 18
BATCH_SIZE = 16 * strategy.num_replicas_in_sync
AUG_BATCH = BATCH_SIZE
all_data = pd.concat([all_data,pd.get_dummies(all_data[objects])],axis = 1)
 print(all_data.shape )<drop_column>
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'
}
all_data = all_data.drop(objects,axis = 1)
 print(all_data.shape )<categorify>
def get_filenames(size):
path = GCS_PATH_SELECT[size]
train_filenames = tf.io.gfile.glob(path + '/train/*.tfrec')
 valid_filenames = tf.io.gfile.glob(path + '/val/*.tfrec')
 test_filenames = tf.io.gfile.glob(path + '/test/*.tfrec')
 return train_filenames, valid_filenames, test_filenames
all_data = all_data.fillna(all_data.mean())
 all_data.head(3 )<drop_column>
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']
train_data = all_data[:1460]
test_data = all_data[1460:].drop('SalePrice',axis = 1 )<import_modules>
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])) :
if label is None:
title = ''
elif isinstance(label, int):
title = CLASSES[label]
else:
idx = np.argmax(label, axis=0)
 title = CLASSES[idx]
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='Reds')
 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.'] )
from sklearn.model_selection import train_test_split<import_modules>
def get_batch_transformatioin_matrix(rotation, shear, height_zoom, width_zoom, height_shift, width_shift):

 batch_size = tf.cast(tf.reduce_sum(tf.ones_like(rotation)) , tf.int64)
 rotation = tf.constant(math.pi)* rotation / 180.0
shear = tf.constant(math.pi)* shear / 180.0
one = tf.ones_like(rotation, dtype=tf.float32)
 zero = tf.zeros_like(rotation, dtype=tf.float32)
 c1 = tf.math.cos(rotation)
 s1 = tf.math.sin(rotation)
 rotation_matrix_temp = tf.stack([c1, s1, zero, -s1, c1, zero, zero, zero, one], axis=0)
 rotation_matrix_temp = tf.transpose(rotation_matrix_temp)
 rotation_matrix = tf.reshape(rotation_matrix_temp, shape=(batch_size, 3, 3))
c2 = tf.math.cos(shear)
 s2 = tf.math.sin(shear)
 shear_matrix_temp = tf.stack([one, s2, zero, zero, c2, zero, zero, zero, one], axis=0)
 shear_matrix_temp = tf.transpose(shear_matrix_temp)
 shear_matrix = tf.reshape(shear_matrix_temp, shape=(batch_size, 3, 3))
zoom_matrix_temp = tf.stack([one / height_zoom, zero, zero, zero, one / width_zoom, zero, zero, zero, one], axis=0)
 zoom_matrix_temp = tf.transpose(zoom_matrix_temp)
 zoom_matrix = tf.reshape(zoom_matrix_temp, shape=(batch_size, 3, 3))
shift_matrix_temp = tf.stack([one, zero, height_shift, zero, one, width_shift, zero, zero, one], axis=0)
 shift_matrix_temp = tf.transpose(shift_matrix_temp)
 shift_matrix = tf.reshape(shift_matrix_temp, shape=(batch_size, 3, 3))
return tf.linalg.matmul(tf.linalg.matmul(rotation_matrix, shear_matrix), tf.linalg.matmul(zoom_matrix, shift_matrix))
from sklearn.model_selection import train_test_split<prepare_x_and_y>
def batch_transform(images, labels):

 DIM = images.shape[1]
XDIM = DIM % 2
batch_size = tf.cast(tf.reduce_sum(tf.ones_like(images)) /(images.shape[1] * images.shape[2] * images.shape[3]), tf.int64)
 rot = 15.0 * tf.random.normal([batch_size], dtype='float32')
 shr = 5.0 * tf.random.normal([batch_size], dtype='float32')
 h_zoom = 1.0 + tf.random.normal([batch_size], dtype='float32')/ 10.0
w_zoom = 1.0 + tf.random.normal([batch_size], dtype='float32')/ 10.0
h_shift = 16.0 * tf.random.normal([batch_size], dtype='float32')
 w_shift = 16.0 * tf.random.normal([batch_size], dtype='float32')
 m = get_batch_transformatioin_matrix(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 = tf.linalg.matmul(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, ]], axis=1)
 d = tf.gather_nd(images, tf.transpose(idx3, perm=[0, 2, 1]), batch_dims=1)
 new_images = tf.reshape(d,(batch_size, DIM, DIM, 3))
return new_images, labels
X = train_data.drop(['SalePrice'],axis = 1)
 print(X.shape)
 y = train_data['SalePrice']
print(y.shape )<split>
def onehot(image,label):
CLASSES = 104
return image,tf.one_hot(label,CLASSES )
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=10 )<compute_train_metric>
def batch_cutmix(images, labels, PROBABILITY=1.0, batch_size=0):
DIM = IMAGE_SIZE[0]
CLASSES = 104
if batch_size == 0:
batch_size = AUG_BATCH
do_cutmix = tf.cast(tf.random.uniform([batch_size], 0, 1)<= PROBABILITY, tf.int32)
 new_image_indices = tf.cast(tf.random.uniform([batch_size], 0, batch_size), tf.int32)
 new_x = tf.cast(tf.random.uniform([batch_size], 0, DIM), tf.int32)
 new_y = tf.cast(tf.random.uniform([batch_size], 0, DIM), tf.int32)
 b = tf.random.uniform([batch_size], 0, 1)
 new_width = tf.cast(DIM * tf.math.sqrt(1-b), tf.int32)* do_cutmix
new_y0 = tf.math.maximum(0, new_y - new_width // 2)
 new_y1 = tf.math.minimum(DIM, new_y + new_width // 2)
 new_x0 = tf.math.maximum(0, new_x - new_width // 2)
 new_x1 = tf.math.minimum(DIM, new_x + new_width // 2)
 target = tf.broadcast_to(tf.range(DIM), shape=(batch_size, DIM))
mask_y = tf.math.logical_and(new_y0[:, tf.newaxis] <= target, target <= new_y1[:, tf.newaxis])
 mask_x = tf.math.logical_and(new_x0[:, tf.newaxis] <= target, target <= new_x1[:, tf.newaxis])
 mask = tf.cast(tf.math.logical_and(mask_y[:, :, tf.newaxis], mask_x[:, tf.newaxis, :]), tf.float32)
 new_images = images * tf.broadcast_to(1 - mask[:, :, :, tf.newaxis], [batch_size, DIM, DIM, 3])+ \
tf.gather(images, new_image_indices)* tf.broadcast_to(mask[:, :, :, tf.newaxis], [batch_size, DIM, DIM, 3])
 a = tf.cast(new_width ** 2 / DIM ** 2, tf.float32)
 if len(labels.shape)== 1:
labels = tf.one_hot(labels, CLASSES)
 new_labels =(1-a)[:, tf.newaxis] * labels + a[:, tf.newaxis] * tf.gather(labels, new_image_indices)
 return new_images, new_labels
def get_mse(model,alpha):
run_model = model(alpha = alpha)
 run_model.fit(X_train,y_train)
 return mean_squared_error(y_pred=run_model.predict(X_test),y_true=y_test )<create_dataframe>
def batch_mixup(images, labels, PROBABILITY=1.0, batch_size=0):
DIM = IMAGE_SIZE[0]
CLASSES = 104
if batch_size == 0:
batch_size = AUG_BATCH
do_mixup = tf.cast(tf.random.uniform([batch_size], 0, 1)<= PROBABILITY, tf.int32)
 new_image_indices = tf.cast(tf.random.uniform([batch_size], 0, batch_size), tf.int32)
 a = tf.random.uniform([batch_size], 0, 1)* tf.cast(do_mixup, tf.float32)
 new_images =(1-a)[:, tf.newaxis, tf.newaxis, tf.newaxis] * images + a[:, tf.newaxis, tf.newaxis, tf.newaxis] * tf.gather(images, new_image_indices)
 if len(labels.shape)== 1:
labels = tf.one_hot(labels, CLASSES)
 new_labels =(1-a)[:, tf.newaxis] * labels + a[:, tf.newaxis] * tf.gather(labels, new_image_indices)
 return new_images, new_labels
pd.DataFrame({'alpha':alphas, 'MSE':ridge_mses} ).sort_values('MSE',ascending = True )<train_model>
def transform_cut_mix(image,label):
DIM = IMAGE_SIZE[0]
CLASSES = 104
SWITCH = 0.5
CUTMIX_PROB = 0.666
MIXUP_PROB = 0.666
image2, label2 = batch_cutmix(image, label, CUTMIX_PROB)
 image3, label3 = batch_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
ridge_model = Ridge(alpha = 5)
 ridge_model.fit(X,y)
 coefs = ridge_model.coef_<create_dataframe>
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):
image = tf.image.random_flip_left_right(image)
 return image, label
def get_training_dataset(dataset, simple_aug=False, advance_aug=False, cut_mix_aug=0):
if simple_aug:
dataset = dataset.map(data_augment, num_parallel_calls=AUTO)
 dataset = dataset.repeat()
dataset = dataset.batch(AUG_BATCH)
 if advance_aug:
dataset = dataset.map(batch_transform, num_parallel_calls=AUTO)
 if cut_mix_aug==1:
dataset = dataset.map(batch_cutmix, num_parallel_calls=AUTO)
 elif cut_mix_aug==2:
dataset = dataset.map(batch_mixup, num_parallel_calls=AUTO)
 elif cut_mix_aug==3:
dataset = dataset.map(transform_cut_mix, 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(dataset, ordered=False, repeated=False):
if repeated:
dataset = dataset.repeat()
dataset = dataset.shuffle(2048)
 dataset = dataset.batch(BATCH_SIZE, drop_remainder=repeated)
 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)
 def int_div_round_up(a, b):
return(a + b - 1)// b
labels_and_weights = pd.DataFrame({'field':X.columns,'weight':coefs} )<predict_on_test>
SIZE = 512
IMAGE_SIZE = [SIZE, SIZE]
TRAINING_FILENAMES, VALIDATION_FILENAMES, TEST_FILENAMES = get_filenames(SIZE)
 print(len(TRAINING_FILENAMES))
if USE_EXTERNAL:
EXT_TRAINING_FILENAMES = get_ext_filenames(SIZE, imagenet=True, inaturalist=True, openimage=False, oxford=False, tfflowers=False)
 print(len(EXT_TRAINING_FILENAMES))
if USE_EXTERNAL:
TRAINING_FILENAMES = TRAINING_FILENAMES + EXT_TRAINING_FILENAMES
if SKIP_VALIDATION:
TRAINING_FILENAMES = TRAINING_FILENAMES + VALIDATION_FILENAMES
NUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)
 NUM_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES)if not SKIP_VALIDATION else 0
NUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)
 STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE
VALIDATION_STEPS = int_div_round_up(NUM_VALIDATION_IMAGES, BATCH_SIZE)
 print('Dataset: {} training images, {} validation images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))
predictions = ridge_model.predict(test_data )<prepare_output>
train_ds = load_dataset(TRAINING_FILENAMES, labeled=True)
 valid_ds = load_dataset(VALIDATION_FILENAMES, labeled=True)if not SKIP_VALIDATION else None
test_ds = load_dataset(TEST_FILENAMES, labeled=False )
print(predictions.mean())
 preds = np.expm1(predictions)
 print(preds.mean() )<create_dataframe>
print("Training data shapes:")
 for image, label in get_training_dataset(train_ds ).take(3):
print(image.numpy().shape, label.numpy().shape)
 print("Training data label examples:", label.numpy())
 if not SKIP_VALIDATION:
print("Validation data shapes:")
 for image, label in get_validation_dataset(valid_ds ).take(3):
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(test_ds ).take(3):
print(image.numpy().shape, idnum.numpy().shape)
 print("Test data IDs:", idnum.numpy().astype('U'))
sub = pd.DataFrame()
sub['Id'] = test_data['Id']
sub['SalePrice'] = preds<save_to_csv>
if 0:
training_dataset = get_training_dataset(train_ds, simple_aug=True, advance_aug=False, cut_mix_aug=1)
 training_dataset = training_dataset.unbatch().batch(20)
 train_batch = iter(training_dataset )
sub.to_csv('submission.csv',index=False )<set_options>
if 0:
display_batch_of_images(next(train_batch))
%matplotlib inline
warnings.filterwarnings('ignore' )<load_from_csv>
if 0:
test_dataset = get_test_dataset(test_ds)
 test_dataset = test_dataset.unbatch().batch(20)
 test_batch = iter(test_dataset )
train = pd.read_csv(".. /input/train.csv")
 test = pd.read_csv(".. /input/test.csv")
 train.describe()<count_missing_values>
if 0:
display_batch_of_images(next(test_batch))
print(train.isnull().sum() )<drop_column>
if 0:
images, labels = next(iter(training_dataset.take(1)))
 new_images, new_labels = batch_cutmix(images, labels, PROBABILITY=1.0, batch_size=20)
 display_batch_of_images(( new_images, new_labels))
train = train.drop(["Ticket"],axis = 1)
 test = test.drop(['Ticket'], axis = 1)
 train = train.drop(["Cabin"],axis = 1)
 test = test.drop(["Cabin"],axis = 1)
 train = train.drop(["CabinBool"],axis = 1)
 test = test.drop(["CabinBool"],axis = 1 )<data_type_conversions>
if 0:
images, labels = next(iter(training_dataset.take(1)))
 new_images, new_labels = batch_mixup(images, labels, PROBABILITY=1.0, batch_size=20)
 display_batch_of_images(( new_images, new_labels))
train = train.fillna({"Embarked": "S"} )<feature_engineering>
LR_START = 0.00003
LR_MAX = 0.00005 * strategy.num_replicas_in_sync
LR_MIN = 0.00001
LR_RAMPUP_EPOCHS = 5
LR_SUSTAIN_EPOCHS = 3
LR_EXP_DECAY =.8
@tf.function
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
rng = [i for i in range(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]))
for dataset in combine:
dataset['Title'] = dataset['Title'].replace(['Lady', 'Capt', 'Col',
'Don', 'Dr', 'Major', 'Rev', 'Jonkheer', 'Dona'], 'Rare')
 dataset['Title'] = dataset['Title'].replace(['Countess', 'Lady', 'Sir'], 'Royal')
 dataset['Title'] = dataset['Title'].replace('Mlle', 'Miss')
 dataset['Title'] = dataset['Title'].replace('Ms', 'Miss')
 dataset['Title'] = dataset['Title'].replace('Mme', 'Mrs')
 train[['Title', 'Survived']].groupby(['Title'], as_index=False ).mean()<categorify>
with strategy.scope() :
pretrained_model = tf.keras.applications.DenseNet201(weights='imagenet', include_top=False ,input_shape=[*IMAGE_SIZE, 3])
 pretrained_model.trainable = True
model1 = tf.keras.Sequential([
pretrained_model,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 class LRSchedule(tf.keras.optimizers.schedules.LearningRateSchedule):
def __call__(self, step):
return lrfn(epoch=step//STEPS_PER_EPOCH)
 optimizer1 = tf.keras.optimizers.Adam(learning_rate=LRSchedule())
 model1.compile(
 optimizer = optimizer1,
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 model1.summary()
train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy()
valid_accuracy = tf.keras.metrics.SparseCategoricalAccuracy()
train_loss = tf.keras.metrics.Sum()
valid_loss = tf.keras.metrics.Sum()
loss_fn = lambda a,b: tf.nn.compute_average_loss(tf.keras.losses.sparse_categorical_crossentropy(a,b), global_batch_size=BATCH_SIZE )
title_map = {"Master":1,"Miss":2,"Mr":3,"Mrs":4,"Rare":5,"Royal":5}
for dataset in combine:
dataset["Title"] = dataset["Title"].map(title_map)
 dataset["Title"] = dataset["Title"].fillna(0)
 train.head()<categorify>
if tpu:
STEPS_PER_TPU_CALL = 99
VALIDATION_STEPS_PER_TPU_CALL = 29
@tf.function
def train_step(model, optimizer, data_iter):
def train_step_fn(images, labels):
with tf.GradientTape() as tape:
probabilities = model(images, training=True)
 loss = loss_fn(labels, probabilities)
 grads = tape.gradient(loss, model.trainable_variables)
 optimizer.apply_gradients(zip(grads, model.trainable_variables))
train_accuracy.update_state(labels, probabilities)
 train_loss.update_state(loss)
 for _ in tf.range(STEPS_PER_TPU_CALL):
strategy.experimental_run_v2(train_step_fn, next(data_iter))
@tf.function
def valid_step(model, data_iter):
def valid_step_fn(images, labels):
probabilities = model(images, training=False)
 loss = loss_fn(labels, probabilities)
 valid_accuracy.update_state(labels, probabilities)
 valid_loss.update_state(loss)
 for _ in tf.range(VALIDATION_STEPS_PER_TPU_CALL):
strategy.experimental_run_v2(valid_step_fn, next(data_iter))
Master_age = train[train["Title"]==1]["AgeGroups"].mode()
Ms_age = train[train["Title"]==2]["AgeGroups"].mode()
Mr_age = train[train["Title"]==3]["AgeGroups"].mode()
Mrs_age = train[train["Title"]==4]["AgeGroups"].mode()
Rare_age = train[train["Title"]==5]["AgeGroups"].mode()
Royal_age = train[train["Title"]==6]["AgeGroups"].mode()
print(Master_age)
 print(Ms_age)
 print(Mrs_age)
 train.head()<feature_engineering>
EPOCHS = 24
start_time = epoch_start_time = time.time()
if tpu:
train_dist_ds = strategy.experimental_distribute_dataset(get_training_dataset(train_ds, simple_aug=True, advance_aug=True, cut_mix_aug=0))
valid_dist_ds = strategy.experimental_distribute_dataset(get_validation_dataset(valid_ds, repeated=True)) if not SKIP_VALIDATION else None
print("Training steps per epoch:", STEPS_PER_EPOCH, "in increment of:", STEPS_PER_TPU_CALL)
 if not SKIP_VALIDATION:
print("Validation images:", NUM_VALIDATION_IMAGES,
"Batch size:", BATCH_SIZE,
"Validation steps:", NUM_VALIDATION_IMAGES//BATCH_SIZE, "in increments of", VALIDATION_STEPS_PER_TPU_CALL)
 print("Repeated validation images:", int_div_round_up(NUM_VALIDATION_IMAGES, BATCH_SIZE*VALIDATION_STEPS_PER_TPU_CALL)*VALIDATION_STEPS_PER_TPU_CALL*BATCH_SIZE-NUM_VALIDATION_IMAGES)
 History = namedtuple('History', 'history')
 history = History(history={'loss': [], 'val_loss': [], 'sparse_categorical_accuracy': [], 'val_sparse_categorical_accuracy': []})if not SKIP_VALIDATION else History(history={'loss': [], 'val_loss': [], 'sparse_categorical_accuracy': []})
 epoch = 0
train_data_iter = iter(train_dist_ds)
 valid_data_iter = iter(valid_dist_ds)if not SKIP_VALIDATION else None
step = 0
epoch_steps = 0
while True:
train_step(model1, optimizer1, train_data_iter)
 epoch_steps += STEPS_PER_TPU_CALL
step += STEPS_PER_TPU_CALL
print('=', end='', flush=True)
 if(step//STEPS_PER_EPOCH)> epoch:
print('|', end='', flush=True)
 if not SKIP_VALIDATION:
valid_epoch_steps = 0
valid_step(model1, valid_data_iter)
 valid_epoch_steps += VALIDATION_STEPS_PER_TPU_CALL
print('=', end='', flush=True)
 history.history['val_sparse_categorical_accuracy'].append(valid_accuracy.result().numpy())
 history.history['val_loss'].append(valid_loss.result().numpy() / VALIDATION_STEPS)
 history.history['sparse_categorical_accuracy'].append(train_accuracy.result().numpy())
 history.history['loss'].append(train_loss.result().numpy() / STEPS_PER_EPOCH)
 epoch_time = time.time() - epoch_start_time
print('
EPOCH {:d}/{:d}'.format(epoch+1, EPOCHS))
if not SKIP_VALIDATION:
print('time: {:0.1f}s'.format(epoch_time),
'loss: {:0.4f}'.format(history.history['loss'][-1]),
'accuracy: {:0.4f}'.format(history.history['sparse_categorical_accuracy'][-1]),
'val_loss: {:0.4f}'.format(history.history['val_loss'][-1]),
'val_acc: {:0.4f}'.format(history.history['val_sparse_categorical_accuracy'][-1]),
'lr: {:0.4g}'.format(lrfn(epoch)) , flush=True)
 else:
print('time: {:0.1f}s'.format(epoch_time),
'loss: {:0.4f}'.format(history.history['loss'][-1]),
'accuracy: {:0.4f}'.format(history.history['sparse_categorical_accuracy'][-1]),
'lr: {:0.4g}'.format(lrfn(epoch)) , flush=True)
 epoch =(step+1)// STEPS_PER_EPOCH
epoch_start_time = time.time()
train_accuracy.reset_states()
if not SKIP_VALIDATION:
valid_accuracy.reset_states()
valid_loss.reset_states()
train_loss.reset_states()
if epoch >= EPOCHS:
break
else:
EPOCHS = 15
history = model1.fit(
 get_training_dataset(train_ds),
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS,
validation_data=get_validation_dataset(valid_ds)if not SKIP_VALIDATION else None 
)
 simple_ctl_training_time = time.time() - start_time
print("OPTIMIZED CTL TRAINING TIME: {:0.1f}s".format(simple_ctl_training_time))
title_age_map = {1: "Small children", 2: "Teens", 3: "Young Adults", 4: "Adults", 5: "Adults", 6: "Adults"}
for x in range(len(train["AgeGroups"])) :
if train["AgeGroups"][x] == "Unknown":
train["AgeGroups"][x] = title_age_map[train["Title"][x]]
for x in range(len(test["AgeGroups"])) :
if test["AgeGroups"][x] == "Unknown":
test["AgeGroups"][x] = title_age_map[train["Title"][x]]<categorify>
model1.save_weights('densenet-flower-tpu.hdf5' )
Age_map = {"Small children": 1, "Children": 2, "Teens": 3, "Adolescent": 4, "Young Adults": 5, "Adults": 6, "Elders": 7}
train["AgeGroups"] = train["AgeGroups"].map(Age_map)
 test["AgeGroups"] = test["AgeGroups"].map(Age_map)
 train.head()<drop_column>
test_ds = get_test_dataset(ordered=True)
 test_images_ds = test_ds.map(lambda image, idnum: image )
train = train.drop(["Name"], axis = 1)
 test = test.drop(["Name"], axis = 1)
 train = train.drop(["Age"], axis = 1)
 test = test.drop(["Age"], axis = 1 )<categorify>
print('Computing predictions model1...')
 preds1 = model1.predict(test_images_ds)
 del model1
gc.collect()
tf.tpu.experimental.initialize_tpu_system(tpu )
sex_mapping = {"male": 0, "female": 1}
train['Sex'] = train['Sex'].map(sex_mapping)
 test['Sex'] = test['Sex'].map(sex_mapping)
 train.head()<categorify>
SIZE = 331
IMAGE_SIZE = [SIZE, SIZE]
TRAINING_FILENAMES, VALIDATION_FILENAMES, TEST_FILENAMES = get_filenames(SIZE)
 print(len(TRAINING_FILENAMES))
if USE_EXTERNAL:
EXT_TRAINING_FILENAMES = get_ext_filenames(SIZE, imagenet=False, inaturalist=False, openimage=True, oxford=True, tfflowers=True)
 print(len(EXT_TRAINING_FILENAMES))
if USE_EXTERNAL:
TRAINING_FILENAMES = TRAINING_FILENAMES + EXT_TRAINING_FILENAMES
if SKIP_VALIDATION:
TRAINING_FILENAMES = TRAINING_FILENAMES + VALIDATION_FILENAMES
NUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)
 NUM_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES)if not SKIP_VALIDATION else 0
NUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)
 STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE
VALIDATION_STEPS = int_div_round_up(NUM_VALIDATION_IMAGES, BATCH_SIZE)
 print('Dataset: {} training images, {} validation images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))
embarked_mapping = {"S": 1, "C": 2, "Q": 3}
train['Embarked'] = train['Embarked'].map(embarked_mapping)
 test['Embarked'] = test['Embarked'].map(embarked_mapping)
 train.head()<split>
train_ds = load_dataset(TRAINING_FILENAMES, labeled=True)
 valid_ds = load_dataset(VALIDATION_FILENAMES, labeled=True)if not SKIP_VALIDATION else None
predict = train.drop(['Survived', 'PassengerId'], axis=1)
 target = train["Survived"]
x_train, x_val, y_train, y_val = train_test_split(predict, target, test_size = 0.22, random_state = 0 )<predict_on_test>
import efficientnet.tfkeras as efn
gaussian = GaussianNB()
gaussian.fit(x_train, y_train)
 y_pred = gaussian.predict(x_val)
 acc_gaussian = round(accuracy_score(y_pred, y_val)* 100, 2)
 print(acc_gaussian )<compute_train_metric>
with strategy.scope() :
pretrained_model2 = efn.EfficientNetB7(weights='noisy-student', include_top=False ,input_shape=[*IMAGE_SIZE, 3])
 pretrained_model2.trainable = True
model2 = tf.keras.Sequential([
pretrained_model2,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 class LRSchedule(tf.keras.optimizers.schedules.LearningRateSchedule):
def __call__(self, step):
return lrfn(epoch=step//STEPS_PER_EPOCH)
 optimizer2 = tf.keras.optimizers.Adam(learning_rate=LRSchedule())
 model2.compile(
 optimizer = optimizer2,
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 model2.summary()
train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy()
valid_accuracy = tf.keras.metrics.SparseCategoricalAccuracy()
train_loss = tf.keras.metrics.Sum()
valid_loss = tf.keras.metrics.Sum()
loss_fn = lambda a,b: tf.nn.compute_average_loss(tf.keras.losses.sparse_categorical_crossentropy(a,b), global_batch_size=BATCH_SIZE )
logreg = LogisticRegression()
logreg.fit(x_train, y_train)
 y_pred = logreg.predict(x_val)
 acc_logreg = round(accuracy_score(y_pred, y_val)* 100, 2)
 print(acc_logreg )<compute_train_metric>
if tpu:
STEPS_PER_TPU_CALL = 99
VALIDATION_STEPS_PER_TPU_CALL = 29
@tf.function
def train_step2(model, optimizer, data_iter):
def train_step_fn(images, labels):
with tf.GradientTape() as tape:
probabilities = model(images, training=True)
 loss = loss_fn(labels, probabilities)
 grads = tape.gradient(loss, model.trainable_variables)
 optimizer.apply_gradients(zip(grads, model.trainable_variables))
train_accuracy.update_state(labels, probabilities)
 train_loss.update_state(loss)
 for _ in tf.range(STEPS_PER_TPU_CALL):
strategy.experimental_run_v2(train_step_fn, next(data_iter))
@tf.function
def valid_step2(model, data_iter):
def valid_step_fn(images, labels):
probabilities = model(images, training=False)
 loss = loss_fn(labels, probabilities)
 valid_accuracy.update_state(labels, probabilities)
 valid_loss.update_state(loss)
 for _ in tf.range(VALIDATION_STEPS_PER_TPU_CALL):
strategy.experimental_run_v2(valid_step_fn, next(data_iter))
svc = SVC()
svc.fit(x_train, y_train)
 y_pred = svc.predict(x_val)
 acc_svc = round(accuracy_score(y_pred, y_val)* 100, 2)
 print(acc_svc )<compute_train_metric>
start_time = epoch_start_time = time.time()
if tpu:
train_dist_ds = strategy.experimental_distribute_dataset(get_training_dataset(train_ds, simple_aug=True, advance_aug=True, cut_mix_aug=0))
valid_dist_ds = strategy.experimental_distribute_dataset(get_validation_dataset(valid_ds, repeated=True)) if not SKIP_VALIDATION else None
print("Training steps per epoch:", STEPS_PER_EPOCH, "in increment of:", STEPS_PER_TPU_CALL)
 if not SKIP_VALIDATION:
print("Validation images:", NUM_VALIDATION_IMAGES,
"Batch size:", BATCH_SIZE,
"Validation steps:", NUM_VALIDATION_IMAGES//BATCH_SIZE, "in increments of", VALIDATION_STEPS_PER_TPU_CALL)
 print("Repeated validation images:", int_div_round_up(NUM_VALIDATION_IMAGES, BATCH_SIZE*VALIDATION_STEPS_PER_TPU_CALL)*VALIDATION_STEPS_PER_TPU_CALL*BATCH_SIZE-NUM_VALIDATION_IMAGES)
 History = namedtuple('History', 'history')
 history = History(history={'loss': [], 'val_loss': [], 'sparse_categorical_accuracy': [], 'val_sparse_categorical_accuracy': []})if not SKIP_VALIDATION else History(history={'loss': [], 'val_loss': [], 'sparse_categorical_accuracy': []})
 epoch = 0
train_data_iter = iter(train_dist_ds)
 valid_data_iter = iter(valid_dist_ds)if not SKIP_VALIDATION else None
step = 0
epoch_steps = 0
while True:
train_step2(model2, optimizer2, train_data_iter)
 epoch_steps += STEPS_PER_TPU_CALL
step += STEPS_PER_TPU_CALL
print('=', end='', flush=True)
 if(step//STEPS_PER_EPOCH)> epoch:
print('|', end='', flush=True)
 if not SKIP_VALIDATION:
valid_epoch_steps = 0
valid_step2(model2, valid_data_iter)
 valid_epoch_steps += VALIDATION_STEPS_PER_TPU_CALL
print('=', end='', flush=True)
 history.history['val_sparse_categorical_accuracy'].append(valid_accuracy.result().numpy())
 history.history['val_loss'].append(valid_loss.result().numpy() / VALIDATION_STEPS)
 history.history['sparse_categorical_accuracy'].append(train_accuracy.result().numpy())
 history.history['loss'].append(train_loss.result().numpy() / STEPS_PER_EPOCH)
 epoch_time = time.time() - epoch_start_time
print('
EPOCH {:d}/{:d}'.format(epoch+1, EPOCHS))
if not SKIP_VALIDATION:
print('time: {:0.1f}s'.format(epoch_time),
'loss: {:0.4f}'.format(history.history['loss'][-1]),
'accuracy: {:0.4f}'.format(history.history['sparse_categorical_accuracy'][-1]),
'val_loss: {:0.4f}'.format(history.history['val_loss'][-1]),
'val_acc: {:0.4f}'.format(history.history['val_sparse_categorical_accuracy'][-1]),
'lr: {:0.4g}'.format(lrfn(epoch)) , flush=True)
 else:
print('time: {:0.1f}s'.format(epoch_time),
'loss: {:0.4f}'.format(history.history['loss'][-1]),
'accuracy: {:0.4f}'.format(history.history['sparse_categorical_accuracy'][-1]),
'lr: {:0.4g}'.format(lrfn(epoch)) , flush=True)
 epoch =(step+1)// STEPS_PER_EPOCH
epoch_start_time = time.time()
train_accuracy.reset_states()
if not SKIP_VALIDATION:
valid_accuracy.reset_states()
valid_loss.reset_states()
train_loss.reset_states()
if epoch >= EPOCHS:
break
else:
EPOCHS = 15
history = model2.fit(
 get_training_dataset(train_ds),
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS,
validation_data=get_validation_dataset(valid_ds)if not SKIP_VALIDATION else None 
)
 simple_ctl_training_time = time.time() - start_time
print("OPTIMIZED CTL TRAINING TIME: {:0.1f}s".format(simple_ctl_training_time))
linear_svc = LinearSVC()
linear_svc.fit(x_train, y_train)
 y_pred = linear_svc.predict(x_val)
 acc_linear_svc = round(accuracy_score(y_pred, y_val)* 100, 2)
 print(acc_linear_svc )<compute_train_metric>
model2.save_weights('effnetb7-flower-tpu.hdf5' )
perceptron = Perceptron()
perceptron.fit(x_train, y_train)
 y_pred = perceptron.predict(x_val)
 acc_perceptron = round(accuracy_score(y_pred, y_val)* 100, 2)
 print(acc_perceptron )<train_model>
test_ds = get_test_dataset(ordered=True)
 test_images_ds = test_ds.map(lambda image, idnum: image )
decisiontree = DecisionTreeClassifier()
decisiontree.fit(x_train, y_train)
 y_pred = decisiontree.predict(x_val)
 acc_decisiontree = round(accuracy_score(y_pred, y_val)* 100, 2)
 print(acc_decisiontree )<train_model>
print('Computing predictions model2...')
 preds2 = model2.predict(test_images_ds)
 del model2
gc.collect()
tf.tpu.experimental.initialize_tpu_system(tpu )
randomforest = RandomForestClassifier()
randomforest.fit(x_train, y_train)
 y_pred = randomforest.predict(x_val)
 acc_randomforest = round(accuracy_score(y_pred, y_val)* 100, 2)
 print(acc_randomforest )<compute_train_metric>
SIZE = 512
IMAGE_SIZE = [SIZE, SIZE]
SKIP_VALIDATION = True
TRAINING_FILENAMES, VALIDATION_FILENAMES, TEST_FILENAMES = get_filenames(SIZE)
 print(len(TRAINING_FILENAMES))
if USE_EXTERNAL:
EXT_TRAINING_FILENAMES = get_ext_filenames(SIZE, imagenet=False, inaturalist=True, openimage=False, oxford=False, tfflowers=True)
 print(len(EXT_TRAINING_FILENAMES))
if USE_EXTERNAL:
TRAINING_FILENAMES = TRAINING_FILENAMES + EXT_TRAINING_FILENAMES
if SKIP_VALIDATION:
TRAINING_FILENAMES = TRAINING_FILENAMES + VALIDATION_FILENAMES
NUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)
 NUM_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES)if not SKIP_VALIDATION else 0
NUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)
 STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE
VALIDATION_STEPS = int_div_round_up(NUM_VALIDATION_IMAGES, BATCH_SIZE)
 print('Dataset: {} training images, {} validation images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))
train_ds = load_dataset(TRAINING_FILENAMES, labeled=True)
 valid_ds = load_dataset(VALIDATION_FILENAMES, labeled=True)if not SKIP_VALIDATION else None
knn = KNeighborsClassifier()
knn.fit(x_train, y_train)
 y_pred = knn.predict(x_val)
 acc_knn = round(accuracy_score(y_pred, y_val)* 100, 2)
 print(acc_knn )<predict_on_test>
with strategy.scope() :
pretrained_model3 = efn.EfficientNetB6(weights='noisy-student', include_top=False ,input_shape=[*IMAGE_SIZE, 3])
 pretrained_model3.trainable = True
model3 = tf.keras.Sequential([
pretrained_model3,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 class LRSchedule(tf.keras.optimizers.schedules.LearningRateSchedule):
def __call__(self, step):
return lrfn(epoch=step//STEPS_PER_EPOCH)
 optimizer3 = tf.keras.optimizers.Adam(learning_rate=LRSchedule())
 model3.compile(
 optimizer = optimizer3,
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 model3.summary()
train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy()
valid_accuracy = tf.keras.metrics.SparseCategoricalAccuracy()
train_loss = tf.keras.metrics.Sum()
valid_loss = tf.keras.metrics.Sum()
loss_fn = lambda a,b: tf.nn.compute_average_loss(tf.keras.losses.sparse_categorical_crossentropy(a,b), global_batch_size=BATCH_SIZE )
sgd = SGDClassifier()
sgd.fit(x_train, y_train)
 y_pred = sgd.predict(x_val)
 acc_sgd = round(accuracy_score(y_pred, y_val)* 100, 2)
 print(acc_sgd )<predict_on_test>
if tpu:
STEPS_PER_TPU_CALL = 99
VALIDATION_STEPS_PER_TPU_CALL = 29
@tf.function
def train_step3(model, optimizer, data_iter):
def train_step_fn(images, labels):
with tf.GradientTape() as tape:
probabilities = model(images, training=True)
 loss = loss_fn(labels, probabilities)
 grads = tape.gradient(loss, model.trainable_variables)
 optimizer.apply_gradients(zip(grads, model.trainable_variables))
train_accuracy.update_state(labels, probabilities)
 train_loss.update_state(loss)
 for _ in tf.range(STEPS_PER_TPU_CALL):
strategy.experimental_run_v2(train_step_fn, next(data_iter))
@tf.function
def valid_step3(model, data_iter):
def valid_step_fn(images, labels):
probabilities = model(images, training=False)
 loss = loss_fn(labels, probabilities)
 valid_accuracy.update_state(labels, probabilities)
 valid_loss.update_state(loss)
 for _ in tf.range(VALIDATION_STEPS_PER_TPU_CALL):
strategy.experimental_run_v2(valid_step_fn, next(data_iter))
gbk = GradientBoostingClassifier()
gbk.fit(x_train, y_train)
 y_pred = gbk.predict(x_val)
 acc_gbk = round(accuracy_score(y_pred, y_val)* 100, 2)
 print(acc_gbk )<create_dataframe>
start_time = epoch_start_time = time.time()
if tpu:
train_dist_ds = strategy.experimental_distribute_dataset(get_training_dataset(train_ds, simple_aug=True, advance_aug=True, cut_mix_aug=0))
valid_dist_ds = strategy.experimental_distribute_dataset(get_validation_dataset(valid_ds, repeated=True)) if not SKIP_VALIDATION else None
print("Training steps per epoch:", STEPS_PER_EPOCH, "in increment of:", STEPS_PER_TPU_CALL)
 if not SKIP_VALIDATION:
print("Validation images:", NUM_VALIDATION_IMAGES,
"Batch size:", BATCH_SIZE,
"Validation steps:", NUM_VALIDATION_IMAGES//BATCH_SIZE, "in increments of", VALIDATION_STEPS_PER_TPU_CALL)
 print("Repeated validation images:", int_div_round_up(NUM_VALIDATION_IMAGES, BATCH_SIZE*VALIDATION_STEPS_PER_TPU_CALL)*VALIDATION_STEPS_PER_TPU_CALL*BATCH_SIZE-NUM_VALIDATION_IMAGES)
 History = namedtuple('History', 'history')
 history = History(history={'loss': [], 'val_loss': [], 'sparse_categorical_accuracy': [], 'val_sparse_categorical_accuracy': []})if not SKIP_VALIDATION else History(history={'loss': [], 'val_loss': [], 'sparse_categorical_accuracy': []})
 epoch = 0
train_data_iter = iter(train_dist_ds)
 valid_data_iter = iter(valid_dist_ds)if not SKIP_VALIDATION else None
step = 0
epoch_steps = 0
while True:
train_step3(model3, optimizer3, train_data_iter)
 epoch_steps += STEPS_PER_TPU_CALL
step += STEPS_PER_TPU_CALL
print('=', end='', flush=True)
 if(step//STEPS_PER_EPOCH)> epoch:
print('|', end='', flush=True)
 if not SKIP_VALIDATION:
valid_epoch_steps = 0
valid_step3(model3, valid_data_iter)
 valid_epoch_steps += VALIDATION_STEPS_PER_TPU_CALL
print('=', end='', flush=True)
 history.history['val_sparse_categorical_accuracy'].append(valid_accuracy.result().numpy())
 history.history['val_loss'].append(valid_loss.result().numpy() / VALIDATION_STEPS)
 history.history['sparse_categorical_accuracy'].append(train_accuracy.result().numpy())
 history.history['loss'].append(train_loss.result().numpy() / STEPS_PER_EPOCH)
 epoch_time = time.time() - epoch_start_time
print('
EPOCH {:d}/{:d}'.format(epoch+1, EPOCHS))
if not SKIP_VALIDATION:
print('time: {:0.1f}s'.format(epoch_time),
'loss: {:0.4f}'.format(history.history['loss'][-1]),
'accuracy: {:0.4f}'.format(history.history['sparse_categorical_accuracy'][-1]),
'val_loss: {:0.4f}'.format(history.history['val_loss'][-1]),
'val_acc: {:0.4f}'.format(history.history['val_sparse_categorical_accuracy'][-1]),
'lr: {:0.4g}'.format(lrfn(epoch)) , flush=True)
 else:
print('time: {:0.1f}s'.format(epoch_time),
'loss: {:0.4f}'.format(history.history['loss'][-1]),
'accuracy: {:0.4f}'.format(history.history['sparse_categorical_accuracy'][-1]),
'lr: {:0.4g}'.format(lrfn(epoch)) , flush=True)
 epoch =(step+1)// STEPS_PER_EPOCH
epoch_start_time = time.time()
train_accuracy.reset_states()
if not SKIP_VALIDATION:
valid_accuracy.reset_states()
valid_loss.reset_states()
train_loss.reset_states()
if epoch >= EPOCHS:
break
else:
EPOCHS = 15
history = model3.fit(
 get_training_dataset(train_ds),
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS,
validation_data=get_validation_dataset(valid_ds)if not SKIP_VALIDATION else None 
)
 simple_ctl_training_time = time.time() - start_time
print("OPTIMIZED CTL TRAINING TIME: {:0.1f}s".format(simple_ctl_training_time))
models = pd.DataFrame({
'Model': ['Support Vector Machines', 'KNN', 'Logistic Regression',
'Random Forest', 'Naive Bayes', 'Perceptron', 'Linear SVC',
'Decision Tree', 'Stochastic Gradient Descent', 'Gradient Boosting Classifier'],
'Score': [acc_svc, acc_knn, acc_logreg,
acc_randomforest, acc_gaussian, acc_perceptron,acc_linear_svc, acc_decisiontree,
acc_sgd, acc_gbk]})
 models.sort_values(by='Score', ascending=False )<save_to_csv>
model3.save_weights('effnetb6-flower-tpu.hdf5' )
ids = test['PassengerId']
predictions = gbk.predict(test.drop('PassengerId', axis=1))
output = pd.DataFrame({ 'PassengerId' : ids, 'Survived': predictions })
 output.to_csv('submission.csv', index=False )<set_options>
test_ds = get_test_dataset(ordered=True)
 test_images_ds = test_ds.map(lambda image, idnum: image )
%matplotlib inline
warnings.filterwarnings("ignore" )<load_from_csv>
print('Computing predictions model3...')
 preds3 = model3.predict(test_images_ds)
 del model3
gc.collect()
tf.tpu.experimental.initialize_tpu_system(tpu )
train = pd.read_csv('.. /input/train.csv')
 test = pd.read_csv('.. /input/test.csv')
 train = train.drop('Id', axis = 1)
 print(train.shape)
 print(test.shape )<load_from_csv>
if 0 and not SKIP_VALIDATION:
cmdataset = get_validation_dataset(load_dataset(VALIDATION_FILENAMES, labeled=True, ordered=True), 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 =(model1.predict(images_ds)+model2.predict(images_ds)) /2
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 )
train = pd.read_csv('.. /input/train.csv')
 test = pd.read_csv('.. /input/test.csv' )<load_from_csv>
if 0 and not SKIP_VALIDATION:
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))
train = pd.read_csv('.. /input/train.csv')
 test = pd.read_csv('.. /input/test.csv' )<sort_values>
alpha = 0.55
missing = train.isnull().sum().sort_values(ascending = False)
 missing_pct = missing /len(train)
 features_to_discard = list(missing_pct[missing_pct > 0.8].index)
 print('features discared:', features_to_discard)
 train.drop(features_to_discard, axis=1, inplace = True )<define_variables>
print('Computing predictions...')
 probabilities = 0.45 *(alpha * preds1 +(1-alpha)* preds2)+ 0.55 * preds3
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
<define_variables><EOS> 
if 0 and not SKIP_VALIDATION:
dataset = get_validation_dataset(valid_ds)
 dataset = dataset.unbatch().batch(20)
 batch = iter(dataset)
 images, labels = next(batch)
 probabilities = model.predict(images)
 predictions = np.argmax(probabilities, axis=-1)
 display_batch_of_images(( images, labels), predictions )