Kaggle competition: House Prices - Advanced Regression Techniques
<SOS> metric: rmsle Kaggle data source: house-prices-advanced-regression-techniques<install_modules>
!pip install feature_engine
!pip install -q efficientnet<train_model>
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.ensemble import GradientBoostingRegressor, RandomForestRegressor
from sklearn.linear_model import Lasso
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.model_selection import train_test_split, GridSearchCV, KFold
from sklearn.pipeline import Pipeline
from sklearn.tree import DecisionTreeRegressor
from lightgbm import LGBMRegressor
from feature_engine import creation
from feature_engine import discretisation as disc
from feature_engine import encoding as enc
from feature_engine import imputation as imp
from feature_engine import selection as sel
start_time = datetime.now()
print('start time:', start_time)
 print("Tensorflow version " + tf.__version__)
 AUTO = tf.data.experimental.AUTOTUNE
def my_tf_initialize() :
gpus = tf.config.experimental.list_physical_devices('GPU')
 if gpus:
try:
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
 logical_gpus = tf.config.experimental.list_logical_devices('GPU')
 print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPUs")
 except RuntimeError as e:
print(e)
 tf.keras.backend.clear_session()
np.random.seed(42)
 tf.random.set_seed(42)
 try:
tpu = tf.distribute.cluster_resolver.TPUClusterResolver()
print('Running on TPU ', tpu.master())
 except ValueError:
tpu = None
my_tf_initialize()
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)
 MIXED_PRECISION = True
if MIXED_PRECISION:
if tpu:
print('Mixed precision not enabled')
 else:
policy = tf.keras.mixed_precision.experimental.Policy('mixed_float16')
 tf.config.optimizer.set_jit(True)
 tf.keras.mixed_precision.experimental.set_policy(policy)
 print('Mixed precision enabled')
<define_variables>
data = pd.read_csv('/kaggle/input/house-prices-advanced-regression-techniques/train.csv')
 submission = pd.read_csv('/kaggle/input/house-prices-advanced-regression-techniques/test.csv' )
