Kaggle competition: Flower Classification with TPUs
<SOS> metric: MacroFScore Kaggle data source: flower-classification-with-tpus<count_missing_values>
!pip install -q efficientnet
print(test[test['Fare'].isnull() ] )<count_missing_values>
!pip install tensorflow_addons
print(test[test['Fare'].isnull() ] )<feature_engineering>
print("Tensorflow version " + tf.__version__)
test['Fare'].iloc[152] = combine['Fare'][combine['Pclass'] == 3].dropna().median()
print(test['Fare'].iloc[152] )<feature_engineering>
import tensorflow_addons as tfa
combine = pd.concat([train.drop('Survived',1),test])
 survived = train['Survived']
combine['Child'] = combine['Age']<=10
combine['Cabin_known'] = combine['Cabin'].isnull() == False
combine['Age_known'] = combine['Age'].isnull() == False
combine['Family'] = combine['SibSp'] + combine['Parch']
combine['Alone'] =(combine['SibSp'] + combine['Parch'])== 0
combine['Large_Family'] =(combine['SibSp']>2)|(combine['Parch']>3)
 combine['Deck'] = combine['Cabin'].str[0]
combine['Deck'] = combine['Deck'].fillna(value='U')
 combine['Ttype'] = combine['Ticket'].str[0]
combine['Title'] = combine['Name'].str.split(", ", expand=True)[1].str.split(".", expand=True)[0]
combine['Fare_cat'] = pd.DataFrame(np.floor(np.log10(combine['Fare'] + 1)) ).astype('int')
 combine['Bad_ticket'] = combine['Ttype'].isin(['3','4','5','6','7','8','A','L','W'])
 combine['Young'] =(combine['Age']<=30)|(combine['Title'].isin(['Master','Miss','Mlle']))
combine['Shared_ticket'] = np.where(combine.groupby('Ticket')['Name'].transform('count')> 1, 1, 0)
 combine['Ticket_group'] = combine.groupby('Ticket')['Name'].transform('count')
 combine['Fare_eff'] = combine['Fare']/combine['Ticket_group']
combine['Fare_eff_cat'] = np.where(combine['Fare_eff']>16.0, 2, 1)
 combine['Fare_eff_cat'] = np.where(combine['Fare_eff']<8.5,0,combine['Fare_eff_cat'])
 test = combine.iloc[len(train):]
train = combine.iloc[:len(train)]
train['Survived'] = survived
surv = train[train['Survived']==1]
nosurv = train[train['Survived']==0]<count_unique_values>
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('flower-classification-with-tpus')
 img_size=512
IMAGE_SIZE = [img_size, img_size]
EPOCHS = 20
BATCH_SIZE = 16 * strategy.num_replicas_in_sync
print(combine['Age'].groupby(combine['Title'] ).count())
 print(combine['Age'].groupby(combine['Title'] ).mean())
 print("There are %i unique titles in total."%(len(combine['Title'].unique())) )<data_type_conversions>
EPOCHS_ = 20
LR_START = 0.0001
LR_MAX = 0.00005 * strategy.num_replicas_in_sync
LR_MIN = 0.000005
LR_RAMPUP_EPOCHS = 3
LR_SUSTAIN_EPOCHS = 3
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)
 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]))
pd.DataFrame(np.floor(np.log10(train['Fare'] + 1)) ).astype('int' ).head(5 )<groupby>
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
TRAINING_FILENAMES = TRAINING_FILENAMES + VALIDATION_FILENAMES
combine.iloc[np.where(combine.groupby('Ticket')['Fare'].transform('std')> 0)]<filter>
SKIP_VALIDATION = True
GCS_DS_PATH1 = KaggleDatasets().get_gcs_path('mytraindataset')
 TRAINING_FILENAMES_ = tf.io.gfile.glob(GCS_DS_PATH1 + '/*.tfrec')
 TRAINING_FILENAMES = TRAINING_FILENAMES + TRAINING_FILENAMES_
