Kaggle competition: House Prices - Advanced Regression Techniques
<SOS> metric: rmsle Kaggle data source: house-prices-advanced-regression-techniques<define_variables>
%matplotlib inline
IMAGE_SIZE=[512,512]
GCS_PATH=GCS_DS_PATH+'/tfrecords-jpeg-512x512'
AUTO=tf.data.experimental.AUTOTUNE
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']
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<train_model>
plt.style.use("ggplot" )
BATCH_SIZE = 16*strategy.num_replicas_in_sync
ds_train = get_training_dataset()
ds_valid = get_validation_dataset()
ds_test = get_test_dataset()
print("Training: ",ds_train)
 print("Validation: ",ds_valid)
 print("Test: ",ds_test )<train_model>
import pandas as pd
import numpy as np
np.set_printoptions(threshold=15, linewidth=80)
 print("Training data shapes:")
 for image,label in ds_train.take(3):
print(image.numpy().shape,label.numpy().shape)
 print("Training data label examples:",label.numpy() )<data_type_conversions>
import pandas as pd
import numpy as np
print("Test data shapes:")
 for image,idnum in ds_test.take(3):
print(image.numpy().shape,idnum.numpy().shape)
 print("Test data IDs:",idnum.numpy().astype('U'))<categorify>
np.random.seed(1234)
 random.seed(1234 )
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(wspce=0, hspace=0)
 else:
plt.subplots_adjust(wspace=0, hspace=SPACING)
 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'] )<define_variables>
train_df = pd.read_csv("/kaggle/input/house-prices-advanced-regression-techniques/train.csv")
 test_df = pd.read_csv("/kaggle/input/house-prices-advanced-regression-techniques/test.csv")
 submission = pd.read_csv("/kaggle/input/house-prices-advanced-regression-techniques/sample_submission.csv" )
ds_iter = iter(ds_train.unbatch().batch(20))<define_variables>
train_df["MSZoning"].value_counts()
dataset = load_dataset(TRAINING_FILENAMES, labeled=True)
 one_element = tf.data.Dataset.from_tensors(next(iter(dataset)))
 augmented_element = one_element.repeat().map(data_augment ).batch(25)
 display_batch_of_images(next(iter(augmented_element)) )<choose_model_class>
all_df = pd.concat([train_df, test_df], sort=False ).reset_index(drop=True )
EPOCHS=20
def exponential_lr(epoch,
start_lr=0.00001,min_lr=0.00001,max_lr=0.00005,
rampup_epochs = 5, sustain_epochs = 0,
exp_decay = 0.8):
def lr(epoch, start_lr, min_lr,max_lr,rampup_epochs,sustain_epochs,
exp_decay):
if epoch < rampup_epochs:
lr=(( max_lr-start_lr)/
rampup_epochs * epoch + start_lr)
 elif epoch < rampup_epochs + sustain_epochs:
lr = max_lr
else:
lr =(( max_lr - min_lr)* exp_decay **(epoch-rampup_epochs-sustain_epochs)
 + min_lr)
 return lr
return lr(epoch,start_lr,min_lr,max_lr,rampup_epochs,sustain_epochs,exp_decay)
 lr_callback = tf.keras.callbacks.LearningRateScheduler(exponential_lr,verbose=True)
 rng = [i for i in range(EPOCHS)]
y = [exponential_lr(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]))<choose_model_class>
from sklearn.preprocessing import LabelEncoder
EPOCHS = 20
with strategy.scope() :
pretained_model=tf.keras.applications.EfficientNetB7(
 weights='imagenet',
include_top=False,
input_shape=[*IMAGE_SIZE,3] 
)
 pretained_model.trainable = True
model = tf.keras.Sequential([
pretained_model,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(len(CLASSES),activation='softmax')] )<choose_model_class>
categories = all_df.columns[all_df.dtypes == "object"]
print(categories )
model.compile(loss='sparse_categorical_crossentropy',optimizer='adam',metrics=['sparse_categorical_accuracy'])
 model.summary()<choose_model_class>
all_df["Alley"].value_counts()
earlystopping=EarlyStopping(monitor='val_loss',patience=2 )<train_model>
for cat in categories:
le = LabelEncoder()
print(cat)
 all_df[cat].fillna("missing", inplace=True)
 le = le.fit(all_df[cat])
 all_df[cat] = le.transform(all_df[cat])
 all_df[cat] = all_df[cat].astype("category" )
EPOCHS = 20
STEPS_PER_EPOCH = NUM_TRAINING_IMAGES//BATCH_SIZE
history = model.fit(ds_train,validation_data=ds_valid,
epochs=EPOCHS,
steps_per_epoch=STEPS_PER_EPOCH,callbacks=[lr_callback,earlystopping]
)<predict_on_test>
train_df_le = all_df[~all_df["SalePrice"].isnull() ]
test_df_le = all_df[all_df["SalePrice"].isnull() ]
cmdataset=get_validation_dataset(ordered=True)
 image_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=model.predict(image_ds)
 cm_predictions = np.argmax(cm_probabilities,axis=-1)
 labels = range(len(CLASSES))
cmat = confusion_matrix(
 cm_correct_labels,
cm_predictions,
labels=labels,)
 cmat=(cmat.T/cmat.sum(axis=1)).T<compute_train_metric>
import lightgbm as lgb
score=f1_score(cm_correct_labels,cm_predictions,labels=labels,average='macro')
 precision=precision_score(cm_correct_labels,cm_predictions,labels=labels,average='macro')
 recall=recall_score(cm_correct_labels,cm_predictions,labels=labels,average='macro')
 display_confusion_matrix(cmat,score,precision,recall )<define_variables>
folds = 3
kf = KFold(n_splits=folds )
dataset=get_validation_dataset()
dataset=dataset.unbatch().batch(20)
 batch=iter(dataset )<predict_on_test>
lgbm_params = {
"objective":"regression",
"random_seed":1234
}
images, labels=next(batch)
 probabilities= model.predict(images)
 predictions=np.argmax(probabilities,axis=-1)
 display_batch_of_images(( images,labels),predictions )<predict_on_test>
train_X = train_df_le.drop(["SalePrice", "Id"], axis=1)
 train_Y = train_df_le["SalePrice"]
test_ds = get_test_dataset(ordered=True)
 print('Computing predictions...')
 test_images_ds=test_ds.map(lambda image, idnum: image)
 probabilities = model.predict(test_images_ds)
 predictions=np.argmax(probabilities,axis=-1)
 print(predictions )<save_to_csv>
from sklearn.metrics import mean_squared_error
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 submssion.csv<save_model>
from sklearn.metrics import mean_squared_error
save_model = model.save('Efficienet_B7_model.h5' )<import_modules>
models = []
rmses = []
oof = np.zeros(len(train_X))
for train_index, val_index in kf.split(train_X):
X_train = train_X.iloc[train_index]
X_valid = train_X.iloc[val_index]
y_train = train_Y.iloc[train_index]
y_valid = train_Y.iloc[val_index]
lgb_train = lgb.Dataset(X_train, y_train)
 lgb_eval = lgb.Dataset(X_valid, y_valid, reference=lgb_train)
 model_lgb = lgb.train(lgbm_params,
lgb_train,
valid_sets=lgb_eval,
num_boost_round=100,
early_stopping_rounds=20,
verbose_eval=10, 
)
 y_pred = model_lgb.predict(X_valid, num_iteration=model_lgb.best_iteration)
 tmp_rmse = np.sqrt(mean_squared_error(np.log(y_valid), np.log(y_pred)))
 print(tmp_rmse)
 models.append(model_lgb)
 rmses.append(tmp_rmse)
 oof[val_index] = y_pred
print("Tensorflow version " + tf.__version__)
<find_best_params>
sum(rmses)/len(rmses )
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 )<define_variables>
np.log(train_df['SalePrice'] )
GCS_DS_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started')
 print(GCS_DS_PATH )<define_variables>
train_df_le["SalePrice_log"] = np.log(train_df_le["SalePrice"] )
IMAGE_SIZE = [512, 512]
GCS_PATH = GCS_DS_PATH + '/tfrecords-jpeg-512x512'
AUTO = tf.data.experimental.AUTOTUNE
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']
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<statistical_test>
train_X = train_df_le.drop(["SalePrice","SalePrice_log","Id"], axis=1)
 train_Y = train_df_le["SalePrice_log"]
def data_augment(image, label):
image = tf.image.random_flip_left_right(image)
 image = tf.image.random_saturation(image, 1, 3)
 image = tf.image.random_contrast(image, 0.4, 0.6)
 return image, label
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)
 weight_per_class = {}
