Kaggle competition: Flower Classification with TPUs
<SOS> metric: MacroFScore Kaggle data source: flower-classification-with-tpus<count_missing_values>
pip install -q efficientnet
data.isna().sum()<data_type_conversions>
print("Tensorflow version " + tf.__version__)
 AUTO = tf.data.experimental.AUTOTUNE
data['Fare'] = data['Fare'].fillna(data['Fare'].dropna().median() )<data_type_conversions>
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 )
print(data['Cabin'].isnull().sum())
 data['Cabin_dep'] = [cabin_no[0] for cabin_no in data['Cabin'].astype("str")]
data['Cabin_dep'] = data['Cabin_dep'].astype("category" )<feature_engineering>
GCS_DS_PATH = KaggleDatasets().get_gcs_path()
indices_age = data.Age[data['Age'].isnull() == False].index
z_scores_age = np.abs(zscore(data.Age[data['Age'].isnull() == False]))
z_scores = pd.DataFrame(columns=['Age','SibSp','Parch','Fare'])
 z_scores['SibSp'] = zscore(data.SibSp)
 z_scores['Parch'] = zscore(data.Parch)
 z_scores['Fare'] = zscore(data.Fare)
 z_scores['Age'] = zscore(data.Age)
 outlier_rows, outlier_cols = np.where(z_scores > 3)
 outliers = {}
for i,col in enumerate(outlier_rows):
if outlier_rows[i] not in outliers:
outliers[outlier_rows[i]] = [outlier_cols[i]]
else:
outliers[outlier_rows[i]].append(outlier_cols[i])
 to_del = []
for outlier in outliers:
if len(outliers[outlier])>= 2 and outlier >= test_orig.shape[0]:
to_del.append(outlier)
 print(len(to_del))
for i in to_del:
data.drop(data.index[i], inplace=True )<count_missing_values>
IMAGE_SIZE = [512, 512]
EPOCHS = 24
BATCH_SIZE = 16 * strategy.num_replicas_in_sync
NUM_CHANNEL = 3
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']
SKIP_VALIDATION = True
if SKIP_VALIDATION:
TRAINING_FILENAMES = TRAINING_FILENAMES + VALIDATION_FILENAMES
data.isnull().sum()<count_missing_values>
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')
 if NUM_CHANNEL == 1:
plt.imshow(tf.reshape(image, [*IMAGE_SIZE]), cmap='gray')
 else:
plt.imshow(tf.reshape(image, [*IMAGE_SIZE, NUM_CHANNEL]))
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.'] )
data.isnull().sum()<feature_engineering>
def decode_image(image_data):
image = tf.image.decode_jpeg(image_data, channels=NUM_CHANNEL)
 image = tf.cast(image, tf.float32)/ 255.0
image = tf.reshape(image, [*IMAGE_SIZE, NUM_CHANNEL])
 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 PCA_whitening(x):

 print("1: ", x.shape)
 x = tf.reshape(x, [512*512, 1])
 print("2: ", x.shape)
 x_trans = tf.transpose(x)
 sigma = tf.linalg.matmul(x, tf.transpose(x))
print("sigma: ", sigma.shape)
 s, u, v = tf.linalg.svd(sigma)
 print("s: ", s.shape)
 print("u: ", u.shape)
 print("v: ", v.shape)
 xTilde = tf.linalg.matmul(tf.transpose(u), x)
 print("xTilde: ", xTilde.shape)
 xPCA = tf.math.add(s, 0.00001)
 xPCA = 1./ tf.math.sqrt(xPCA)
 xPCA = tf.linalg.diag(xPCA)
 print("diag: ", xPCA.shape)
 xPCA = tf.linalg.matmul(xPCA, xTilde)
 print("return: ", xPCA.shape)
 xPCA = tf.reshape(xPCA, [512, 512])
 print("reshape: ", xPCA.shape)
 return xPCA
