Kaggle competition: Flower Classification with TPUs
<SOS> metric: MacroFScore Kaggle data source: flower-classification-with-tpus<define_search_model>
!pip install -q efficientnet
clfs = []
seed = 3
clfs.append(( "LogReg",
Pipeline([("Scaler", StandardScaler()), 
("LogReg", LogisticRegression())])))
 clfs.append(( "XGBClassifier",
Pipeline([("Scaler", StandardScaler()), 
("XGB", XGBClassifier())])))
 clfs.append(( "KNN",
Pipeline([("Scaler", StandardScaler()), 
("KNN", KNeighborsClassifier(n_neighbors=8)) ])))
 clfs.append(( "DecisionTreeClassifier",
Pipeline([("Scaler", StandardScaler()), 
("DecisionTrees", DecisionTreeClassifier())])))
 clfs.append(( "RandomForestClassifier",
Pipeline([("Scaler", StandardScaler()), 
("RandomForest", RandomForestClassifier())])))
 clfs.append(( "GradientBoostingClassifier",
Pipeline([("Scaler", StandardScaler()), 
("GradientBoosting", GradientBoostingClassifier(n_estimators=100)) ])))
 clfs.append(( "RidgeClassifier",
Pipeline([("Scaler", StandardScaler()), 
("RidgeClassifier", RidgeClassifier())])))
 clfs.append(( "BaggingRidgeClassifier",
Pipeline([("Scaler", StandardScaler()), 
("BaggingClassifier", BaggingClassifier())])))
 clfs.append(( "ExtraTreesClassifier",
Pipeline([("Scaler", StandardScaler()), 
("ExtraTrees", ExtraTreesClassifier())])))
 scoring = 'accuracy'
n_folds = 7
results, names = [], []
for name, model in clfs:
kfold = KFold(n_splits=n_folds, random_state=seed)
 cv_results = cross_val_score(model, X_train, y_train,
cv= 5, scoring=scoring,
n_jobs=-1)
 names.append(name)
 results.append(cv_results)
 msg = "%s: %f(+/- %f)" %(name, cv_results.mean() , cv_results.std())
 print(msg)
 fig = plt.figure(figsize=(15,6))
fig.suptitle('Classifier Algorithm Comparison', fontsize=22)
 ax = fig.add_subplot(111)
 sns.boxplot(x=names, y=results)
 ax.set_xticklabels(names)
 ax.set_xlabel("Algorithmn", fontsize=20)
 ax.set_ylabel("Accuracy of Models", fontsize=18)
 ax.set_xticklabels(ax.get_xticklabels() ,rotation=45)
 plt.show()<train_model>
tf.to_float = lambda x: tf.cast(x, tf.float32)
 print("Tensorflow version " + tf.__version__)
 AUTO = tf.data.experimental.AUTOTUNE
perm_xgb = PermutationImportance(XGBClassifier().fit(X_train, y_train), random_state=1 ).fit(X_test,y_test)
 eli5.show_weights(perm_xgb, feature_names = train_ready.drop('Survived',axis=1 ).columns.tolist() )<train_model>
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 )
perm_knn = PermutationImportance(KNeighborsClassifier(n_neighbors=8 ).fit(X_train, y_train), random_state=1 ).fit(X_test,y_test)
 eli5.show_weights(perm_knn, feature_names = train_ready.drop('Survived',axis=1 ).columns.tolist() )<train_model>
GCS_DS_PATH = KaggleDatasets().get_gcs_path()
perm_gbc = PermutationImportance(GradientBoostingClassifier(n_estimators=100 ).fit(X_train, y_train), random_state=1 ).fit(X_test,y_test)
 eli5.show_weights(perm_gbc, feature_names = train_ready.drop('Survived',axis=1 ).columns.tolist() )<train_model>
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']
perm_gbc = PermutationImportance(RidgeClassifier().fit(X_train, y_train), random_state=1 ).fit(X_test,y_test)
 eli5.show_weights(perm_gbc, feature_names = train_ready.drop('Survived',axis=1 ).columns.tolist() )<normalization>
VALIDATION = False
if not VALIDATION:
TRAINING_FILENAMES = TRAINING_FILENAMES+VALIDATION_FILENAMES
scaler = StandardScaler()
scaler.fit(X)
 scaled_features = scaler.transform(X)
 train_sc = pd.DataFrame(scaled_features)
 X_csv_test = test_ready.values