NUM_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES)
 NUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)
 print('Dataset: {} training images, {} validation images, {} unlabeled test images'.format(num_training_images, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))
def get_training_dataset() :
dataset = load_dataset(TRAINING_FILENAMES, labeled=True)
 dataset = dataset.map(data_augment, num_parallel_calls=AUTO ).concatenate(dataset)
 label_counter = Counter()
for images, labels in dataset:
label_counter.update([labels.numpy() ])
 total = sum(label_counter.values())
 print("Nr of labels: ", total)
 num_training_images = total
TARGET_NUM_PER_CLASS = total / len(CLASSES)
 def get_weight_for_class(class_id):
counting = label_counter[class_id]
weight = TARGET_NUM_PER_CLASS / counting
return weight
weight_per_class = {class_id: get_weight_for_class(class_id)for class_id in range(104)}
dataset = dataset.shuffle(total, reshuffle_each_iteration=True)
 dataset = dataset.repeat()
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<train_model>
models = []
rmses = []
oof = np.zeros(len(train_X))
for train_index, val_index in kf.split(train_X):
X_train = train_X.iloc[train_index]
X_valid = train_X.iloc[val_index]
y_train = train_Y.iloc[train_index]
y_valid = train_Y.iloc[val_index]
lgb_train = lgb.Dataset(X_train, y_train)
 lgb_eval = lgb.Dataset(X_valid, y_valid, reference=lgb_train)
 model_lgb = lgb.train(lgbm_params,
lgb_train,
valid_sets=lgb_eval,
num_boost_round=100,
early_stopping_rounds=20,
verbose_eval=10, 
)
 y_pred = model_lgb.predict(X_valid, num_iteration=model_lgb.best_iteration)
 tmp_rmse = np.sqrt(mean_squared_error(y_valid, y_pred))
print(tmp_rmse)
 models.append(model_lgb)
 rmses.append(tmp_rmse)
 oof[val_index] = y_pred
BATCH_SIZE = 16 * strategy.num_replicas_in_sync
ds_train = get_training_dataset()
ds_valid = get_validation_dataset()
ds_test = get_test_dataset()
print("Training:", ds_train)
 print("Validation:", ds_valid)
 print("Test:", ds_test )<train_model>
sum(rmses)/len(rmses )
np.set_printoptions(threshold=15, linewidth=80)
 print("Training data shapes:")
 for image, label in ds_train.take(3):
print(image.numpy().shape, label.numpy().shape)
 print("Training data label examples:", label.numpy() )<data_type_conversions>
all_df = pd.concat([train_df, test_df], sort=False ).reset_index(drop=True )
print("Test data shapes:")
 for image, idnum in ds_test.take(3):
print(image.numpy().shape, idnum.numpy().shape)
 print("Test data IDs:", idnum.numpy().astype('U'))<categorify>
categories = all_df.columns[all_df.dtypes == "object"]
print(categories )
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_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.'])
 def plot_class_distribution() :
dataset = load_dataset(VALIDATION_FILENAMES, labeled=True)
 label_counter = Counter()
for images, labels in dataset:
label_counter.update([labels.numpy() ])
 ordered_labels = label_counter.most_common()
print("Most common: ", ordered_labels[0])
 print("Least common: ", ordered_labels[len(ordered_labels)-1])
 plt.bar(label_counter.keys() , label_counter.values() )<define_variables>
all_df.isnull().sum().sort_values(ascending=False ).head(40 )
ds_iter = iter(ds_train.unbatch().batch(20))<define_variables>
all_df.PoolQC.value_counts()
one_batch = next(ds_iter)
 display_batch_of_images(one_batch )<choose_model_class>
all_df.loc[~all_df["PoolQC"].isnull() , "PoolQC"] = 1
all_df.loc[all_df["PoolQC"].isnull() , "PoolQC"] = 0
with strategy.scope() :
pretrained_model = tf.keras.applications.DenseNet201(
 weights='imagenet',
include_top=False ,
input_shape=[*IMAGE_SIZE, 3] 
)
 pretrained_model.trainable = False
model = tf.keras.Sequential([
pretrained_model,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dropout(0.1),
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ] )<choose_model_class>
all_df.PoolQC.value_counts()
model.compile(
 optimizer='adam',
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'], 
)
 model.summary()<train_model>
all_df.loc[~all_df["MiscFeature"].isnull() , "MiscFeature"] = 1
all_df.loc[all_df["MiscFeature"].isnull() , "MiscFeature"] = 0
EPOCHS = 18
STEPS_PER_EPOCH = num_training_images // BATCH_SIZE
early_stopping = tf.keras.callbacks.EarlyStopping(
 monitor='val_loss', patience=2, restore_best_weights=True)
 history = model.fit(
 ds_train,
validation_data=ds_valid,
epochs=EPOCHS,
steps_per_epoch=STEPS_PER_EPOCH,
callbacks=[early_stopping],
class_weight=weight_per_class
)<train_model>
all_df.loc[~all_df["Alley"].isnull() , "Alley"] = 1
all_df.loc[all_df["Alley"].isnull() , "Alley"] = 0
for layer in model.layers:
layer.trainable = True
opt = tf.keras.optimizers.Adam(learning_rate=0.0001)
 model.compile(
 optimizer=opt,
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'], 
)
 history = model.fit(
 ds_train,
validation_data=ds_valid,
epochs=12,
steps_per_epoch=STEPS_PER_EPOCH,
callbacks=[early_stopping]
)<predict_on_test>
HighFacility_col = ["PoolQC","MiscFeature","Alley"]
for col in HighFacility_col:
if all_df[col].dtype == "object":
if len(all_df[all_df[col].isnull() ])> 0:
all_df.loc[~all_df[col].isnull() , col] = 1
all_df.loc[all_df[col].isnull() , col] = 0
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 = model.predict(images_ds)
 cm_predictions = np.argmax(cm_probabilities, axis=-1)
 labels = range(len(CLASSES))
cmat = confusion_matrix(
 cm_correct_labels,
cm_predictions,
labels=labels, 
)
 cmat =(cmat.T / cmat.sum(axis=1)).T<compute_train_metric>
all_df["hasHighFacility"] = all_df["PoolQC"] + all_df["MiscFeature"] + all_df["Alley"]
score = f1_score(
 cm_correct_labels,
cm_predictions,
labels=labels,
average='macro', 
)
 precision = precision_score(
 cm_correct_labels,
cm_predictions,
labels=labels,
average='macro', 
)
 recall = recall_score(
 cm_correct_labels,
cm_predictions,
labels=labels,
average='macro', 
)
 display_confusion_matrix(cmat, score, precision, recall )<define_variables>
all_df["hasHighFacility"] = all_df["hasHighFacility"].astype(int )
dataset = get_validation_dataset()
dataset = dataset.unbatch().batch(20)
 batch = iter(dataset )<predict_on_test>
all_df["hasHighFacility"].value_counts()
images, labels = next(batch)
 probabilities = model.predict(images)
 predictions = np.argmax(probabilities, axis=-1)
 display_batch_of_images(( images, labels), predictions )<predict_on_test>
all_df = all_df.drop(["PoolQC","MiscFeature","Alley"],axis=1 )
test_ds = get_test_dataset(ordered=True)
 print('Computing predictions...')
 test_images_ds = test_ds.map(lambda image, idnum: image)
 probabilities = model.predict(test_images_ds)
 predictions = np.argmax(probabilities, axis=-1)
 print(predictions )<save_to_csv>
train_df_num = train_df.select_dtypes(include=[np.number] )
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<import_modules>
nonratio_features = ["Id", "MSSubClass", "OverallQual", "OverallCond", "YearBuilt", "YearRemodAdd", "MoSold", "YrSold"]
tf.data.experimental.AUTOTUNE
print("TF version " + tf.__version__)
 AUTO = tf.data.experimental.AUTOTUNE 
<set_options>
num_features = sorted(list(set(train_df_num)- set(nonratio_features)) )
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 )<define_variables>
train_df_num_rs = train_df_num[num_features]
IMAGE_SIZE = [512, 512]
EPOCHS = 8
BATCH_SIZE = 16 * strategy.num_replicas_in_sync
SEED = 752
SKIP_VALIDATION = False
TTA_NUM = 5
random.seed(SEED)
 np.random.seed(SEED)
 tf.random.set_seed(SEED )<categorify>