combine[(combine['Pclass']==1)&(combine['Fare_eff']>0)&(combine['Fare_eff']<10)]<filter>
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']
combine[(combine['Pclass']==3)&(np.log10(combine['Fare_eff'])>1.2)]<data_type_conversions>
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.one_hot(example['class'], 104)
 return image, label
def read_labeled_tfrecord_train(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.one_hot(example['class'], 104)
 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 load_dataset_train(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_train if labeled else read_unlabeled_tfrecord, num_parallel_calls=AUTO)
 return dataset
def get_training_dataset(do_aug=False):
dataset = load_dataset_train(TRAINING_FILENAMES, labeled=True)
 dataset = dataset.map(data_augment, num_parallel_calls=AUTO)
 if do_aug: dataset = dataset.map(transform, num_parallel_calls=AUTO)
 dataset = dataset.repeat()
dataset = dataset.shuffle(2048)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.prefetch(AUTO)
 return dataset
def data_augment(image, label):
image = tf.image.random_flip_left_right(image)
 return image, label
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))
combine = pd.concat([train.drop('Survived',1),test])
 survived = train['Survived']
combine["Sex"] = combine["Sex"].astype("category")
 combine["Sex"].cat.categories = [0,1]
combine["Sex"] = combine["Sex"].astype("int")
 combine["Embarked"] = combine["Embarked"].astype("category")
 combine["Embarked"].cat.categories = [0,1,2]
combine["Embarked"] = combine["Embarked"].astype("int")
 combine["Deck"] = combine["Deck"].astype("category")
 combine["Deck"].cat.categories = [0,1,2,3,4,5,6,7,8]
combine["Deck"] = combine["Deck"].astype("int")
 test = combine.iloc[len(train):]
train = combine.iloc[:len(train)]
train['Survived'] = survived
train.loc[:,["Sex","Embarked"]].head()<split>
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))
training, testing = train_test_split(train, test_size=0.2, random_state=0)
 print("Total sample size = %i; training sample size = %i, testing sample size = %i"\
%(train.shape[0],training.shape[0],testing.shape[0]))<prepare_x_and_y>
def transform(image,label):
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]),label
cols = ['Sex','Pclass','Cabin_known','Large_Family','Parch',
'SibSp','Young','Alone','Shared_ticket','Child']
tcols = np.append(['Survived'],cols)
 df = training.loc[:,tcols].dropna()
X = df.loc[:,cols]
y = np.ravel(df.loc[:,['Survived']] )<train_on_grid>
test_ds = get_test_dataset(ordered=True)
 test_images_ds = test_ds.map(lambda image, idnum: image )
clf_log = LogisticRegression()
clf_log = clf_log.fit(X,y)
 score_log = clf_log.score(X,y)
 print(score_log )<create_dataframe>
training_dataset = get_training_dataset()
training_dataset = training_dataset.unbatch().batch(20)
 train_batch = iter(training_dataset )
