Kaggle competition: Flower Classification with TPUs
<SOS> metric: MacroFScore Kaggle data source: flower-classification-with-tpus<categorify>
!pip install -q efficientnet
images=["%s%s"%("pixel",pixel_no)for pixel_no in range(0,784)]
train_images=np.array(df_train[images])
 train_images=(train_images.astype('float32')/255)**k
train_labels=df_train['label']
train_labels_cat=to_categorical(train_labels,num_classes=10)
 test_images=np.array(df_test[images])
 test_images=(test_images.astype('float32')/255)**k
[train_images.shape,train_labels_cat.shape,test_images.shape]<split>
%matplotlib inline
print("Tensorflow version " + tf.__version__ )
X_train,X_test,y_train,y_test=\
train_test_split(train_images,train_labels_cat,
test_size=.2,random_state=32)
 n=int(len(X_test)/2)
 X_valid,y_valid=X_test[:n],y_test[:n]
X_test,y_test=X_test[n:],y_test[n:]
y_train_num=np.array([np.argmax(x)for x in y_train])
 y_test_num=np.array([np.argmax(x)for x in y_test])
 y_valid_num=np.array([np.argmax(x)for x in y_valid])
 [X_train.shape,X_test.shape,X_valid.shape,\
y_train.shape,y_test.shape,y_valid.shape]<choose_model_class>
AUTO = tf.data.experimental.AUTOTUNE
tpu = tf.distribute.cluster_resolver.TPUClusterResolver()
tf.config.experimental_connect_to_cluster(tpu)
 tf.tpu.experimental.initialize_tpu_system(tpu)
 strategy = tf.distribute.experimental.TPUStrategy(tpu)
 GCS_DS_PATH = KaggleDatasets().get_gcs_path()
IMAGE_SIZE = [512, 512]
EPOCHS = 30
BATCH_SIZE = 16 * strategy.num_replicas_in_sync
def cnn_model() :
model_input=Input(shape=(28,28,1))
x=BatchNormalization()(model_input)
 x=Conv2D(28,(5,5),padding='same' )(x)
 x=LeakyReLU(alpha=.02 )(x)
 x=MaxPooling2D(strides=(2,2))(x)
 x=Dropout (.25 )(x)
 x=Conv2D(96,(5,5))(x)
 x=LeakyReLU(alpha=.02 )(x)
 x=MaxPooling2D(strides=(2,2))(x)
 x=Dropout (.25 )(x)
 x=GlobalMaxPooling2D()(x)
 x=Dense(512 )(x)
 x=LeakyReLU(alpha=.02 )(x)
 x=Dropout (.5 )(x)
 y=Dense(10,activation='softmax' )(x)
 model=Model(input=model_input,output=y)
 model.compile(loss='categorical_crossentropy',optimizer='nadam',
metrics=[categorical_accuracy,top_3_categorical_accuracy])
 return model
cnn_model=cnn_model()
cnn_model.summary()<train_model>
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 = True
if SKIP_VALIDATION:
TRAINING_FILENAMES = TRAINING_FILENAMES + VALIDATION_FILENAMES
VALIDATION_MISMATCHES_IDS = ['861282b96','df1fd14b4','b402b6acd','861282b96','741999f79','4dab7fa08','6423cd23e','617a30d60','87d91aefb','2023d3cac','5f56bcb7f','4571b9509',
'f4ec48685','f9c50db87','96379ff01','28594d9ce','6a3a28a06','fbd61ef17','55a883e16','83a80db99','9ee42218f','b5fb20185',
'868bf8b0c','d0caf04b9','ef945a176','9b8f2f5bd','f8da3867d','0bf0b39b3','bab3ef1f5','293c37e25','f739f3e83','5253af526',
'f27f9a100','077803f97','b4becad84']
checkpointer=ModelCheckpoint(filepath=wcnn,verbose=2,save_best_only=True)
 lr_reduction=ReduceLROnPlateau(monitor='val_loss',patience=5,verbose=2,factor=.8)
 estopping=EarlyStopping(monitor='val_loss',patience=20,verbose=2)
 history=cnn_model.fit(X_train.reshape(-1,28,28,1),y_train,
validation_data=(X_valid.reshape(-1,28,28,1),y_valid),
epochs=100,batch_size=128,verbose=2,
callbacks=[checkpointer,lr_reduction,estopping] )<train_model>
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']
steps,epochs=1000,10
data_generator=\
ImageDataGenerator(featurewise_std_normalization=True,
zoom_range=.2,shear_range=.2,rotation_range=30,
height_shift_range=.2,width_shift_range=.2)
 history=cnn_model.\
