Kaggle competition: Flower Classification with TPUs
<SOS> metric: MacroFScore Kaggle data source: flower-classification-with-tpus<define_variables>
import os
women = train_data.loc[train_data.Sex == 'female']["Survived"]
rate_women = sum(women)/len(women)
 print("% of women who survived:", rate_women )<define_variables>
!pip install -U --pre efficientnet
men = train_data.loc[train_data.Sex == 'male']["Survived"]
rate_men = sum(men)/len(men)
 print("% of men who survived:", rate_men )<data_type_conversions>
print("Tensorflow version " + tf.__version__)
data = [train_data, test_data]
for dataset in data:
mean = train_data["Age"].mean()
std = test_data["Age"].std()
is_null = dataset["Age"].isnull().sum()
rand_age = np.random.randint(mean - std, mean + std, size = is_null)
 age_slice = dataset["Age"].copy()
age_slice[np.isnan(age_slice)] = rand_age
dataset["Age"] = age_slice
dataset["Age"] = train_data["Age"].astype(int )<load_from_csv>
AUTO = tf.data.experimental.AUTOTUNE
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)
 GCS_DS_PATH = 'gs://kds-a44744780cb28b908f65e7fa3b4a473ef199bb9ffe8048dbbf29ffeb'
IMAGE_SIZE = [512, 512]
EPOCHS1=25
EPOCHS2=25
BATCH_SIZE = 1 * 16 * strategy.num_replicas_in_sync
df = pd.read_csv('.. /input/titanic/train.csv')
 fig = px.scatter_3d(df, x='Name', y='Sex', z='Age',
color='Age')
 fig.show()<load_from_csv>
LR_START = 0.0001
LR_MAX = 0.00005 * strategy.num_replicas_in_sync
LR_MIN = 0.00001
LR_RAMPUP_EPOCHS = 5
LR_SUSTAIN_EPOCHS = 5
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 )
df = pd.read_csv('.. /input/test-file/tested.csv')
 for template in ["plotly"]:
fig = px.scatter(df,
x="PassengerId", y="Age", color="Survived",
log_x=True, size_max=20,
template=template, title="Which Age Survived?")
 fig.show()<categorify>
def count_data_items(filenames):
n = [int(re.compile(r"-([0-9]*)\." ).search(filename ).group(1)) for filename in filenames]
return np.sum(n )
embarked_mode = train_data['Embarked'].mode()
data = [train_data, test_data]
for dataset in data:
dataset['Embarked'] = dataset['Embarked'].fillna(embarked_mode )<load_from_csv>
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 = False
if SKIP_VALIDATION:
TRAINING_FILENAMES = TRAINING_FILENAMES + VALIDATION_FILENAMES
df = pd.read_csv(".. /input/titanic/train.csv")
 fig = px.histogram(df, x="SibSp", y="Parch", color="Sex", marginal="rug",
hover_data=df.columns)
 fig.show()<define_search_space>
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']
param_test1 = {
'n_estimators': [100,200,500,750,1000],
'max_depth': [3,5,7,9],
'min_child_weight': [1,3,5],
'gamma':[i/10.0 for i in range(0,5)],
'subsample':[i/10.0 for i in range(6,10)],
'colsample_bytree':[i/10.0 for i in range(6,10)],
'reg_alpha':[0, 0.001, 0.005, 0.01, 0.05, 0.1, 1],
'learning_rate': [0.01, 0.02, 0.05, 0.1]
}<load_from_csv>
img_size=512
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 )
url="https://github.com/thisisjasonjafari/my-datascientise-handcode/raw/master/005-datavisualization/titanic.csv"
s=requests.get(url ).content
c=pd.read_csv(io.StringIO(s.decode('utf-8')))
 test_labels = c
test = pd.read_csv('.. /input/titanic/test.csv')
 warnings.filterwarnings('ignore')
 for i, name in enumerate(test_labels['name']):
if '"' in name:
test_labels['name'][i] = re.sub('"', '', name)
 for i, name in enumerate(test['Name']):
if '"' in name:
test['Name'][i] = re.sub('"', '', name)
 survived = []
for name in test['Name']:
survived.append(int(test_labels.loc[test_labels['name'] == name]['survived'].values[-1]))
submission = pd.read_csv('.. /input/titanic/gender_submission.csv')
 submission['Survived'] = survived
submission.to_csv('submission_titanic.csv', index=False )<categorify>
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.repeat()
dataset = dataset.shuffle(2345)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.prefetch(AUTO)
 return dataset
