Kaggle competition: Flower Classification with TPUs
<SOS> metric: MacroFScore Kaggle data source: flower-classification-with-tpus<compute_test_metric>
!pip install -q efficientnet
print('Accuracy using all model:',accuracy_score(list_models_bag.apply(lambda x: x['model'].predict(X_val), axis=1, result_type='expand' ).mode().values.reshape(-1,), y_val))<save_to_csv>
print("Tensorflow version " + tf.__version__)
 AUTO = tf.data.experimental.AUTOTUNE
list_models_bag = pd.DataFrame(list_base_model.items() , columns = ['name', 'model'] ).set_index('name')
 list_models_bag['model'] = list_models_bag.apply(lambda x: x['model'].fit(X_train_full, y_train_full), axis=1)
 my_submission = pd.DataFrame({'PassengerId': test.index, 'Survived': list_models_bag.apply(lambda x: x['model'].predict(X_test), axis=1, result_type='expand' ).mode().values.reshape(-1,)})
 my_submission.to_csv('submission_bag.csv', index=False )<choose_model_class>
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 )
list_base_model = {
'Tree' : AdaBoostClassifier(DecisionTreeClassifier(max_depth=10), n_estimators=20, random_state=0, learning_rate=1.05),
'SVC' : AdaBoostClassifier(SVC(C=0.3), algorithm='SAMME',n_estimators=5, random_state=0, learning_rate=1.1),
'gauss' : AdaBoostClassifier(GaussianNB() , n_estimators=5, random_state=0, learning_rate=1.3),
'bern' : AdaBoostClassifier(BernoulliNB(alpha=0.01, binarize=0.5), n_estimators=5, random_state=0, learning_rate=1.3)
 }
list_models_boost = pd.DataFrame(list_base_model.items() , columns = ['name', 'model'] ).set_index('name')
 list_models_boost['model'] = list_models_boost.apply(lambda x: x['model'].fit(X_train, y_train), axis=1)
 list_models_boost['score'] = list_models_boost.apply(lambda x: x['model'].predict(X_val), axis=1, result_type='reduce' ).apply(lambda x: accuracy_score(x, y_val))
print('Score for Boosting model:')
 print(list_models_boost['score'] )<predict_on_test>