def RGB_whitening(image, label):

 r = PCA_whitening(image[:, :, 0])
 g = PCA_whitening(image[:, :, 1])
 b = PCA_whitening(image[:, :, 2])
 r = tf.expand_dims(r, axis=2)
 g = tf.expand_dims(g, axis=2)
 b = tf.expand_dims(b, axis=2)
 image = tf.concat([r, g, b], axis=2)
 print(image.shape)
 print(image.dtype)
 return image, label
def random_shift(image, seed=42):
shift = [randint(0, 20), randint(0, 20)]
image = tf.image.crop_to_bounding_box(image, offset_height=shift[0], offset_width=shift[1],
target_height=IMAGE_SIZE[0]-shift[0], target_width=IMAGE_SIZE[1]-shift[1])
 image = tf.image.pad_to_bounding_box(image, offset_height=0, offset_width=0, target_height=IMAGE_SIZE[0], target_width=IMAGE_SIZE[1])
 return image
def random_rotate(image, seed=42):
dice = randint(0, 10)
 if dice > 3:
dice = 0
return tf.image.rot90(image, dice)
 def data_augment(image, label):
image = tf.image.random_flip_left_right(image, seed=42)
 image = random_shift(image, seed=42)
 return image, label
def data_standardization(image, label):
image = tf.image.per_image_standardization(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.map(data_standardization, 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.map(data_standardization, num_parallel_calls=AUTO)
 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.map(data_standardization, num_parallel_calls=AUTO)
 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 create_title(name_col):
for name in name_col:
matches = re.findall("\w+\.",name)
 yield matches[0]
data['Title'] = list(create_title(data['Name']))
data['Title'] = data['Title'].replace({'Mlle.':'Miss.','Ms.':'Miss.','Jonkheer.':"Mr.","Major.":"Mr.","Countess.":"Mrs.","Don.":"Mr.", "Dona.":"Mrs.","Sir.":"Mr.","Mme.":"Miss.", "Col.":"Military", "Major.":"Military","Capt.":"Military", "Lady.":"Mrs."})
 print(data['Title'].value_counts())
 x = np.arange(0,14,2)
 plt.bar(x - 0.25, data.Title[data['Survived'] == 0].value_counts().sort_index() , color = "r", width = 0.5)
 plt.bar(x[:6] + 0.25, data.Title[data['Survived'] == 1].value_counts().sort_index() , color = "b", width = 0.5)
 plt.xticks(x,["Dr.", "Master.", "Military","Miss.","Mr.","Mrs.","Revenant"])
 plt.legend(["Died","Survived"])
 plt.show() 
<categorify>
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'))
data = pd.get_dummies(data.drop(['Cabin','Ticket','Name'], axis = 1))
data.head()<groupby>
training_dataset = get_training_dataset()
training_dataset = training_dataset.unbatch().batch(20)
 train_batch = iter(training_dataset )
train, test = [x for _, x in data.groupby(data['Survived'].isnull())]
train = train.drop(['index', 'PassengerId'], axis = 1)
 test = test.drop(['index', 'PassengerId'], axis = 1)

train.Survived.value_counts()<prepare_x_and_y>
display_batch_of_images(next(train_batch))
X_train = train.drop(['Survived'], axis = 1)
 y_train = train['Survived']
X_test = test.drop(['Survived'], axis = 1 )<choose_model_class>
test_dataset = get_test_dataset()
test_dataset = test_dataset.unbatch().batch(20)
 test_batch = iter(test_dataset )
kern_ridge = KernelRidge()
params = {'alpha': [0.01,0.1, 1.0],
'coef0': [0,0.1,1],
'degree': [1,2,3],
'gamma': [0.01,1,10],
'kernel': ['rbf']
}
grid_params = {
'estimator':kern_ridge,
'param_grid':params,
'n_jobs':5,
'iid':False,
'verbose':True,
'scoring':'neg_mean_squared_error',
'cv':10
}
y_preds_ridge, ridge_model = run_model(train, test, grid_params, file_name = "submission_ridge.csv", regression = True )<train_model>
display_batch_of_images(next(test_batch))
log_reg_model = LogisticRegression()
log_reg_params = {'C': [0.1,1.0,10,100],
'class_weight': [None],
'dual': [None],
'fit_intercept': [True,False],
'max_iter': [10000],
'multi_class': ['ovr'],
'class_weight':[class_weights],
'n_jobs': [1],
'penalty': ['l1','l2'],
'random_state': [123],
'tol': [0.0001, 0.0005,0.001],
'solver':['saga'],
'warm_start': [False]}
grid_params['estimator'] = log_reg_model
grid_params['param_grid'] = log_reg_params
grid_params['scoring'] = 'accuracy'
test_preds_log_reg, log_reg_model = run_model(train, test, grid_params, file_name = "submission_log_reg.csv" )<choose_model_class>
def lrfn(epoch):
LR_START = 0.00001
LR_MAX = 0.00005 * strategy.num_replicas_in_sync
LR_MIN = 0.00001
LR_RAMPUP_EPOCHS = 5
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
rng = [i for i in range(25 if EPOCHS<25 else 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]))
xgb_model = XGBClassifier()
params_xgb = {
'base_score':[0.3,0.5],
'colsample_bytree':[0.4,0.7],
'gamma':[0.01,0.5,0.9],
'min_child_weight':[1,3],
'learning_rate':[0.01,0.1,1],
'max_depth':[3,4,5],
'n_estimators':[500],
'reg_alpha':[1e-5, 0.1],
'reg_lambda':[1e-5, 0.1],
'subsample':[0.8]
}
grid_params['estimator'] = xgb_model
grid_params['param_grid'] = params_xgb
grid_params['n_jobs'] = 5
test_preds_xgb, xgb_model = run_model(train, test, grid_params, file_name = "submission_xgb.csv")
<normalization>
lr_schedule = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=1 )
test_gp = test.copy()
train_gp = train.copy()
data_gp = pd.concat([test_gp,train_gp])
 data_gp[['Age','Fare','SibSp','Parch']] = scale(data_gp[['Age','Fare','SibSp','Parch']])
 print(data_gp.head())
 data_gp['Survived'].replace({1:1, 0:-1})
 train_gp, test_gp = [x for _, x in data_gp.groupby(data_gp['Survived'].isnull())]