for col in num_features:
if train_df_num_rs[col].nunique() < 15:
print(col, train_df_num_rs[col].nunique() )
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.'] )<categorify>
for col in num_features:
tmp_df = train_df_num_rs[(train_df_num_rs[col] > train_df_num_rs[col].mean() + train_df_num_rs[col].std() *3)| \ 
(train_df_num_rs[col] < train_df_num_rs[col].mean() - train_df_num_rs[col].std() *3)]
print(col, len(tmp_df))
def random_blockout(img, sl=0.1, sh=0.2, rl=0.4):
p=random.random()
if p>=0.25:
w, h, c = IMAGE_SIZE[0], IMAGE_SIZE[1], 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)
 else:
return tf.cast(img, img.dtype )<categorify>
all_df[all_df["BsmtFinSF1"] > 5000]
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, seed=SEED)
 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 = 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)) 
<define_variables>
all_df[all_df["TotalBsmtSF"] > 6000]
if SKIP_VALIDATION:
TRAINING_FILENAMES = TRAINING_FILENAMES + VALIDATION_FILENAMES<train_model>
all_df[all_df["GrLivArea"] > 5000]
training_dataset = get_training_dataset()
validation_dataset = get_validation_dataset()
training_dataset,validation_dataset<train_model>
all_df[all_df["1stFlrSF"] > 4000]
print("Number of classes: {}".format(len(CLASSES)))
 print("First five classes, sorted alphabetically:")
 for name in sorted(CLASSES)[:5]:
print(name)
 print("Number of training images: {}".format(NUM_TRAINING_IMAGES))<train_model>
all_df = all_df[(all_df['BsmtFinSF1'] < 2000)|(all_df['SalePrice'].isnull())]
all_df = all_df[(all_df['TotalBsmtSF'] < 3000)|(all_df['SalePrice'].isnull())]
all_df = all_df[(all_df['GrLivArea'] < 4500)|(all_df['SalePrice'].isnull())]
all_df = all_df[(all_df['1stFlrSF'] < 2500)|(all_df['SalePrice'].isnull())]
all_df = all_df[(all_df['LotArea'] < 100000)|(all_df['SalePrice'].isnull())]
print("Training data shapes:")
 for image, label in get_training_dataset().take(1):
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(1):
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(1):
print(image.numpy().shape, idnum.numpy().shape)
 print("Test data IDs:", idnum.numpy().astype('U'))<train_model>
categories = categories.drop(["PoolQC","MiscFeature","Alley"] )
training_dataset = get_training_dataset()
training_dataset = training_dataset.unbatch().batch(20)
 train_batch = iter(training_dataset )<define_variables>
for cat in categories:
le = LabelEncoder()
print(cat)
 all_df[cat].fillna("missing", inplace=True)
 le = le.fit(all_df[cat])
 all_df[cat] = le.transform(all_df[cat])
 all_df[cat] = all_df[cat].astype("category" )
display_batch_of_images(next(train_batch))<define_variables>
train_df_le = all_df[~all_df["SalePrice"].isnull() ]
test_df_le = all_df[all_df["SalePrice"].isnull() ]
train_df_le["SalePrice_log"] = np.log(train_df_le["SalePrice"])
 train_X = train_df_le.drop(["SalePrice","SalePrice_log", "Id"], axis=1)
 train_Y = train_df_le["SalePrice_log"]
test_dataset = get_test_dataset()
test_dataset = test_dataset.unbatch().batch(20)
 test_batch = iter(test_dataset )<define_variables>
models = []
rmses = []
oof = np.zeros(len(train_X))
for train_index, val_index in kf.split(train_X):
X_train = train_X.iloc[train_index]
X_valid = train_X.iloc[val_index]
y_train = train_Y.iloc[train_index]
y_valid = train_Y.iloc[val_index]
lgb_train = lgb.Dataset(X_train, y_train)
 lgb_eval = lgb.Dataset(X_valid, y_valid, reference=lgb_train)
 model_lgb = lgb.train(lgbm_params,
lgb_train,
valid_sets=lgb_eval,
num_boost_round=100,
early_stopping_rounds=20,
verbose_eval=10, 
)
 y_pred = model_lgb.predict(X_valid, num_iteration=model_lgb.best_iteration)
 tmp_rmse = np.sqrt(mean_squared_error(y_valid, y_pred))
print(tmp_rmse)
 models.append(model_lgb)
 rmses.append(tmp_rmse)
 oof[val_index] = y_pred
display_batch_of_images(next(test_batch))<choose_model_class>
sum(rmses)/len(rmses )
LR_START = 0.00001
LR_MAX = 0.00006 * 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(25 if EPOCHS<25 else EPOCHS)]
y = [lrfn(x)for x in rng]
plt.plot(rng, y)
 print("Learning rate schedule: {:.3g} to {:.3g} to {:.3g}".format(y[0], max(y), y[-1]))<install_modules>
all_df["Age"] = all_df["YrSold"] - all_df["YearBuilt"]
!pip install -q efficientnet 
<choose_model_class>
train_df_le = all_df[~all_df["SalePrice"].isnull() ]
test_df_le = all_df[all_df["SalePrice"].isnull() ]
train_df_le["SalePrice_log"] = np.log(train_df_le["SalePrice"])
 train_X = train_df_le.drop(["SalePrice","SalePrice_log","Id"], axis=1)
 train_Y = train_df_le["SalePrice_log"]
with strategy.scope() :
enet = efn.EfficientNetB7(input_shape=[*IMAGE_SIZE, 3], weights='imagenet', include_top=False)
 enet.trainable = True