scaler.fit(X_csv_test)
 scaled_features_test = scaler.transform(X_csv_test)
 test_sc = pd.DataFrame(scaled_features_test )<train_model>
def autocontrast(image):

 def scale_channel(image):

 lo = tf.to_float(tf.reduce_min(image))
hi = tf.to_float(tf.reduce_max(image))
def scale_values(im):
scale = 255.0 /(hi - lo)
 offset = -lo * scale
im = tf.to_float(im)* scale + offset
im = tf.clip_by_value(im, 0.0, 255.0)
 return tf.cast(im, tf.uint8)
 result = tf.cond(hi > lo, lambda: scale_values(image), lambda: image)
 return result
s1 = scale_channel(image[:, :, 0])
 s2 = scale_channel(image[:, :, 1])
 s3 = scale_channel(image[:, :, 2])
 image = tf.stack([s1, s2, s3], 2)
 return image
neighbors = np.arange(1, 19)
 train_accuracy = np.empty(len(neighbors))
test_accuracy = np.empty(len(neighbors))
for i, k in enumerate(neighbors):
knn = KNeighborsClassifier(n_neighbors=k)
 knn.fit(X_train, y_train)
 train_accuracy[i] = knn.score(X_train, y_train)
 test_accuracy[i] = knn.score(X_test, y_test)
 plt.title('k-NN: Varying Number of Neighbors')
 plt.plot(neighbors, test_accuracy, label = 'Testing Accuracy')
 plt.plot(neighbors, train_accuracy, label = 'Training Accuracy')
 plt.legend()
plt.xlabel('Number of Neighbors')
 plt.ylabel('Accuracy' )<train_model>
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.'] )
knn_6 = KNeighborsClassifier(n_neighbors = 6)
 knn_6.fit(scaled_features,y)
 y_pred_knn_6 = knn_6.predict(scaled_features_test )<train_model>
def decode_image(image_data):
image = tf.image.decode_jpeg(image_data, channels=3)
 image = tf.reshape(image, [*IMAGE_SIZE, 3])
 image = autocontrast(image)
 image = tf.cast(image, tf.float32)/ 255.0
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 = 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))
knn_10 = KNeighborsClassifier(n_neighbors = 10)
 knn_10.fit(scaled_features,y)
 y_pred_knn_10 = knn_10.predict(scaled_features_test )<save_to_csv>
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'))
result_knn_6 = pd.read_csv(".. /input/gender_submission.csv")
 result_knn_6['Survived'] = y_pred_knn_6
result_knn_6.to_csv('Titanic_knn_5.csv', index=False )<save_to_csv>
training_dataset = get_training_dataset()
training_dataset = training_dataset.unbatch().batch(20)
 train_batch = iter(training_dataset )
result_knn_10 = pd.read_csv(".. /input/gender_submission.csv")
 result_knn_10['Survived'] = y_pred_knn_10
result_knn_10.to_csv('Titanic_knn_7.csv', index=False )<choose_model_class>
display_batch_of_images(next(train_batch))
logreg = LogisticRegression()
logreg.fit(scaled_features,y)
 y_pred_logreg = logreg.predict(scaled_features_test)
 y_pred_logreg.shape<save_to_csv>
test_dataset = get_test_dataset()
test_dataset = test_dataset.unbatch().batch(20)
 test_batch = iter(test_dataset )
result_logreg = pd.read_csv(".. /input/gender_submission.csv")
 result_logreg['Survived'] = y_pred_logreg
result_logreg.to_csv('Titanic_logreg.csv', index=False )<train_model>
display_batch_of_images(next(test_batch))
clf = xgb.XGBClassifier(n_estimators=250, random_state=4,bagging_fraction= 0.791787170136272, colsample_bytree= 0.7150126733821065,feature_fraction= 0.6929758008695552,gamma= 0.6716290491053838,learning_rate= 0.030240003246947006,max_depth= 2,min_child_samples= 5,num_leaves= 15,reg_alpha= 0.05822089056228967,reg_lambda= 0.14016232510869098,subsample= 0.9)
 clf.fit(scaled_features, y)
 y_pred_xgb= clf.predict(scaled_features_test )<save_to_csv>
with strategy.scope() :
enb7 = efn.EfficientNetB7(weights='noisy-student', include_top=False, input_shape=[*IMAGE_SIZE, 3])
 enb7.trainable = True
