Kaggle competition: Flower Classification with TPUs
<SOS> metric: MacroFScore Kaggle data source: flower-classification-with-tpus<train_model>
import numpy as np
import pandas as pd
import os
class AveragedModel(BaseEstimator, RegressorMixin, TransformerMixin):
def __init__(self, models, weights):
self.models = models
self.weights = weights
def fit(self, X, y):
self.models_ = [clone(x)for x in self.models]
for model in self.models_:
model.fit(X, y)
 return self
def predict(self, X):
predictions = np.column_stack([
model.predict(X)for model in self.models_
])
 return np.dot(predictions,self.weights)
 class StackedAveragedModel(BaseEstimator, RegressorMixin, TransformerMixin):
def __init__(self, base_models, meta_model, nfold=5):
self.base_models = base_models
self.meta_model = meta_model
self.nfold = nfold
def fit(self, X, y):
self.base_models_ = [list() for x in self.base_models]
self.meta_model_ = clone(self.meta_model)
 kfold = KFold(n_splits=self.nfold, shuffle=True, random_state=156)
 out_of_fold_predictions = np.zeros(( X.shape[0], len(self.base_models)))
 for i, model in enumerate(self.base_models):
for train_index, holdout_index in kfold.split(X, y):
instance = clone(model)
 self.base_models_[i].append(instance)
 instance.fit(X[train_index], y[train_index])
 y_pred = instance.predict(X[holdout_index])
 out_of_fold_predictions[holdout_index, i] = y_pred
self.meta_model_.fit(out_of_fold_predictions, y)
 return self
def predict(self, X):
meta_features = np.column_stack([
np.column_stack([model.predict(X)for model in base_models] ).mean(axis=1)
 for base_models in self.base_models_ ])
 return self.meta_model_.predict(meta_features )<train_on_grid>
!pip install -q efficientnet
print("Tensorflow version " + tf.__version__)
 AUTO = tf.data.experimental.AUTOTUNE
flag=True
if flag:
steps = [('scaler',RobustScaler()),('select',SelectFromModel(Lasso(alpha =5e-4, random_state=1,selection='cyclic'))), 
('lasso', Lasso(alpha =5e-4, random_state=1,selection='cyclic')) ]
lasso_p = Pipeline(steps)
 alphas=(np.linspace(1e-4,1e-3,num=10))
selections=['random','cyclic']
gscv = GridSearchCV(lasso_p, cv=nfold, param_grid={'lasso__alpha': alphas, 'lasso__selection': selections}, n_jobs=1, verbose=1)
 gscv.fit(new_train.values, y_train)
 lasso_ = gscv.best_estimator_.named_steps.lasso