pd.DataFrame(list(zip(X.columns, np.transpose(clf_log.coef_))))<prepare_x_and_y>
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("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'))
cols = ['Sex','Pclass','Cabin_known','Large_Family','Shared_ticket','Young','Alone','Child']
tcols = np.append(['Survived'],cols)
 df = training.loc[:,tcols].dropna()
X = df.loc[:,cols]
y = np.ravel(df.loc[:,['Survived']])
 df_test = testing.loc[:,tcols].dropna()
X_test = df_test.loc[:,cols]
y_test = np.ravel(df_test.loc[:,['Survived']] )<compute_train_metric>
def binary_focal_loss(gamma=2., alpha=.25):

 def binary_focal_loss_fixed(y_true, y_pred):

 pt_1 = tf.where(tf.equal(y_true, 1), y_pred, tf.ones_like(y_pred))
pt_0 = tf.where(tf.equal(y_true, 0), y_pred, tf.zeros_like(y_pred))
epsilon = K.epsilon()
pt_1 = K.clip(pt_1, epsilon, 1.- epsilon)
 pt_0 = K.clip(pt_0, epsilon, 1.- epsilon)
 return -K.sum(alpha * K.pow(1.- pt_1, gamma)* K.log(pt_1)) \
-K.sum(( 1 - alpha)* K.pow(pt_0, gamma)* K.log(1.- pt_0))
return binary_focal_loss_fixed
def categorical_focal_loss(gamma=2., alpha=.25):

 def categorical_focal_loss_fixed(y_true, y_pred):

 y_pred /= K.sum(y_pred, axis=-1, keepdims=True)
 epsilon = K.epsilon()
y_pred = K.clip(y_pred, epsilon, 1.- epsilon)
 cross_entropy = -y_true * K.log(y_pred)
 loss = alpha * K.pow(1 - y_pred, gamma)* cross_entropy
return K.sum(loss, axis=1)
 return categorical_focal_loss_fixed
clf_log = LogisticRegression()
clf_log = clf_log.fit(X,y)
 score_log = cross_val_score(clf_log, X, y, cv=5 ).mean()
print(score_log )<train_on_grid>
LR_START = 0.00001
LR_MAX = 0.00005 * strategy.num_replicas_in_sync
LR_MIN = 0.00001
LR_RAMPUP_EPOCHS = 4
LR_SUSTAIN_EPOCHS = 4
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)
clf_pctr = Perceptron(
 class_weight='balanced' 
)
 clf_pctr = clf_pctr.fit(X,y)
 score_pctr = cross_val_score(clf_pctr, X, y, cv=5 ).mean()