print(train_gp.shape )<choose_model_class>
es_callback = tf.keras.callbacks.EarlyStopping(min_delta=0, patience=10, verbose=1, mode='auto', restore_best_weights=True )
params = {'copy_X_train': [True],
'kernel': [RBF(1.0),RBF(0.01),RBF(0.001),RBF(10), RBF(5), RBF(3), RBF(2)],
'max_iter_predict': [100],
'multi_class': ['one_vs_rest'],
'n_jobs': [3],
'n_restarts_optimizer': [0],
'optimizer': ['fmin_l_bfgs_b'],
'random_state': [123],
'warm_start': [False]
}
grid_params['estimator'] = GaussianProcessClassifier()
grid_params['param_grid'] = params
test_preds_gauss, gp_model = run_model(train_gp, test_gp, grid_params, file_name = "submission_gauss_process.csv" )<find_best_params>
with strategy.scope() :
dense_net = tf.keras.applications.DenseNet201(weights='imagenet', include_top=False ,input_shape=[*IMAGE_SIZE, 3])
 dense_net.trainable = True
model1 = tf.keras.Sequential([
dense_net,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model1.compile(
 optimizer= tf.keras.optimizers.Adam() ,
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 model1.summary()
params = {'C': [0.01,0.1,0.5,1.0,10,50],
'class_weight': [class_weights],
'coef0': [0.0,0.1,0.5,1],
'decision_function_shape': ['ovr'],
'degree': [2,3],
'gamma': ['auto_deprecated'],
'kernel': ['rbf','poly'],
'max_iter': [-1],
'probability': [False],
'random_state': [123],
'shrinking': [True],
'tol': [0.001,0.003,0.005,0.01]}
grid_params['estimator'] = SVC()
grid_params['param_grid'] = params
test_preds_svm, svm_model = run_model(train_gp, test_gp, grid_params, file_name = "submission_gauss_process.csv" )<define_search_space>
history1 = model1.fit(get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS, callbacks=[lr_schedule],
validation_data=None if SKIP_VALIDATION else get_validation_dataset() )
rf_model = RandomForestClassifier()
params_rf = {
'bootstrap': [True,False],
'class_weight': [None],
'criterion': ['gini','entropy'],
'max_depth': [None],
'max_features': ['auto'],
'max_leaf_nodes': [None],
'min_impurity_decrease': [0.0,0.01,0.1,1],
'min_impurity_split': [None],
'min_samples_leaf': [1,5,10,15],
'min_samples_split': [2,5,10],
'min_weight_fraction_leaf': [0.0],
'n_estimators': [5,10,20,100],
'n_jobs': [None],
'oob_score': [False],
'random_state': [123]
}
grid_params['estimator'] = rf_model
grid_params['param_grid'] = params_rf
test_preds_rf, rf_model = run_model(train, test, grid_params, file_name = "submission_rf.csv" )<predict_on_test>
with strategy.scope() :
efficient_net = efn.EfficientNetB7(input_shape=[*IMAGE_SIZE, 3], weights='imagenet',include_top=False)
 efficient_net.trainable = True
model2 = tf.keras.Sequential([
efficient_net,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model2.compile(
 optimizer= tf.keras.optimizers.Adam() ,
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 model2.summary()
svm_model.set_params(probability = True)
 vc_model = VotingClassifier([('rf',rf_model),('xgb',xgb_model),('gp',gp_model),('svm',svm_model)], voting = 'soft')
 X_train = train_gp.drop(['Survived'], axis = 1)
 y_train = train_gp['Survived']
X_test = test_gp.drop(['Survived'],axis = 1)
 vc_model.fit(X_train, y_train)
 preds_train = vc_model.predict(X_train)
 print(confusion_matrix(y_train, preds_train))
y_preds_test = vc_model.predict(X_test)
 create_submission(test_gp,y_preds_test, "submission_vc_soft.csv" )<import_modules>
history2 = model2.fit(get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS, callbacks=[lr_schedule, es_callback],
validation_data=None if SKIP_VALIDATION else get_validation_dataset() )
import numpy as np
import pandas as pd
import os<load_from_csv>
with strategy.scope() :
res_net = tf.keras.applications.inception_resnet_v2.InceptionResNetV2(include_top=False, weights='imagenet', input_tensor=None, input_shape=[*IMAGE_SIZE, 3], pooling=None, classes=1000)
 res_net.trainable = True
model3 = tf.keras.Sequential([
res_net,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model3.compile(
 optimizer= tf.keras.optimizers.Adam() ,
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 model3.summary()
training = pd.read_csv(".. /input/train.csv");
x_test = pd.read_csv(".. /input/test.csv");<feature_engineering>
history3 = model3.fit(get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS, callbacks=[lr_schedule],
validation_data=None if SKIP_VALIDATION else get_validation_dataset() )
training['n_new']= training['Name'].apply(lambda x: x.split(',')[1].split('.')[0].strip() )<count_values>
test_ds = get_test_dataset(ordered=True)
 test_images_ds = test_ds.map(lambda image, idnum: image)
 print('Computing predictions for model 1...... ')
 preds1 = model1.predict(test_images_ds)
 print('Computing predictions for model 2...... ')
 preds2 = model2.predict(test_images_ds)
 print('Computing predictions for model 3...... ')
 preds3 = model3.predict(test_images_ds )
<feature_engineering><EOS> 
probabilities =(preds1 + preds2 + preds3)/ 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