score = cv_score(lasso_)
 print("
Lasso score: {:.4f}({:.4f})
 ".format(score.mean() , score.std()))
print('Best Lasso: ',lasso_)
 lasso = make_pipeline(RobustScaler() ,SelectFromModel(lasso_), lasso_)
 steps = [('scaler',RobustScaler()),('select',SelectFromModel(ElasticNet(alpha=1e-3,
l1_ratio=5e-1, random_state=3, selection='random'))),('enet', ElasticNet(alpha=1e-3,
l1_ratio=5e-1, random_state=3, selection='random')) ]
enet_p = Pipeline(steps)
 alphas=np.linspace(1e-3,1e-2,num=10)
 l1_ratios=np.linspace(0,1,num=11)
 selections=['random','cyclic']
gscv = GridSearchCV(enet_p, cv=nfold,
param_grid={'enet__alpha': alphas, 'enet__l1_ratio': l1_ratios, 'enet__selection':selections }, n_jobs=1, verbose=1)
 gscv.fit(new_train.values, y_train)
 enet_ = gscv.best_estimator_.named_steps.enet
score = cv_score(enet_)
 print("
ElasticNet score: {:.4f}({:.4f})
 ".format(score.mean() , score.std()))
print('Best ElasticNet: ',enet_)
 enet = make_pipeline(RobustScaler() ,SelectFromModel(enet_), enet_)
 steps = [('scaler',RobustScaler()),('select',SelectFromModel(lasso_)) ,('krr',KernelRidge(alpha=6e-1,
kernel='polynomial', degree=2, coef0=4)) ]
krr_p = Pipeline(steps)
 alphas=np.linspace(1e-1,1,num=10)
 degrees=[1,2,3]
coef0s = [1,2,4,8]
gscv = GridSearchCV(krr_p, cv=nfold,
param_grid={'krr__alpha': alphas, 'krr__degree': degrees, 'krr__coef0':coef0s }, n_jobs=1, verbose=1)
 gscv.fit(new_train.values, y_train)
 krr_ = gscv.best_estimator_.named_steps.krr
score = cv_score(krr_)
 print("
Kernel Ridge score: {:.4f}({:.4f})
 ".format(score.mean() , score.std()))
print('Best Kernel Ridge: ',krr_)
 krr = make_pipeline(RobustScaler() ,SelectFromModel(lasso_), krr_)
 steps = [('scaler',RobustScaler()),('select',SelectFromModel(lasso_)) ,('gboost',GradientBoostingRegressor(n_estimators=2000,
learning_rate=2e-2, max_depth=5, max_features='log2',
min_samples_leaf=5, min_samples_split=15, loss='huber', random_state =5)) ]
gboost_p = Pipeline(steps)
 n_estimatorss=[1000,2000,3000]
learning_rates=np.linspace(1e-2,1e-1,num=10)
 max_depths=[1,2,3,4,5]
max_featuress=['sqrt','log2']
min_samples_leafs=[5,10,15,20]
min_samples_splits=[5,10,15,20]
rscv = RandomizedSearchCV(gboost_p, cv=nfold,
param_distributions={'gboost__n_estimators': n_estimatorss, 'gboost__learning_rate': learning_rates, 'gboost__max_depth': max_depths,
'gboost__min_samples_leaf': min_samples_leafs, 'gboost__min_samples_split': min_samples_splits, 'gboost__max_features': max_featuress},
n_jobs=1, verbose=1, random_state=7)
 rscv.fit(new_train.values, y_train)
 gboost_ = rscv.best_estimator_.named_steps.gboost
score = cv_score(gboost_)
 print("
Gradient Boosting score: {:.4f}({:.4f})
 ".format(score.mean() , score.std()))
print('Best Gradient Boosting: ',gboost_)
 gboost = make_pipeline(RobustScaler() ,SelectFromModel(lasso_), gboost_)
 steps = [('scaler',RobustScaler()),('select',SelectFromModel(lasso_)) ,('xgboost', xgb.XGBRegressor(colsample_bytree=6e-1, gamma=1e-2,
learning_rate=4e-2, max_depth=3, min_child_weight=1.5, n_estimators=1000, reg_alpha=4e-1, reg_lambda=9e-1, subsample=4e-1,
silent=1, random_state =7,n_jobs = 1)) ]
xgboost_p = Pipeline(steps)
 n_estimatorss=[1000,2000,3000]
learning_rates=np.linspace(1e-2,1e-1,num=10)
 max_depths=[1,2,3,4,5]
gammas=np.linspace(1e-2,1e-1,num=10)
 min_child_weights=[1.5,1.6,1.7,1.8,1.9]
colsample_bytrees=np.linspace(1e-1,1,num=10)
 reg_alphas=[0.3,0.4,0.5]
reg_lambdas=[0.7,0.8,0.9]
subsamples=[0.3,0.4,0.5,0.6,0.7]
rscv = RandomizedSearchCV(xgboost_p, cv=nfold,
param_distributions={'xgboost__n_estimators': n_estimatorss, 'xgboost__learning_rate': learning_rates,
'xgboost__max_depth': max_depths, 'xgboost__gamma': gammas, 'xgboost__min_child_weight': min_child_weights,
'xgboost__colsample_bytree': colsample_bytrees, 'xgboost__reg_alpha' : reg_alphas, 'xgboost__reg_lambda': reg_lambdas,
'xgboost__subsample': subsamples},
n_jobs=1, verbose=1, random_state=7)
 rscv.fit(new_train.values, y_train)
 xgboost_ = rscv.best_estimator_.named_steps.xgboost
score = cv_score(xgboost_)
 print("
X Gradient Boosting score: {:.4f}({:.4f})
 ".format(score.mean() , score.std()))
print('Best X Gradient Boosting: ',xgboost_)
 xgboost = make_pipeline(RobustScaler() ,SelectFromModel(lasso_), xgboost_)
 steps = [('scaler',RobustScaler()),('select',SelectFromModel(lasso_)) ,('lgbm',
lgb.LGBMRegressor(objective='regression',num_leaves=5, learning_rate=6e-2, n_estimators=500, max_bin = 60,
bagging_fraction = 1, bagging_freq = 5, feature_fraction = 1e-1, feature_fraction_seed=9, bagging_seed=9,
min_data_in_leaf =6, min_sum_hessian_in_leaf = 10, verbose=-1)) ]
lgbm_p = Pipeline(steps)
 n_estimatorss=[500,600,700,800,900,1000]
learning_rates=np.linspace(1e-2,1e-1,num=10)
 num_leavess=[5,10,15]
max_bins=[10,20,30,40,50,60,70,80,90,100]
bagging_fractions=[0.2,0.4,0.6,0.8,1]
bagging_freqs=[1,3,5,7,9]
feature_fractions=np.linspace(1e-1,1,num=10)
 min_data_in_leafs=[2,4,6,8,10]
min_sum_hessian_in_leafs=[10,20,30]
rscv = RandomizedSearchCV(lgbm_p, cv=nfold,
param_distributions={'lgbm__n_estimators': n_estimatorss, 'lgbm__learning_rate': learning_rates,
'lgbm__num_leaves': num_leavess, 'lgbm__max_bin': max_bins, 'lgbm__bagging_fraction': bagging_fractions,
'lgbm__bagging_freq': bagging_freqs, 'lgbm__feature_fraction' : feature_fractions, 'lgbm__min_data_in_leaf': min_data_in_leafs,
'lgbm__min_sum_hessian_in_leaf': min_sum_hessian_in_leafs},
n_jobs=1, verbose=1, random_state=7)
 rscv.fit(new_train.values, y_train)
 lgbm_ = rscv.best_estimator_.named_steps.lgbm
score = cv_score(lgbm_)
 print("
Light Gradient Boosting score: {:.4f}({:.4f})
 ".format(score.mean() , score.std()))
print('Best Light Gradient Boosting: ',lgbm_)
 lgbm = make_pipeline(RobustScaler() ,SelectFromModel(lasso_), lgbm_ )<compute_test_metric>
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 )
if flag:
score = cv_score(lasso)
 lasso_w = 1.0/score.std()
print("
Lasso score: {:.4f}({:.4f})
 ".format(score.mean() , score.std()))
score = cv_score(enet)
 enet_w = 1.0/score.std()
print("
ElasticNet score: {:.4f}({:.4f})
 ".format(score.mean() , score.std()))
score = cv_score(krr)
 krr_w = 1.0/score.std()
print("
Kernel Ridge score: {:.4f}({:.4f})
 ".format(score.mean() , score.std()))
score = cv_score(gboost)
 gboost_w = 1.0/score.std()
print("
Gradient Boosting score: {:.4f}({:.4f})
 ".format(score.mean() , score.std()))
score = cv_score(xgboost)
 xgboost_w = 1.0/score.std()
print("
X Gradient Boosting score: {:.4f}({:.4f})
 ".format(score.mean() , score.std()))
score = cv_score(lgbm)
 lgbm_w = 1.0/score.std()
print("
Light Gradient Boosting score: {:.4f}({:.4f})
 ".format(score.mean() , score.std()))
weights = [enet_w, gboost_w, krr_w, lasso_w, xgboost_w, lgbm_w]
averaged_model = AveragedModel(models =(enet, gboost, krr, lasso, xgboost, lgbm), weights=weights/sum(weights))
score = cv_score(averaged_model)
 averaged_model_w = 1.0/score.std()
print("
Averaged base models score: {:.4f}({:.4f})
 ".format(score.mean() , score.std()))
stacked_averaged_model = StackedAveragedModel(base_models =(lasso, enet, gboost, krr, xgboost, lgbm), meta_model = lasso)
 score=cv_score(stacked_averaged_model)
 stacked_averaged_model_w = 1.0/score.std()
print("
Stacked Averaged model score: {:.4f}({:.4f})
 ".format(score.mean() , score.std())) 
<compute_train_metric>
GCS_DS_PATH = KaggleDatasets().get_gcs_path()
if flag:
stacked_averaged_model.fit(new_train.values, y_train)
 stacked_train_pred = stacked_averaged_model.predict(new_train.values)
 stacked_pred = stacked_averaged_model.predict(new_test.values)
 print("
Stacked Averaged model train prediction error: {:.4f}
".format(np.sqrt(mean_squared_error(y_train, stacked_train_pred))))
averaged_model.fit(new_train.values, y_train)
 averaged_train_pred = averaged_model.predict(new_train.values)
 averaged_pred = averaged_model.predict(new_test.values)
 print("
Averaged base model train prediction error: {:.4f}
".format(np.sqrt(mean_squared_error(y_train, averaged_train_pred))))
total_weight = stacked_averaged_model_w+averaged_model_w
train_pred =(stacked_train_pred*stacked_averaged_model_w + averaged_train_pred*averaged_model_w)/total_weight
print("
Stacked and Averaged train prediction error: {:4f}
".format(np.sqrt(mean_squared_error(y_train, train_pred))))
prediction = stacked_pred
sub = pd.DataFrame()
sub['Id'] = test_ID
sub['SalePrice'] = np.expm1(prediction)
 sub.to_csv('submission.csv',index=False )<import_modules>
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']
import re
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.model_selection import StratifiedKFold
from collections import Counter
from imblearn.under_sampling import RandomUnderSampler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import *
from sklearn import preprocessing
from sklearn.preprocessing import OneHotEncoder
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import GridSearchCV
from sklearn.linear_model import SGDClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.linear_model import Perceptron
from sklearn.svm import LinearSVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score
from pprint import pprint
import xgboost
from sklearn.model_selection import cross_val_score, GridSearchCV, KFold, RandomizedSearchCV
from sklearn.metrics import auc, accuracy_score, confusion_matrix, mean_squared_error
from xgboost import XGBClassifier
import time
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler<compute_train_metric>
VALIDATION = False
if not VALIDATION:
TRAINING_FILENAMES = TRAINING_FILENAMES+VALIDATION_FILENAMES
def get_cv_roc_pr_rc(clf, skf, X, y):
roc_auc = []
pr_auc = []
precision = []
recall = []
models = []
for train, test in skf.split(X, y):
models.append(clf.fit(X.iloc[train,:], y.iloc[train]))
y_pred = clf.predict(X.iloc[test,:])
 y_pred_prob = clf.predict_proba(X.iloc[test,:])[:,1]
roc_auc.append(roc_auc_score(y.iloc[test], y_pred_prob))
pr_auc.append(average_precision_score(y.iloc[test], y_pred_prob))
precision.append(precision_score(y.iloc[test], y_pred))
recall.append(recall_score(y.iloc[test], y_pred))
print('ROC-AUC:', np.mean(roc_auc))
print('PR-AUC:', np.mean(pr_auc))
print('Precission:', np.mean(precision))
print('Recall:', np.mean(recall))
return roc_auc, pr_auc, precision, recall, models<compute_train_metric>
def get_mat(rotation, shear, height_zoom, width_zoom, height_shift, width_shift):
rotation = math.pi * rotation / 180.
 shear = math.pi * shear / 180.
 c1 = tf.math.cos(rotation)
 s1 = tf.math.sin(rotation)
 one = tf.constant([1],dtype='float32')
 zero = tf.constant([0],dtype='float32')
 rotation_matrix = tf.reshape(tf.concat([c1,s1,zero, -s1,c1,zero, zero,zero,one],axis=0),[3,3])
 c2 = tf.math.cos(shear)
 s2 = tf.math.sin(shear)
 shear_matrix = tf.reshape(tf.concat([one,s2,zero, zero,c2,zero, zero,zero,one],axis=0),[3,3])
 zoom_matrix = tf.reshape(tf.concat([one/height_zoom,zero,zero, zero,one/width_zoom,zero, zero,zero,one],axis=0),[3,3])
 shift_matrix = tf.reshape(tf.concat([one,zero,height_shift, zero,one,width_shift, zero,zero,one],axis=0),[3,3])
 return K.dot(K.dot(rotation_matrix, shear_matrix), K.dot(zoom_matrix, shift_matrix))
def random_rotate(image):
DIM = IMAGE_SIZE[0]
XDIM = DIM%2
rot = 15.* tf.random.normal([1],dtype='float32')
 shr = 5.* tf.random.normal([1],dtype='float32')
 h_zoom = 1.0 + tf.random.normal([1],dtype='float32')/10.
 w_zoom = 1.0 + tf.random.normal([1],dtype='float32')/10.
 h_shift = 16.* tf.random.normal([1],dtype='float32')
 w_shift = 16.* tf.random.normal([1],dtype='float32')
 m = get_mat(rot,shr,h_zoom,w_zoom,h_shift,w_shift)
 x = tf.repeat(tf.range(DIM//2,-DIM//2,-1), DIM)
 y = tf.tile(tf.range(-DIM//2,DIM//2),[DIM])
 z = tf.ones([DIM*DIM],dtype='int32')
 idx = tf.stack([x,y,z])
 idx2 = K.dot(m,tf.cast(idx,dtype='float32'))
idx2 = K.cast(idx2,dtype='int32')
 idx2 = K.clip(idx2,-DIM//2+XDIM+1,DIM//2)
 idx3 = tf.stack([DIM//2-idx2[0,], DIM//2-1+idx2[1,]])
 d = tf.gather_nd(image,tf.transpose(idx3))
return tf.reshape(d,[DIM,DIM,3] )
def get_cv_roc_pr_rc_2(clf, skf, X, y):
roc_auc = []
pr_auc = []
precision = []
recall = []
models = []
for train, test in skf.split(X, y):
models.append(clf.fit(X.iloc[train,:], y.iloc[train]))
y_pred = clf.predict(X.iloc[test,:])
 roc_auc.append(roc_auc_score(y.iloc[test], y_pred))
pr_auc.append(average_precision_score(y.iloc[test], y_pred))
precision.append(precision_score(y.iloc[test], y_pred))
recall.append(recall_score(y.iloc[test], y_pred))
print('ROC-AUC:', np.mean(roc_auc))
print('PR-AUC:', np.mean(pr_auc))
print('Precission:', np.mean(precision))
print('Recall:', np.mean(recall))
return roc_auc, pr_auc, precision, recall, models<load_from_csv>
def decode_image(image_data):
image = tf.image.decode_jpeg(image_data, channels=3)
 image = tf.cast(image, tf.float32)/ 255.0
image = tf.reshape(image, [*IMAGE_SIZE, 3])
 return image
def read_labeled_tfrecord(example):
LABELED_TFREC_FORMAT = {
"image": tf.io.FixedLenFeature([], tf.string),
"class": tf.io.FixedLenFeature([], tf.int64),
}
example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)
 image = decode_image(example['image'])
 label = tf.cast(example['class'], tf.int32)
 return image, label
def read_unlabeled_tfrecord(example):
UNLABELED_TFREC_FORMAT = {
"image": tf.io.FixedLenFeature([], tf.string),
"id": tf.io.FixedLenFeature([], tf.string),
}
example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT)
 image = decode_image(example['image'])
 idnum = example['id']
return image, idnum
def load_dataset(filenames, labeled=True, ordered=False):
ignore_order = tf.data.Options()
if not ordered:
ignore_order.experimental_deterministic = False
dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO)
 dataset = dataset.with_options(ignore_order)
 dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls=AUTO)
 return dataset
def data_augment(image, label):
image = tf.image.random_flip_left_right(image)
 return image, label
def get_training_dataset() :
dataset = 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))
train = pd.read_csv('/kaggle/input/titanic/train.csv')
 test = pd.read_csv('/kaggle/input/titanic/test.csv' )<concatenate>
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.concat([train.drop(['Survived'], axis=1), test] )<groupby>
training_dataset = get_training_dataset()
training_dataset = training_dataset.unbatch().batch(20)
 train_batch = iter(training_dataset )
train.groupby('Pclass' ).Survived.mean()<groupby>
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.'] )
train.groupby(['Pclass', 'Sex'] ).Survived.mean()<filter>
display_batch_of_images(next(train_batch))
train.loc[train.Fare==0]<feature_engineering>
test_dataset = get_test_dataset()
test_dataset = test_dataset.unbatch().batch(20)
 test_batch = iter(test_dataset )
data['Fam_Size'] = data.Parch + data.SibSp + 1
data['Fam_type'] = pd.cut(data.Fam_Size, [0,1,4,7,11], labels=['Solo', 'Small', 'Big', 'Very big'] )<feature_engineering>
display_batch_of_images(next(test_batch))
data['Ticket_lett'] = data.Ticket.apply(lambda x: x[:2])
 data['Ticket_len'] = data.Ticket.apply(lambda x: len(x))<data_type_conversions>
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()
data['Age'] = data['Age'].interpolate(limit_direction='both', method='linear')
 data['Fare'] = data['Fare'].interpolate(limit_direction='both', method='linear')
 data['Embarked'] = data['Embarked'].fillna(data['Embarked'].value_counts().index[0] )<feature_engineering>
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()
data['CatAge'] = pd.qcut(data.Age, q=4, labels=False )<drop_column>
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 )
data = data.drop(['PassengerId', 'Name', 'SibSp', 'Parch',
'Ticket', 'Cabin', 'Fam_Size', 'Age'], axis = 1 )<categorify>
es_callback = tf.keras.callbacks.EarlyStopping(min_delta=0, patience=10, verbose=1, mode='auto', restore_best_weights=True )
data_dun = pd.get_dummies(data, drop_first=True)
 data_dun.shape<prepare_x_and_y>
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])
y_train = train['Survived']<choose_model_class>
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])
skf = StratifiedKFold(n_splits=5 )<split>
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 )
data_dun_train = data_dun[:891]
data_dun_test = data_dun[891:]<train_model>
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))
ros = RandomUnderSampler(random_state=0)
 ros.fit(data_dun_train, y_train)
 X_resampled, y_resampled = ros.fit_sample(data_dun_train, y_train )<choose_model_class>
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)*0.6 + model2.predict(test_images_ds)*0.4
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
lr = LogisticRegression(max_iter = 10000, penalty="l2" )<define_search_space>
if VALIDATION:
dataset = get_validation_dataset()
dataset = dataset.unbatch().batch(20)
 batch = iter(dataset )
<train_model><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 )