Kaggle competition: Flower Classification with TPUs
<SOS> metric: MacroFScore Kaggle data source: flower-classification-with-tpus<train_model>
!pip install -q efficientnet
batch_size = 86
epochs = 100 
<train_model>
print("Tensorflow version " + tf.__version__)
model = cnn(y_train.shape[1])
 history = model.fit_generator(datagen.flow(X_train, y_train, batch_size = batch_size),
validation_data=(X_val, y_val),
epochs = epochs,
steps_per_epoch = X_train.shape[0] // batch_size,
callbacks = [learning_rate_reduction],
verbose=2 )<save_to_csv>
AUTO = tf.data.experimental.AUTOTUNE
tpu = tf.distribute.cluster_resolver.TPUClusterResolver()
tf.config.experimental_connect_to_cluster(tpu)
 tf.tpu.experimental.initialize_tpu_system(tpu)
 strategy = tf.distribute.experimental.TPUStrategy(tpu)
 GCS_DS_PATH = KaggleDatasets().get_gcs_path()
img_size=512
IMAGE_SIZE = [512, 512]
EPOCHS = 20
BATCH_SIZE = 16 * strategy.num_replicas_in_sync
prediction = model.predict(test)
 prediction = np.argmax(prediction, axis =1)
 dataframe = pd.read_csv(".. /input/sample_submission.csv")
 list_of_images = dataframe.ImageId.values
name = 'submission'
submission = pd.DataFrame({'ImageId':list_of_images})
 submission['Label'] = prediction
submission.to_csv(f'{name}.csv',index=False )<load_from_csv>
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
def lrfn(epoch):
if epoch < LR_RAMPUP_EPOCHS:
lr =(LR_MAX - LR_START)/ LR_RAMPUP_EPOCHS * epoch + LR_START
elif epoch < LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS:
lr = LR_MAX
else:
lr =(LR_MAX - LR_MIN)* LR_EXP_DECAY**(epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS)+ LR_MIN
return lr
lr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=True)
 rng = [i for i in range(EPOCHS)]
y = [lrfn(x)for x in rng]
plt.plot(rng, y)
 print("Learning rate schedule: {:.3g} to {:.3g} to {:.3g}".format(y[0], max(y), y[-1]))
raw_train = pd.read_csv('/kaggle/input/titanic/train.csv')
 raw_test = pd.read_csv('/kaggle/input/titanic/test.csv')
 raw_train.head()<categorify>