print(score_pctr )<find_best_model_class>
with strategy.scope() :
desnet=tf.keras.applications.Xception(
 weights='imagenet',
include_top=False 
)
 model1 = tf.keras.Sequential([
desnet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model1.compile(
 optimizer=tf.keras.optimizers.Adam(lr=0.0001),
loss = 'categorical_crossentropy',
metrics=[tfa.metrics.F1Score(num_classes=104, average="macro")] 
)
 model1.summary()
model1.load_weights('.. /input/mytopmodel/Xception_best.h5' )
clf_knn = KNeighborsClassifier(
 n_neighbors=10,
weights='distance' 
)
 clf_knn = clf_knn.fit(X,y)
 score_knn = cross_val_score(clf_knn, X, y, cv=5 ).mean()
print(score_knn )<train_on_grid>
with strategy.scope() :
desnet=tf.keras.applications.DenseNet201(
 weights='imagenet',
include_top=False 
)
 model2 = tf.keras.Sequential([
desnet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model2.compile(
 optimizer=tf.keras.optimizers.Adam(lr=0.0001),
loss = 'categorical_crossentropy',
metrics=[tfa.metrics.F1Score(num_classes=104, average="macro")] 
)
 model2.summary()
model2.load_weights('.. /input/mytopmodel/dense_best.h5' )
clf_svm = svm.SVC(
 class_weight='balanced' 
)
 clf_svm.fit(X, y)
 score_svm = cross_val_score(clf_svm, X, y, cv=5 ).mean()
print(score_svm )<compute_train_metric>
with strategy.scope() :
desnet=tf.keras.applications.InceptionResNetV2(
 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 = 'categorical_crossentropy',
metrics=[tfa.metrics.F1Score(num_classes=104, average="macro")] 
)
 model3.summary()
model3.load_weights('.. /input/mytopmodel/InceptionResV2_best.h5' )
clf_bay = GaussianNB()
clf_bay.fit(X,y)
 score_bay = cross_val_score(clf_bay, X, y, cv=5 ).mean()
print(score_bay )<train_model>
with strategy.scope() :
desnet=tf.keras.applications.VGG19(
 weights='imagenet',
include_top=False 
)
 model4 = tf.keras.Sequential([
desnet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model4.compile(
 optimizer=tf.keras.optimizers.Adam(lr=0.0001),
loss = 'categorical_crossentropy',
metrics=[tfa.metrics.F1Score(num_classes=104, average="macro")] 
)
 model4.summary()
model4.load_weights('.. /input/mytopmodel/VGG_best.h5' )
bagging = BaggingClassifier(
 KNeighborsClassifier(
 n_neighbors=2,
weights='distance' 
),
oob_score=True,
max_samples=0.5,
max_features=1.0 
)
 clf_bag = bagging.fit(X,y)
 score_bag = clf_bag.oob_score_
print(score_bag )<train_on_grid>
with strategy.scope() :
desnet=efn.EfficientNetB5(
 weights='noisy-student',
include_top=False 
)
 model5 = tf.keras.Sequential([
desnet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model5.compile(
 optimizer=tf.keras.optimizers.Adam(lr=0.0001),
loss = 'categorical_crossentropy',
metrics=[tfa.metrics.F1Score(num_classes=104, average="macro")] 
)
 model5.summary()
model5.load_weights('.. /input/mytopmodel/B5_best.h5' )
clf_tree = tree.DecisionTreeClassifier(
 class_weight="balanced",\
min_weight_fraction_leaf=0.01\ 
)
 clf_tree = clf_tree.fit(X,y)
 score_tree = cross_val_score(clf_tree, X, y, cv=5 ).mean()
print(score_tree )<compute_train_metric>
with strategy.scope() :
desnet=tf.keras.applications.ResNet152V2(
 weights='imagenet',
include_top=False 
)
 model6 = tf.keras.Sequential([
desnet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model6.compile(
 optimizer=tf.keras.optimizers.Adam(lr=0.0001),
loss = 'categorical_crossentropy',
metrics=[tfa.metrics.F1Score(num_classes=104, average="macro")] 
)
 model6.summary()
model6.load_weights('.. /input/mytopmodel/Res152_best.h5' )
clf_rf = RandomForestClassifier(
 n_estimators=1000, \
max_depth=None, \
min_samples_split=10 \ 
)
 clf_rf = clf_rf.fit(X,y)
 score_rf = cross_val_score(clf_rf, X, y, cv=5 ).mean()
print(score_rf )<train_on_grid>
models = [model1, model2, model3, model4, model5, model6]
clf_ext = ExtraTreesClassifier(
 max_features='auto',
bootstrap=True,
oob_score=True,
n_estimators=1000,
max_depth=None,
min_samples_split=10 
)
 clf_ext = clf_ext.fit(X,y)
 score_ext = cross_val_score(clf_ext, X, y, cv=5 ).mean()
print(score_ext )<train_on_grid>
test_ds = get_test_dataset(ordered=True)
 test_images_ds = test_ds.map(lambda image, idnum: image)
 print('Computing predictions...')
 probabilities = np.average([models[i].predict(test_images_ds)for i in range(6)], axis = 0)
 predictions = np.argmax(probabilities, axis=-1)
 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='')
 return histories, models
warnings.filterwarnings("ignore")
 clf_gb = GradientBoostingClassifier(
 n_estimators=1000,
learning_rate=0.1,
max_depth=3,
subsample=0.5,
random_state=0 ).fit(X, y)
 clf_gb.fit(X,y)
 score_gb = cross_val_score(clf_gb, X, y, cv=5 ).mean()
print(score_gb )<train_on_grid>
clf_ada = AdaBoostClassifier(n_estimators=400, learning_rate=0.1)
 clf_ada.fit(X,y)
 score_ada = cross_val_score(clf_ada, X, y, cv=5 ).mean()
print(score_ada )<train_on_grid>
clf_xgb = xgb.XGBClassifier(
 max_depth=2,
n_estimators=500,
subsample=0.5,
learning_rate=0.1 
)
 clf_xgb.fit(X,y)
 score_xgb = cross_val_score(clf_xgb, X, y, cv=5 ).mean()
print(score_xgb )<train_on_grid>
clf_lgb = lgb.LGBMClassifier(
 max_depth=2,
n_estimators=500,
subsample=0.5,
learning_rate=0.1 
)
 clf_lgb.fit(X,y)
 score_lgb = cross_val_score(clf_lgb, X, y, cv=5 ).mean()
print(score_lgb )<train_on_grid>
<train_model><EOS>