GCS_DS_PATH = KaggleDatasets().get_gcs_path()
print('Accuracy using all model:',accuracy_score(list_models_boost.apply(lambda x: x['model'].predict(X_val), axis=1, result_type='expand' ).mode().iloc[0,:].values.reshape(-1,), y_val))<save_to_csv>
img_size=512
IMAGE_SIZE = [512, 512]
BATCH_SIZE = 16 * strategy.num_replicas_in_sync
GCS_PATH_SELECT = {
192: GCS_DS_PATH + '/tfrecords-jpeg-192x192',
224: GCS_DS_PATH + '/tfrecords-jpeg-224x224',
331: GCS_DS_PATH + '/tfrecords-jpeg-331x331',
512: GCS_DS_PATH + '/tfrecords-jpeg-512x512'
}
GCS_PATH = GCS_PATH_SELECT[IMAGE_SIZE[0]]
TRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/train/*.tfrec')
 VALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec')
 TEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec')
 CLASSES = ['pink primrose', 'hard-leaved pocket orchid', 'canterbury bells', 'sweet pea', 'wild geranium', 'tiger lily', 'moon orchid', 'bird of paradise', 'monkshood', 'globe thistle',
'snapdragon', "colt's foot", 'king protea', 'spear thistle', 'yellow iris', 'globe-flower', 'purple coneflower', 'peruvian lily', 'balloon flower', 'giant white arum lily',
'fire lily', 'pincushion flower', 'fritillary', 'red ginger', 'grape hyacinth', 'corn poppy', 'prince of wales feathers', 'stemless gentian', 'artichoke', 'sweet william',
'carnation', 'garden phlox', 'love in the mist', 'cosmos', 'alpine sea holly', 'ruby-lipped cattleya', 'cape flower', 'great masterwort', 'siam tulip', 'lenten rose',
'barberton daisy', 'daffodil', 'sword lily', 'poinsettia', 'bolero deep blue', 'wallflower', 'marigold', 'buttercup', 'daisy', 'common dandelion',
'petunia', 'wild pansy', 'primula', 'sunflower', 'lilac hibiscus', 'bishop of llandaff', 'gaura', 'geranium', 'orange dahlia', 'pink-yellow dahlia',
'cautleya spicata', 'japanese anemone', 'black-eyed susan', 'silverbush', 'californian poppy', 'osteospermum', 'spring crocus', 'iris', 'windflower', 'tree poppy',
'gazania', 'azalea', 'water lily', 'rose', 'thorn apple', 'morning glory', 'passion flower', 'lotus', 'toad lily', 'anthurium',
'frangipani', 'clematis', 'hibiscus', 'columbine', 'desert-rose', 'tree mallow', 'magnolia', 'cyclamen ', 'watercress', 'canna lily',
'hippeastrum ', 'bee balm', 'pink quill', 'foxglove', 'bougainvillea', 'camellia', 'mallow', 'mexican petunia', 'bromelia', 'blanket flower',
'trumpet creeper', 'blackberry lily', 'common tulip', 'wild rose']
list_models_boost = pd.DataFrame(list_base_model.items() , columns = ['name', 'model'] ).set_index('name')
 list_models_boost['model'] = list_models_boost.apply(lambda x: x['model'].fit(X_train_full, y_train_full), axis=1)
 my_submission = pd.DataFrame({'PassengerId': test.index, 'Survived': list_models_boost.apply(lambda x: x['model'].predict(X_test), axis=1, result_type='expand' ).mode().iloc[0,:].astype(int ).values.reshape(-1,)})
 my_submission.to_csv('submission_boost.csv', index=False )<set_options>
VALIDATION = False
if not VALIDATION:
TRAINING_FILENAMES = TRAINING_FILENAMES+VALIDATION_FILENAMES
warnings.filterwarnings("ignore")
 %matplotlib inline 
<drop_column>
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.'] )
def drop_col_not_req(df, cols):
df.drop(cols, axis = 1, inplace = True )<groupby>
def random_blockout(img, sl=0.1, sh=0.2, rl=0.4):
h, w, c = img_size, img_size, 3
origin_area = tf.cast(h*w, tf.float32)
 e_size_l = tf.cast(tf.round(tf.sqrt(origin_area * sl * rl)) , tf.int32)
 e_size_h = tf.cast(tf.round(tf.sqrt(origin_area * sh / rl)) , tf.int32)
 e_height_h = tf.minimum(e_size_h, h)
 e_width_h = tf.minimum(e_size_h, w)
 erase_height = tf.random.uniform(shape=[], minval=e_size_l, maxval=e_height_h, dtype=tf.int32)
 erase_width = tf.random.uniform(shape=[], minval=e_size_l, maxval=e_width_h, dtype=tf.int32)
 erase_area = tf.zeros(shape=[erase_height, erase_width, c])
 erase_area = tf.cast(erase_area, tf.uint8)
 pad_h = h - erase_height
pad_top = tf.random.uniform(shape=[], minval=0, maxval=pad_h, dtype=tf.int32)
 pad_bottom = pad_h - pad_top
pad_w = w - erase_width
pad_left = tf.random.uniform(shape=[], minval=0, maxval=pad_w, dtype=tf.int32)
 pad_right = pad_w - pad_left
erase_mask = tf.pad([erase_area], [[0,0],[pad_top, pad_bottom], [pad_left, pad_right], [0,0]], constant_values=1)
 erase_mask = tf.squeeze(erase_mask, axis=0)
 erased_img = tf.multiply(tf.cast(img,tf.float32), tf.cast(erase_mask, tf.float32))
return tf.cast(erased_img, img.dtype )
def pclass_fare_category(df, Pclass_1_mean_fare, Pclass_2_mean_fare, Pclass_3_mean_fare):
if(df['Pclass'] == 1):
if(df['Fare'] <= Pclass_1_mean_fare):
return 'Pclass_1_Low_Fare'
else:
return 'Pclass_1_High_Fare'
elif(df['Pclass'] == 2):
if(df['Fare'] <= Pclass_2_mean_fare):
return 'Pclass_2_Low_Fare'
else:
return 'Pclass_2_High_Fare'
elif(df['Pclass'] == 3):
if(df['Fare'] <= Pclass_3_mean_fare):
return 'Pclass_3_Low_Fare'
else:
return 'Pclass_3_High_Fare'<train_on_grid>
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)
 image=random_blockout(image)
 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
def count_data_items(filenames):
n = [int(re.compile(r"-([0-9]*)\." ).search(filename ).group(1)) for filename in filenames]
return np.sum(n)
 NUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)
 NUM_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES)
 NUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)
 STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE
print('Dataset: {} training images, {} validation images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))
def fill_missing_age(missing_age_train, missing_age_test):
missing_age_X_train = missing_age_train.drop(['Age'], axis = 1)
 missing_age_y_train = missing_age_train['Age']
missing_age_X_test = missing_age_test.drop(['Age'], axis = 1)
 gbm_reg = ensemble.GradientBoostingRegressor(random_state = 42)
 gbm_reg_param_grid = {'n_estimators': [2000], 'max_depth': [3], 'learning_rate': [0.01], 'max_features': [3]}
gbm_reg_grid = model_selection.GridSearchCV(gbm_reg, gbm_reg_param_grid, cv = 5, n_jobs = 25, verbose = 1, scoring = 'neg_mean_squared_error')
 gbm_reg_grid.fit(missing_age_X_train, missing_age_y_train)
 print("Age feature Best GB Params: " + str(gbm_reg_grid.best_params_))
print("Age feature Best GB Score: " + str(gbm_reg_grid.best_score_))
print("GB Train Error for 'Age' Feature Regressor: " + str(gbm_reg_grid.score(missing_age_X_train, missing_age_y_train)))
 missing_age_test['Age_GB'] = gbm_reg_grid.predict(missing_age_X_test)
 print(missing_age_test['Age_GB'][:4])
 lrf_reg = LinearRegression()
lrf_reg_param_grid = {'fit_intercept': [True], 'normalize': [True]}
lrf_reg_grid = model_selection.GridSearchCV(lrf_reg, lrf_reg_param_grid, cv = 5, n_jobs = 25, verbose = 1, scoring = 'neg_mean_squared_error')
 lrf_reg_grid.fit(missing_age_X_train, missing_age_y_train)
 print("Age feature Best LR Params: " + str(lrf_reg_grid.best_params_))
print("Age feature Best LR Score: " + str(lrf_reg_grid.best_score_))
print("LR Train Error for 'Age' Feature Regressor: " + str(lrf_reg_grid.score(missing_age_X_train, missing_age_y_train)))
 missing_age_test['Age_LRF'] = lrf_reg_grid.predict(missing_age_X_test)
 print(missing_age_test['Age_LRF'][:4])
 missing_age_test['Age'] = missing_age_test[['Age_GB', 'Age_LRF']].mean(axis = 1)
 print(missing_age_test['Age'][:4])
 drop_col_not_req(missing_age_test, ['Age_GB', 'Age_LRF'])
 return missing_age_test<train_on_grid>
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'))
def get_top_n_features(titanic_train_data_X, titanic_train_data_y, top_n_features):
rf_est = RandomForestClassifier(random_state = 42)
 rf_param_grid = {'n_estimators' : [500], 'min_samples_split':[2, 3], 'max_depth':[20]}
rf_grid = model_selection.GridSearchCV(rf_est, rf_param_grid, n_jobs = 25, cv = 10, verbose = 1)
 rf_grid.fit(titanic_train_data_X, titanic_train_data_y)
 print("Top N Features Best RF Params: " + str(rf_grid.best_params_))
print("Top N Features Best RF Score: " + str(rf_grid.best_score_))
print("Top N Features RF Train Error: " + str(rf_grid.score(titanic_train_data_X, titanic_train_data_y)))
 feature_imp_sorted_rf = pd.DataFrame({'feature': list(titanic_train_data_X), 'importance': rf_grid.best_estimator_.feature_importances_} ).sort_values('importance', ascending = False)
 features_top_n_rf = feature_imp_sorted_rf.head(top_n_features)['feature']
print("Sample 25 Features from RF Classifier:")
 print(str(features_top_n_rf[:25]))
ada_est = ensemble.AdaBoostClassifier(random_state = 42)
 ada_param_grid = {'n_estimators' : [500], 'learning_rate': [0.5, 0.6]}
ada_grid = model_selection.GridSearchCV(ada_est, ada_param_grid, n_jobs = 25, cv = 10, verbose = 1)
 ada_grid.fit(titanic_train_data_X, titanic_train_data_y)
 print("Top N Features Best Ada Params: " + str(ada_grid.best_params_))
print("Top N Features Best Ada Score: " + str(ada_grid.best_score_))
print("Top N Features Ada Train Error: " + str(ada_grid.score(titanic_train_data_X, titanic_train_data_y)))
 feature_imp_sorted_ada = pd.DataFrame({'feature': list(titanic_train_data_X), 'importance': ada_grid.best_estimator_.feature_importances_} ).sort_values('importance', ascending = False)
 features_top_n_ada = feature_imp_sorted_ada.head(top_n_features)['feature']
print("Sample 25 Features from Ada Classifier:")
 print(str(features_top_n_ada[:25]))
et_est = ensemble.ExtraTreesClassifier(random_state = 42)
 et_param_grid = {'n_estimators' : [500], 'min_samples_split':[3, 4], 'max_depth':[15]}
et_grid = model_selection.GridSearchCV(et_est, et_param_grid, n_jobs = 25, cv = 10, verbose = 1)
 et_grid.fit(titanic_train_data_X, titanic_train_data_y)
 print("Top N Features Best ET Params: " + str(et_grid.best_params_))
print("Top N Features Best ET Score: " + str(et_grid.best_score_))
print("Top N Features ET Train Error: " + str(et_grid.score(titanic_train_data_X, titanic_train_data_y)))
 feature_imp_sorted_et = pd.DataFrame({'feature': list(titanic_train_data_X), 'importance': et_grid.best_estimator_.feature_importances_} ).sort_values('importance', ascending = False)
 features_top_n_et = feature_imp_sorted_et.head(top_n_features)['feature']
print("Sample 25 Features from ET Classifier:")
 print(str(features_top_n_et[:25]))
features_top_n = pd.concat([features_top_n_rf, features_top_n_ada, features_top_n_et], ignore_index = True ).drop_duplicates()
return features_top_n<load_from_csv>
training_dataset = get_training_dataset()
training_dataset = training_dataset.unbatch().batch(20)
 train_batch = iter(training_dataset )
train_data_orig = pd.read_csv('.. /input/train.csv')
 test_data_orig = pd.read_csv('.. /input/test.csv' )<categorify>
display_batch_of_images(next(train_batch))
print(combined_train_test.groupby(['Survived', 'Embarked'])['Survived'].count())
 print(combined_train_test['PassengerId'].groupby(by = combined_train_test['Embarked'] ).count().sort_values(ascending = False))
print(combined_train_test['Fare'].groupby(by = combined_train_test['Embarked'] ).mean().sort_values(ascending = False))
if(combined_train_test['Embarked'].isnull().sum() != 0):
combined_train_test['Embarked'].fillna(combined_train_test['Embarked'].mode().iloc[0], inplace=True)
 combined_train_test.info()
emb_dummies_df = pd.get_dummies(combined_train_test['Embarked'],
prefix = combined_train_test[['Embarked']].columns[0])
 combined_train_test = pd.concat([combined_train_test, emb_dummies_df], axis = 1 )<categorify>
test_dataset = get_test_dataset()
test_dataset = test_dataset.unbatch().batch(20)
 test_batch = iter(test_dataset )
print(combined_train_test['Sex'].groupby(by = combined_train_test['Sex'] ).count().sort_values(ascending = False))
print(combined_train_test.groupby(['Survived', 'Sex'])['Survived'].count())

sex_dummies_df = pd.get_dummies(combined_train_test['Sex'],
prefix = combined_train_test[['Sex']].columns[0])
 combined_train_test = pd.concat([combined_train_test, sex_dummies_df], axis = 1 )<define_variables>
display_batch_of_images(next(test_batch))
title_Dict = {}
title_Dict.update(dict.fromkeys(["Capt", "Col", "Major", "Dr", "Rev"], "Officer"))
title_Dict.update(dict.fromkeys(["Jonkheer", "Don", "Sir", "the Countess", "Dona", "Lady"], "Royalty"))
title_Dict.update(dict.fromkeys(["Mme", "Ms", "Mrs"], "Mrs"))
title_Dict.update(dict.fromkeys(["Mlle", "Miss"], "Miss"))
title_Dict.update(dict.fromkeys(["Mr", "Ms"], "Mr"))
title_Dict.update(dict.fromkeys(["Master"], "Master"))<categorify>
with strategy.scope() :
dn201 = tf.keras.applications.DenseNet201(weights='imagenet', include_top=False, input_shape=[*IMAGE_SIZE, 3])
 dn201.trainable = True
model1 = tf.keras.Sequential([
dn201,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model1.compile(
 optimizer = tf.keras.optimizers.Adam(learning_rate=0.001, beta_1=0.9, beta_2=0.999, amsgrad=False),
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 model1.summary()
combined_train_test['Title'] = combined_train_test['Title'].map(title_Dict)
 print(combined_train_test['Title'].groupby(by = combined_train_test['Title'] ).count().sort_values(ascending = False))
title_dummies_df = pd.get_dummies(combined_train_test['Title'],
prefix = combined_train_test[['Title']].columns[0])
 combined_train_test = pd.concat([combined_train_test, title_dummies_df], axis = 1 )<groupby>
with strategy.scope() :
enb7 = efn.EfficientNetB7(weights='noisy-student', include_top=False, input_shape=[*IMAGE_SIZE, 3])
 enb7.trainable = True
model2 = tf.keras.Sequential([
enb7,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model2.compile(
 optimizer = tf.keras.optimizers.Adam(learning_rate=0.001, beta_1=0.9, beta_2=0.999, amsgrad=False),
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 model2.summary()
combined_train_test['Name_Length'] = combined_train_test['Name'].str.len()
print(combined_train_test['Name_Length'].groupby(by = combined_train_test['Name_Length'] ).count().sort_values(ascending = False)[:5] )<categorify>
LR_START = 0.0001
LR_MAX = 0.00005 * strategy.num_replicas_in_sync
LR_MIN = 0.00001
LR_RAMPUP_EPOCHS = 4
LR_SUSTAIN_EPOCHS = 6
LR_EXP_DECAY =.8
def lrfn(epoch):
if epoch < LR_RAMPUP_EPOCHS:
lr = np.random.random_sample() * 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 )
combined_train_test['Name_Length_Category'] = combined_train_test['Name_Length'].map(name_len_category)
 print(combined_train_test['Name_Length_Category'].groupby(by = combined_train_test['Name_Length_Category'] ).count().sort_values(ascending = False))
le_fare = LabelEncoder()
le_fare.fit(np.array(['Very_Short_Name', 'Short_Name', 'Medium_Name', 'Long_Name', 'Very_High_Fare']))
combined_train_test['Name_Length_Category'] = le_fare.transform(combined_train_test['Name_Length_Category'])
 print(combined_train_test[['Name_Length_Category', 'Survived']].corr())
 first_name_dummies_df = pd.get_dummies(combined_train_test['Name_Length_Category'],
prefix = combined_train_test[['Name_Length_Category']].columns[0])
 combined_train_test = pd.concat([combined_train_test, first_name_dummies_df], axis = 1 )<categorify>
es_callback = tf.keras.callbacks.EarlyStopping(min_delta=0, patience=10, verbose=1, mode='auto', restore_best_weights=True )
combined_train_test['First_Name'] = combined_train_test['Name'].str.extract('^ (.+?),' ).str.strip()
print(combined_train_test['First_Name'].groupby(by = combined_train_test['First_Name'] ).count().sort_values(ascending = False)[:5])
 first_name_dummies_df = pd.get_dummies(combined_train_test['First_Name'],
prefix = combined_train_test[['First_Name']].columns[0])
 combined_train_test = pd.concat([combined_train_test, first_name_dummies_df], axis = 1 )<categorify>
if VALIDATION:
history1 = model1.fit(get_training_dataset() , steps_per_epoch=STEPS_PER_EPOCH, epochs=40, validation_data=get_validation_dataset() , callbacks = [lr_callback, es_callback])
 else:
history1 = model1.fit(get_training_dataset() , steps_per_epoch=STEPS_PER_EPOCH, epochs=30, callbacks = [lr_callback] )
combined_train_test['Last_Name'] = combined_train_test['Name'].str.split("\." ).str[1].str.strip()
combined_train_test['Last_Name'] = combined_train_test['Last_Name'].str.strip("\([^)]*\)")
 combined_train_test['Last_Name'].fillna(combined_train_test['Name'].str.split("\." ).str[1].str.strip())
 print(combined_train_test['Last_Name'].groupby(by = combined_train_test['Last_Name'] ).count().sort_values(ascending = False)[:5])
 last_name_dummies_df = pd.get_dummies(combined_train_test['Last_Name'],
prefix = combined_train_test[['Last_Name']].columns[0])
 combined_train_test = pd.concat([combined_train_test, last_name_dummies_df], axis = 1 )<categorify>
if VALIDATION:
history2 = model2.fit(get_training_dataset() , steps_per_epoch=STEPS_PER_EPOCH, epochs=40, validation_data=get_validation_dataset() , callbacks = [lr_callback, es_callback])
 else:
history2 = model2.fit(get_training_dataset() , steps_per_epoch=STEPS_PER_EPOCH, epochs=30, callbacks = [lr_callback] )
combined_train_test['Original_Name'] = combined_train_test['Name'].str.split("\((.*?)\)" ).str[1].str.strip (<categorify>
if VALIDATION:
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 =(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 )
if(combined_train_test['Fare'].isnull().sum() != 0):
combined_train_test['Fare'] = combined_train_test[['Fare']].fillna(combined_train_test.groupby('Pclass' ).transform('mean'))
combined_train_test.info()<categorify>
if 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')
 display_confusion_matrix(cmat, score, precision, recall)
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score, precision, recall))
combined_train_test['Group_Ticket'] = combined_train_test['Fare'].groupby(by = combined_train_test['Ticket'] ).transform('count')
 combined_train_test['Fare'] = combined_train_test['Fare']/combined_train_test['Group_Ticket']
combined_train_test.drop(['Group_Ticket'], axis = 1, inplace = True )<feature_engineering>
test_ds = get_test_dataset(ordered=True)
 print('Computing predictions...')
 test_images_ds = test_ds.map(lambda image, idnum: image)
 probabilities =(model1.predict(test_images_ds)+model2.predict(test_images_ds)) /2
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='')
 np.savez_compressed('probs.npz', a=probabilities)
 !head submission.csv
if(sum(n == 0 for n in combined_train_test.Fare.values.flatten())> 0):
combined_train_test.loc[combined_train_test.Fare == 0, 'Fare'] = np.nan
combined_train_test['Fare'] = combined_train_test[['Fare']].fillna(combined_train_test.groupby('Pclass' ).transform('mean'))
combined_train_test['Fare'].describe()<categorify>
if VALIDATION:
dataset = get_validation_dataset()
dataset = dataset.unbatch().batch(20)
 batch = iter(dataset )
<groupby><EOS> 
if VALIDATION:
images, labels = next(batch)
 probabilities =(model1.predict(images)+model2.predict(images)) /2
predictions = np.argmax(probabilities, axis=-1)
 display_batch_of_images(( images, labels), predictions )