GCS_PATH_SELECT = {
192: GCS_DS_PATH + '/tfrecords-jpeg-192x192',
224: GCS_DS_PATH + '/tfrecords-jpeg-224x224',
331: GCS_DS_PATH + '/tfrecords-jpeg-331x331',
512: GCS_DS_PATH + '/tfrecords-jpeg-512x512'
}
GCS_PATH = GCS_PATH_SELECT[IMAGE_SIZE[0]]
TRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/train/*.tfrec')
 VALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec')
 TEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec')
 SKIP_VALIDATION = True
if SKIP_VALIDATION:
TRAINING_FILENAMES = TRAINING_FILENAMES + VALIDATION_FILENAMES
columns = ['Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Fare', 'Embarked', 'Name', 'PassengerId']
train = raw_train[np.append(columns, ['Survived'])].copy().set_index('PassengerId')
 test = raw_test[columns].copy().set_index('PassengerId')
 class OneHotEncoder(SklearnOneHotEncoder):
def __init__(self, **kwargs):
super(OneHotEncoder, self ).__init__(**kwargs)
 self.fit_flag = False
def fit(self, X, **kwargs):
out = super().fit(X)
 self.fit_flag = True
return out
def transform(self, X, categories, index='', name='', **kwargs):
sparse_matrix = super(OneHotEncoder, self ).transform(X)
 new_columns = self.get_new_columns(X=X, name=name, categories=categories)
 d_out = pd.DataFrame(sparse_matrix.toarray() , columns=new_columns, index=index)
 return d_out
def fit_transform(self, X, categories, index, name, **kwargs):
self.fit(X)
 return self.transform(X, categories=categories, index=index, name=name)
 def get_new_columns(self, X, name, categories):
new_columns = []
for j in range(len(categories)) :
new_columns.append('{}_{}'.format(name, categories[j]))
return new_columns
class data_preparation() :
def __init__(self):
self.enc_sex = LabelEncoder()
self.scaler_age = StandardScaler()
self.enc_title = LabelEncoder()
self.onehotenc_title = OneHotEncoder(handle_unknown='ignore')
 self.onehotenc_pclass = OneHotEncoder(handle_unknown='ignore')
 self.enc_embarked = LabelEncoder()
self.onehotenc_embarked = OneHotEncoder(handle_unknown='ignore')
 def transform(self, data_untouched):
data = data_untouched.copy(deep=True)
 data['Title'] = data['Name'].str.extract('([A-Za-z]+)\.', expand = False)
 data['Embarked'] = data['Embarked'].fillna(data['Embarked'].mode() [0])
 try:
data['Sex'] = self.enc_sex.transform(data['Sex'].values)
 data['Age'] = self.scaler_age.transform(data['Age'].values.reshape(-1, 1))
data['Title'] = data['Title'].map(lambda x: self.enc_title.transform([x])[0] if x in self.enc_title.classes_ else -1)
 data['Embarked'] = data['Embarked'].map(lambda x: self.enc_embarked.transform([str(x)])[0] if x in self.enc_embarked.classes_ else -1)
 data = pd.concat([self.onehotenc_title.transform(data['Title'].values.reshape(-1,1), categories=self.enc_title.classes_,name='Title', index=data.index),
self.onehotenc_pclass.transform(data['Pclass'].values.reshape(-1,1), categories=[3,2,1], name='Pclass', index=data.index),
self.onehotenc_embarked.transform(data['Embarked'].values.reshape(-1,1), categories=self.enc_embarked.classes_, name='Embarked', index=data.index),
data],axis=1)
 except NotFittedError:
self.mean_age = data['Age'].median()
self.median_fare = data['Fare'].median()
data['Sex'] = self.enc_sex.fit_transform(data['Sex'].values)
 data['Age'] = self.scaler_age.fit_transform(data['Age'].values.reshape(-1, 1))
data['Title'] = self.enc_title.fit_transform(data['Title'].values)
 data['Embarked'] = self.enc_embarked.fit_transform(data['Embarked'].astype(str ).values)
 data = pd.concat([self.onehotenc_title.fit_transform(data['Title'].values.reshape(-1,1), categories=self.enc_title.classes_, name='Title', index=data.index),
self.onehotenc_pclass.fit_transform(data['Pclass'].values.reshape(-1,1), categories=[3,2,1], name='Pclass', index=data.index),
self.onehotenc_embarked.fit_transform(data['Embarked'].values.reshape(-1,1), categories=self.enc_embarked.classes_, name='Embarked', index=data.index),
data], axis=1)
 data['Family_size'] = data['SibSp'] + data['Parch']
data['IsAlone'] =(data['Family_size'] == 0 ).astype(int)
 data['Age'] = data['Age'].fillna(self.mean_age)
 data['Fare'] = data['Fare'].fillna(self.median_fare)
 data = data.drop(columns=['Pclass', 'Embarked', 'Title', 'Name'])
 return data
data_prep = data_preparation()
X_train_full = data_prep.transform(train.drop(columns='Survived'))
y_train_full = train['Survived']
X_test = data_prep.transform(test)
 np.random.seed(0)
 X_train, X_val, y_train, y_val = train_test_split(X_train_full, y_train_full, test_size=0.10, random_state=50 )<import_modules>
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']
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import accuracy_score
from sklearn.tree import DecisionTreeClassifier
from sklearn.svm import SVC
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.naive_bayes import BernoulliNB
from sklearn.ensemble import VotingClassifier<choose_model_class>
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 )
list_params = {
'Tree':{'max_depth': np.logspace(2,8,6)},
'SVC':{'C' : np.linspace(0.01,1,3), 'kernel':['poly'], 'degree':np.linspace(2,8,4 ).astype(int)},
'KNN':{'n_neighbors' : np.linspace(2,30,29 ).astype(int)},
'gauss':{'var_smoothing' : np.logspace(-8,-10,3)},
'bern':{'alpha' : np.linspace(0.1,1,10)}
}
list_base_model = {
'Tree' : DecisionTreeClassifier(random_state=0),
'SVC' : SVC(random_state=0),
'KNN' : KNeighborsClassifier() ,
'gauss' : GaussianNB() ,
'bern' : BernoulliNB()
}
list_models = pd.DataFrame(list_params.items() , columns = ['name', 'params'] ).set_index('name')
 list_models['model'] = list_base_model.values()
list_models['grid_model'] = list_models.apply(lambda x: GridSearchCV(x['model'], x['params']), axis=1)
 list_models['grid_model'] = list_models.apply(lambda x: x['grid_model'].fit(X_train, y_train), axis=1)
 list_models['score'] = list_models.apply(lambda x: x['grid_model'].predict(X_val), axis=1, result_type='reduce' ).apply(lambda x: accuracy_score(x, y_val))
print('Score for each base model using GridSearch:')
 print(list_models['score'] )<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 =(1 - SKIP_VALIDATION)* 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))
models =(( 'Tree', DecisionTreeClassifier(**list_models.loc['Tree', 'grid_model'].best_params_, random_state=40)) , 
('SVC', SVC(**list_models.loc['SVC', 'grid_model'].best_params_, random_state=40, probability=True)) , 
('KNN', KNeighborsClassifier(**list_models.loc['KNN', 'grid_model'].best_params_)) , 
('gauss', GaussianNB(**list_models.loc['gauss', 'grid_model'].best_params_)) , 
('bern', BernoulliNB(**list_models.loc['bern', 'grid_model'].best_params_)))
 vot = VotingClassifier(models, voting='hard')
 vot.fit(X_train,y_train)
 print('Score of the VotingClassifer with hard voting:', accuracy_score(vot.predict(X_val), y_val))<compute_train_metric>
with strategy.scope() :
enet = efn.EfficientNetB7(
 input_shape=(512, 512, 3),
weights='imagenet',
include_top=False 
)
 model = tf.keras.Sequential([
enet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model.compile(
 optimizer=tf.keras.optimizers.Adam(lr=0.0001),
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 model.summary()
vot = VotingClassifier(models, voting='soft')
 vot.fit(X_train,y_train)
 print('Score of the VotingClassifer with soft voting:', accuracy_score(vot.predict(X_val), y_val))<train_model>
history = model.fit(
 get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS,
callbacks=[lr_callback],
validation_data=None if SKIP_VALIDATION else get_validation_dataset()
)
vot = VotingClassifier(models, voting='soft', weights=list_models['score']/list_models['score'].sum())
 vot.fit(X_train,y_train)
 print('Score of the VotingClassifer with soft weighted voting:', accuracy_score(vot.predict(X_val), y_val))<save_to_csv>
with strategy.scope() :
Inet = InceptionResNetV2(
 input_shape=(512, 512, 3),
weights='imagenet',
include_top=False 
)
 model2 = tf.keras.Sequential([
Inet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model2.compile(
 optimizer=tf.keras.optimizers.Adam(lr=0.0001),
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 model2.summary()
vot = VotingClassifier(models, voting='soft')
 vot.fit(X_train_full,y_train_full)
 submission = pd.DataFrame({'PassengerId': test.index, 'Survived': vot.predict(X_test)})
 submission.to_csv('submission_stack.csv', index=False )<choose_model_class>
history2 = model2.fit(
 get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS,
callbacks=[lr_callback],
validation_data=None if SKIP_VALIDATION else get_validation_dataset()
)
models =(( 'Tree', DecisionTreeClassifier(**list_models.loc['Tree', 'grid_model'].best_params_, random_state=40)) , 
('SVC', SVC(**list_models.loc['SVC', 'grid_model'].best_params_, random_state=40, probability=True)) , 
('KNN', KNeighborsClassifier(**list_models.loc['KNN', 'grid_model'].best_params_)) , 
('gauss', GaussianNB(**list_models.loc['gauss', 'grid_model'].best_params_)) , 
('bern', BernoulliNB(**list_models.loc['bern', 'grid_model'].best_params_)))
 final_estimator = MLPClassifier(hidden_layer_sizes =(100,50,), random_state=1)
 stack = StackingClassifier(models, final_estimator=final_estimator)
 stack.fit(X_train,y_train)
 print('Score of the StackingClassifer with hard voting:', accuracy_score(stack.predict(X_val), y_val))<choose_model_class>
with strategy.scope() :
desnet=DenseNet201(
 weights='imagenet',
include_top=False 
)
 model3 = tf.keras.Sequential([
desnet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model3.compile(
 optimizer=tf.keras.optimizers.Adam(lr=0.0001),
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 model3.summary()
models =(( 'Tree', DecisionTreeClassifier(**list_models.loc['Tree', 'grid_model'].best_params_, random_state=40)) , 
('SVC', SVC(**list_models.loc['SVC', 'grid_model'].best_params_, random_state=40, probability=True)) , 
('KNN', KNeighborsClassifier(**list_models.loc['KNN', 'grid_model'].best_params_)) , 
('gauss', GaussianNB(**list_models.loc['gauss', 'grid_model'].best_params_)) , 
('bern', BernoulliNB(**list_models.loc['bern', 'grid_model'].best_params_)))
 MLP = MLPClassifier(hidden_layer_sizes =(50,5,), random_state=1)
 stack_MLP = StackingClassifier(models, final_estimator=MLP)
 log = LogisticRegression()
stack_log = StackingClassifier(models, final_estimator=log)
 QDA = QuadraticDiscriminantAnalysis()
stack_QDA = StackingClassifier(models, final_estimator=QDA)
 small_MLP = MLPClassifier(hidden_layer_sizes =(5,), random_state=10)
 stack_final = StackingClassifier([('MLP',stack_MLP),('log', stack_log),('QDA', stack_QDA)], final_estimator=small_MLP)
 stack_final.fit(X_train,y_train)
 print('Score of the StackingClassifer:', accuracy_score(stack_final.predict(X_val), y_val))<choose_model_class>
history3 = model3.fit(
 get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS,
callbacks=[lr_callback],
validation_data=None if SKIP_VALIDATION else get_validation_dataset()
)
list_base_model = {
'Tree' : BaggingClassifier(DecisionTreeClassifier(max_depth=10), n_estimators=100, max_samples=0.5, random_state=10),
'SVC' : BaggingClassifier(SVC(C=0.2), n_estimators=20, max_samples=0.5, random_state=10),
'KNN' : BaggingClassifier(KNeighborsClassifier(n_neighbors=8, weights='distance'), n_estimators=50, max_samples=0.3, random_state=10),
'gauss' : BaggingClassifier(GaussianNB() , n_estimators=100, max_samples=0.5, random_state=10),
'bern' : BaggingClassifier(BernoulliNB(alpha=0.01, binarize=0.5), n_estimators=200, max_samples=0.4, random_state=10)
 }
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, y_train), axis=1)
 list_models_bag['score'] = list_models_bag.apply(lambda x: x['model'].predict(X_val), axis=1, result_type='reduce' ).apply(lambda x: accuracy_score(x, y_val))
print('Score for Bagging model on samples:')
 print(list_models_bag['score'] )<compute_test_metric>
if not SKIP_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()
m = model.predict(images_ds)
 m2 = model2.predict(images_ds)
 m3 = model3.predict(images_ds)
 scores = []
best_score,best_alpha,best_beta=0,0,0
for alpha in np.linspace(0,1,100):
for beta in np.linspace(0,1,100):
cm_probabilities = alpha*m+(beta)*m2+(1-alpha-beta)*m3
cm_predictions = np.argmax(cm_probabilities, axis=-1)
 score = f1_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
 if(score > best_score):
best_alpha = alpha
best_beta = beta
best_score = score
scores.append(best_score)
 plt.plot(scores)
 print("best_alha:",best_alpha,"best_beta:",best_beta)
 cm_probabilities = best_alpha*m+best_beta*m2+(1-best_alpha)*m3
cm_predictions = np.argmax(cm_probabilities, axis=-1)
 else:
best_alpha = 0.37
best_beta = 0.26
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))<choose_model_class>
print(best_alpha,best_beta )
list_base_model = {
'Tree' : BaggingClassifier(DecisionTreeClassifier(max_depth=10), n_estimators=10, max_features=0.7, random_state=10),
'SVC' : BaggingClassifier(SVC(C=0.2), n_estimators=50, max_features=0.3, random_state=10),
'KNN' : BaggingClassifier(KNeighborsClassifier(n_neighbors=8, weights='distance'), n_estimators=10, max_features=0.7, random_state=10),
'gauss' : BaggingClassifier(GaussianNB() , n_estimators=10, max_features=0.7, random_state=10),
'bern' : BaggingClassifier(BernoulliNB(alpha=0.01, binarize=0.5), n_estimators=10, max_features=0.7, random_state=10)
 }
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, y_train), axis=1)
 list_models_bag['score'] = list_models_bag.apply(lambda x: x['model'].predict(X_val), axis=1, result_type='reduce' ).apply(lambda x: accuracy_score(x, y_val))
print('Score for Bagging model on features:')
 print(list_models_bag['score'] )<compute_test_metric>
if not SKIP_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))
<choose_model_class><EOS> 
test_ds = get_test_dataset(ordered=True)
 print('Computing predictions...')
 test_images_ds = test_ds.map(lambda image, idnum: image)
 probabilities = 0.85*(0.44*model.predict(test_images_ds)+0.56*model3.predict(test_images_ds)) +(0.15)*model2.predict(test_images_ds)
 predictions = np.argmax(probabilities, axis=-1)
 print(predictions)
 print('Generating submission.csv file...')
 test_ids_ds = test_ds.map(lambda image, idnum: idnum ).unbatch()
test_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES)) ).numpy().astype('U')
 np.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')
 np.savez_compressed('probs.npz', a=probabilities )