def get_training_dataset1() :
dataset = load_dataset(TRAINING_FILENAMES_1, labeled=True)
 dataset = dataset.map(data_augment, num_parallel_calls=AUTO)
 dataset = dataset.repeat()
dataset = dataset.shuffle(2345)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.prefetch(AUTO)
 return dataset
def get_training_dataset2() :
dataset = load_dataset(TRAINING_FILENAMES_2, labeled=True)
 dataset = dataset.map(data_augment, num_parallel_calls=AUTO)
 dataset = dataset.repeat()
dataset = dataset.shuffle(2345)
 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_validation_dataset1(ordered=False):
dataset = load_dataset(VALIDATION_FILENAMES_1, labeled=True, ordered=ordered)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.cache()
dataset = dataset.prefetch(AUTO)
 return dataset
def get_validation_dataset2(ordered=False):
dataset = load_dataset(VALIDATION_FILENAMES_2, 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 data_augment2(image, label):
image = tf.image.flip_left_right(image)
 return image, label
def get_test_dataset2(ordered=False):
dataset = load_dataset(TEST_FILENAMES, labeled=False, ordered=ordered)
 dataset = dataset.map(data_augment2, num_parallel_calls=AUTO)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.prefetch(AUTO)
 return dataset
def get_validation_dataset1a(ordered=False):
dataset = load_dataset(VALIDATION_FILENAMES_1, labeled=True, ordered=ordered)
 dataset = dataset.map(data_augment2, num_parallel_calls=AUTO)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.cache()
dataset = dataset.prefetch(AUTO)
 return dataset
def get_validation_dataset2a(ordered=False):
dataset = load_dataset(VALIDATION_FILENAMES_2, labeled=True, ordered=ordered)
 dataset = dataset.map(data_augment2, num_parallel_calls=AUTO)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.cache()
dataset = dataset.prefetch(AUTO)
 return dataset
y = train_data["Survived"]
features = ["Pclass", "Sex", "SibSp", "Parch"]
X = pd.get_dummies(train_data[features])
 X_test = pd.get_dummies(test_data[features])
 model = RandomForestClassifier(n_estimators=100, max_depth=3, random_state=2)
 model.fit(X, y)
 predictions = model.predict(X_test)
<set_options>
with strategy.scope() :
enet = efn.EfficientNetB7(
 input_shape=(512, 512, 3),
weights=None,
include_top=False 
)
 model1 = tf.keras.Sequential([
enet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model1.compile(
 optimizer=tf.keras.optimizers.Adam(lr=0.0001),
loss = 'sparse_categorical_crossentropy',
metrics=[] 
)
 model1.load_weights('/kaggle/input/flower-class-tpu-efficientnet-training-v2/EfficientNetB7_validation2_35.h5')
warnings.filterwarnings("ignore")
 pd.set_option('max_columns',100)
 pd.set_option('max_rows',100 )<load_from_csv>
with strategy.scope() :
enet = efn.EfficientNetB7(
 input_shape=(512, 512, 3),
weights=None,
include_top=False 
)
 model1b = tf.keras.Sequential([
enet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model1b.compile(
 optimizer=tf.keras.optimizers.Adam(lr=0.0001),
loss = 'sparse_categorical_crossentropy',
metrics=[] 
)
 model1b.load_weights('/kaggle/input/flower-class-tpu-efficientnet-training-v3/EfficientNetB7_validation2_40.h5' )
train = pd.read_csv('.. /input/house-prices-advanced-regression-techniques/train.csv')
 train = reduce_mem_usage(train )<load_from_csv>
with strategy.scope() :
enet = efn.EfficientNetB7(
 input_shape=(512, 512, 3),
weights=None,
include_top=False 
)
 model11 = tf.keras.Sequential([
enet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model11.compile(
 optimizer=tf.keras.optimizers.Adam(lr=0.0001),
loss = 'sparse_categorical_crossentropy',
metrics=[] 
)
 model11.load_weights('/kaggle/input/flower-class-tpu-efficientnet-training-v2/EfficientNetB7_validation1_35.h5' )
test = pd.read_csv('.. /input/house-prices-advanced-regression-techniques/test.csv')
 test = reduce_mem_usage(test )<load_from_csv>
with strategy.scope() :
enet = efn.EfficientNetB7(
 input_shape=(512, 512, 3),
weights=None,
include_top=False 
)
 model11b = tf.keras.Sequential([
enet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model11b.compile(
 optimizer=tf.keras.optimizers.Adam(lr=0.0001),
loss = 'sparse_categorical_crossentropy',
metrics=[] 
)
 model11b.load_weights('/kaggle/input/flower-class-tpu-efficientnet-training-v3/EfficientNetB7_validation1_40.h5' )
sub = pd.read_csv('.. /input/house-prices-advanced-regression-techniques/sample_submission.csv')
 sub.head(3 )<categorify>
with strategy.scope() :
rnet = DenseNet201(
 input_shape=(512, 512, 3),
weights=None,
include_top=False 
)
 model2 = tf.keras.Sequential([
rnet,
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=[] 
)
 model2.load_weights('/kaggle/input/flower-class-tpu-densenet-training-v2/DenseNet201_validation2_35.h5')
numerics = ['int8', 'int16', 'int32', 'int64', 'float16', 'float32', 'float64']
categorical_columns = []
features = train.columns.values.tolist()
for col in features:
if train[col].dtype in numerics: continue
categorical_columns.append(col)
 for col in categorical_columns:
if col in train.columns:
le = LabelEncoder()
le.fit(list(train[col].astype(str ).values)+ list(test[col].astype(str ).values))
train[col] = le.transform(list(train[col].astype(str ).values))
test[col] = le.transform(list(test[col].astype(str ).values))<prepare_x_and_y>
with strategy.scope() :
rnet = DenseNet201(
 input_shape=(512, 512, 3),
weights=None,
include_top=False 
)
 model2b = tf.keras.Sequential([
rnet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model2b.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=[] 
)
 model2b.load_weights('/kaggle/input/flower-class-tpu-densenet-training-v3/DenseNet201_validation2_50.h5' )
target = train['SalePrice']
del train['SalePrice']<drop_column>
with strategy.scope() :
rnet = DenseNet201(
 input_shape=(512, 512, 3),
weights=None,
include_top=False 
)
 model22 = tf.keras.Sequential([
rnet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model22.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=[] 
)
 model22.load_weights('/kaggle/input/flower-class-tpu-densenet-training-v2/DenseNet201_validation1_35.h5' )
train = reduce_mem_usage(train )<categorify>
with strategy.scope() :
rnet = DenseNet201(
 input_shape=(512, 512, 3),
weights=None,
include_top=False 
)
 model22b = tf.keras.Sequential([
rnet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model22b.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=[] 
)
 model22b.load_weights('/kaggle/input/flower-class-tpu-densenet-training-v3/DenseNet201_validation1_50.h5' )
train = train.fillna(-1)
 test = test.fillna(-1 )<prepare_x_and_y>
from scipy.special import logit, expit
import pandas as pd
X = train
z = target<split>
SKIP_VALIDATION = False
if not SKIP_VALIDATION:
cmdataset1 = get_validation_dataset1(ordered=True)
 cmdataset2 = get_validation_dataset2(ordered=True)
 images_ds1 = cmdataset1.map(lambda image, label: image)
 images_ds2 = cmdataset2.map(lambda image, label: image)
 labels_ds1 = cmdataset1.map(lambda image, label: label ).unbatch()
labels_ds2 = cmdataset2.map(lambda image, label: label ).unbatch()
cm_correct_labels1 = next(iter(labels_ds1.batch(NUM_VALIDATION_IMAGES)) ).numpy()
cm_correct_labels2 = next(iter(labels_ds2.batch(NUM_VALIDATION_IMAGES)) ).numpy()
cm_correct_labels = np.concatenate(( cm_correct_labels1,cm_correct_labels2),axis=0)
 valid_1 = model11.predict(images_ds1)
 valid_2 = model1.predict(images_ds2)
 m = np.concatenate(( valid_1,valid_2),axis=0)
 valid_1 = model22.predict(images_ds1)
 valid_2 = model2.predict(images_ds2)
 m2 = np.concatenate(( valid_1,valid_2),axis=0)
 for i in range(104):
m[:,i] = np.nan_to_num(logit(m[:,i]))
m2[:,i] = np.nan_to_num(logit(m2[:,i]))
valid_1 = model11b.predict(images_ds1)
 valid_2 = model1b.predict(images_ds2)
 mb = np.concatenate(( valid_1,valid_2),axis=0)
 valid_1 = model22b.predict(images_ds1)
 valid_2 = model2b.predict(images_ds2)
 m2b = np.concatenate(( valid_1,valid_2),axis=0)
 for i in range(104):
mb[:,i] = np.nan_to_num(logit(mb[:,i]))
m2b[:,i] = np.nan_to_num(logit(m2b[:,i]))
m = 0.5*m+0.5*mb
m2 = 0.5*m2+0.5*m2b
del mb,m2b
alpha_best = 0
score_best = 0
for alpha in np.linspace(0,1,101):
alpha = np.round(alpha,2)
 cm_probabilities = alpha*m+(1-alpha)*m2
if alpha == 0:
probabilities = cm_probabilities
cm_predictions = np.argmax(cm_probabilities, axis=-1)
 auxi = f1_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
 print('alpha:',alpha,'--- f1_score:',auxi)
 if auxi > score_best:
score_best = auxi
alpha_best = alpha
probabilities = cm_probabilities
best_score1 = score_best
best_alpha1 = alpha_best
cm_probabilities1 = probabilities
else:
best_alpha1 = 0.50
Xtrain, Xval, Ztrain, Zval = train_test_split(X, z, test_size=0.2, random_state=0)
 train_set = lgbm.Dataset(Xtrain, Ztrain, silent=False)
 valid_set = lgbm.Dataset(Xval, Zval, silent=False )<init_hyperparams>
if not SKIP_VALIDATION:
cmdataset1 = get_validation_dataset1a(ordered=True)
 cmdataset2 = get_validation_dataset2a(ordered=True)
 images_ds1 = cmdataset1.map(lambda image, label: image)
 images_ds2 = cmdataset2.map(lambda image, label: image)
 labels_ds1 = cmdataset1.map(lambda image, label: label ).unbatch()
labels_ds2 = cmdataset2.map(lambda image, label: label ).unbatch()
cm_correct_labels1 = next(iter(labels_ds1.batch(NUM_VALIDATION_IMAGES)) ).numpy()
cm_correct_labels2 = next(iter(labels_ds2.batch(NUM_VALIDATION_IMAGES)) ).numpy()
cm_correct_labels = np.concatenate(( cm_correct_labels1,cm_correct_labels2),axis=0)
 valid_1 = model11.predict(images_ds1)
 valid_2 = model1.predict(images_ds2)
 mm = np.concatenate(( valid_1,valid_2),axis=0)
 valid_1 = model22.predict(images_ds1)
 valid_2 = model2.predict(images_ds2)
 mm2 = np.concatenate(( valid_1,valid_2),axis=0)
 for i in range(104):
mm[:,i] = np.nan_to_num(logit(mm[:,i]))
mm2[:,i] = np.nan_to_num(logit(mm2[:,i]))
valid_1 = model11b.predict(images_ds1)
 valid_2 = model1b.predict(images_ds2)
 mmb = np.concatenate(( valid_1,valid_2),axis=0)
 valid_1 = model22b.predict(images_ds1)
 valid_2 = model2b.predict(images_ds2)
 mm2b = np.concatenate(( valid_1,valid_2),axis=0)
 for i in range(104):
mmb[:,i] = np.nan_to_num(logit(mmb[:,i]))
mm2b[:,i] = np.nan_to_num(logit(mm2b[:,i]))
mm = 0.5*mm+0.5*mmb
mm2 = 0.5*mm2+0.5*mm2b
del mmb,mm2b
alpha_best = 0
score_best = 0
for alpha in np.linspace(0,1,101):
alpha = np.round(alpha,2)
 cm_probabilities = alpha*mm+(1-alpha)*mm2
if alpha == 0:
probabilities = cm_probabilities
cm_predictions = np.argmax(cm_probabilities, axis=-1)
 auxi = f1_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
 print('alpha:',alpha,'--- f1_score:',auxi)
 if auxi > score_best:
score_best = auxi
alpha_best = alpha
probabilities = cm_probabilities
best_score2 = score_best
best_alpha2 = alpha_best
cm_probabilities2 = probabilities
else:
best_alpha2 = 0.50
params = {
'boosting_type':'gbdt',
'objective': 'regression',
'num_leaves': 45,
'learning_rate': 0.01,
'max_depth': -1,
'subsample': 0.8,
'bagging_fraction' : 1,
'max_bin' : 5000 ,
'bagging_freq': 20,
'colsample_bytree': 0.6,
'metric': 'rmse',
'min_split_gain': 0.5,
'min_child_weight': 1,
'min_child_samples': 10,
'scale_pos_weight':1,
'zero_as_missing': True,
'seed':0,
}
modelL = lgbm.train(params, train_set = train_set, num_boost_round=5000,
early_stopping_rounds=50,verbose_eval=50, valid_sets=valid_set )<predict_on_test>
if not SKIP_VALIDATION:
alpha_best = 0
score_best = 0
for alpha in np.linspace(0,1,101):
alpha = np.round(alpha,2)
 cm_probabilities = alpha*cm_probabilities1+(1-alpha)*cm_probabilities2
if alpha == 0:
probabilities = cm_probabilities
cm_predictions = np.argmax(cm_probabilities, axis=-1)
 auxi = f1_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
 print('alpha:',alpha,'--- f1_score:',auxi)
 if auxi > score_best:
score_best = auxi
alpha_best = alpha
probabilities = cm_probabilities
best_score3 = score_best
best_alpha3 = alpha_best
cm_probabilities3 = probabilities
else:
best_alpha3 = 0.5
pred_lgb = modelL.predict(test )<create_dataframe>
test_ds = get_test_dataset(ordered=True)
 test_ds2 = get_test_dataset2(ordered=True)
 print('Computing predictions...')
 test_images_ds = test_ds.map(lambda image, idnum: image)
 test_images_ds2 = test_ds2.map(lambda image, idnum: image)
 m1 = model1.predict(test_images_ds)
 m11 = model11.predict(test_images_ds)
 m1b = model1b.predict(test_images_ds)
 m11b = model11b.predict(test_images_ds)
 m2 = model2.predict(test_images_ds)
 m22 = model22.predict(test_images_ds)
 m2b = model2b.predict(test_images_ds)
 m22b = model22b.predict(test_images_ds)
 for i in range(104):
m1[:,i] = np.nan_to_num(logit(m1[:,i]))
m11[:,i] = np.nan_to_num(logit(m11[:,i]))
m1b[:,i] = np.nan_to_num(logit(m1b[:,i]))
m11b[:,i] = np.nan_to_num(logit(m11b[:,i]))
m2[:,i] = np.nan_to_num(logit(m2[:,i]))
m22[:,i] = np.nan_to_num(logit(m22[:,i]))
m2b[:,i] = np.nan_to_num(logit(m2b[:,i]))
m22b[:,i] = np.nan_to_num(logit(m22b[:,i]))
m1 = 0.25*m1+0.25*m11+0.25*m1b+0.25*m11b
m2 = 0.25*m2+0.25*m22+0.25*m2b+0.25*m22b
del m11,m22,m1b,m2b,m11b,m22b
cm_probabilities1 = best_alpha1*m1+(1-best_alpha1)*m2
m1 = model1.predict(test_images_ds2)
 m11 = model11.predict(test_images_ds2)
 m1b = model1b.predict(test_images_ds2)
 m11b = model11b.predict(test_images_ds2)
 m2 = model2.predict(test_images_ds2)
 m22 = model22.predict(test_images_ds2)
 m2b = model2b.predict(test_images_ds2)
 m22b = model22b.predict(test_images_ds2)
 for i in range(104):
m1[:,i] = np.nan_to_num(logit(m1[:,i]))
m11[:,i] = np.nan_to_num(logit(m11[:,i]))
m1b[:,i] = np.nan_to_num(logit(m1b[:,i]))
m11b[:,i] = np.nan_to_num(logit(m11b[:,i]))
m2[:,i] = np.nan_to_num(logit(m2[:,i]))
m22[:,i] = np.nan_to_num(logit(m22[:,i]))
m2b[:,i] = np.nan_to_num(logit(m2b[:,i]))
m22b[:,i] = np.nan_to_num(logit(m22b[:,i]))
m1 = 0.25*m1+0.25*m11+0.25*m1b+0.25*m11b
m2 = 0.25*m2+0.25*m22+0.25*m2b+0.25*m22b
del m11,m22,m1b,m2b,m11b,m22b
cm_probabilities2 = best_alpha2*m1+(1-best_alpha2)*m2
cm_probabilities3 = best_alpha3*cm_probabilities1+(1-best_alpha3)*cm_probabilities2
predictions = np.argmax(cm_probabilities3, axis=-1)
 print(predictions)
 for i in range(104):
cm_probabilities3[:,i] = expit(cm_probabilities3[:,i])
 pd.DataFrame(cm_probabilities3 ).to_csv('probabilities.csv', index=False)
 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='' )