fit_generator(data_generator.flow(X_train.reshape(-1,28,28,1),
y_train,batch_size=128),
steps_per_epoch=steps,epochs=epochs,verbose=2,
validation_data=(X_valid.reshape(-1,28,28,1),y_valid),
callbacks=[checkpointer,lr_reduction,estopping] )<compute_test_metric>
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='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.'])
 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='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.'] )
cnn_model.load_weights(wcnn)
 scores=cnn_model.evaluate(X_test.reshape(-1,28,28,1),y_test,verbose=0)
 print("CNN Scores: ",(scores))
print("CNN Error: %.2f%%"%(100-scores[1]*100))<choose_model_class>
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_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 )
Model
def mlp_model() :
model=Sequential()
model.add(Dense(784,activation='relu',input_shape=(784,)))
 model.add(Dropout (.25))
model.add(Dense(392,activation='relu'))
model.add(Dropout (.25))
model.add(Dense(196,activation='relu'))
model.add(Dropout (.25))
model.add(Dense(10,activation='softmax'))
model.compile(optimizer='nadam',loss='categorical_crossentropy',
metrics=[categorical_accuracy,top_3_categorical_accuracy])
 return model
mlp_model=mlp_model()<train_model>
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 + NUM_VALIDATION_IMAGES)// BATCH_SIZE
print('Dataset: {} training images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES+NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))
checkpointer=ModelCheckpoint(filepath=wcnn,verbose=2,save_best_only=True)
 lr_reduction=ReduceLROnPlateau(monitor='val_loss',patience=5,verbose=2,factor=.75)
 estopping=EarlyStopping(monitor='val_loss',patience=20,verbose=2)
 history=mlp_model.fit(X_train,y_train,validation_data=(X_valid,y_valid),
epochs=100,batch_size=128,verbose=2,
callbacks=[checkpointer,lr_reduction,estopping] )<compute_test_metric>
print("Training data shapes:")
 for image, label in get_training_dataset().take(3):
print(image.numpy().shape, label.numpy().shape)
 print("Training data label examples:", label.numpy())
 print("Validation data shapes:")
 for image, label in get_validation_dataset().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().take(3):
print(image.numpy().shape, idnum.numpy().shape)
 print("Test data IDs:", idnum.numpy().astype('U'))
hplot(history)
 scores=mlp_model.evaluate(X_test,y_test)
 print("
MLP Scores: ",(scores))
print("MLP Error: %.2f%%"%(100-scores[1]*100))<choose_model_class>
training_dataset = get_training_dataset()
training_dataset = training_dataset.unbatch().batch(20)
 train_batch = iter(training_dataset)
def rnn_model() :
model=Sequential()
model.add(LSTM(196,return_sequences=True,input_shape=(1,784)))
 model.add(LSTM(196,return_sequences=True))
model.add(LSTM(196))
model.add(Dense(10,activation='softmax'))
model.compile(loss='categorical_crossentropy',optimizer='nadam',
metrics=[categorical_accuracy,top_3_categorical_accuracy])
 return model
rnn_model=rnn_model()<train_model>
display_batch_of_images(next(train_batch))
checkpointer=ModelCheckpoint(filepath=wcnn,verbose=2,save_best_only=True)
 lr_reduction=ReduceLROnPlateau(monitor='val_loss',patience=5,verbose=2,factor=.75)
 estopping=EarlyStopping(monitor='val_loss',patience=20,verbose=2)
 history=rnn_model.fit(X_train.reshape(-1,1,X_train.shape[1]),y_train,
epochs=100,batch_size=128,verbose=2,
validation_data=(X_valid.reshape(-1,1,X_valid.shape[1]),y_valid),
callbacks=[checkpointer,lr_reduction,estopping] )<train_model>
test_dataset = get_test_dataset()
test_dataset = test_dataset.unbatch().batch(20)
 test_batch = iter(test_dataset )
n_total=7000; X2=np.copy(X_train[:n_total])
 y2=np.copy(y_train_num[:n_total] ).astype('int64')
 clf=MLPClassifier(hidden_layer_sizes=(784,),max_iter=100,alpha=1e-4,
solver='lbfgs',verbose=1,tol=1e-6,random_state=1,
learning_rate_init=7e-4,batch_size=128)
 clf.fit(X2,y2)
 print("MNIST.MLPClassifier.Train score: %f"%(clf.score(X2,y2)*100),'%')
 print("MNIST.MLPClassifier.Test score: %f"%(clf.score(X_test,y_test_num)*100),'%' )<train_model>
display_batch_of_images(next(test_batch))
n_total=5000; n_labeled=4000
X2=np.copy(X_train[:n_total])
 y2=np.copy(y_train_num[:n_total] ).astype('int64')
 y2[n_labeled:]=-1
lp_model=label_propagation\ 
.LabelSpreading(kernel='knn',n_neighbors=10,max_iter=20)
 lp_model.fit(X2,y2)
 predicted_labels=lp_model.transduction_[n_labeled:n_total]
true_labels=y_train_num[n_labeled:n_total]
print('Label Spreading: %d labeled & %d unlabeled points(%d total)'% 
(n_labeled,n_total-n_labeled,n_total))
print(classification_report(true_labels,predicted_labels))
print('Confusion matrix')
 print(confusion_matrix(true_labels,predicted_labels,
labels=lp_model.classes_))
predict_entropies=\
stats.distributions.entropy(lp_model.label_distributions_.T)
 uncertainty_index=np.argsort(predict_entropies)[-10:]<predict_on_test>
validation_dataset = get_validation_dataset()
validation_dataset = validation_dataset.unbatch().batch(20)
 validation_batch = iter(validation_dataset )
predict_labels=cnn_model.predict(test_images.reshape(-1,28,28,1))
predict_labels=predict_labels.argmax(axis=-1 )<save_to_csv>
display_batch_of_images(next(validation_batch))
submission=pd.DataFrame({"ImageId":range(1,len(predict_labels)+1),
"Label":predict_labels})
 print(submission[0:10])
 submission.to_csv('kaggle_digits_cnn.csv',index=False )<set_options>
def lrfn(epoch):
LR_START = 0.00001
LR_MAX = 0.00005 * strategy.num_replicas_in_sync
LR_MIN = 0.00001
LR_RAMPUP_EPOCHS = 10
LR_SUSTAIN_EPOCHS = 0
LR_EXP_DECAY =.8
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(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]))
%matplotlib inline
random_state=42
warnings.filterwarnings(action='ignore' )<load_from_csv>
def freeze(model):
for layer in model.layers:
layer.trainable = False
def unfreeze(model):
for layer in model.layers:
layer.trainable = True
train=pd.read_csv('.. /input/titanic/train.csv')
 test=pd.read_csv('.. /input/titanic/test.csv' )<load_from_csv>
with strategy.scope() :
enet = efn.EfficientNetB7(
 input_shape=(512, 512, 3),
weights='imagenet',
include_top=False 
)
 model = tf.keras.Sequential([
enet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model.compile(
 optimizer=tf.keras.optimizers.Adam() ,
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 model.summary()
gender=pd.read_csv('.. /input/titanic/gender_submission.csv')
 gender<prepare_x_and_y>
lr_schedule = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=1)
 history = model.fit(
 get_train_valid_datasets() ,
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS,
callbacks=[lr_schedule],
validation_data=None if SKIP_VALIDATION else get_validation_dataset()
)
X=train.drop('Survived',axis=1)
 y=train['Survived']<split>
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 = 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 )
<create_dataframe><EOS> 
test_ds = get_test_dataset(ordered=True)
 print('Computing predictions...')
 test_images_ds = test_ds.map(lambda image, idnum: image)
 probabilities = model.predict(test_images_ds)
 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='' )