model1 = tf.keras.Sequential([
enet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model1.compile(
 optimizer=tf.keras.optimizers.Adam() ,
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 model1.summary()<choose_model_class>
models = []
rmses = []
oof = np.zeros(len(train_X))
for train_index, val_index in kf.split(train_X):
X_train = train_X.iloc[train_index]
X_valid = train_X.iloc[val_index]
y_train = train_Y.iloc[train_index]
y_valid = train_Y.iloc[val_index]
lgb_train = lgb.Dataset(X_train, y_train)
 lgb_eval = lgb.Dataset(X_valid, y_valid, reference=lgb_train)
 model_lgb = lgb.train(lgbm_params,
lgb_train,
valid_sets=lgb_eval,
num_boost_round=100,
early_stopping_rounds=20,
verbose_eval=10, 
)
 y_pred = model_lgb.predict(X_valid, num_iteration=model_lgb.best_iteration)
 tmp_rmse = np.sqrt(mean_squared_error(y_valid, y_pred))
print(tmp_rmse)
 models.append(model_lgb)
 rmses.append(tmp_rmse)
 oof[val_index] = y_pred
weight_path_save1 = 'Effnet_best_model.hdf5'
checkpoint = ModelCheckpoint(weight_path_save1,
monitor= 'val_loss',
verbose=1,
save_best_only=True,
mode= 'min',
save_weights_only = False,
period = 1)
 early = EarlyStopping(monitor= 'val_loss',
mode= 'min',
patience=2)
 callbacks_list = [checkpoint, early, lr_callback]<train_model>
sum(rmses)/len(rmses )
if not SKIP_VALIDATION:
history1 = model1.fit(get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS,
validation_data=get_validation_dataset() ,
callbacks = callbacks_list)
 else:
history1 = model1.fit(get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS,
callbacks = callbacks_list )<choose_model_class>
all_df["TotalSF"] = all_df["TotalBsmtSF"] + all_df["1stFlrSF"] + all_df["2ndFlrSF"]
all_df["Total_Bathrooms"] = all_df["FullBath"] + all_df["HalfBath"] + all_df["BsmtFullBath"] + all_df["BsmtHalfBath"]
with strategy.scope() :
densenet = tf.keras.applications.DenseNet201(input_shape=[*IMAGE_SIZE, 3], weights='imagenet', include_top=False)
 densenet.trainable = True
model2 = tf.keras.Sequential([
densenet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model2.compile(
 optimizer=tf.keras.optimizers.Adam() ,
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 model2.summary()<choose_model_class>
all_df["Total_PorchSF"] = all_df["WoodDeckSF"] + all_df["OpenPorchSF"] + all_df["EnclosedPorch"] + all_df["3SsnPorch"] + all_df["ScreenPorch"]
weight_path_save2 = 'Dense_best_model.hdf5'
checkpoint = ModelCheckpoint(weight_path_save2,
monitor= 'val_loss',
verbose=1,
save_best_only=True,
mode= 'min',
save_weights_only = False)
 early = EarlyStopping(monitor= 'val_loss',
mode= 'min',
patience=2)
 callbacks_list = [checkpoint, early, lr_callback]<train_model>
all_df["hasPorch"] = all_df["Total_PorchSF"].apply(lambda x: 1 if x > 0 else 0)
 all_df = all_df.drop("Total_PorchSF",axis=1 )
if not SKIP_VALIDATION:
history2 = model2.fit(get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS,
validation_data=get_validation_dataset() ,
callbacks = callbacks_list)
 else:
history2 = model2.fit(get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS,
callbacks = [lr_callback] )<load_pretrained>
train_df_le = all_df[~all_df["SalePrice"].isnull() ]
test_df_le = all_df[all_df["SalePrice"].isnull() ]
train_df_le["SalePrice_log"] = np.log(train_df_le["SalePrice"])
 train_X = train_df_le.drop(["SalePrice","SalePrice_log","Id"], axis=1)
 train_Y = train_df_le["SalePrice_log"]
model1.load_weights(weight_path_save1)
 model2.load_weights(weight_path_save2 )<predict_on_test>
models = []
rmses = []
oof = np.zeros(len(train_X))
for train_index, val_index in kf.split(train_X):
X_train = train_X.iloc[train_index]
X_valid = train_X.iloc[val_index]
y_train = train_Y.iloc[train_index]
y_valid = train_Y.iloc[val_index]
lgb_train = lgb.Dataset(X_train, y_train)
 lgb_eval = lgb.Dataset(X_valid, y_valid, reference=lgb_train)
 model_lgb = lgb.train(lgbm_params,
lgb_train,
valid_sets=lgb_eval,
num_boost_round=100,
early_stopping_rounds=20,
verbose_eval=10, 
)
 y_pred = model_lgb.predict(X_valid, num_iteration=model_lgb.best_iteration)
 tmp_rmse = np.sqrt(mean_squared_error(y_valid, y_pred))
print(tmp_rmse)
 models.append(model_lgb)
 rmses.append(tmp_rmse)
 oof[val_index] = y_pred
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()
m1 = model1.predict(images_ds)
 m2 = model2.predict(images_ds)
 scores = []
for alpha in np.linspace(0,1,100):
cm_probabilities = alpha*m1+(1-alpha)*m2
cm_predictions = np.argmax(cm_probabilities, axis=-1)
 scores.append(f1_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro'))
best_alpha = np.argmax(scores)/100
else:
best_alpha = 0.51
print('Best alpha: ' + str(best_alpha)) 
<compute_test_metric>
sum(rmses)/len(rmses )
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))<predict_on_test>
import optuna
def predict_tta(model, n_iter):
probs = []
for i in range(n_iter):
test_ds = get_test_dataset(ordered=True)
 test_images_ds = test_ds.map(lambda image, idnum: image)
 probs.append(model.predict(test_images_ds,verbose=0))
return probs<predict_on_test>
from sklearn.model_selection import train_test_split
test_ds = get_test_dataset(ordered=True)
 print('Calculating predictions...')
 test_images_ds = test_ds.map(lambda image, idnum: image)
 probs1 = np.mean(predict_tta(model1, TTA_NUM), axis=0)
 probs2 = np.mean(predict_tta(model2, TTA_NUM), axis=0)
 probabilities = best_alpha*probs1 +(1-best_alpha)*probs2
predictions = np.argmax(probabilities, axis=-1)
 print('Generating submission 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='' )<define_variables>
from sklearn.model_selection import train_test_split
Image(filename=".. /input/images/Petals to the Metal 31.png", width=1200, height=1000 )<define_variables>
X_train, X_valid, y_train, y_valid = train_test_split(train_X, train_Y, test_size=0.2, random_state=1234, shuffle=False, stratify=None )
Image(filename=".. /input/images/Petals to the Metal 32.png", width=1200, height=1000 )<define_variables>
def objective(trial):
params = {
"objective":"regression",
"random_seed":1234,
"learning_rate":0.05,
"n_estimators":1000,
"num_leaves":trial.suggest_int("num_leaves",4,64),
"max_bin":trial.suggest_int("max_bin",50,200),
"bagging_fraction":trial.suggest_uniform("bagging_fraction",0.4,0.9),
"bagging_freq":trial.suggest_int("bagging_freq",1,10),
"feature_fraction":trial.suggest_uniform("feature_fraction",0.4,0.9),
"min_data_in_leaf":trial.suggest_int("min_data_in_leaf",2,16),
"min_sum_hessian_in_leaf":trial.suggest_int("min_sum_hessian_in_leaf",1,10),
}
lgb_train = lgb.Dataset(X_train, y_train)
 lgb_eval = lgb.Dataset(X_valid, y_valid, reference=lgb_train)
 model_lgb = lgb.train(params, lgb_train,
valid_sets=lgb_eval,
num_boost_round=100,
early_stopping_rounds=20,
verbose_eval=10,)
 y_pred = model_lgb.predict(X_valid, num_iteration=model_lgb.best_iteration)
 score = np.sqrt(mean_squared_error(y_valid, y_pred))
return score
Image(filename=".. /input/images/Petals to the Metal 28.png", width=1200, height=1000 )<define_variables>
study = optuna.create_study(sampler=optuna.samplers.RandomSampler(seed=0))
study.optimize(objective, n_trials=50)
 study.best_params
Image(filename=".. /input/images/3d_plot3.png", width=1200, height=1000 )<define_variables>
lgbm_params = {
"objective":"regression",
"random_seed":1234,
"learning_rate":0.05,
"n_estimators":1000,
"num_leaves":12,
"bagging_fraction": 0.8319278029616157,
"bagging_freq": 5,
"feature_fraction": 0.4874544371547538,
"max_bin":189,
"min_data_in_leaf":13,
"min_sum_hessian_in_leaf":4
}
Image(filename=".. /input/images/3d_plot4.png", width=1200, height=1000 )<define_variables>
models = []
rmses = []
oof = np.zeros(len(train_X))
for train_index, val_index in kf.split(train_X):
X_train = train_X.iloc[train_index]
X_valid = train_X.iloc[val_index]
y_train = train_Y.iloc[train_index]
y_valid = train_Y.iloc[val_index]
lgb_train = lgb.Dataset(X_train, y_train)
 lgb_eval = lgb.Dataset(X_valid, y_valid, reference=lgb_train)
 model_lgb = lgb.train(lgbm_params,
lgb_train,
valid_sets=lgb_eval,
num_boost_round=100,
early_stopping_rounds=20,
verbose_eval=10, 
)
 y_pred = model_lgb.predict(X_valid, num_iteration=model_lgb.best_iteration)
 tmp_rmse = np.sqrt(mean_squared_error(y_valid, y_pred))
print(tmp_rmse)
 models.append(model_lgb)
 rmses.append(tmp_rmse)
 oof[val_index] = y_pred
Image(filename=".. /input/images/3d_plot5.png", width=1200, height=1000 )<define_variables>
sum(rmses)/len(rmses )
Image(filename=".. /input/images/Petals to the Metal 10.png", width=1200, height=1000 )<define_variables>
test_X = test_df_le.drop(["SalePrice", "Id"], axis=1 )
Image(filename=".. /input/images/Petals to the Metal 25.png", width=1200, height=1000 )<define_variables>
preds = []
for model in models:
pred = model.predict(test_X)
 preds.append(pred )
Image(filename=".. /input/images/Petals to the Metal 26.png", width=1200, height=1000 )<define_variables>
preds_array = np.array(preds)
 preds_mean = np.mean(preds_array, axis=0 )
Image(filename=".. /input/images/Petals to the Metal 22.png", width=1200, height=1000 )<define_variables>
preds_exp = np.exp(preds_mean )
Image(filename=".. /input/images/Deep Learning Adventures.png", width=1200, height=1000 )<install_modules>
submission["SalePrice"] = preds_exp
!pip install seaborn --upgrade
print("Tensorflow version " + tf.__version__ )<define_variables>
submission.to_csv("./houseprices_submit01.csv",index=False )
GCS_DS_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started')
 print(GCS_DS_PATH )<define_variables>
from sklearn.ensemble import RandomForestRegressor as rf
IMAGE_SIZE = [512, 512]
GCS_PATH = GCS_DS_PATH + '/tfrecords-jpeg-512x512'
AUTO = tf.data.experimental.AUTOTUNE
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']
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<define_variables>
hasnan_cat = []
for col in all_df.columns:
tmp_null_count = all_df[col].isnull().sum()
if(tmp_null_count > 0)&(col != "SalePrice"):
print(col, tmp_null_count)
 hasnan_cat.append(col )
GCS_DS_PATH_EXT = KaggleDatasets().get_gcs_path('tf-flower-photo-tfrec')
 GCS_PATH_SELECT_EXT = {
192: '/tfrecords-jpeg-192x192',
224: '/tfrecords-jpeg-224x224',
331: '/tfrecords-jpeg-331x331',
512: '/tfrecords-jpeg-512x512'
}
GCS_PATH_EXT = GCS_PATH_SELECT_EXT[IMAGE_SIZE[0]]
IMAGENET_FILES = tf.io.gfile.glob(GCS_DS_PATH_EXT + '/imagenet' + GCS_PATH_EXT + '/*.tfrec')
 INATURELIST_FILES = tf.io.gfile.glob(GCS_DS_PATH_EXT + '/inaturalist' + GCS_PATH_EXT + '/*.tfrec')
 OPENIMAGE_FILES = tf.io.gfile.glob(GCS_DS_PATH_EXT + '/openimage' + GCS_PATH_EXT + '/*.tfrec')
 OXFORD_FILES = tf.io.gfile.glob(GCS_DS_PATH_EXT + '/oxford_102' + GCS_PATH_EXT + '/*.tfrec')
 TENSORFLOW_FILES = tf.io.gfile.glob(GCS_DS_PATH_EXT + '/tf_flowers' + GCS_PATH_EXT + '/*.tfrec')
 ADDITIONAL_TRAINING_FILENAMES = IMAGENET_FILES + INATURELIST_FILES + OPENIMAGE_FILES + OXFORD_FILES + TENSORFLOW_FILES
TRAINING_FILENAMES = TRAINING_FILENAMES + ADDITIONAL_TRAINING_FILENAMES<categorify>
for col in all_df.columns:
tmp_null_count = all_df[col].isnull().sum()
if(tmp_null_count > 0)&(col != "SalePrice"):
print(col, tmp_null_count)
 all_df[col] = all_df[col].fillna(all_df[col].median() )
SEED = 2020
def random_blockout(img, sl=0.1, sh=0.2, rl=0.4):
p=random.random()
if p>=0.25:
w, h, c = IMAGE_SIZE[0], IMAGE_SIZE[1], 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)
 else:
return tf.cast(img, img.dtype)
 def data_augment_v2(image, label):
flag = random.randint(1,3)
 coef_1 = random.randint(70, 90)* 0.01
coef_2 = random.randint(70, 90)* 0.01
if flag == 1:
image = tf.image.random_flip_left_right(image, seed=SEED)
 elif flag == 2:
image = tf.image.random_flip_up_down(image, seed=SEED)
 else:
image = tf.image.random_crop(image, [int(IMAGE_SIZE[0]*coef_1), int(IMAGE_SIZE[0]*coef_2), 3],seed=SEED)
 image = random_blockout(image)
 return image, label<normalization>
train_df_le = all_df[~all_df["SalePrice"].isnull() ]
test_df_le = all_df[all_df["SalePrice"].isnull() ]
train_df_le["SalePrice_log"] = np.log(train_df_le["SalePrice"] )
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)
 print('Dataset: {} training images, {} validation images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES)) 
<count_unique_values>
train_X = train_df_le.drop(["SalePrice","SalePrice_log","Id"], axis=1)
 train_Y = train_df_le["SalePrice_log"]
strategy.num_replicas_in_sync<define_variables>
folds = 3
kf = KFold(n_splits=folds )
16 * strategy.num_replicas_in_sync<train_model>
models_rf = []
rmses_rf = []
oof_rf = np.zeros(len(train_X))
for train_index, val_index in kf.split(train_X):
X_train = train_X.iloc[train_index]
X_valid = train_X.iloc[val_index]
y_train = train_Y.iloc[train_index]
y_valid = train_Y.iloc[val_index]
model_rf = rf(
 n_estimators=50,
random_state=1234 
)
 model_rf.fit(X_train, y_train)
 y_pred = model_rf.predict(X_valid)
 tmp_rmse = np.sqrt(mean_squared_error(y_valid, y_pred))
print(tmp_rmse)
 models_rf.append(model_rf)
 rmses_rf.append(tmp_rmse)
 oof_rf[val_index] = y_pred
BATCH_SIZE = 16 * strategy.num_replicas_in_sync
ds_train = get_training_dataset()
ds_valid = get_validation_dataset()
ds_test = get_test_dataset()
print("Training:", ds_train)
 print("Validation:", ds_valid)
 print("Test:", ds_test )<train_model>
sum(rmses_rf)/len(rmses_rf )
np.set_printoptions(threshold=15, linewidth=80)
 print("Training data shapes:")
 for image, label in ds_train.take(3):
print(image.numpy().shape, label.numpy().shape)
 print("Training data label examples:", label.numpy() )<data_type_conversions>
test_X = test_df_le.drop(["SalePrice","Id"], axis=1 )
print("Test data shapes:")
 for image, idnum in ds_test.take(3):
print(image.numpy().shape, idnum.numpy().shape)
 print("Test data IDs:", idnum.numpy().astype('U'))<categorify>
preds_rf = []
for model in models_rf:
pred = model.predict(test_X)
 preds_rf.append(pred )
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, display_mismatches_only=False):

 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
if display_mismatches_only:
if predictions[i] != label:
subplot = display_one_flower(image, title, subplot, not correct, titlesize=dynamic_titlesize)
 else:
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_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.'])
 def display_training_curves_v2(training, validation, learning_rate_list, 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, color='b')
 ax.set_xlabel('epoch')
 ax.legend(['train', 'valid.', 'learning rate'])
 ax2 = ax.twinx()
ax2.plot(learning_rate_list, 'g-')
 ax2.set_ylabel('learning rate', color='g' )<define_variables>
preds_array_rf = np.array(preds_rf)
 preds_mean_rf = np.mean(preds_array_rf, axis=0)
 preds_exp_rf = np.exp(preds_mean_rf)
 submission["SalePrice"] = preds_exp_rf
ds_iter = iter(ds_train.unbatch().batch(20))<define_variables>
submission.to_csv("./houseprices_submit02.csv",index=False )
one_batch = next(ds_iter)
 display_batch_of_images(one_batch )<define_variables>
import xgboost as xgb
[*IMAGE_SIZE, 3]<train_model>
categories = train_X.columns[train_X.dtypes == "category"]
early_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=3 )<find_best_params>
for col in categories:
train_X[col] = train_X[col].astype("int8")
 test_X[col] = test_X[col].astype("int8" )
class LearningRateTracking(tf.keras.callbacks.Callback):
def on_epoch_end(self, epoch, logs=None):
keys = list(logs.keys())
 print("End epoch {} of training; got log keys: {}".format(epoch, keys)) 
<install_modules>
X_train, X_valid, y_train, y_valid = train_test_split(train_X, train_Y, test_size=0.2, random_state=1234, shuffle=False, stratify=None )
use_efficientnet = False
if use_efficientnet:
!pip install -q efficientnet 
<create_dataframe>
def objective(trial):
xgb_params = {
"learning_rate":0.05,
"seed":1234,
"max_depth":trial.suggest_int("max_depth",3,16),
"colsample_bytree":trial.suggest_uniform("colsample_bytree",0.2,0.9),
"sublsample":trial.suggest_uniform("sublsample",0.2,0.9),
}
xgb_train = xgb.DMatrix(X_train, label=y_train)
 xgb_eval = xgb.DMatrix(X_valid, label=y_valid)
 evals = [(xgb_train, "train"),(xgb_eval, "eval")]
model_xgb = xgb.train(xgb_params, xgb_train,
evals=evals,
num_boost_round=1000,
early_stopping_rounds=20,
verbose_eval=10,)
 y_pred = model_xgb.predict(xgb_eval)
 score = np.sqrt(mean_squared_error(y_valid, y_pred))
return score
weight_per_class = True
if weight_per_class:
gc.enable()
def get_training_dataset_raw() :
dataset = load_dataset(TRAINING_FILENAMES, labeled = True, ordered = False)
 return dataset
raw_training_dataset = get_training_dataset_raw()
label_counter = Counter()
for images, labels in raw_training_dataset:
label_counter.update([labels.numpy() ])
 del raw_training_dataset
TARGET_NUM_PER_CLASS = 122
def get_weight_for_class(class_id):
counting = label_counter[class_id]
weight = TARGET_NUM_PER_CLASS / counting
return weight
weight_per_class = {class_id: get_weight_for_class(class_id)for class_id in range(104)}<define_variables>
study = optuna.create_study(sampler=optuna.samplers.RandomSampler(seed=0))
study.optimize(objective, n_trials=50)
 study.best_params
using_ensemble_models = False<choose_model_class>
xgb_params = {
"learning_rate":0.05,
"seed":1234,
"max_depth": 6,
"colsample_bytree": 0.330432640328732,
"sublsample": 0.7158427239902707
}
if not using_ensemble_models:
with strategy.scope() :
pretrained_model = tf.keras.applications.MobileNetV2(
 include_top=False ,
weights='imagenet',
input_shape=[*IMAGE_SIZE, 3] 
)
 pretrained_model.trainable = True
model = tf.keras.Sequential([
pretrained_model,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ] )<choose_model_class>
models_xgb = []
rmses_xgb = []
oof_xgb = np.zeros(len(train_X))
for train_index, val_index in kf.split(train_X):
X_train = train_X.iloc[train_index]
X_valid = train_X.iloc[val_index]
y_train = train_Y.iloc[train_index]
y_valid = train_Y.iloc[val_index]
xgb_train = xgb.DMatrix(X_train, label=y_train)
 xgb_eval = xgb.DMatrix(X_valid, label=y_valid)
 evals = [(xgb_train, "train"),(xgb_eval, "eval")]
model_xgb = xgb.train(xgb_params, xgb_train,
evals=evals,
num_boost_round=1000,
early_stopping_rounds=20,
verbose_eval=20,)
 y_pred = model_xgb.predict(xgb_eval)
 tmp_rmse = np.sqrt(mean_squared_error(y_valid, y_pred))
print(tmp_rmse)
 models_xgb.append(model_xgb)
 rmses_xgb.append(tmp_rmse)
 oof_xgb[val_index] = y_pred
if not using_ensemble_models:
model.compile(
 optimizer='nadam',
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'],
)<define_variables>
sum(rmses_xgb)/len(rmses_xgb )
if not using_ensemble_models:
EPOCHS = 30
BATCH_SIZE = 16 * strategy.num_replicas_in_sync
STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE<choose_model_class>
xgb_test = xgb.DMatrix(test_X )
if not using_ensemble_models:
def exponential_lr(epoch,
start_lr = 0.00001, min_lr = 0.00001, max_lr = 0.00005 * strategy.num_replicas_in_sync,
rampup_epochs = 5, sustain_epochs = 0,
exp_decay = 0.75):
def lr(epoch, start_lr, min_lr, max_lr, rampup_epochs, sustain_epochs, exp_decay):
if epoch < rampup_epochs:
lr =(( max_lr - start_lr)/
rampup_epochs * epoch + start_lr)
 elif epoch < rampup_epochs + sustain_epochs:
lr = max_lr
else:
lr =(( max_lr - min_lr)*
exp_decay**(epoch - rampup_epochs - sustain_epochs)+
min_lr)
 return lr
return lr(epoch,
start_lr,
min_lr,
max_lr,
rampup_epochs,
sustain_epochs,
exp_decay)
 lr_callback = tf.keras.callbacks.LearningRateScheduler(exponential_lr, verbose=True)
 rng = [i for i in range(EPOCHS)]
y = [exponential_lr(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]))<train_model>
preds_xgb = []
for model in models_xgb:
pred = model.predict(xgb_test)
 preds_xgb.append(pred )
if not using_ensemble_models:
history = model.fit(
 ds_train,
validation_data=ds_valid,
epochs=EPOCHS,
steps_per_epoch=STEPS_PER_EPOCH,
callbacks=[lr_callback, checkpoint],
class_weight = weight_per_class
)<load_pretrained>
preds_array_xgb= np.array(preds_xgb)
 preds_mean_xgb = np.mean(preds_array_xgb, axis=0)
 preds_exp_xgb = np.exp(preds_mean_xgb)
 submission["SalePrice"] = preds_exp_xgb
if not using_ensemble_models:
model.load_weights(checkpoint_filepath )<define_variables>
submission.to_csv("./houseprices_submit03.csv",index=False )
print(checkpoint_filepath)
 tflite_model_name = checkpoint_filepath.replace('.h5', '.tflite')
 tflite_model_name<choose_model_class>
preds_ans = preds_exp_xgb * 0.5 + preds_exp * 0.5
def get_pretrained_model(model_name, image_dataset_weights, trainable=True):
pretrained_model= model_name(
 include_top=False ,
weights=image_dataset_weights,
input_shape=[*IMAGE_SIZE, 3] 
)
 pretrained_model.trainable = trainable
model = tf.keras.Sequential([
pretrained_model,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 return model<load_pretrained>
submission["SalePrice"] = preds_ans
if using_ensemble_models:
with strategy.scope() :
model_EB7 = get_pretrained_model(EfficientNetB7, 'noisy-student', trainable=True)
 model_EB7.load_weights('.. /input/models/Petals_to_the_Metal-70K_images-trainable_True-EfficientNetB7.h5' )<load_pretrained>
submission.to_csv("./houseprices_submit04.csv",index=False )
if using_ensemble_models:
with strategy.scope() :
model_D201 = get_pretrained_model(tf.keras.applications.DenseNet201, 'imagenet', trainable=True)
 model_D201.load_weights('.. /input/models/Petals_to_the_Metal-70K_images-trainable_True-DenseNet201.h5' )<import_modules>
train_df_le_dn = train_df_le.dropna()
from sklearn.metrics import f1_score, precision_score, recall_score, confusion_matrix<predict_on_test>
from sklearn import preprocessing
if using_ensemble_models:
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()
m1 = model_EB7.predict(images_ds)
 m2 = model_D201.predict(images_ds)
 scores = []
for alpha in np.linspace(0,1,100):
cm_probabilities = alpha*m1+(1-alpha)*m2
cm_predictions = np.argmax(cm_probabilities, axis=-1)
 scores.append(f1_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro'))
print("Correct labels: ", cm_correct_labels.shape, cm_correct_labels)
 print("Predicted labels: ", cm_predictions.shape, cm_predictions)
 plt.plot(scores)
 best_alpha = np.argmax(scores)/100
cm_probabilities = best_alpha*m1+(1-best_alpha)*m2
cm_predictions = np.argmax(cm_probabilities, axis=-1)
<find_best_params>
train_scaled = preprocessing.scale(train_df_le_dn.drop(["Id"],axis=1))
if using_ensemble_models:
print(best_alpha, max(scores))<predict_on_test>
train_scaled_df = pd.DataFrame(train_scaled)
 train_scaled_df.columns = train_df_le_dn.drop(["Id"],axis=1 ).columns
if using_ensemble_models:
test_ds = get_test_dataset(ordered=True)
 print('Computing predictions...')
 test_images_ds = test_ds.map(lambda image, idnum: image)
 probabilities1 = model_EB7.predict(test_images_ds)
 probabilities2 = model_D201.predict(test_images_ds)
 probabilities = best_alpha * probabilities1 +(1 - best_alpha)* probabilities2
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<find_best_model_class>
from sklearn.cluster import KMeans
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()
if using_ensemble_models:
print('using_ensemble_models')
 probabilities1 = model_EB7.predict(images_ds)
 probabilities2 = model_D201.predict(images_ds)
 cm_probabilities = best_alpha * probabilities1 +(1 - best_alpha)* probabilities2
else:
cm_probabilities = model.predict(images_ds)
 cm_predictions = np.argmax(cm_probabilities, axis=-1)
 labels = range(len(CLASSES))
cmat = confusion_matrix(
 cm_correct_labels,
cm_predictions,
labels=labels, 
)
 cmat =(cmat.T / cmat.sum(axis=1)).T<compute_train_metric>
np.random.seed(1234 )
score = f1_score(
 cm_correct_labels,
cm_predictions,
labels=labels,
average='macro', 
)
 precision = precision_score(
 cm_correct_labels,
cm_predictions,
labels=labels,
average='macro', 
)
 recall = recall_score(
 cm_correct_labels,
cm_predictions,
labels=labels,
average='macro', 
)
 display_confusion_matrix(cmat, score, precision, recall )<create_dataframe>
house_cluster = KMeans(n_clusters=4 ).fit_predict(train_scaled )
model_performance_report = pd.DataFrame(columns=['model-family', 'model', 'epochs', 'arg min loss', 'arg max accuracy',
'min loss', 'max accuracy', 'f1', 'precision', 'recall'])
 model_performance_report.loc[len(model_performance_report)]={ 'model-family': 'VGG',
'model':'VGG16',
'epochs':12,
'arg min loss':11,
'arg max accuracy':11,
'min loss':3.47,
'max accuracy':0.23,
'f1':0.123,
'precision':0.146,
'recall':0.226}
model_performance_report.loc[len(model_performance_report)]={ 'model-family': 'DenseNet',
'model':'DenseNet201',
'epochs':12,
'arg min loss':11,
'arg max accuracy':10,
'min loss':1.31,
'max accuracy':0.74,
'f1':0.643,
'precision':0.761,
'recall':0.599}
model_performance_report.loc[len(model_performance_report)]={ 'model-family':'InceptionResNet',
'model':'InceptionResNetV2',
'epochs':12,
'arg min loss':11,
'arg max accuracy':11,
'min loss':1.57,
'max accuracy':0.66,
'f1':0.513,
'precision':0.640,
'recall':0.480}
model_performance_report.loc[len(model_performance_report)]={ 'model-family':'Inception',
'model':'InceptionV3',
'epochs':12,
'arg min loss':11,
'arg max accuracy':11,
'min loss':1.48,
'max accuracy':0.69,
'f1':0.581,
'precision':0.728,
'recall':0.538}
model_performance_report.loc[len(model_performance_report)]={ 'model-family':'MobileNet',
'model':'MobileNet',
'epochs':12,
'arg min loss':11,
'arg max accuracy':10,
'min loss':1.11,
'max accuracy':0.76,
'f1':0.717,
'precision':0.798,
'recall':0.679}
model_performance_report.loc[len(model_performance_report)]={ 'model-family':'MobileNet',
'model':'MobileNetV2',
'epochs':12,
'arg min loss':11,
'arg max accuracy':11,
'min loss':1.26,
'max accuracy':0.72,
'f1':0.650,
'precision':0.763,
'recall':0.606}
model_performance_report.loc[len(model_performance_report)]={ 'model-family':'NASNetMobile',
'model':'NASNetMobile',
'epochs':12,
'arg min loss':11,
'arg max accuracy':11,
'min loss':2.69,
'max accuracy':0.38,
'f1':0.224,
'precision':0.401,
'recall':0.203}
model_performance_report.loc[len(model_performance_report)]={ 'model-family':'ResNet',
'model':'ResNet50',
'epochs':12,
'arg min loss':11,
'arg max accuracy':11,
'min loss':3.85,
'max accuracy':0.12,
'f1':0.017,
'precision':0.035,
'recall':0.025}
model_performance_report.loc[len(model_performance_report)]={ 'model-family':'ResNet',
'model':'R101V2',
'epochs':12,
'arg min loss':11,
'arg max accuracy':9,
'min loss':0.87,
'max accuracy':0.83,
'f1':0.775,
'precision':0.842,
'recall':0.741}
model_performance_report.loc[len(model_performance_report)]={ 'model-family':'VGG',
'model':'VGG19',
'epochs':12,
'arg min loss':11,
'arg max accuracy':11,
'min loss':3.58,
'max accuracy':0.21,
'f1':0.031,
'precision':0.036,
'recall':0.048}
model_performance_report.loc[len(model_performance_report)]={ 'model-family':'Xception',
'model':'Xception',
'epochs':12,
'arg min loss':11,
'arg max accuracy':11,
'min loss':1.43,
'max accuracy':0.71,
'f1':0.575,
'precision':0.712,
'recall':0.536}
model_performance_report.loc[len(model_performance_report)]={ 'model-family':'ResNet',
'model':'R2 30e',
'epochs':30,
'arg min loss':29,
'arg max accuracy':28,
'min loss':0.83,
'max accuracy':0.83,
'f1':0.788,
'precision':0.863,
'recall':0.753}
model_performance_report.loc[len(model_performance_report)]={ 'model-family':'ResNet',
'model':'R101V2 1,2,3+OF',
'epochs':30,
'arg min loss':26,
'arg max accuracy':27,
'min loss':0.52,
'max accuracy':0.88,
'f1':0.864,
'precision':0.916,
'recall':0.842}
model_performance_report.loc[len(model_performance_report)]={ 'model-family':'DenseNet',
'model':'D 1,2',
'epochs':30,
'arg min loss':29,
'arg max accuracy':29,
'min loss':0.92,
'max accuracy':0.81,
'f1':0.767,
'precision':0.833,
'recall':0.732}
model_performance_report.loc[len(model_performance_report)]={ 'model-family':'DenseNet',
'model':'D201 1,2,4',
'epochs':30,
'arg min loss':29,
'arg max accuracy':27,
'min loss':0.92,
'max accuracy':0.82,
'f1':0.772,
'precision':0.846,
'recall':0.734}
model_performance_report.loc[len(model_performance_report)]={ 'model-family':'ResNet',
'model':'R101V2 1,2,4',
'epochs':30,
'arg min loss':29,
'arg max accuracy':28,
'min loss':0.66,
'max accuracy':0.85,
'f1':0.829,
'precision':0.870,
'recall':0.802}
model_performance_report.loc[len(model_performance_report)]={ 'model-family':'ResNet',
'model':'R101V2 1,2,4,5',
'epochs':30,
'arg min loss':29,
'arg max accuracy':23,
'min loss':0.66,
'max accuracy':0.86,
'f1':0.829,
'precision':0.883,
'recall':0.802}
model_performance_report.loc[len(model_performance_report)]={ 'model-family':'DenseNet',
'model':'D 1,8',
'epochs':30,
'arg min loss':26,
'arg max accuracy':28,
'min loss':0.23,
'max accuracy':0.95,
'f1':0.945,
'precision':0.950,
'recall':0.946}
model_performance_report.loc[len(model_performance_report)]={ 'model-family':'ResNet',
'model':'R101V2 1,8',
'epochs':30,
'arg min loss':10,
'arg max accuracy':16,
'min loss':0.36,
'max accuracy':0.92,
'f1':0.909,
'precision':0.913,
'recall':0.911}
model_performance_report.loc[len(model_performance_report)]={ 'model-family':'ResNet',
'model':'D 1,2,8',
'epochs':30,
'arg min loss':10,
'arg max accuracy':11,
'min loss':0.21,
'max accuracy':0.95,
'f1':0.953,
'precision':0.960,
'recall':0.950}
model_performance_report.loc[len(model_performance_report)]={ 'model-family':'EfficientNet',
'model':'EB7 1,2,9,10',
'epochs':30,
'arg min loss':29,
'arg max accuracy':27,
'min loss':0.73,
'max accuracy':0.84,
'f1':0.779,
'precision':0.839,
'recall':0.755}
model_performance_report.loc[len(model_performance_report)]={ 'model-family':'EfficientNet',
'model':'EB7 +11',
'epochs':30,
'arg min loss':29,
'arg max accuracy':28,
'min loss':1.0,
'max accuracy':0.81,
'f1':0.775,
'precision':0.769,
'recall':0.821}
model_performance_report.loc[len(model_performance_report)]={ 'model-family':'EfficientNet',
'model':'EB7 1,2,8,9,10,11',
'epochs':30,
'arg min loss':15,
'arg max accuracy':18,
'min loss':0.25,
'max accuracy':0.96,
'f1':0.955,
'precision':0.950,
'recall':0.964}
model_performance_report.loc[len(model_performance_report)]={ 'model-family':'ResNet',
'model':'D 1,2,8,11',
'epochs':30,
'arg min loss':24,
'arg max accuracy':23,
'min loss':0.22,
'max accuracy':0.95,
'f1':0.956,
'precision':0.957,
'recall':0.958}
model_performance_report.loc[len(model_performance_report)]={ 'model-family':'Ensemble',
'model':'Ensemble EB7+D201',
'epochs':30,
'arg min loss':24,
'arg max accuracy':23,
'min loss':0.22,
'max accuracy':0.95,
'f1':0.962,
'precision':0.960,
'recall':0.966}
extra_columns = ['total params', 'trainable params', 'non-trainable params','training time per epoch(sec)']
model_performance_report[extra_columns] = pd.DataFrame([[np.nan, np.nan, np.nan, np.nan]], index=model_performance_report.index)
 model_performance_report.loc[len(model_performance_report)]={ 'model-family':'DenseNet',
'model':'D 1,2,6',
'total params':18_521_768,
'trainable params':199_784,
'non-trainable params':18_321_984,
'training time per epoch(sec)':114,
'epochs':30,
'arg min loss':29,
'arg max accuracy':29,
'min loss':0.71,
'max accuracy':0.85,
'f1':0.826,
'precision':0.791,
'recall':0.890}
model_performance_report.loc[len(model_performance_report)]={ 'model-family':'DenseNet',
'model':'D 1,2,6,12',
'total params':18_521_768,
'trainable params':199_784,
'non-trainable params':18_321_984,
'training time per epoch(sec)':114,
'epochs':30,
'arg min loss':29,
'arg max accuracy':29,
'min loss':0.71,
'max accuracy':0.85,
'f1':0.826,
'precision':0.791,
'recall':0.890}
model_performance_report.loc[len(model_performance_report)]={ 'model-family':'DenseNet',
'model':'D 1,2,6,8',
'total params':18_521_768,
'trainable params':18_292_712,
'non-trainable params':229_056,
'training time per epoch(sec)':274,
'epochs':30,
'arg min loss':26,
'arg max accuracy':28,
'min loss':0.22,
'max accuracy':0.96,
'f1':0.948,
'precision':0.942,
'recall':0.957}
model_performance_report.loc[len(model_performance_report)]={ 'model-family':'DenseNet',
'model':'D 1,2,6,8,12',
'total params':18_521_768,
'trainable params':18_292_712,
'non-trainable params':229_056,
'training time per epoch(sec)':274,
'epochs':30,
'arg min loss':26,
'arg max accuracy':28,
'min loss':0.22,
'max accuracy':0.96,
'f1':0.948,
'precision':0.942,
'recall':0.957}
model_performance_report.loc[len(model_performance_report)]={ 'model-family':'EfficientNet',
'model':'EB7 1,2,6,8,9,10,11',
'total params':64_364_024,
'trainable params':64_053_304,
'non-trainable params':310_720,
'training time per epoch(sec)':511,
'epochs':30,
'arg min loss':20,
'arg max accuracy':28,
'min loss':0.24,
'max accuracy':0.96,
'f1':0.956,
'precision':0.949,
'recall':0.967}
model_performance_report.loc[len(model_performance_report)]={ 'model-family':'Ensemble',
'model':'Ensemble 6,12 EB7+D201',
'total params':82_885_792,
'trainable params':82_346_016,
'non-trainable params':539_776,
'training time per epoch(sec)':785,
'epochs':30,
'arg min loss':20,
'arg max accuracy':28,
'min loss':0.24,
'max accuracy':0.96,
'f1':0.962,
'precision':0.956,
'recall':0.971}
model_performance_report.loc[len(model_performance_report)]={ 'model-family':'MobileNet',
'model':'MobileNetV2 1,2,6',
'total params':2_391_208,
'trainable params':133_224,
'non-trainable params':2_257_984,
'training time per epoch(sec)':79,
'epochs':30,
'arg min loss':29,
'arg max accuracy':26,
'min loss':0.83,
'max accuracy':0.8,
'f1':0.781,
'precision':0.752,
'recall':0.850}
model_performance_report.loc[len(model_performance_report)]={ 'model-family':'MobileNet',
'model':'MobileNetV2 1,2,6,8',
'total params':2_391_208,
'trainable params':2_357_096,
'non-trainable params':34_112,
'training time per epoch(sec)':102,
'epochs':30,
'arg min loss':24,
'arg max accuracy':27,
'min loss':0.27,
'max accuracy':0.95,
'f1':0.936,
'precision':0.929,
'recall':0.951}<sort_values>
train_scaled_df["km_cluster"] = house_cluster
model_performance_report = model_performance_report.sort_values(by='max accuracy')
 model_performance_report<define_variables>
train_scaled_df["km_cluster"].value_counts()
dataset = get_validation_dataset()
dataset = dataset.unbatch().batch(20)
 batch = iter(dataset )<define_variables>
cluster_mean = train_scaled_df[["km_cluster","SalePrice","TotalSF","OverallQual","Age","Total_Bathrooms","YearRemodAdd","GarageArea",
"MSZoning","OverallCond","KitchenQual","FireplaceQu"]].groupby("km_cluster" ).mean().reset_index()
images, labels = next(batch )<predict_on_test>
cluster_mean = cluster_mean.T
if using_ensemble_models:
probabilities1 = model_EB7.predict(images)
 probabilities2 = model_D201.predict(images)
 probabilities = best_alpha * probabilities1 +(1 - best_alpha)* probabilities2
else:
probabilities = model.predict(images )<groupby>
from sklearn.decomposition import PCA
predictions = np.argmax(probabilities, axis=-1)
 display_batch_of_images(( images, labels), predictions )<train_model>
pca = PCA(n_components=2)
 house_pca = pca.fit(train_scaled ).transform(train_scaled )
mismatches = sum(cm_predictions!=cm_correct_labels)
 print('Number of mismatches on validation data: {} out of {} or({:.2%})'.format(mismatches, NUM_VALIDATION_IMAGES, mismatches/NUM_VALIDATION_IMAGES))<define_variables>
house_pca_df = pd.DataFrame(house_pca)
 house_pca_df.columns = ["pca1","pca2"]
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()
mismatches_images, mismatches_predictions, mismatches_labels = [], [], []
mismatches_dataset = tf.data.Dataset.from_tensors([])
 val_batch = iter(cmdataset.unbatch().batch(1))
for image_index in range(NUM_VALIDATION_IMAGES):
batch = next(val_batch)
 if cm_predictions[image_index] != cm_correct_labels[image_index]:
print('Predicted vs Correct labels: {}, {}'.format(cm_predictions[image_index], cm_correct_labels[image_index])) 
<define_variables>
train_scaled_df = pd.concat([train_scaled_df, house_pca_df], axis=1 )
dataset = get_validation_dataset()
dataset = dataset.unbatch().batch(20)
 batch = iter(dataset)
 images, labels = next(batch )<define_variables>
my_colors = plt.rcParams['axes.prop_cycle'].by_key() ['color']
for i in range(3):
display_batch_of_images(( images, labels), predictions, display_mismatches_only=True)
 images, labels = next(batch )<define_variables>
pca_comp_df = pd.DataFrame(pca.components_,columns=train_scaled_df.drop(["km_cluster","pca1","pca2"],axis=1 ).columns ).T
pca_comp_df.columns = ["pca1","pca2"]
one_batch = next(ds_iter)
 display_batch_of_images(one_batch )<define_variables>
train_df_le.loc[train_df["SalePrice"] >= 278000, "high_class"] = 1
using_tta = False
tta_iterations = 3<categorify>
train_df_le["high_class"] = train_df_le["high_class"].fillna(0 )
if using_tta:
def get_test_dataset(ordered=False):
dataset = load_dataset(TEST_FILENAMES, labeled=False, ordered=ordered)
 dataset = dataset.map(data_augment, num_parallel_calls=AUTO)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.prefetch(AUTO)
 return dataset<predict_on_test>
!pip install pydotplus
def predict_tta(model, tta_iterations):
probs = []
for i in range(tta_iterations):
print('TTA iteration ', i)
 test_ds = get_test_dataset(ordered=True)
 test_images_ds = test_ds.map(lambda image, idnum: image)
 if using_ensemble_models:
print('using_ensemble_models')
 probabilities1 = model_EB7.predict(test_images_ds)
 probabilities2 = model_D201.predict(test_images_ds)
 probabilities = best_alpha * probabilities1 +(1 - best_alpha)* probabilities2
probs.append(probabilities)
 else:
probs.append(model.predict(test_images_ds,verbose=0))
return probs<predict_on_test>
from sklearn import tree
import pydotplus
from six import StringIO
test_ds = get_test_dataset(ordered=True)
 test_images_ds = test_ds.map(lambda image, idnum: image)
 if using_tta:
print('Computing predictions using TTA...')
 probabilities = np.mean(predict_tta(model, tta_iterations), axis=0)
 else:
print('Computing predictions...')
 probabilities = model.predict(test_images_ds)
 predictions = np.argmax(probabilities, axis=-1)
 print(predictions )<save_to_csv>
tree_x = train_df_le[["TotalSF","OverallQual","Age","GrLivArea","GarageCars","Total_Bathrooms","GarageType",
"YearRemodAdd","GarageArea","CentralAir","MSZoning","OverallCond","KitchenQual","FireplaceQu","1stFlrSF"]]
tree_y = train_df_le[["high_class"]]
print('using_ensemble_models:', using_ensemble_models)
 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<install_modules>
clf = tree.DecisionTreeClassifier(max_depth=4)
 clf = clf.fit(tree_x, tree_y )
!pip install -q efficientnet<import_modules>
dot_data = StringIO()
tree.export_graphviz(clf, out_file=dot_data,feature_names=tree_x.columns)
 graph = pydotplus.graph_from_dot_data(dot_data.getvalue() )
<set_options><EOS> 
Image(graph.create_png() )