if tpu:
IMAGE_SIZE = [512, 512]
else:
IMAGE_SIZE = [192, 192]
EPOCHS = 20
BATCH_SIZE = 16 * strategy.num_replicas_in_sync
if tpu:
BATCH_SIZE = 16 * strategy.num_replicas_in_sync
else:
BATCH_SIZE = 16 * strategy.num_replicas_in_sync
BATCH_SIZE = 4 * strategy.num_replicas_in_sync
GCS_PATH_SELECT = {
192: GCS_DS_PATH + '/tfrecords-jpeg-192x192',
224: GCS_DS_PATH + '/tfrecords-jpeg-224x224',
331: GCS_DS_PATH + '/tfrecords-jpeg-331x331',
512: GCS_DS_PATH + '/tfrecords-jpeg-512x512'
}
GCS_PATH = GCS_PATH_SELECT[IMAGE_SIZE[0]]
TRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/train/*.tfrec')
 VALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec')
 TEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec')
 CLASSES = ['pink primrose', 'hard-leaved pocket orchid', 'canterbury bells', 'sweet pea', 'wild geranium', 'tiger lily', 'moon orchid', 'bird of paradise', 'monkshood', 'globe thistle',
'snapdragon', "colt's foot", 'king protea', 'spear thistle', 'yellow iris', 'globe-flower', 'purple coneflower', 'peruvian lily', 'balloon flower', 'giant white arum lily',
'fire lily', 'pincushion flower', 'fritillary', 'red ginger', 'grape hyacinth', 'corn poppy', 'prince of wales feathers', 'stemless gentian', 'artichoke', 'sweet william',
'carnation', 'garden phlox', 'love in the mist', 'cosmos', 'alpine sea holly', 'ruby-lipped cattleya', 'cape flower', 'great masterwort', 'siam tulip', 'lenten rose',
'barberton daisy', 'daffodil', 'sword lily', 'poinsettia', 'bolero deep blue', 'wallflower', 'marigold', 'buttercup', 'daisy', 'common dandelion',
'petunia', 'wild pansy', 'primula', 'sunflower', 'lilac hibiscus', 'bishop of llandaff', 'gaura', 'geranium', 'orange dahlia', 'pink-yellow dahlia',
'cautleya spicata', 'japanese anemone', 'black-eyed susan', 'silverbush', 'californian poppy', 'osteospermum', 'spring crocus', 'iris', 'windflower', 'tree poppy',
'gazania', 'azalea', 'water lily', 'rose', 'thorn apple', 'morning glory', 'passion flower', 'lotus', 'toad lily', 'anthurium',
'frangipani', 'clematis', 'hibiscus', 'columbine', 'desert-rose', 'tree mallow', 'magnolia', 'cyclamen ', 'watercress', 'canna lily',
'hippeastrum ', 'bee balm', 'pink quill', 'foxglove', 'bougainvillea', 'camellia', 'mallow', 'mexican petunia', 'bromelia', 'blanket flower',
'trumpet creeper', 'blackberry lily', 'common tulip', 'wild rose']<categorify>
X_train, X_test, y_train, y_test = train_test_split(data.drop(
 ['Id', 'SalePrice'], axis=1),
data['SalePrice'],
test_size=0.05,
random_state=0)
 X_train.shape, X_test.shape
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[np.argmax(label, axis=-1)], True
correct =(label == correct_label)
 return "{} [{}{}{}]".format(CLASSES[np.argmax(label, axis=-1)], 'OK' if correct else 'NO', u"\u2192" if not correct else '',
CLASSES[np.argmax(correct_label, axis=-1)] 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[np.argmax(label, axis=-1)]
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>
id_ = submission['Id']
submission.drop('Id', axis=1, inplace=True)
 submission.shape
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_to_label(image, label):
return label
def data_to_categorical(image, label):
label = tf.one_hot(label, depth=len(CLASSES))
return image, label
def data_augment(image, label):
image = tf.image.random_flip_left_right(image)
 image = tf.image.random_saturation(image, 0, 2)
 return image, label
def element_mixup(a, b):
X_a, y_a = a
X_b, y_b = b
lambda_1 = tf.random.uniform(shape=[], minval=0., maxval=1.)
lambda_2 = tf.math.subtract(tf.constant(1.) , lambda_1)
 X = tf.math.add(tf.math.scalar_mul(lambda_1, X_a), tf.math.scalar_mul(lambda_2, X_b))
y = tf.math.add(tf.math.scalar_mul(lambda_1, y_a), tf.math.scalar_mul(lambda_2, y_b))
return tf.data.Dataset.from_tensors(( X, y))
def dataset_mixup(dataset_a):
dataset_b = dataset_a.shuffle(2048)
 dataset = tf.data.Dataset.zip(( dataset_a, dataset_b))
dataset = dataset.flat_map(lambda a, b: element_mixup(a, b))
return dataset
def get_training_dataset() :
dataset = load_dataset(TRAINING_FILENAMES, labeled=True)
 dataset = dataset.map(data_to_categorical, num_parallel_calls=AUTO)
 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_training_dataset_mixup() :
dataset = load_dataset(TRAINING_FILENAMES, labeled=True)
 dataset = dataset.map(data_to_categorical, num_parallel_calls=AUTO)
 dataset = dataset_mixup(dataset)
 dataset = dataset.repeat()
dataset = dataset.shuffle(2048)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.prefetch(AUTO)
 return dataset
def get_validation_dataset_labels(ordered=False):
dataset = load_dataset(VALIDATION_FILENAMES, labeled=True, ordered=ordered)
 dataset = dataset.map(data_to_label, num_parallel_calls=AUTO)
 dataset = dataset.cache()
dataset = dataset.prefetch(AUTO)
 return dataset
def get_validation_dataset(ordered=False):
dataset = load_dataset(VALIDATION_FILENAMES, labeled=True, ordered=ordered)
 dataset = dataset.map(data_to_categorical, num_parallel_calls=AUTO)
 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))
print("Training data shapes:")
 for image, label in get_training_dataset().take(3):
print(image.numpy().shape, label.numpy().shape)
 print("Training data label examples:", label.numpy())
 print("Validation data shapes:")
 for image, label in get_validation_dataset().take(3):
print(image.numpy().shape, label.numpy().shape)
 print("Validation data label examples:", label.numpy())
 print("Test data shapes:")
 for image, idnum in get_test_dataset().take(3):
print(image.numpy().shape, idnum.numpy().shape)
 print("Test data IDs:", idnum.numpy().astype('U'))
training_dataset = get_training_dataset()
training_dataset = training_dataset.unbatch().batch(20)
 train_batch = iter(training_dataset)
 test_dataset = get_test_dataset()
test_dataset = test_dataset.unbatch().batch(20)
 test_batch = iter(test_dataset)
<normalization>
def create_master_data(train, test, submission, y_train, y_test):
train = train.copy()
test = test.copy()
submission = submission.copy()
train['target'] = y_train
train['data'] = 'train'
train.reset_index(drop=True, inplace=True)
 test['target'] = y_test
test['data'] = 'test'
test.reset_index(drop=True, inplace=True)
 submission['target'] = np.nan
submission['data'] = 'submission'
submission.reset_index(drop=True, inplace=True)
 master_data = pd.concat([train, test, submission], axis=0)
 master_data.reset_index(drop=True, inplace=True)
 return master_data
labels = get_validation_dataset_labels().take(NUM_VALIDATION_IMAGES)
 labels = list(labels.as_numpy_iterator())
 sns.countplot(labels)
 class_weights = class_weight.compute_class_weight('balanced', np.unique(labels), labels)
<define_variables>
y_train = np.log(y_train)
 y_test = np.log(y_test )
display_batch_of_images(next(train_batch))<define_variables>
X_train['HasPool'] = np.where(X_train['PoolArea']>0,1,0)
 X_test['HasPool'] = np.where(X_test['PoolArea']>0,1,0)
 submission['HasPool'] = np.where(submission['PoolArea']>0,1,0)
 X_train['HasAlley'] = np.where(X_train['Alley'].isnull() , 0, 1)
 X_test['HasAlley'] = np.where(X_test['Alley'].isnull() , 0, 1)
 submission['HasAlley'] = np.where(submission['Alley'].isnull() , 0, 1 )
display_batch_of_images(next(test_batch))<choose_model_class>
X_train['Condition_total'] = np.where(X_train['Condition2'] == X_train['Condition1'], 0, 1)
 X_test['Condition_total'] = np.where(X_test['Condition2'] == X_test['Condition1'], 0, 1)
 submission['Condition_total'] = np.where(submission['Condition2'] == submission['Condition1'], 0, 1)
 X_train['Condition_total'].value_counts()
early_stopping_cb = tf.keras.callbacks.EarlyStopping(monitor='val_loss', min_delta=0.01, patience=5, restore_best_weights=True)
 if tpu:
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 =.8
else:
start_lr = 0.00001
min_lr = 0.00001
max_lr = 0.0002
rampup_epochs = 5
sustain_epochs = 0
exp_decay =.8
def lrfn(epoch):
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(lambda epoch: lrfn(epoch), verbose=True)
 rng = [i for i in range(EPOCHS)]
y = [lrfn(x)for x in rng]
plt.plot(rng, [lrfn(x)for x in rng])
 print(y[0], y[-1] )<choose_model_class>
X_train['Exterior_total'] = np.where(X_train['Exterior1st'] == X_train['Exterior2nd'], 0, 1)
 X_test['Exterior_total'] = np.where(X_test['Exterior1st'] == X_test['Exterior2nd'], 0, 1)
 submission['Exterior_total'] = np.where(submission['Exterior1st'] == submission['Exterior2nd'], 0, 1)
 X_train['Exterior_total'].value_counts()
with strategy.scope() :
DefaultConv2D = partial(tf.keras.layers.Conv2D,
kernel_size=3, activation='relu', padding="SAME")
 simple_cnn_model = tf.keras.models.Sequential([
DefaultConv2D(filters=64, kernel_size=7, input_shape=[*IMAGE_SIZE, 3]),
tf.keras.layers.MaxPooling2D(pool_size=2),
DefaultConv2D(filters=128),
DefaultConv2D(filters=128),
tf.keras.layers.MaxPooling2D(pool_size=2),
DefaultConv2D(filters=256),
DefaultConv2D(filters=256),
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation="softmax")
 ])
 simple_cnn_model.compile(
 optimizer='adam',
loss = 'categorical_crossentropy',
metrics=['categorical_accuracy'] 
)
 enetb7_base_model = efntf.EfficientNetB7(weights='imagenet', include_top=False ,input_shape=[*IMAGE_SIZE, 3])
 enetb7_avg = tf.keras.layers.GlobalAveragePooling2D()(enetb7_base_model.output)
 enetb7_output = tf.keras.layers.Dense(len(CLASSES), activation="softmax" )(enetb7_avg)
 enetb7_model = tf.keras.Model(inputs=enetb7_base_model.input, outputs=enetb7_output)
 enetb7_model.trainable = True
enetb7_base_model2 = efntf.EfficientNetB7(weights='imagenet', include_top=False ,input_shape=[*IMAGE_SIZE, 3])
 enetb7_avg2 = tf.keras.layers.GlobalAveragePooling2D()(enetb7_base_model2.output)
 enetb7_output2 = tf.keras.layers.Dense(len(CLASSES), activation="softmax" )(enetb7_avg2)
 enetb7_model2 = tf.keras.Model(inputs=enetb7_base_model2.input, outputs=enetb7_output2)
 enetb7_model2.trainable = True
dense201_base_model = tf.keras.applications.densenet.DenseNet201(weights='imagenet', include_top=False ,input_shape=[*IMAGE_SIZE, 3])
 dense201_avg = tf.keras.layers.GlobalAveragePooling2D()(dense201_base_model.output)
 dense201_output = tf.keras.layers.Dense(len(CLASSES), activation="softmax" )(dense201_avg)
 dense201_model = tf.keras.Model(inputs=dense201_base_model.input, outputs=dense201_output)
 dense201_model.trainable = True
dense201_base_model2 = tf.keras.applications.densenet.DenseNet201(weights='imagenet', include_top=False ,input_shape=[*IMAGE_SIZE, 3])
 dense201_avg2 = tf.keras.layers.GlobalAveragePooling2D()(dense201_base_model2.output)
 dense201_output2 = tf.keras.layers.Dense(len(CLASSES), activation="softmax" )(dense201_avg2)
 dense201_model2 = tf.keras.Model(inputs=dense201_base_model2.input, outputs=dense201_output2)
 dense201_model2.trainable = True
enetb7_model.compile(
 optimizer='adam',
loss = 'categorical_crossentropy',
metrics=['categorical_accuracy'] 
)
 enetb7_model2.compile(
 optimizer='adam',
loss = 'categorical_crossentropy',
metrics=['categorical_accuracy'] 
)
 dense201_model.compile(
 optimizer='adam',
loss = 'categorical_crossentropy',
metrics=['categorical_accuracy'] 
)
 dense201_model2.compile(
 optimizer='adam',
loss = 'categorical_crossentropy',
metrics=['categorical_accuracy'] 
)
<train_model>
categorical = [var for var in data.columns if data[var].dtype == 'O']
categorical = categorical + ['MSSubClass']
len(categorical )
model = enetb7_model
history = model.fit(get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH, epochs=EPOCHS,
validation_data=get_validation_dataset() ,
callbacks=[early_stopping_cb, lr_callback])
 display_training_curves(history.history['loss'], history.history['val_loss'], 'loss', 211)
 display_training_curves(history.history['categorical_accuracy'], history.history['val_categorical_accuracy'], 'accuracy', 212)
 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_correct_labels = np.argmax(cm_correct_labels, axis=-1)
 cm_probabilities = model.predict(images_ds)
 cm_predictions = np.argmax(cm_probabilities, axis=-1)
 print("Correct labels: ", cm_correct_labels.shape, cm_correct_labels)
 print("Predicted labels: ", cm_predictions.shape, cm_predictions)
 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')
 cmat =(cmat.T / cmat.sum(axis=1)).T
display_confusion_matrix(cmat, score, precision, recall)
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score, precision, recall))<train_model>
X_train[categorical] = X_train[categorical].astype('O')
 X_test[categorical] = X_test[categorical].astype('O')
 submission[categorical] = submission[categorical].astype('O' )
model = dense201_model
history = model.fit(get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH, epochs=EPOCHS,
validation_data=get_validation_dataset() ,
callbacks=[early_stopping_cb, lr_callback])
 display_training_curves(history.history['loss'], history.history['val_loss'], 'loss', 211)
 display_training_curves(history.history['categorical_accuracy'], history.history['val_categorical_accuracy'], 'accuracy', 212)
 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_correct_labels = np.argmax(cm_correct_labels, axis=-1)
 cm_probabilities = model.predict(images_ds)
 cm_predictions = np.argmax(cm_probabilities, axis=-1)
 print("Correct labels: ", cm_correct_labels.shape, cm_correct_labels)
 print("Predicted labels: ", cm_predictions.shape, cm_predictions)
 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')
 cmat =(cmat.T / cmat.sum(axis=1)).T
display_confusion_matrix(cmat, score, precision, recall)
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score, precision, recall))<train_model>
drop_features = sel.DropFeatures(features_to_drop = ['Alley', 'MiscFeature', 'PoolQC'])
 X_train = drop_features.fit_transform(X_train)
 X_test = drop_features.transform(X_test)
 submission = drop_features.transform(submission)
 X_train.shape, X_test.shape, submission.shape
model = dense201_model2
history = model.fit(get_training_dataset_mixup() ,
steps_per_epoch=STEPS_PER_EPOCH, epochs=EPOCHS,
validation_data=get_validation_dataset() ,
callbacks=[early_stopping_cb, lr_callback])
 display_training_curves(history.history['loss'], history.history['val_loss'], 'loss', 211)
 display_training_curves(history.history['categorical_accuracy'], history.history['val_categorical_accuracy'], 'accuracy', 212)
 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_correct_labels = np.argmax(cm_correct_labels, axis=-1)
 cm_probabilities = model.predict(images_ds)
 cm_predictions = np.argmax(cm_probabilities, axis=-1)
 print("Correct labels: ", cm_correct_labels.shape, cm_correct_labels)
 print("Predicted labels: ", cm_predictions.shape, cm_predictions)
 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')
 cmat =(cmat.T / cmat.sum(axis=1)).T
display_confusion_matrix(cmat, score, precision, recall)
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score, precision, recall))<predict_on_test>
cat_imputer = imp.CategoricalImputer(return_object=True)
 cat_imputer.fit(X_train)
 cat_imputer.variables[0:10]
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_correct_labels = np.argmax(cm_correct_labels, axis=-1)
 enetb7_modelcm_probabilities = enetb7_model.predict(images_ds)
 enetb7_model2cm_probabilities = enetb7_model2.predict(images_ds)
 dense201_modelcm_probabilities = dense201_model.predict(images_ds)
 dense201_model2cm_probabilities = dense201_model2.predict(images_ds)
 cm_probabilities = enetb7_modelcm_probabilities + enetb7_model2cm_probabilities + dense201_modelcm_probabilities + dense201_model2cm_probabilities
cm_predictions = np.argmax(cm_probabilities, axis=-1)
 print("Correct labels: ", cm_correct_labels.shape, cm_correct_labels)
 print("Predicted labels: ", cm_predictions.shape, cm_predictions)
 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')
 cmat =(cmat.T / cmat.sum(axis=1)).T
display_confusion_matrix(cmat, score, precision, recall)
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score, precision, recall))
print('run time: ', datetime.now() - start_time )<predict_on_test>
len(cat_imputer.variables )
test_ds = get_test_dataset(ordered=True)
 print('Computing predictions...')
 test_images_ds = test_ds.map(lambda image, idnum: image)
 enetb7_modelcm_probabilities = enetb7_model.predict(test_images_ds)
 enetb7_model2cm_probabilities = enetb7_model2.predict(test_images_ds)
 dense201_modelcm_probabilities = dense201_model.predict(test_images_ds)
 dense201_model2cm_probabilities = dense201_model2.predict(test_images_ds)
 probabilities = enetb7_modelcm_probabilities + enetb7_model2cm_probabilities + dense201_modelcm_probabilities + dense201_model2cm_probabilities
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='')
 with open('submission.csv')as myfile:
head = [next(myfile)for x in range(10)]
print(head )<install_modules>
X_train = cat_imputer.transform(X_train)
 X_test = cat_imputer.transform(X_test)
 submission = cat_imputer.transform(submission)
 X_train.shape, X_test.shape, submission.shape
!pip install -q efficientnet<set_options>
[c for c in cat_imputer.variables if X_train[c].isnull().sum() >0]
print('TensorFlow version', tf.__version__)
 AUTO = tf.data.experimental.AUTOTUNE<define_variables>
categorical = cat_imputer.variables
len(categorical )
start_time = datetime.now()
print('Time now is', start_time)
 end_training_by_tdelta = timedelta(seconds=8400)
 this_run_file_prefix = start_time.strftime('%Y%m%d_%H%M_')
 print(this_run_file_prefix)
 IMAGE_SIZE = [512, 512]
BATCH_SIZE = 16 * strategy.num_replicas_in_sync
GCS_PATH_SELECT = {
192: GCS_DS_PATH + '/tfrecords-jpeg-192x192',
224: GCS_DS_PATH + '/tfrecords-jpeg-224x224',
331: GCS_DS_PATH + '/tfrecords-jpeg-331x331',
512: GCS_DS_PATH + '/tfrecords-jpeg-512x512'
}
GCS_PATH = GCS_PATH_SELECT[IMAGE_SIZE[0]]
TRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/train/*.tfrec')
 VALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec')
 TEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec')
 MOREIMAGES_PATH_SELECT = {
192: '/tfrecords-jpeg-192x192',
224: '/tfrecords-jpeg-224x224',
331: '/tfrecords-jpeg-331x331',
512: '/tfrecords-jpeg-512x512'
}
MOREIMAGES_PATH = MOREIMAGES_PATH_SELECT[IMAGE_SIZE[0]]
IMAGENET_FILES = tf.io.gfile.glob(MORE_IMAGES_GCS_DS_PATH + '/imagenet' + MOREIMAGES_PATH + '/*.tfrec')
 INATURELIST_FILES = tf.io.gfile.glob(MORE_IMAGES_GCS_DS_PATH + '/inaturalist' + MOREIMAGES_PATH + '/*.tfrec')
 OPENIMAGE_FILES = tf.io.gfile.glob(MORE_IMAGES_GCS_DS_PATH + '/openimage' + MOREIMAGES_PATH + '/*.tfrec')
 OXFORD_FILES = tf.io.gfile.glob(MORE_IMAGES_GCS_DS_PATH + '/oxford_102' + MOREIMAGES_PATH + '/*.tfrec')
 TENSORFLOW_FILES = tf.io.gfile.glob(MORE_IMAGES_GCS_DS_PATH + '/tf_flowers' + MOREIMAGES_PATH + '/*.tfrec')
 ADDITIONAL_TRAINING_FILENAMES = IMAGENET_FILES + INATURELIST_FILES + OPENIMAGE_FILES + OXFORD_FILES + TENSORFLOW_FILES
print('----')
 TRAINING_FILENAMES = TRAINING_FILENAMES + ADDITIONAL_TRAINING_FILENAMES
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']<choose_model_class>
constant = sel.DropConstantFeatures(tol=0.94, variables=categorical)
 constant.fit(X_train)
 constant.features_to_drop_
LR_START = 0.00001
LR_MAX = 0.00005 * strategy.num_replicas_in_sync
LR_MIN = LR_START
LR_RAMPUP_EPOCHS = 5
LR_SUSTAIN_EPOCHS = 0
LR_EXP_DECAY = 0.80
def lrfn(epoch):
if epoch < LR_RAMPUP_EPOCHS:
lr = LR_START +(epoch *(LR_MAX - LR_START)/ LR_RAMPUP_EPOCHS)
 elif epoch <(LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS):
lr = LR_MAX
else:
lr = LR_MIN +(LR_MAX - LR_MIN)* LR_EXP_DECAY **(epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS)
 return lr
lr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose = True)
 rng = [i for i in range(20)]
y = [lrfn(x)for x in rng]
print(y )<categorify>
data = create_master_data(X_train, X_test, submission, y_train, y_test)
 data.shape
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>
rare_enc = enc.RareLabelEncoder(tol = 0.1,
n_categories=1,
variables=constant.features_to_drop_,
replace_with='Other', 
)
 rare_enc.fit(X_train )
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 = tf.image.random_saturation(image, 0, 2)
 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>
X_train = rare_enc.transform(X_train)
 X_test = rare_enc.transform(X_test)
 submission = rare_enc.transform(submission )
training_dataset = get_training_dataset()
training_dataset = training_dataset.unbatch().batch(20)
 train_batch = iter(training_dataset)
<create_dataframe>
qual_mappings = {'Po': 1, 'Fa': 2, 'TA': 3, 'Gd': 4, 'Ex': 5, 'Missing': 0, 'NA': 0}
qual_vars = ['ExterQual', 'ExterCond', 'BsmtQual', 'BsmtCond',
'HeatingQC', 'KitchenQual', 'FireplaceQu',
'GarageQual', 'GarageCond',
]
for var in qual_vars:
X_train[var] = X_train[var].map(qual_mappings)
 X_test[var] = X_test[var].map(qual_mappings)
 submission[var] = submission[var].map(qual_mappings )
test_dataset = get_test_dataset()
test_dataset = test_dataset.unbatch().batch(20)
 test_batch = iter(test_dataset)
<choose_model_class>
exposure_mappings = {'No': 1, 'Mn': 2, 'Av': 3, 'Gd': 4, 'Missing': 0, 'NA': 0}
var = 'BsmtExposure'
X_train[var] = X_train[var].map(exposure_mappings)
 X_test[var] = X_test[var].map(exposure_mappings)
 submission[var] = submission[var].map(exposure_mappings )
early_stop = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=20, restore_best_weights = True )<choose_model_class>
finish_mappings = {'Missing': 0, 'NA': 0, 'Unf': 1, 'LwQ': 2, 'Rec': 3, 'BLQ': 4, 'ALQ': 5, 'GLQ': 6}
finish_vars = ['BsmtFinType1', 'BsmtFinType2']
for var in finish_vars:
X_train[var] = X_train[var].map(finish_mappings)
 X_test[var] = X_test[var].map(finish_mappings)
 submission[var] = submission[var].map(finish_mappings )
def create_VGG16_model() :
pretrained_model = tf.keras.applications.VGG16(weights = 'imagenet', include_top = False, 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')
 ])
 model.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics = ['sparse_categorical_accuracy'])
 return model<choose_model_class>
garage_mappings = {'Missing': 0, 'NA': 0, 'Unf': 1, 'RFn': 2, 'Fin': 3}
var = 'GarageFinish'
X_train[var] = X_train[var].map(garage_mappings)
 X_test[var] = X_test[var].map(garage_mappings)
 submission[var] = submission[var].map(garage_mappings )
def create_Xception_model() :
pretrained_model = tf.keras.applications.Xception(include_top = False, 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')
 ])
 model.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics = ['sparse_categorical_accuracy'])
 return model<choose_model_class>
fence_mappings = {'Missing': 0, 'NA': 0, 'MnWw': 1, 'GdWo': 2, 'MnPrv': 3, 'GdPrv': 4}
var = 'Fence'
X_train[var] = X_train[var].map(fence_mappings)
 X_test[var] = X_test[var].map(fence_mappings)
 submission[var] = submission[var].map(fence_mappings )
def create_DenseNet_model() :
pretrained_model = tf.keras.applications.DenseNet201(weights = 'imagenet', include_top = False, 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')
 ])
 model.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics = ['sparse_categorical_accuracy'])
 return model<choose_model_class>
qual_vars = qual_vars + finish_vars + ['BsmtExposure','GarageFinish','Fence']
def create_EfficientNet_model() :
pretrained_model = efficientnet.EfficientNetB7(weights = 'noisy-student', include_top = False, 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')
 ])
 model.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics = ['sparse_categorical_accuracy'])
 return model<choose_model_class>
categorical = [c for c in categorical if c not in constant.features_to_drop_]
categorical = [c for c in categorical if c not in qual_vars]
len(categorical )
def create_InceptionV3_model() :
pretrained_model = tf.keras.applications.InceptionV3(weights = 'imagenet', include_top = False, 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')
 ])
 model.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics = ['sparse_categorical_accuracy'])
 return model<choose_model_class>
def calculate_mean_target_per_category(df, var):
df = pd.concat([df, y_train], axis=1)
 total_houses = len(df)
 temp_df = pd.Series(df[var].value_counts() / total_houses ).reset_index()
temp_df.columns = [var, 'perc_houses']
temp_df = temp_df.merge(df.groupby([var])['SalePrice'].mean().reset_index() ,
on=var,
how='left')
 return temp_df
def create_ResNet152_model() :
pretrained_model = tf.keras.applications.ResNet152V2(weights = 'imagenet', include_top = False, 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')
 ])
 model.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics = ['sparse_categorical_accuracy'])
 return model<choose_model_class>
temp_df = calculate_mean_target_per_category(X_train, 'Neighborhood')
 temp_df.head()
def create_MobileNetV2_model() :
pretrained_model = tf.keras.applications.MobileNetV2(weights = 'imagenet', include_top = False, 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')
 ])
 model.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics = ['sparse_categorical_accuracy'])
 return model<choose_model_class>
X_train['Neigh_Price'] = np.where(X_train['Neighborhood'].isin(cheap_neighbourhoods),
0, np.where(X_train['Neighborhood'].isin(expensive_neighbourhoods),
2, 1))
X_test['Neigh_Price'] = np.where(X_test['Neighborhood'].isin(cheap_neighbourhoods),
0, np.where(X_test['Neighborhood'].isin(expensive_neighbourhoods),
2, 1))
submission['Neigh_Price'] = np.where(submission['Neighborhood'].isin(cheap_neighbourhoods),
0, np.where(submission['Neighborhood'].isin(expensive_neighbourhoods),
2, 1))
X_train['Neigh_Price'].value_counts()
def create_InceptionResNetV2_model() :
pretrained_model = tf.keras.applications.InceptionResNetV2(weights = 'imagenet', include_top = False, 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')
 ])
 model.compile(optimizer = 'adam', loss = 'sparse_categorical_crossentropy', metrics = ['sparse_categorical_accuracy'])
 return model<define_variables>
rare_enc = enc.RareLabelEncoder(tol = 0.05,
n_categories=4,
variables=categorical 
)
 rare_enc.fit(X_train )
<categorify>
X_train = rare_enc.transform(X_train)
 X_test = rare_enc.transform(X_test)
 submission = rare_enc.transform(submission)
 X_train.shape, X_test.shape, submission.shape
class TimeCallback(tf.keras.callbacks.Callback):
def on_epoch_end(self, epoch, logs={}):
if(( datetime.now() - start_time ).total_seconds() > 9500):
self.model.stop_training = True
time_callback = TimeCallback()<train_model>
data = create_master_data(X_train, X_test, submission, y_train, y_test )
%%time
EPOCHS = 30
print('LR_EXP_DECAY:', LR_EXP_DECAY, '.LR_MAX:', LR_MAX)
 history = model.fit(get_training_dataset() , steps_per_epoch = STEPS_PER_EPOCH, epochs = EPOCHS, validation_data = get_validation_dataset() , callbacks = [lr_callback, early_stop, time_callback] )<categorify>
selector = sel.SelectByTargetMeanPerformance(
 variables=categorical,
scoring='r2_score',
threshold=0.1,
cv=2,
random_state=0)
 selector.fit(X_train, y_train )
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()<define_variables>
len(selector.features_to_drop_ )
%%time
test_ds = get_test_dataset(ordered = True)
 test_images_ds = test_ds.map(lambda image, idnum: image)
 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' )<predict_on_test>
X_train = selector.transform(X_train)
 X_test = selector.transform(X_test)
 submission = selector.transform(submission)
 X_train.shape, X_test.shape, submission.shape
val_probabilities = model.predict(images_ds)
 np.save(model_name + '_val_probabilities', val_probabilities)
 cm_predictions = np.argmax(val_probabilities, axis = -1)
 print('Correct labels: ', cm_correct_labels.shape, cm_correct_labels)
 print('Predicted labels: ', cm_predictions.shape, cm_predictions )<compute_train_metric>
categorical = [var for var in X_train.columns if X_train[var].dtype == 'O']
categorical = categorical + ['MSSubClass']
len(categorical)
def getFitPrecisionRecall(correct_labels, predictions):
score = f1_score(correct_labels, predictions, labels = range(len(CLASSES)) , average = 'macro')
 precision = precision_score(correct_labels, predictions, labels = range(len(CLASSES)) , average = 'macro')
 recall = recall_score(correct_labels, predictions, labels = range(len(CLASSES)) , average = 'macro')
 return score, precision, recall 
<compute_test_metric>
X_train[categorical] = X_train[categorical].astype('O')
 X_test[categorical] = X_test[categorical].astype('O')
 submission[categorical] = submission[categorical].astype('O' )
cmat = confusion_matrix(cm_correct_labels, cm_predictions, labels = range(len(CLASSES)))
 score, precision, recall = getFitPrecisionRecall(cm_correct_labels, cm_predictions)
 cmat =(cmat.T / cmat.sum(axis = -1)).T
display_confusion_matrix(cmat, score, precision, recall)
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score, precision, recall))<define_variables>
encoder = enc.OrdinalEncoder(encoding_method='ordered',
variables=categorical)
 encoder.fit(X_train, y_train )
def create_submission_file(filename, probabilities):
predictions = np.argmax(probabilities, axis = -1)
 print('Generating submission file...', filename)
 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(filename, np.rec.fromarrays([test_ids, predictions]), fmt = ['%s', '%d'], delimiter = ',', header = 'id,label', comments = '')
<save_to_csv>
encoder.encoder_dict_
%%time
test_probabilities_no_val = model.predict(test_images_ds)
 create_submission_file('submission_no_val.csv', test_probabilities_no_val )<train_model>
X_train = encoder.transform(X_train)
 X_test = encoder.transform(X_test)
 submission = encoder.transform(submission)
 X_train.shape, X_test.shape, submission.shape
%%time
print('LR_EXP_DECAY:', LR_EXP_DECAY, '.LR_MAX:', LR_MAX)
 model.fit(get_validation_dataset() , steps_per_epoch = STEPS_PER_EPOCH, epochs = 25, callbacks = [lr_callback] )<define_variables>
[c for c in categorical if X_train[c].isnull().sum() >0]
%%time
test_probabilities = model.predict(test_images_ds)
 create_submission_file('submission.csv', test_probabilities )<load_pretrained>
[c for c in categorical if X_test[c].isnull().sum() >0]
pklfile = open(model_name + '_test_probs_with_val.pkl', 'ab')
 pickle.dump(dict(zip(test_ids, test_probabilities)) , pklfile)
 pklfile.close()<load_pretrained>
[c for c in categorical if submission[c].isnull().sum() >0]
model.save_weights(model_name + '_weights.h5' )<install_modules>
year_vars = [var for var in data.columns if 'Yr' in var or 'Year' in var]
year_vars
!pip install -q efficientnet<import_modules>
data = create_master_data(X_train, X_test, submission, y_train, y_test )
print("Tensorflow version " + tf.__version__)
 AUTO = tf.data.experimental.AUTOTUNE<set_options>
create = creation.CombineWithReferenceFeature(
 variables_to_combine = ['YrSold'],
reference_variables = ['YearBuilt', 'YearRemodAdd', 'GarageYrBlt'],
operations=['sub'], 
)
 create.fit(X_train )
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>
X_train = create.transform(X_train)
 X_test = create.transform(X_test)
 submission = create.transform(submission)
 X_train.shape, X_test.shape, submission.shape
GCS_DS_PATH = KaggleDatasets().get_gcs_path('flower-classification' )<define_variables>
remodelled = creation.CombineWithReferenceFeature(
 variables_to_combine = ['YearRemodAdd'],
reference_variables = ['YearBuilt'],
operations=['sub'], 
)
 remodelled.fit(X_train )
EXT_DS_PATH = KaggleDatasets().get_gcs_path('tf-flower-photo-tfrec' )<define_variables>
X_train = remodelled.transform(X_train)
 X_test = remodelled.transform(X_test)
 submission = remodelled.transform(submission)
 X_train.shape, X_test.shape, submission.shape
USE_EXTERNAL = False
SKIP_VALIDATION = True
if tpu:
SIZE = 512
else:
SIZE = 192
IMAGE_SIZE = [SIZE, SIZE]
EPOCHS = 18
BATCH_SIZE = 16 * strategy.num_replicas_in_sync
AUG_BATCH = BATCH_SIZE<define_variables>
drop_features = sel.DropFeatures(features_to_drop =['YearBuilt', 'YearRemodAdd', 'GarageYrBlt','YrSold'])
 X_train = drop_features.fit_transform(X_train)
 X_test = drop_features.transform(X_test)
 submission = drop_features.transform(submission)
 X_train.shape, X_test.shape, submission.shape
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'
} 
<define_variables>
X_train[[
'YrSold_sub_YearBuilt', 'YrSold_sub_YearRemodAdd' ,'YrSold_sub_GarageYrBlt', 'YearRemodAdd_sub_YearBuilt']
].isnull().mean()
def get_filenames(size):
path = GCS_PATH_SELECT[size]
train_filenames = tf.io.gfile.glob(path + '/train/*.tfrec')
 valid_filenames = tf.io.gfile.glob(path + '/val/*.tfrec')
 test_filenames = tf.io.gfile.glob(path + '/test/*.tfrec')
 return train_filenames, valid_filenames, test_filenames<define_variables>
X_test[[
'YrSold_sub_YearBuilt', 'YrSold_sub_YearRemodAdd' ,'YrSold_sub_GarageYrBlt', 'YearRemodAdd_sub_YearBuilt']
].isnull().mean()
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']<categorify>
submission[[
'YrSold_sub_YearBuilt', 'YrSold_sub_YearRemodAdd' ,'YrSold_sub_GarageYrBlt', 'YearRemodAdd_sub_YearBuilt']
].isnull().mean()
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])) :
if label is None:
title = ''
elif isinstance(label, int):
title = CLASSES[label]
else:
idx = np.argmax(label, axis=0)
 title = CLASSES[idx]
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>
discrete = [
var for var in X_train.columns if X_train[var].dtype != 'O'
and var not in year_vars
and var not in qual_vars+categorical
and len(X_train[var].unique())< 20
]
len(discrete )
def get_batch_transformatioin_matrix(rotation, shear, height_zoom, width_zoom, height_shift, width_shift):

 batch_size = tf.cast(tf.reduce_sum(tf.ones_like(rotation)) , tf.int64)
 rotation = tf.constant(math.pi)* rotation / 180.0
shear = tf.constant(math.pi)* shear / 180.0
one = tf.ones_like(rotation, dtype=tf.float32)
 zero = tf.zeros_like(rotation, dtype=tf.float32)
 c1 = tf.math.cos(rotation)
 s1 = tf.math.sin(rotation)
 rotation_matrix_temp = tf.stack([c1, s1, zero, -s1, c1, zero, zero, zero, one], axis=0)
 rotation_matrix_temp = tf.transpose(rotation_matrix_temp)
 rotation_matrix = tf.reshape(rotation_matrix_temp, shape=(batch_size, 3, 3))
c2 = tf.math.cos(shear)
 s2 = tf.math.sin(shear)
 shear_matrix_temp = tf.stack([one, s2, zero, zero, c2, zero, zero, zero, one], axis=0)
 shear_matrix_temp = tf.transpose(shear_matrix_temp)
 shear_matrix = tf.reshape(shear_matrix_temp, shape=(batch_size, 3, 3))
zoom_matrix_temp = tf.stack([one / height_zoom, zero, zero, zero, one / width_zoom, zero, zero, zero, one], axis=0)
 zoom_matrix_temp = tf.transpose(zoom_matrix_temp)
 zoom_matrix = tf.reshape(zoom_matrix_temp, shape=(batch_size, 3, 3))
shift_matrix_temp = tf.stack([one, zero, height_shift, zero, one, width_shift, zero, zero, one], axis=0)
 shift_matrix_temp = tf.transpose(shift_matrix_temp)
 shift_matrix = tf.reshape(shift_matrix_temp, shape=(batch_size, 3, 3))
return tf.linalg.matmul(tf.linalg.matmul(rotation_matrix, shear_matrix), tf.linalg.matmul(zoom_matrix, shift_matrix))<categorify>
drop_features = sel.DropFeatures(features_to_drop =['PoolArea'])
 X_train = drop_features.fit_transform(X_train)
 X_test = drop_features.transform(X_test)
 submission = drop_features.transform(submission)
 X_train.shape, X_test.shape, submission.shape
def batch_transform(images, labels):

 DIM = images.shape[1]
XDIM = DIM % 2
batch_size = tf.cast(tf.reduce_sum(tf.ones_like(images)) /(images.shape[1] * images.shape[2] * images.shape[3]), tf.int64)
 rot = 15.0 * tf.random.normal([batch_size], dtype='float32')
 shr = 5.0 * tf.random.normal([batch_size], dtype='float32')
 h_zoom = 1.0 + tf.random.normal([batch_size], dtype='float32')/ 10.0
w_zoom = 1.0 + tf.random.normal([batch_size], dtype='float32')/ 10.0
h_shift = 16.0 * tf.random.normal([batch_size], dtype='float32')
 w_shift = 16.0 * tf.random.normal([batch_size], dtype='float32')
 m = get_batch_transformatioin_matrix(rot, shr, h_zoom, w_zoom, h_shift, w_shift)
 x = tf.repeat(tf.range(DIM // 2, -DIM // 2, -1), DIM)
 y = tf.tile(tf.range(-DIM // 2, DIM // 2), [DIM])
 z = tf.ones([DIM * DIM], dtype='int32')
 idx = tf.stack([x, y, z])
 idx2 = tf.linalg.matmul(m, tf.cast(idx, dtype='float32'))
idx2 = K.cast(idx2, dtype='int32')
 idx2 = K.clip(idx2, -DIM // 2 + XDIM + 1, DIM // 2)
 idx3 = tf.stack([DIM // 2 - idx2[:, 0, ], DIM // 2 - 1 + idx2[:, 1, ]], axis=1)
 d = tf.gather_nd(images, tf.transpose(idx3, perm=[0, 2, 1]), batch_dims=1)
 new_images = tf.reshape(d,(batch_size, DIM, DIM, 3))
return new_images, labels<categorify>
numerical = [
var for var in X_train.columns
if var not in categorical + qual_vars + discrete + year_vars
]
len(numerical )
def onehot(image,label):
CLASSES = 104
return image,tf.one_hot(label,CLASSES )<define_variables>
vars_to_impute = [c for c in null_num.keys() ]
vars_to_impute = vars_to_impute + ['GarageCars', 'BsmtFullBath', 'BsmtHalfBath']
indicator = imp.AddMissingIndicator(missing_only = False,
variables = vars_to_impute, 
)
 indicator.fit(X_train )
def batch_cutmix(images, labels, PROBABILITY=1.0, batch_size=0):
DIM = IMAGE_SIZE[0]
CLASSES = 104
if batch_size == 0:
batch_size = AUG_BATCH
do_cutmix = tf.cast(tf.random.uniform([batch_size], 0, 1)<= PROBABILITY, tf.int32)
 new_image_indices = tf.cast(tf.random.uniform([batch_size], 0, batch_size), tf.int32)
 new_x = tf.cast(tf.random.uniform([batch_size], 0, DIM), tf.int32)
 new_y = tf.cast(tf.random.uniform([batch_size], 0, DIM), tf.int32)
 b = tf.random.uniform([batch_size], 0, 1)
 new_width = tf.cast(DIM * tf.math.sqrt(1-b), tf.int32)* do_cutmix
new_y0 = tf.math.maximum(0, new_y - new_width // 2)
 new_y1 = tf.math.minimum(DIM, new_y + new_width // 2)
 new_x0 = tf.math.maximum(0, new_x - new_width // 2)
 new_x1 = tf.math.minimum(DIM, new_x + new_width // 2)
 target = tf.broadcast_to(tf.range(DIM), shape=(batch_size, DIM))
mask_y = tf.math.logical_and(new_y0[:, tf.newaxis] <= target, target <= new_y1[:, tf.newaxis])
 mask_x = tf.math.logical_and(new_x0[:, tf.newaxis] <= target, target <= new_x1[:, tf.newaxis])
 mask = tf.cast(tf.math.logical_and(mask_y[:, :, tf.newaxis], mask_x[:, tf.newaxis, :]), tf.float32)
 new_images = images * tf.broadcast_to(1 - mask[:, :, :, tf.newaxis], [batch_size, DIM, DIM, 3])+ \
tf.gather(images, new_image_indices)* tf.broadcast_to(mask[:, :, :, tf.newaxis], [batch_size, DIM, DIM, 3])
 a = tf.cast(new_width ** 2 / DIM ** 2, tf.float32)
 if len(labels.shape)== 1:
labels = tf.one_hot(labels, CLASSES)
 new_labels =(1-a)[:, tf.newaxis] * labels + a[:, tf.newaxis] * tf.gather(labels, new_image_indices)
 return new_images, new_labels<define_variables>
indicator.variables_
def batch_mixup(images, labels, PROBABILITY=1.0, batch_size=0):
DIM = IMAGE_SIZE[0]
CLASSES = 104
if batch_size == 0:
batch_size = AUG_BATCH
do_mixup = tf.cast(tf.random.uniform([batch_size], 0, 1)<= PROBABILITY, tf.int32)
 new_image_indices = tf.cast(tf.random.uniform([batch_size], 0, batch_size), tf.int32)
 a = tf.random.uniform([batch_size], 0, 1)* tf.cast(do_mixup, tf.float32)
 new_images =(1-a)[:, tf.newaxis, tf.newaxis, tf.newaxis] * images + a[:, tf.newaxis, tf.newaxis, tf.newaxis] * tf.gather(images, new_image_indices)
 if len(labels.shape)== 1:
labels = tf.one_hot(labels, CLASSES)
 new_labels =(1-a)[:, tf.newaxis] * labels + a[:, tf.newaxis] * tf.gather(labels, new_image_indices)
 return new_images, new_labels<categorify>
X_train = indicator.transform(X_train)
 X_test = indicator.transform(X_test)
 submission = indicator.transform(submission)
 X_train.shape, X_test.shape, submission.shape
def transform_cut_mix(image,label):
DIM = IMAGE_SIZE[0]
CLASSES = 104
SWITCH = 0.5
CUTMIX_PROB = 0.666
MIXUP_PROB = 0.666
image2, label2 = batch_cutmix(image, label, CUTMIX_PROB)
 image3, label3 = batch_mixup(image, label, MIXUP_PROB)
 imgs = []; labs = []
for j in range(AUG_BATCH):
P = tf.cast(tf.random.uniform([],0,1)<=SWITCH, tf.float32)
 imgs.append(P*image2[j,]+(1-P)*image3[j,])
 labs.append(P*label2[j,]+(1-P)*label3[j,])
 image4 = tf.reshape(tf.stack(imgs),(AUG_BATCH,DIM,DIM,3))
label4 = tf.reshape(tf.stack(labs),(AUG_BATCH,CLASSES))
return image4,label4<categorify>
num_imputer = imp.MeanMedianImputer(imputation_method = 'median',
variables = vars_to_impute, 
)
 num_imputer.fit(X_train)
 num_imputer.imputer_dict_
def decode_image(image_data):
image = tf.image.decode_jpeg(image_data, channels=3)
 image = tf.cast(image, tf.float32)/ 255.0
image = tf.reshape(image, [*IMAGE_SIZE, 3])
 return image
def read_labeled_tfrecord(example):
LABELED_TFREC_FORMAT = {
"image": tf.io.FixedLenFeature([], tf.string),
"class": tf.io.FixedLenFeature([], tf.int64),
}
example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)
 image = decode_image(example['image'])
 label = tf.cast(example['class'], tf.int32)
 return image, label
def read_unlabeled_tfrecord(example):
UNLABELED_TFREC_FORMAT = {
"image": tf.io.FixedLenFeature([], tf.string),
"id": tf.io.FixedLenFeature([], tf.string),
}
example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT)
 image = decode_image(example['image'])
 idnum = example['id']
return image, idnum
def load_dataset(filenames, labeled=True, ordered=False):
ignore_order = tf.data.Options()
if not ordered:
ignore_order.experimental_deterministic = False
dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO)
 dataset = dataset.with_options(ignore_order)
 dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls=AUTO)
 return dataset
def data_augment(image, label):
image = tf.image.random_flip_left_right(image)
 return image, label
def get_training_dataset(dataset, simple_aug=False, advance_aug=False, cut_mix_aug=0):
if simple_aug:
dataset = dataset.map(data_augment, num_parallel_calls=AUTO)
 dataset = dataset.repeat()
dataset = dataset.batch(AUG_BATCH)
 if advance_aug:
dataset = dataset.map(batch_transform, num_parallel_calls=AUTO)
 if cut_mix_aug==1:
dataset = dataset.map(batch_cutmix, num_parallel_calls=AUTO)
 elif cut_mix_aug==2:
dataset = dataset.map(batch_mixup, num_parallel_calls=AUTO)
 elif cut_mix_aug==3:
dataset = dataset.map(transform_cut_mix, num_parallel_calls=AUTO)
 dataset = dataset.unbatch()
dataset = dataset.shuffle(2048)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.prefetch(AUTO)
 return dataset
def get_validation_dataset(dataset, ordered=False, repeated=False):
if repeated:
dataset = dataset.repeat()
dataset = dataset.shuffle(2048)
 dataset = dataset.batch(BATCH_SIZE, drop_remainder=repeated)
 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)
 def int_div_round_up(a, b):
return(a + b - 1)// b 
<define_variables>
X_train = num_imputer.transform(X_train)
 X_test = num_imputer.transform(X_test)
 submission = num_imputer.transform(submission)
 X_train.shape, X_test.shape, submission.shape
SIZE = 512
IMAGE_SIZE = [SIZE, SIZE]
TRAINING_FILENAMES, VALIDATION_FILENAMES, TEST_FILENAMES = get_filenames(SIZE)
 print(len(TRAINING_FILENAMES))
if USE_EXTERNAL:
EXT_TRAINING_FILENAMES = get_ext_filenames(SIZE, imagenet=True, inaturalist=True, openimage=False, oxford=False, tfflowers=False)
 print(len(EXT_TRAINING_FILENAMES))
if USE_EXTERNAL:
TRAINING_FILENAMES = TRAINING_FILENAMES + EXT_TRAINING_FILENAMES
if SKIP_VALIDATION:
TRAINING_FILENAMES = TRAINING_FILENAMES + VALIDATION_FILENAMES
NUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)
 NUM_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES)if not SKIP_VALIDATION else 0
NUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)
 STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE
VALIDATION_STEPS = int_div_round_up(NUM_VALIDATION_IMAGES, BATCH_SIZE)
 print('Dataset: {} training images, {} validation images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))<create_dataframe>
[c for c in X_train.columns if X_train[c].isnull().sum() >0]
train_ds = load_dataset(TRAINING_FILENAMES, labeled=True)
 valid_ds = load_dataset(VALIDATION_FILENAMES, labeled=True)if not SKIP_VALIDATION else None
test_ds = load_dataset(TEST_FILENAMES, labeled=False )<train_model>
[c for c in X_test.columns if X_test[c].isnull().sum() >0]
print("Training data shapes:")
 for image, label in get_training_dataset(train_ds ).take(3):
print(image.numpy().shape, label.numpy().shape)
 print("Training data label examples:", label.numpy())
 if not SKIP_VALIDATION:
print("Validation data shapes:")
 for image, label in get_validation_dataset(valid_ds ).take(3):
print(image.numpy().shape, label.numpy().shape)
 print("Validation data label examples:", label.numpy())
 print("Test data shapes:")
 for image, idnum in get_test_dataset(test_ds ).take(3):
print(image.numpy().shape, idnum.numpy().shape)
 print("Test data IDs:", idnum.numpy().astype('U'))<define_variables>
[c for c in submission.columns if submission[c].isnull().sum() >0]
if 0:
training_dataset = get_training_dataset(train_ds, simple_aug=True, advance_aug=False, cut_mix_aug=1)
 training_dataset = training_dataset.unbatch().batch(20)
 train_batch = iter(training_dataset )<define_variables>
bath_bsmt = creation.MathematicalCombination(
 variables_to_combine=['BsmtHalfBath', 'BsmtFullBath'],
math_operations=['sum'],
new_variables_names=['BsmtBath_total'], 
)
 bath_ground = creation.MathematicalCombination(
 variables_to_combine=['FullBath', 'HalfBath'],
math_operations=['sum'],
new_variables_names=['Bath_total'], 
)
 X_train = bath_bsmt.fit_transform(X_train)
 X_test = bath_bsmt.transform(X_test)
 submission = bath_bsmt.transform(submission)
 X_train = bath_ground.fit_transform(X_train)
 X_test = bath_ground.transform(X_test)
 submission = bath_ground.transform(submission)
 X_train.shape, X_test.shape, submission.shape
if 0:
display_batch_of_images(next(train_batch))<define_variables>
X_train.reset_index(drop=True, inplace=True)
 y_train.reset_index(drop=True, inplace=True )
if 0:
test_dataset = get_test_dataset(test_ds)
 test_dataset = test_dataset.unbatch().batch(20)
 test_batch = iter(test_dataset )<define_variables>
def nested_cross_val(model, grid):
cv_outer = KFold(n_splits=5, shuffle=True, random_state=1)
 outer_results = list()
for train_ix, test_ix in cv_outer.split(X_train):
xtrain, xtest = X_train.loc[train_ix, :], X_train.loc[test_ix, :]
ytrain, ytest = y_train[train_ix], y_train[test_ix]
cv_inner = KFold(n_splits=5, shuffle=True, random_state=1)
 search = GridSearchCV(model, grid, scoring='neg_root_mean_squared_error', cv=cv_inner, refit=True)
 search.fit(xtrain, ytrain)
 yhat = search.predict(xtest)
 rmse = mean_squared_error(ytest, yhat, squared=False)
 outer_results.append(rmse)
 print('>rmse_outer=%.3f, rmse_inner=%.3f, cfg=%s' %(rmse, search.best_score_, search.best_params_))
print('rmse_outer: %.3f +- %.3f' %(np.mean(outer_results), np.std(outer_results)))
 return search.fit(X_train, y_train )
if 0:
display_batch_of_images(next(test_batch))<define_variables>
gbm = GradientBoostingRegressor(
 loss='ls',
n_estimators=100,
criterion='friedman_mse',
min_samples_split=2,
max_depth=3,
random_state=0,
n_iter_no_change=2,
tol=0.0001, 
)
 param_grid = dict(
 loss=['ls', 'huber'],
n_estimators=[10, 20, 50, 100, 200, 500, 1000, 2000],
min_samples_split=[0.1, 0.3, 0.5],
max_depth=[1,2,3,4,None], 
)
 search = nested_cross_val(gbm, param_grid )
if 0:
images, labels = next(iter(training_dataset.take(1)))
 new_images, new_labels = batch_cutmix(images, labels, PROBABILITY=1.0, batch_size=20)
 display_batch_of_images(( new_images, new_labels))<define_variables>
X_train_preds = search.predict(X_train)
 X_test_preds = search.predict(X_test)
 submission_preds = search.predict(submission)
 print('Train rmse: ', mean_squared_error(y_train, X_train_preds, squared=False))
print('Test rmse: ', mean_squared_error(y_test, X_test_preds, squared=False))
print()
print('Train r2: ', r2_score(y_train, X_train_preds))
print('Test r2: ', r2_score(y_test, X_test_preds))
if 0:
images, labels = next(iter(training_dataset.take(1)))
 new_images, new_labels = batch_mixup(images, labels, PROBABILITY=1.0, batch_size=20)
 display_batch_of_images(( new_images, new_labels))<choose_model_class>
np.exp(submission_preds )
LR_START = 0.00003
LR_MAX = 0.00005 * strategy.num_replicas_in_sync
LR_MIN = 0.00001
LR_RAMPUP_EPOCHS = 5
LR_SUSTAIN_EPOCHS = 3
LR_EXP_DECAY =.8
@tf.function
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
rng = [i for i in range(EPOCHS)]
y = [lrfn(x)for x in rng]
plt.plot(rng, y)
 print("Learning rate schedule: {:.3g} to {:.3g} to {:.3g}".format(y[0], max(y), y[-1]))<choose_model_class>
lgbm_param = {
"num_leaves": [6, 8, 20, 30],
"max_depth": [2, 4, 6, 8, 10],
"n_estimators": [50, 100, 200, 500],
'colsample_bytree': [0.3, 1.0],
}
lgbm = LGBMRegressor(
 learning_rate = 0.1,
min_child_weight = 0.4,
objective='regression',
random_state=0)
 search = nested_cross_val(lgbm, lgbm_param )
with strategy.scope() :
pretrained_model = tf.keras.applications.DenseNet201(weights='imagenet', include_top=False ,input_shape=[*IMAGE_SIZE, 3])
 pretrained_model.trainable = True
model1 = tf.keras.Sequential([
pretrained_model,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 class LRSchedule(tf.keras.optimizers.schedules.LearningRateSchedule):
def __call__(self, step):
return lrfn(epoch=step//STEPS_PER_EPOCH)
 optimizer1 = tf.keras.optimizers.Adam(learning_rate=LRSchedule())
 model1.compile(
 optimizer = optimizer1,
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 model1.summary()
train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy()
valid_accuracy = tf.keras.metrics.SparseCategoricalAccuracy()
train_loss = tf.keras.metrics.Sum()
valid_loss = tf.keras.metrics.Sum()
loss_fn = lambda a,b: tf.nn.compute_average_loss(tf.keras.losses.sparse_categorical_crossentropy(a,b), global_batch_size=BATCH_SIZE )<train_model>
X_train_preds = search.predict(X_train)
 X_test_preds = search.predict(X_test)
 submission_preds = search.predict(submission)
 print('Train rmse: ', mean_squared_error(y_train, X_train_preds, squared=False))
print('Test rmse: ', mean_squared_error(y_test, X_test_preds, squared=False))
print()
print('Train r2: ', r2_score(y_train, X_train_preds))
print('Test r2: ', r2_score(y_test, X_test_preds))
if tpu:
STEPS_PER_TPU_CALL = 99
VALIDATION_STEPS_PER_TPU_CALL = 29
@tf.function
def train_step(model, optimizer, data_iter):
def train_step_fn(images, labels):
with tf.GradientTape() as tape:
probabilities = model(images, training=True)
 loss = loss_fn(labels, probabilities)
 grads = tape.gradient(loss, model.trainable_variables)
 optimizer.apply_gradients(zip(grads, model.trainable_variables))
train_accuracy.update_state(labels, probabilities)
 train_loss.update_state(loss)
 for _ in tf.range(STEPS_PER_TPU_CALL):
strategy.experimental_run_v2(train_step_fn, next(data_iter))
@tf.function
def valid_step(model, data_iter):
def valid_step_fn(images, labels):
probabilities = model(images, training=False)
 loss = loss_fn(labels, probabilities)
 valid_accuracy.update_state(labels, probabilities)
 valid_loss.update_state(loss)
 for _ in tf.range(VALIDATION_STEPS_PER_TPU_CALL):
strategy.experimental_run_v2(valid_step_fn, next(data_iter)) 
<split>
np.exp(submission_preds )
EPOCHS = 24
start_time = epoch_start_time = time.time()
if tpu:
train_dist_ds = strategy.experimental_distribute_dataset(get_training_dataset(train_ds, simple_aug=True, advance_aug=True, cut_mix_aug=0))
valid_dist_ds = strategy.experimental_distribute_dataset(get_validation_dataset(valid_ds, repeated=True)) if not SKIP_VALIDATION else None
print("Training steps per epoch:", STEPS_PER_EPOCH, "in increment of:", STEPS_PER_TPU_CALL)
 if not SKIP_VALIDATION:
print("Validation images:", NUM_VALIDATION_IMAGES,
"Batch size:", BATCH_SIZE,
"Validation steps:", NUM_VALIDATION_IMAGES//BATCH_SIZE, "in increments of", VALIDATION_STEPS_PER_TPU_CALL)
 print("Repeated validation images:", int_div_round_up(NUM_VALIDATION_IMAGES, BATCH_SIZE*VALIDATION_STEPS_PER_TPU_CALL)*VALIDATION_STEPS_PER_TPU_CALL*BATCH_SIZE-NUM_VALIDATION_IMAGES)
 History = namedtuple('History', 'history')
 history = History(history={'loss': [], 'val_loss': [], 'sparse_categorical_accuracy': [], 'val_sparse_categorical_accuracy': []})if not SKIP_VALIDATION else History(history={'loss': [], 'val_loss': [], 'sparse_categorical_accuracy': []})
 epoch = 0
train_data_iter = iter(train_dist_ds)
 valid_data_iter = iter(valid_dist_ds)if not SKIP_VALIDATION else None
step = 0
epoch_steps = 0
while True:
train_step(model1, optimizer1, train_data_iter)
 epoch_steps += STEPS_PER_TPU_CALL
step += STEPS_PER_TPU_CALL
print('=', end='', flush=True)
 if(step//STEPS_PER_EPOCH)> epoch:
print('|', end='', flush=True)
 if not SKIP_VALIDATION:
valid_epoch_steps = 0
valid_step(model1, valid_data_iter)
 valid_epoch_steps += VALIDATION_STEPS_PER_TPU_CALL
print('=', end='', flush=True)
 history.history['val_sparse_categorical_accuracy'].append(valid_accuracy.result().numpy())
 history.history['val_loss'].append(valid_loss.result().numpy() / VALIDATION_STEPS)
 history.history['sparse_categorical_accuracy'].append(train_accuracy.result().numpy())
 history.history['loss'].append(train_loss.result().numpy() / STEPS_PER_EPOCH)
 epoch_time = time.time() - epoch_start_time
print('
EPOCH {:d}/{:d}'.format(epoch+1, EPOCHS))
if not SKIP_VALIDATION:
print('time: {:0.1f}s'.format(epoch_time),
'loss: {:0.4f}'.format(history.history['loss'][-1]),
'accuracy: {:0.4f}'.format(history.history['sparse_categorical_accuracy'][-1]),
'val_loss: {:0.4f}'.format(history.history['val_loss'][-1]),
'val_acc: {:0.4f}'.format(history.history['val_sparse_categorical_accuracy'][-1]),
'lr: {:0.4g}'.format(lrfn(epoch)) , flush=True)
 else:
print('time: {:0.1f}s'.format(epoch_time),
'loss: {:0.4f}'.format(history.history['loss'][-1]),
'accuracy: {:0.4f}'.format(history.history['sparse_categorical_accuracy'][-1]),
'lr: {:0.4g}'.format(lrfn(epoch)) , flush=True)
 epoch =(step+1)// STEPS_PER_EPOCH
epoch_start_time = time.time()
train_accuracy.reset_states()
if not SKIP_VALIDATION:
valid_accuracy.reset_states()
valid_loss.reset_states()
train_loss.reset_states()
if epoch >= EPOCHS:
break
else:
EPOCHS = 15
history = model1.fit(
 get_training_dataset(train_ds),
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS,
validation_data=get_validation_dataset(valid_ds)if not SKIP_VALIDATION else None 
)
 simple_ctl_training_time = time.time() - start_time
print("OPTIMIZED CTL TRAINING TIME: {:0.1f}s".format(simple_ctl_training_time))<load_pretrained>
my_submission = pd.DataFrame({'Id': id_, 'SalePrice': np.exp(submission_preds)})
 my_submission.to_csv('submission_lgbm_full.csv', index=False )
model1.save_weights('densenet-flower-tpu.hdf5' )<create_dataframe>
sel_perf = sel.SelectBySingleFeaturePerformance(
 estimator=DecisionTreeRegressor(random_state=2, max_depth=2),
scoring='r2',
cv=3,
threshold=0.01,
variables=None, 
)
 sel_perf.fit(X_train, y_train )
test_ds = get_test_dataset(ordered=True)
 test_images_ds = test_ds.map(lambda image, idnum: image )<predict_on_test>
print('total features: ', X_train.shape[1])
 print('features to drop: ', len(sel_perf.features_to_drop_))
print('remaining features: ', X_train.shape[1] - len(sel_perf.features_to_drop_))
print('Computing predictions model1...')
 preds1 = model1.predict(test_images_ds)
 del model1
gc.collect()
tf.tpu.experimental.initialize_tpu_system(tpu )<define_variables>
rfm = RandomForestRegressor(
 n_estimators=100,
random_state=0,
max_depth=2, 
)
 rfe = sel.RecursiveFeatureElimination(
 estimator = rfm,
scoring ='neg_root_mean_squared_error',
cv=3,
threshold=0.001,
variables=None, 
)
 rfe.fit(X_train, y_train )
SIZE = 331
IMAGE_SIZE = [SIZE, SIZE]
TRAINING_FILENAMES, VALIDATION_FILENAMES, TEST_FILENAMES = get_filenames(SIZE)
 print(len(TRAINING_FILENAMES))
if USE_EXTERNAL:
EXT_TRAINING_FILENAMES = get_ext_filenames(SIZE, imagenet=False, inaturalist=False, openimage=True, oxford=True, tfflowers=True)
 print(len(EXT_TRAINING_FILENAMES))
if USE_EXTERNAL:
TRAINING_FILENAMES = TRAINING_FILENAMES + EXT_TRAINING_FILENAMES
if SKIP_VALIDATION:
TRAINING_FILENAMES = TRAINING_FILENAMES + VALIDATION_FILENAMES
NUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)
 NUM_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES)if not SKIP_VALIDATION else 0
NUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)
 STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE
VALIDATION_STEPS = int_div_round_up(NUM_VALIDATION_IMAGES, BATCH_SIZE)
 print('Dataset: {} training images, {} validation images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))<create_dataframe>
rfe.initial_model_performance_
train_ds = load_dataset(TRAINING_FILENAMES, labeled=True)
 valid_ds = load_dataset(VALIDATION_FILENAMES, labeled=True)if not SKIP_VALIDATION else None<import_modules>
X_train = sel_perf.transform(X_train)
 X_test = sel_perf.transform(X_test)
 submission = sel_perf.transform(submission)
 X_train.shape, X_test.shape, submission.shape
import efficientnet.tfkeras as efn<choose_model_class>
gbm = GradientBoostingRegressor(
 loss='ls',
n_estimators=100,
criterion='friedman_mse',
min_samples_split=2,
max_depth=3,
random_state=0,
n_iter_no_change=2,
tol=0.0001,
)
with strategy.scope() :
pretrained_model2 = efn.EfficientNetB7(weights='noisy-student', include_top=False ,input_shape=[*IMAGE_SIZE, 3])
 pretrained_model2.trainable = True
model2 = tf.keras.Sequential([
pretrained_model2,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 class LRSchedule(tf.keras.optimizers.schedules.LearningRateSchedule):
def __call__(self, step):
return lrfn(epoch=step//STEPS_PER_EPOCH)
 optimizer2 = tf.keras.optimizers.Adam(learning_rate=LRSchedule())
 model2.compile(
 optimizer = optimizer2,
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 model2.summary()
train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy()
valid_accuracy = tf.keras.metrics.SparseCategoricalAccuracy()
train_loss = tf.keras.metrics.Sum()
valid_loss = tf.keras.metrics.Sum()
loss_fn = lambda a,b: tf.nn.compute_average_loss(tf.keras.losses.sparse_categorical_crossentropy(a,b), global_batch_size=BATCH_SIZE )<train_model>
param_grid = dict(
 loss=['ls', 'huber'],
n_estimators=[10, 20, 50, 100, 200, 500, 1000, 2000],
min_samples_split=[0.1, 0.3, 0.5],
max_depth=[1,2,3,4,None],
)
if tpu:
STEPS_PER_TPU_CALL = 99
VALIDATION_STEPS_PER_TPU_CALL = 29
@tf.function
def train_step2(model, optimizer, data_iter):
def train_step_fn(images, labels):
with tf.GradientTape() as tape:
probabilities = model(images, training=True)
 loss = loss_fn(labels, probabilities)
 grads = tape.gradient(loss, model.trainable_variables)
 optimizer.apply_gradients(zip(grads, model.trainable_variables))
train_accuracy.update_state(labels, probabilities)
 train_loss.update_state(loss)
 for _ in tf.range(STEPS_PER_TPU_CALL):
strategy.experimental_run_v2(train_step_fn, next(data_iter))
@tf.function
def valid_step2(model, data_iter):
def valid_step_fn(images, labels):
probabilities = model(images, training=False)
 loss = loss_fn(labels, probabilities)
 valid_accuracy.update_state(labels, probabilities)
 valid_loss.update_state(loss)
 for _ in tf.range(VALIDATION_STEPS_PER_TPU_CALL):
strategy.experimental_run_v2(valid_step_fn, next(data_iter))<train_model>
search = nested_cross_val(gbm, param_grid )
start_time = epoch_start_time = time.time()
if tpu:
train_dist_ds = strategy.experimental_distribute_dataset(get_training_dataset(train_ds, simple_aug=True, advance_aug=True, cut_mix_aug=0))
valid_dist_ds = strategy.experimental_distribute_dataset(get_validation_dataset(valid_ds, repeated=True)) if not SKIP_VALIDATION else None
print("Training steps per epoch:", STEPS_PER_EPOCH, "in increment of:", STEPS_PER_TPU_CALL)
 if not SKIP_VALIDATION:
print("Validation images:", NUM_VALIDATION_IMAGES,
"Batch size:", BATCH_SIZE,
"Validation steps:", NUM_VALIDATION_IMAGES//BATCH_SIZE, "in increments of", VALIDATION_STEPS_PER_TPU_CALL)
 print("Repeated validation images:", int_div_round_up(NUM_VALIDATION_IMAGES, BATCH_SIZE*VALIDATION_STEPS_PER_TPU_CALL)*VALIDATION_STEPS_PER_TPU_CALL*BATCH_SIZE-NUM_VALIDATION_IMAGES)
 History = namedtuple('History', 'history')
 history = History(history={'loss': [], 'val_loss': [], 'sparse_categorical_accuracy': [], 'val_sparse_categorical_accuracy': []})if not SKIP_VALIDATION else History(history={'loss': [], 'val_loss': [], 'sparse_categorical_accuracy': []})
 epoch = 0
train_data_iter = iter(train_dist_ds)
 valid_data_iter = iter(valid_dist_ds)if not SKIP_VALIDATION else None
step = 0
epoch_steps = 0
while True:
train_step2(model2, optimizer2, train_data_iter)
 epoch_steps += STEPS_PER_TPU_CALL
step += STEPS_PER_TPU_CALL
print('=', end='', flush=True)
 if(step//STEPS_PER_EPOCH)> epoch:
print('|', end='', flush=True)
 if not SKIP_VALIDATION:
valid_epoch_steps = 0
valid_step2(model2, valid_data_iter)
 valid_epoch_steps += VALIDATION_STEPS_PER_TPU_CALL
print('=', end='', flush=True)
 history.history['val_sparse_categorical_accuracy'].append(valid_accuracy.result().numpy())
 history.history['val_loss'].append(valid_loss.result().numpy() / VALIDATION_STEPS)
 history.history['sparse_categorical_accuracy'].append(train_accuracy.result().numpy())
 history.history['loss'].append(train_loss.result().numpy() / STEPS_PER_EPOCH)
 epoch_time = time.time() - epoch_start_time
print('
EPOCH {:d}/{:d}'.format(epoch+1, EPOCHS))
if not SKIP_VALIDATION:
print('time: {:0.1f}s'.format(epoch_time),
'loss: {:0.4f}'.format(history.history['loss'][-1]),
'accuracy: {:0.4f}'.format(history.history['sparse_categorical_accuracy'][-1]),
'val_loss: {:0.4f}'.format(history.history['val_loss'][-1]),
'val_acc: {:0.4f}'.format(history.history['val_sparse_categorical_accuracy'][-1]),
'lr: {:0.4g}'.format(lrfn(epoch)) , flush=True)
 else:
print('time: {:0.1f}s'.format(epoch_time),
'loss: {:0.4f}'.format(history.history['loss'][-1]),
'accuracy: {:0.4f}'.format(history.history['sparse_categorical_accuracy'][-1]),
'lr: {:0.4g}'.format(lrfn(epoch)) , flush=True)
 epoch =(step+1)// STEPS_PER_EPOCH
epoch_start_time = time.time()
train_accuracy.reset_states()
if not SKIP_VALIDATION:
valid_accuracy.reset_states()
valid_loss.reset_states()
train_loss.reset_states()
if epoch >= EPOCHS:
break
else:
EPOCHS = 15
history = model2.fit(
 get_training_dataset(train_ds),
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS,
validation_data=get_validation_dataset(valid_ds)if not SKIP_VALIDATION else None 
)
 simple_ctl_training_time = time.time() - start_time
print("OPTIMIZED CTL TRAINING TIME: {:0.1f}s".format(simple_ctl_training_time))<load_pretrained>
results = pd.DataFrame(search.cv_results_)
 results.head()
model2.save_weights('effnetb7-flower-tpu.hdf5' )<create_dataframe>
results.sort_values(by='mean_test_score', ascending=False, inplace=True)
 results.reset_index(drop=True, inplace=True)
 results[['params','mean_test_score', 'std_test_score']]
test_ds = get_test_dataset(ordered=True)
 test_images_ds = test_ds.map(lambda image, idnum: image )<predict_on_test>
X_train_preds = search.predict(X_train)
 X_test_preds = search.predict(X_test)
 submission_preds = search.predict(submission )
print('Computing predictions model2...')
 preds2 = model2.predict(test_images_ds)
 del model2
gc.collect()
tf.tpu.experimental.initialize_tpu_system(tpu )<define_variables>
print('Train rmse: ', mean_squared_error(y_train, X_train_preds, squared=False))
print('Test rmse: ', mean_squared_error(y_test, X_test_preds, squared=False))
SIZE = 512
IMAGE_SIZE = [SIZE, SIZE]
SKIP_VALIDATION = True
TRAINING_FILENAMES, VALIDATION_FILENAMES, TEST_FILENAMES = get_filenames(SIZE)
 print(len(TRAINING_FILENAMES))
if USE_EXTERNAL:
EXT_TRAINING_FILENAMES = get_ext_filenames(SIZE, imagenet=False, inaturalist=True, openimage=False, oxford=False, tfflowers=True)
 print(len(EXT_TRAINING_FILENAMES))
if USE_EXTERNAL:
TRAINING_FILENAMES = TRAINING_FILENAMES + EXT_TRAINING_FILENAMES
if SKIP_VALIDATION:
TRAINING_FILENAMES = TRAINING_FILENAMES + VALIDATION_FILENAMES
NUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)
 NUM_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES)if not SKIP_VALIDATION else 0
NUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)
 STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE
VALIDATION_STEPS = int_div_round_up(NUM_VALIDATION_IMAGES, BATCH_SIZE)
 print('Dataset: {} training images, {} validation images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))
train_ds = load_dataset(TRAINING_FILENAMES, labeled=True)
 valid_ds = load_dataset(VALIDATION_FILENAMES, labeled=True)if not SKIP_VALIDATION else None<choose_model_class>
print('Train r2: ', r2_score(y_train, X_train_preds))
print('Test r2: ', r2_score(y_test, X_test_preds))
with strategy.scope() :
pretrained_model3 = efn.EfficientNetB6(weights='noisy-student', include_top=False ,input_shape=[*IMAGE_SIZE, 3])
 pretrained_model3.trainable = True
model3 = tf.keras.Sequential([
pretrained_model3,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 class LRSchedule(tf.keras.optimizers.schedules.LearningRateSchedule):
def __call__(self, step):
return lrfn(epoch=step//STEPS_PER_EPOCH)
 optimizer3 = tf.keras.optimizers.Adam(learning_rate=LRSchedule())
 model3.compile(
 optimizer = optimizer3,
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 model3.summary()
train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy()
valid_accuracy = tf.keras.metrics.SparseCategoricalAccuracy()
train_loss = tf.keras.metrics.Sum()
valid_loss = tf.keras.metrics.Sum()
loss_fn = lambda a,b: tf.nn.compute_average_loss(tf.keras.losses.sparse_categorical_crossentropy(a,b), global_batch_size=BATCH_SIZE )<train_model>
np.exp(submission_preds )
if tpu:
STEPS_PER_TPU_CALL = 99
VALIDATION_STEPS_PER_TPU_CALL = 29
@tf.function
def train_step3(model, optimizer, data_iter):
def train_step_fn(images, labels):
with tf.GradientTape() as tape:
probabilities = model(images, training=True)
 loss = loss_fn(labels, probabilities)
 grads = tape.gradient(loss, model.trainable_variables)
 optimizer.apply_gradients(zip(grads, model.trainable_variables))
train_accuracy.update_state(labels, probabilities)
 train_loss.update_state(loss)
 for _ in tf.range(STEPS_PER_TPU_CALL):
strategy.experimental_run_v2(train_step_fn, next(data_iter))
@tf.function
def valid_step3(model, data_iter):
def valid_step_fn(images, labels):
probabilities = model(images, training=False)
 loss = loss_fn(labels, probabilities)
 valid_accuracy.update_state(labels, probabilities)
 valid_loss.update_state(loss)
 for _ in tf.range(VALIDATION_STEPS_PER_TPU_CALL):
strategy.experimental_run_v2(valid_step_fn, next(data_iter))<train_model>
my_submission = pd.DataFrame({'Id': id_, 'SalePrice': np.exp(submission_preds)})
 my_submission.to_csv('submission_gbm_small.csv', index=False )
start_time = epoch_start_time = time.time()
if tpu:
train_dist_ds = strategy.experimental_distribute_dataset(get_training_dataset(train_ds, simple_aug=True, advance_aug=True, cut_mix_aug=0))
valid_dist_ds = strategy.experimental_distribute_dataset(get_validation_dataset(valid_ds, repeated=True)) if not SKIP_VALIDATION else None
print("Training steps per epoch:", STEPS_PER_EPOCH, "in increment of:", STEPS_PER_TPU_CALL)
 if not SKIP_VALIDATION:
print("Validation images:", NUM_VALIDATION_IMAGES,
"Batch size:", BATCH_SIZE,
"Validation steps:", NUM_VALIDATION_IMAGES//BATCH_SIZE, "in increments of", VALIDATION_STEPS_PER_TPU_CALL)
 print("Repeated validation images:", int_div_round_up(NUM_VALIDATION_IMAGES, BATCH_SIZE*VALIDATION_STEPS_PER_TPU_CALL)*VALIDATION_STEPS_PER_TPU_CALL*BATCH_SIZE-NUM_VALIDATION_IMAGES)
 History = namedtuple('History', 'history')
 history = History(history={'loss': [], 'val_loss': [], 'sparse_categorical_accuracy': [], 'val_sparse_categorical_accuracy': []})if not SKIP_VALIDATION else History(history={'loss': [], 'val_loss': [], 'sparse_categorical_accuracy': []})
 epoch = 0
train_data_iter = iter(train_dist_ds)
 valid_data_iter = iter(valid_dist_ds)if not SKIP_VALIDATION else None
step = 0
epoch_steps = 0
while True:
train_step3(model3, optimizer3, train_data_iter)
 epoch_steps += STEPS_PER_TPU_CALL
step += STEPS_PER_TPU_CALL
print('=', end='', flush=True)
 if(step//STEPS_PER_EPOCH)> epoch:
print('|', end='', flush=True)
 if not SKIP_VALIDATION:
valid_epoch_steps = 0
valid_step3(model3, valid_data_iter)
 valid_epoch_steps += VALIDATION_STEPS_PER_TPU_CALL
print('=', end='', flush=True)
 history.history['val_sparse_categorical_accuracy'].append(valid_accuracy.result().numpy())
 history.history['val_loss'].append(valid_loss.result().numpy() / VALIDATION_STEPS)
 history.history['sparse_categorical_accuracy'].append(train_accuracy.result().numpy())
 history.history['loss'].append(train_loss.result().numpy() / STEPS_PER_EPOCH)
 epoch_time = time.time() - epoch_start_time
print('
EPOCH {:d}/{:d}'.format(epoch+1, EPOCHS))
if not SKIP_VALIDATION:
print('time: {:0.1f}s'.format(epoch_time),
'loss: {:0.4f}'.format(history.history['loss'][-1]),
'accuracy: {:0.4f}'.format(history.history['sparse_categorical_accuracy'][-1]),
'val_loss: {:0.4f}'.format(history.history['val_loss'][-1]),
'val_acc: {:0.4f}'.format(history.history['val_sparse_categorical_accuracy'][-1]),
'lr: {:0.4g}'.format(lrfn(epoch)) , flush=True)
 else:
print('time: {:0.1f}s'.format(epoch_time),
'loss: {:0.4f}'.format(history.history['loss'][-1]),
'accuracy: {:0.4f}'.format(history.history['sparse_categorical_accuracy'][-1]),
'lr: {:0.4g}'.format(lrfn(epoch)) , flush=True)
 epoch =(step+1)// STEPS_PER_EPOCH
epoch_start_time = time.time()
train_accuracy.reset_states()
if not SKIP_VALIDATION:
valid_accuracy.reset_states()
valid_loss.reset_states()
train_loss.reset_states()
if epoch >= EPOCHS:
break
else:
EPOCHS = 15
history = model3.fit(
 get_training_dataset(train_ds),
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS,
validation_data=get_validation_dataset(valid_ds)if not SKIP_VALIDATION else None 
)
 simple_ctl_training_time = time.time() - start_time
print("OPTIMIZED CTL TRAINING TIME: {:0.1f}s".format(simple_ctl_training_time))<load_pretrained>
lgbm_param = {
"num_leaves": [6, 8, 20, 30],
"max_depth": [2, 4, 6, 8, 10],
"n_estimators": [50, 100, 200, 500],
'colsample_bytree': [0.3, 1.0],
}
lgbm = LGBMRegressor(
 learning_rate = 0.1,
min_child_weight = 0.4,
objective='regression',
random_state=0 )
model3.save_weights('effnetb6-flower-tpu.hdf5' )<create_dataframe>
search = nested_cross_val(lgbm, lgbm_param )
test_ds = get_test_dataset(ordered=True)
 test_images_ds = test_ds.map(lambda image, idnum: image )<predict_on_test>
X_train_preds = search.predict(X_train)
 X_test_preds = search.predict(X_test)
 submission_preds = search.predict(submission )
print('Computing predictions model3...')
 preds3 = model3.predict(test_images_ds)
 del model3
gc.collect()
tf.tpu.experimental.initialize_tpu_system(tpu )<predict_on_test>
print('Train rmse: ', mean_squared_error(y_train, X_train_preds,squared=False))
print('Test rmse: ', mean_squared_error(y_test, X_test_preds,squared=False))
if 0 and not SKIP_VALIDATION:
cmdataset = get_validation_dataset(load_dataset(VALIDATION_FILENAMES, labeled=True, ordered=True), ordered=True)
 images_ds = cmdataset.map(lambda image, label: image)
 labels_ds = cmdataset.map(lambda image, label: label ).unbatch()
cm_correct_labels = next(iter(labels_ds.batch(NUM_VALIDATION_IMAGES)) ).numpy()
cm_probabilities =(model1.predict(images_ds)+model2.predict(images_ds)) /2
cm_predictions = np.argmax(cm_probabilities, axis=-1)
 print("Correct labels: ", cm_correct_labels.shape, cm_correct_labels)
 print("Predicted labels: ", cm_predictions.shape, cm_predictions )<compute_train_metric>
print('Train r2: ', r2_score(y_train, X_train_preds))
print('Test r2: ', r2_score(y_test, X_test_preds))
if 0 and 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')
 cmat =(cmat.T / cmat.sum(axis=1)).T
display_confusion_matrix(cmat, score, precision, recall)
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score, precision, recall))<define_variables>
np.exp(submission_preds )
<save_to_csv><EOS> 
my_submission = pd.DataFrame({'Id': id_, 'SalePrice': np.exp(submission_preds)})
 my_submission.to_csv('submission_lgbm_small.csv', index=False )