model1 = tf.keras.Sequential([
enb7,
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()
result_xgb = pd.read_csv(".. /input/gender_submission.csv")
 result_xgb['Survived'] = y_pred_xgb
result_xgb.to_csv('Titanic_xgb.csv', index=False )<train_on_grid>
with strategy.scope() :
enb5 = efn.EfficientNetB5(weights='noisy-student', include_top=False, input_shape=[*IMAGE_SIZE, 3])
 enb5.trainable = True
model2 = tf.keras.Sequential([
enb5,
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()
rcf= RidgeClassifier()
rcf.fit(scaled_features, y)
 y_pred_rcf= rcf.predict(scaled_features_test )<save_to_csv>
with strategy.scope() :
enb4 = efn.EfficientNetB4(weights='noisy-student', include_top=False, input_shape=[*IMAGE_SIZE, 3])
 enb4.trainable = True
model3 = tf.keras.Sequential([
enb4,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model3.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'] 
)
 model3.summary()
result_rcf = pd.read_csv(".. /input/gender_submission.csv")
 result_rcf['Survived'] = y_pred_rcf
result_rcf.to_csv('Titanic_rcf.csv', index=False )<predict_on_test>
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 = LearningRateScheduler(lrfn, verbose=True )
gbc= GradientBoostingClassifier(n_estimators=100)
 gbc.fit(scaled_features, y)
 y_pred_gbc= gbc.predict(scaled_features_test )<save_to_csv>
checkpoint = ModelCheckpoint(filepath='best_model.h5', monitor='loss',mode='min', save_best_only=True, verbose=1 )
result_gbc = pd.read_csv(".. /input/gender_submission.csv")
 result_gbc['Survived'] = y_pred_gbc
result_gbc.to_csv('Titanic_gbc.csv', index=False )<import_modules>
if VALIDATION:
history1 = model1.fit(get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
epochs=40,
validation_data=get_validation_dataset() ,
callbacks = [checkpoint, lr_callback] 
)
 model1.load_weights("best_model.h5")
 else:
history1 = model1.fit(get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
epochs=30,
callbacks = [checkpoint, lr_callback])
 model1.load_weights("best_model.h5" )
import matplotlib.pyplot
import seaborn as sns<load_from_csv>
lr_callback = LearningRateScheduler(lrfn, verbose=True)
 checkpoint = ModelCheckpoint(filepath='best_model.h5', monitor='loss',mode='min', save_best_only=True, verbose=1)
 if VALIDATION:
history2 = model2.fit(get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
epochs=40,
validation_data=get_validation_dataset() ,
callbacks = [checkpoint, lr_callback] 
)
 model2.load_weights("best_model.h5")
 else:
history2 = model2.fit(get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
epochs=35,
callbacks = [checkpoint, lr_callback] 
)
 model2.load_weights("best_model.h5")
dataset = pd.read_csv('.. /input/train.csv')
 train = pd.read_csv('.. /input/train.csv')
 test = pd.read_csv('.. /input/test.csv' )<prepare_x_and_y>
lr_callback = LearningRateScheduler(lrfn, verbose=True)
 checkpoint = ModelCheckpoint(filepath='best_model.h5', monitor='loss',mode='min', save_best_only=True, verbose=1)
 if VALIDATION:
history3 = model3.fit(get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
epochs=40,
validation_data=get_validation_dataset() ,
callbacks = [checkpoint, lr_callback] 
)
 model3.load_weights("best_model.h5")
 else:
history3 = model3.fit(get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
epochs=35,
callbacks = [checkpoint, lr_callback] 
)
 model3.load_weights("best_model.h5")
Y_train = train.iloc[:,1].values
train.drop(columns=['Survived','Name','Ticket'],axis=1,inplace=True)
 train.drop(columns=['Embarked','Cabin'],axis=1,inplace=True)
 train = pd.get_dummies(train,columns=['Sex'],drop_first=True )<drop_column>
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 )
train.drop(columns=['PassengerId'],axis=1,inplace=True )<feature_engineering>
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))
mean_value=train['Age'].mean()
train['Age']=train['Age'].fillna(mean_value)
 mean_val=train['Fare'].mean()
train['Fare']=train['Fare'].fillna(mean_val )<prepare_x_and_y>
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)+model3.predict(test_images_ds)) /3
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
X_train = train.iloc[:,:].values<categorify>
if VALIDATION:
dataset = get_validation_dataset()
dataset = dataset.unbatch().batch(20)
 batch = iter(dataset )
<feature_engineering><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 )