Kaggle competition: House Prices - Advanced Regression Techniques
<SOS> metric: rmsle Kaggle data source: house-prices-advanced-regression-techniques<import_modules>
!pip install --upgrade seaborn
np.random.seed(42)
 plt.rcParams.update({'figure.max_open_warning': 0})
 pd.options.mode.chained_assignment = None
pd.set_option('display.max_rows', 250)
 pd.set_option('display.max_columns', 250 )
AUTO = tf.data.experimental.AUTOTUNE
AUTO, tf.__version__<define_variables>
!pip install --upgrade lightgbm
IMAGE_SIZE = [512, 512]
BATCH_SIZE = 16 * strategy.num_replicas_in_sync
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'] 
<define_variables>
train = pd.read_csv(".. /input/house-prices-advanced-regression-techniques/train.csv")
 test = pd.read_csv(".. /input/house-prices-advanced-regression-techniques/test.csv")
 train_id = train.Id
test_id = test.Id
print("Train set: ", train.shape)
 print("Test set: ", test.shape)
 train.info()
GCS_DS_PATH = KaggleDatasets().get_gcs_path()
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')+ tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec')
 VALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec')
 TEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec' )<groupby>
df = pd.concat([train, test])
 df
def count_data_items(filenames):
n = [int(re.compile(r"-([0-9]*)\." ).search(filename ).group(1)) for filename in filenames]
return np.sum(n )<count_values>
def col_types(df):
num_cols = df.loc[:, df.dtypes != "object"].columns.tolist()
cat_cols = df.loc[:, df.dtypes == "object"].columns.tolist()
ord_cols = []
for col in num_cols:
if df[col].value_counts().size < 20:
ord_cols.append(col)
 num_cols = [x for x in num_cols if x not in ord_cols + ["Id", "SalePrice"]]
return num_cols, cat_cols, ord_cols
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
BATCH_SIZE, STEPS_PER_EPOCH, NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES<normalization>
def missing(df):
miss = pd.DataFrame({"no_missing_values": df.isnull().sum() ,
"missing_value_ratio":(df.isnull().sum() / df.shape[0] ).round(4),
"missing_in_train": df[df.SalePrice.notnull() ].isnull().sum() ,
"missing_in_test": df[df.SalePrice.isnull() ].isnull().sum() })
 return miss[miss.no_missing_values > 0].sort_values("no_missing_values", ascending=False)
 missing(df )
def data_augment(image, label):
image = tf.image.random_flip_left_right(image)
 return(image), label<normalization>
df[(df.GarageFinish.isnull())&(df.GarageType.notnull())]
def get_mat(rotation, shear, height_zoom, width_zoom, height_shift, width_shift):
rotation = math.pi * rotation / 180.
 shear = math.pi * shear / 180.
 c1 = tf.math.cos(rotation)
 s1 = tf.math.sin(rotation)
 one = tf.constant([1],dtype='float32')
 zero = tf.constant([0],dtype='float32')
 rotation_matrix = tf.reshape(tf.concat([c1,s1,zero, -s1,c1,zero, zero,zero,one],axis=0),[3,3])
 c2 = tf.math.cos(shear)
 s2 = tf.math.sin(shear)
 shear_matrix = tf.reshape(tf.concat([one,s2,zero, zero,c2,zero, zero,zero,one],axis=0),[3,3])
 zoom_matrix = tf.reshape(tf.concat([one/height_zoom,zero,zero, zero,one/width_zoom,zero, zero,zero,one],axis=0),[3,3])
 shift_matrix = tf.reshape(tf.concat([one,zero,height_shift, zero,one,width_shift, zero,zero,one],axis=0),[3,3])
 return K.dot(K.dot(rotation_matrix, shear_matrix), K.dot(zoom_matrix, shift_matrix))<categorify>
df.loc[(df.GarageFinish.isnull())&(df.GarageType.notnull()), "GarageFinish"] = "Fin"
df.loc[(df.GarageCars.isnull())&(df.GarageType.notnull()), "GarageCars"] = 1
df.loc[(df.GarageQual.isnull())&(df.GarageType.notnull()), "GarageQual"] = "TA"
df.loc[(df.GarageCond.isnull())&(df.GarageType.notnull()), "GarageCond"] = "TA"
def transform(image, label):
DIM = IMAGE_SIZE[0]
XDIM = DIM%2
rot = 15.* tf.random.normal([1],dtype='float32')
 shr = 5.* tf.random.normal([1],dtype='float32')
 h_zoom = 1.0 + tf.random.normal([1],dtype='float32')/10.
 w_zoom = 1.0 + tf.random.normal([1],dtype='float32')/10.
 h_shift = 16.* tf.random.normal([1],dtype='float32')
 w_shift = 16.* tf.random.normal([1],dtype='float32')
 m = get_mat(rot,shr,h_zoom,w_zoom,h_shift,w_shift)
 x = tf.repeat(tf.range(DIM//2,-DIM//2,-1), DIM)
 y = tf.tile(tf.range(-DIM//2,DIM//2),[DIM])
 z = tf.ones([DIM*DIM],dtype='int32')
 idx = tf.stack([x,y,z])
 idx2 = K.dot(m,tf.cast(idx,dtype='float32'))
idx2 = K.cast(idx2,dtype='int32')
 idx2 = K.clip(idx2,-DIM//2+XDIM+1,DIM//2)
 idx3 = tf.stack([DIM//2-idx2[0,], DIM//2-1+idx2[1,]])
 d = tf.gather_nd(image,tf.transpose(idx3))
return tf.reshape(d,[DIM,DIM,3]),label<categorify>
df[df.GarageYrBlt == df.YearBuilt].shape[0]
def read_labelled_tfrec(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 = tf.image.decode_jpeg(example['image'], channels=3)
 image = tf.cast(image, tf.float32)/ 255.0
image = tf.reshape(image, [*IMAGE_SIZE, 3])
 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 = tf.image.decode_jpeg(example['image'], channels=3)
 image = tf.cast(image, tf.float32)/ 255.0
image = tf.reshape(image, [*IMAGE_SIZE, 3])
 idnum = example['id']
return image, idnum<create_dataframe>
df.loc[(df.GarageYrBlt.isnull())&(df.GarageType.notnull()), "GarageYrBlt"] = df.loc[(df.GarageYrBlt.isnull())&(df.GarageType.notnull())].YearBuilt
def read_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_labelled_tfrec if labeled else read_unlabeled_tfrecord, num_parallel_calls=AUTO)
 return dataset
def read_train_data() :
dataset = read_dataset(TRAINING_FILENAMES, labeled=True)
 dataset = dataset.map(data_augment, num_parallel_calls=AUTO)
 return dataset.repeat().shuffle(2048, reshuffle_each_iteration = True ).batch(BATCH_SIZE ).prefetch(AUTO)
 def read_validation_data(ordered=False):
return read_dataset(VALIDATION_FILENAMES, labeled=True, ordered=ordered ).batch(BATCH_SIZE ).cache().prefetch(AUTO)
 def read_test_data(ordered=False):
return read_dataset(TEST_FILENAMES, labeled=False, ordered=ordered ).batch(BATCH_SIZE ).prefetch(AUTO )<categorify>
df[(df.GarageType == "Detchd")&(df.YearBuilt < 1930)&(df.YearRemodAdd < 2000)&(df.YearRemodAdd > 1980)&(df.GarageCars == 1)].GarageArea.median()
def get_training_dataset(dataset,do_aug=True):
dataset = dataset.map(data_augment, num_parallel_calls=AUTO)
 if do_aug: dataset = dataset.map(transform, num_parallel_calls=AUTO)
 dataset = dataset.repeat()
dataset = dataset.shuffle(2048)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.prefetch(AUTO)
 return dataset
def get_validation_dataset(dataset):
dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.cache()
dataset = dataset.prefetch(AUTO)
 return dataset 
<init_hyperparams>
df.loc[(df.GarageArea.isnull())&(df.GarageType.notnull()), "GarageArea"] = 234
LR_START = 0.0001
LR_MAX = 0.00005 * strategy.num_replicas_in_sync
LR_MIN = 0.00001
LR_RAMPUP_EPOCHS = 4
LR_SUSTAIN_EPOCHS = 6
LR_EXP_DECAY =.8
def lr_scheduler_2(epoch):
if epoch < LR_RAMPUP_EPOCHS:
lr = np.random.random_sample() * LR_START
elif epoch < LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS:
lr = LR_MAX
else:
lr =(LR_MAX - LR_MIN)* LR_EXP_DECAY**(epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS)+ LR_MIN
return lr 
<choose_model_class>
num_cols, cat_cols, ord_cols = col_types(df )
lr_callback = tf.keras.callbacks.LearningRateScheduler(lr_scheduler_2, verbose = True )<predict_on_test>
none_cols = ["PoolQC", "MiscFeature", "Alley", "Fence", "FireplaceQu", "GarageCond", "GarageFinish", "GarageQual",
"GarageType", "BsmtExposure", "BsmtCond", "BsmtQual", "BsmtFinType1", "MasVnrType", "BsmtFinType2"]
for col in none_cols:
df[col].fillna("None", inplace=True)
 missing(df )
def tta(model, TTA_NUM = 10):
probabilities = []
for i in range(TTA_NUM):
print('TTA Number: ',i)
 test_ds = read_test_data(ordered=True)
 test_images_ds = test_ds.map(lambda image, idnum: image)
 gc.collect()
probabilities.append(model.predict(test_images_ds,verbose =1))
prob2 = np.mean(probabilities,axis =0)
 return prob2<predict_on_test>
df.loc[(df.MasVnrArea.isnull())&(df.MasVnrType == "None"), "MasVnrArea"] = 0
def train_and_predict(models, TTA_NUM = 10):
test_ds = read_test_data(ordered=True)
 test_images_ds = test_ds.map(lambda image, idnum: image)
 gc.collect()
print('Computing predictions...')
 print("TTA")
 probability =([tta(models[i], TTA_NUM)for i in range(len(models)) ])
 probabilities = np.average(probability, axis = 0)
 predictions = np.argmax(probabilities, axis=-1)
 gc.collect()
print('Generating submission.csv file...')
 test_ids_ds = test_ds.map(lambda image, idnum: idnum ).unbatch()
test_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES)) ).numpy().astype('U')
 np.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')
 return models<choose_model_class>
for col in ["BsmtFullBath", "BsmtHalfBath", "BsmtFinSF1", "BsmtFinSF2", "BsmtUnfSF", "GarageYrBlt"]:
df[col].fillna(0, inplace = True)
 df["TotalBsmtSF"].fillna(df["BsmtFinSF1"] + df["BsmtFinSF2"] + df["BsmtUnfSF"], inplace = True)
 missing(df )
def get_model1() :
with strategy.scope() :
enet = efn.EfficientNetB7(
 input_shape=(IMAGE_SIZE[0], IMAGE_SIZE[0], 3),
weights='noisy-student',
include_top=False 
)
 model = tf.keras.Sequential([
enet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(classes), activation='softmax')
 ])
 model.compile(
 optimizer=tf.keras.optimizers.Adam() ,
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 return model<choose_model_class>
print(df.MSZoning.value_counts())
 df[df.MSZoning.isnull() ]
def get_model2() :
with strategy.scope() :
enet = tf.keras.applications.DenseNet201(weights='imagenet',
include_top=False,
input_shape=[*IMAGE_SIZE, 3])
 model = tf.keras.Sequential([
enet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(classes), activation='softmax')
 ])
 model.compile(
 optimizer=tf.keras.optimizers.Adam() ,
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 return model<define_variables>
df.groupby("Neighborhood" ).MSZoning.value_counts()
SEED = 25
TTA_NUM = 10
EPOCHS_1 = 32
EPOCHS_2 = 20<define_variables>
df.loc[(df.MSZoning.isnull())&(df.Neighborhood == "IDOTRR"), "MSZoning"] = "C(all)"
df.loc[(df.MSZoning.isnull())&(df.Neighborhood == "Mitchel"), "MSZoning"] = "RL"
models = []<train_model>
df.KitchenQual.value_counts()
gc.collect()
enet_model = get_model1()
history = enet_model.fit(read_train_data() , steps_per_epoch=STEPS_PER_EPOCH, epochs=EPOCHS_1,
callbacks = [lr_callback])
 models.append(enet_model )<train_model>
print(df.groupby(["OverallQual", "KitchenAbvGr"] ).KitchenQual.value_counts())
 df.loc[(df.KitchenQual.isnull())&(df.OverallQual == 5)&(df.KitchenAbvGr == 1), "KitchenQual"] = "TA"
gc.collect()
dnet_model = get_model2()
history = dnet_model.fit(read_train_data() , steps_per_epoch=STEPS_PER_EPOCH, epochs=EPOCHS_2,
callbacks = [lr_callback])
 models.append(dnet_model )<predict_on_test>
print(df.SaleType.value_counts())
 df[df.SaleType.isnull() ]
model_h = train_and_predict(models, TTA_NUM )<import_modules>
print(df.groupby(["Neighborhood", "SaleCondition"] ).SaleType.value_counts())
 df.loc[(df.SaleType.isnull())&(df.Neighborhood == "Sawyer")&(df.SaleCondition == "Normal"), "SaleType"] = "WD"
import numpy as np
import pandas as pd
import os 
<set_options>
print(df.Electrical.value_counts())
 df[df.Electrical.isnull() ]
!pip install -q efficientnet
print("Tensorflow version " + tf.__version__)
 AUTO = tf.data.experimental.AUTOTUNE<set_options>
df[(df.YearBuilt > 2005)].Electrical.value_counts()
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>
df.Electrical.fillna("SBrkr", inplace=True )
GCS_DS_PATH = KaggleDatasets().get_gcs_path()<define_variables>
print(df.Exterior1st.value_counts())
 df[df.Exterior1st.isnull() ]
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')
 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']<define_variables>
print(df[(df.RoofMatl == "Tar&Grv")].Exterior1st.value_counts())
 df.Exterior1st.fillna("Plywood", inplace=True )
VALIDATION = False
if not VALIDATION:
TRAINING_FILENAMES = TRAINING_FILENAMES+VALIDATION_FILENAMES<normalization>
print(df[(df.RoofMatl == "Tar&Grv")].Exterior2nd.value_counts())
 df.Exterior2nd.fillna("Plywood", inplace=True )
def get_mat(rotation, shear, height_zoom, width_zoom, height_shift, width_shift):
rotation = math.pi * rotation / 180.
 shear = math.pi * shear / 180.
 c1 = tf.math.cos(rotation)
 s1 = tf.math.sin(rotation)
 one = tf.constant([1],dtype='float32')
 zero = tf.constant([0],dtype='float32')
 rotation_matrix = tf.reshape(tf.concat([c1,s1,zero, -s1,c1,zero, zero,zero,one],axis=0),[3,3])
 c2 = tf.math.cos(shear)
 s2 = tf.math.sin(shear)
 shear_matrix = tf.reshape(tf.concat([one,s2,zero, zero,c2,zero, zero,zero,one],axis=0),[3,3])
 zoom_matrix = tf.reshape(tf.concat([one/height_zoom,zero,zero, zero,one/width_zoom,zero, zero,zero,one],axis=0),[3,3])
 shift_matrix = tf.reshape(tf.concat([one,zero,height_shift, zero,one,width_shift, zero,zero,one],axis=0),[3,3])
 return K.dot(K.dot(rotation_matrix, shear_matrix), K.dot(zoom_matrix, shift_matrix))<define_search_space>
print(df.Functional.value_counts())
 df[df.Functional.isnull() ]
def transform(image,label):
DIM = IMAGE_SIZE[0]
XDIM = DIM%2
rot = 15.* tf.random.normal([1],dtype='float32')
 shr = 5.* tf.random.normal([1],dtype='float32')
 h_zoom = 1.0 + tf.random.normal([1],dtype='float32')/10.
 w_zoom = 1.0 + tf.random.normal([1],dtype='float32')/10.
 h_shift = 16.* tf.random.normal([1],dtype='float32')
 w_shift = 16.* tf.random.normal([1],dtype='float32')
 m = get_mat(rot,shr,h_zoom,w_zoom,h_shift,w_shift)
 x = tf.repeat(tf.range(DIM//2,-DIM//2,-1), DIM)
 y = tf.tile(tf.range(-DIM//2,DIM//2),[DIM])
 z = tf.ones([DIM*DIM],dtype='int32')
 idx = tf.stack([x,y,z])
 idx2 = K.dot(m,tf.cast(idx,dtype='float32'))
idx2 = K.cast(idx2,dtype='int32')
 idx2 = K.clip(idx2,-DIM//2+XDIM+1,DIM//2)
 idx3 = tf.stack([DIM//2-idx2[0,], DIM//2-1+idx2[1,]])
 d = tf.gather_nd(image,tf.transpose(idx3))
return tf.reshape(d,[DIM,DIM,3]),label<categorify>
df[(df.Neighborhood == "IDOTRR")&(df.OverallQual < 5)&(df.YearRemodAdd < 1960)&(df.ExterQual == "Fa")].Functional.value_counts()
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 = 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))<train_model>
df.Functional.fillna("Mod", inplace = True )
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'))<train_model>
df["LotFrontage"] = df["LotFrontage"].fillna(df.groupby(["Neighborhood", "LotShape", "LotConfig"])["LotFrontage"].transform("median"))
df["LotFrontage"] = df["LotFrontage"].fillna(df.groupby(["Neighborhood", "LotShape"])["LotFrontage"].transform("median"))
df["LotFrontage"] = df["LotFrontage"].fillna(df.groupby("Neighborhood")["LotFrontage"].transform("median"))
training_dataset = get_training_dataset()
training_dataset = training_dataset.unbatch().batch(20)
 train_batch = iter(training_dataset )<categorify>
df.Utilities.fillna(df.Utilities.mode() [0], inplace=True)
 missing(df )
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.'] )<define_variables>
df["MSSubClass"] = df["MSSubClass"].astype("str" )
display_batch_of_images(next(train_batch))<define_variables>
df.loc[(df.GarageYrBlt == 2207), "GarageYrBlt"] = 2007
df.loc[(df.Exterior2nd == "CmentBd"), "Exterior2nd"] = "CemntBd"
df.loc[(df.Exterior2nd == "Wd Shng"), "Exterior2nd"] = "WdShing"
df.loc[(df.Exterior2nd == "Brk Cmn"), "Exterior2nd"] = "BrkComm"
test_dataset = get_test_dataset()
test_dataset = test_dataset.unbatch().batch(20)
 test_batch = iter(test_dataset )<define_variables>
dff = df.copy()
display_batch_of_images(next(test_batch))<choose_model_class>
num_cols, cat_cols, ord_cols = col_types(dff)
 for col in dff.columns:
print("For column: ", col + "
")
 print(dff[col].value_counts() , "
" )
with strategy.scope() :
enb7 = efn.EfficientNetB7(weights='imagenet', include_top=False, input_shape=[*IMAGE_SIZE, 3])
 enb7.trainable = True
model1 = tf.keras.Sequential([
enb7,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model1.compile(
 optimizer = tf.keras.optimizers.Adam(learning_rate=0.001, beta_1=0.9, beta_2=0.999, amsgrad=False),
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 model1.summary() 
<choose_model_class>
dff["Older1945"] = dff["MSSubClass"].apply(lambda x: 1 if x in ["30", "70"] else 0)
 dff["Newer1946"] = dff["MSSubClass"].apply(lambda x: 1 if x in ["20", "60", "120", "160"] else 0)
 dff["AllStyles"] = dff["MSSubClass"].apply(lambda x: 1 if x in ["20", "90", "190"] else 0)
 dff["AllAges"] = dff["MSSubClass"].apply(lambda x: 1 if x in ["40", "45", "50", "75", "90", "150", "190"] else 0)
 dff["Pud"] = dff["MSSubClass"].apply(lambda x: 1 if x in ["120", "150", "160", "180"] else 0)
 dff["Split"] = dff["MSSubClass"].apply(lambda x: 1 if x in ["80", "85""180"] else 0)
 dff["MSSubClass"] = dff["MSSubClass"].apply(lambda x: "180" if x == "150" else x )
with strategy.scope() :
enb7 = efn.EfficientNetB7(weights='noisy-student', include_top=False, input_shape=[*IMAGE_SIZE, 3])
 enb7.trainable = True
model2 = tf.keras.Sequential([
enb7,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model2.compile(
 optimizer = tf.keras.optimizers.Adam(learning_rate=0.001, beta_1=0.9, beta_2=0.999, amsgrad=False),
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 model2.summary()<randomize_order>
dff["MSZoning"] = dff["MSZoning"].apply(lambda x: "R" if x.startswith("R")else x )
LR_START = 0.0001
LR_MAX = 0.00005 * strategy.num_replicas_in_sync
LR_MIN = 0.00001
LR_RAMPUP_EPOCHS = 4
LR_SUSTAIN_EPOCHS = 6
LR_EXP_DECAY =.8
def lrfn(epoch):
if epoch < LR_RAMPUP_EPOCHS:
lr = np.random.random_sample() * LR_START
elif epoch < LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS:
lr = LR_MAX
else:
lr =(LR_MAX - LR_MIN)* LR_EXP_DECAY**(epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS)+ LR_MIN
return lr
lr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=True )<choose_model_class>
dff["North"] = dff["Neighborhood"].apply(lambda x: 1 if x in ["Blmngtn", "BrDale", "ClearCr", "Gilbert", "Names", "NoRidge",
"NPkVill", "NWAmes", "NoRidge", "NridgHt", "Sawyer", "Somerst",
"StoneBr", "Veenker", "NridgHt"] else 0)
 dff["South"] = dff["Neighborhood"].apply(lambda x: 1 if x in ["Blueste", "Edwards", "Mitchel", "MeadowV",
"SWISU", "IDOTRR", "Timber"] else 0)
 dff["Downtown"] = dff["Neighborhood"].apply(lambda x: 1 if x in ["BrkSide", "Crawfor", "OldTown", "CollgCr"] else 0)
 dff["East"] = dff["Neighborhood"].apply(lambda x: 1 if x in ["IDOTRR", "Mitchel"] else 0)
 dff["West"] = dff["Neighborhood"].apply(lambda x: 1 if x in ["Edwards", "NWAmes", "SWISU", "Sawyer", "SawyerW"] else 0 )
es_callback = tf.keras.callbacks.EarlyStopping(min_delta=0, patience=10, verbose=1, mode='auto', restore_best_weights=True )<train_model>
dff.loc[(dff["Condition1"] == "Feedr")|(dff["Condition2"] == "Feedr"), "StreetDegree"] = 1
dff.loc[(dff["Condition1"] == "Artery")|(dff["Condition2"] == "Artery"), "StreetDegree"] = 2
dff["StreetDegree"].fillna(0, inplace = True)
 dff.loc[(dff["Condition1"].isin(["RRNn", "RRNe"])) |(dff["Condition2"].isin(["RRNn", "RRNe"])) , "RailroadDegree"] = 1
dff.loc[(dff["Condition1"].isin(["RRAn", "RRAe"])) |(dff["Condition2"].isin(["RRAn", "RRAe"])) , "RailroadDegree"] = 2
dff["RailroadDegree"].fillna(0, inplace = True)
 dff.loc[(dff["Condition1"] == "PosN")|(dff["Condition2"] == "PosN"), "OffsiteFeature"] = 1
dff.loc[(dff["Condition1"] == "PosA")|(dff["Condition2"] == "PosA"), "OffsiteFeature"] = 2
dff["OffsiteFeature"].fillna(0, inplace = True)
 dff["Norm1"] = dff["Condition1"].apply(lambda x: 1 if x == "Norm" else 0)
 dff["Norm2"] = dff["Condition2"].apply(lambda x: 1 if x == "Norm" else 0)
 dff["Norm"] = dff["Norm1"] + dff["Norm2"]
dff.drop(["Norm1", "Norm2"], axis = 1, inplace = True )
if VALIDATION:
history1 = model1.fit(get_training_dataset() , steps_per_epoch=STEPS_PER_EPOCH, epochs=40, validation_data=get_validation_dataset() , callbacks = [lr_callback, es_callback])
 else:
history1 = model1.fit(get_training_dataset() , steps_per_epoch=STEPS_PER_EPOCH, epochs=30, callbacks = [lr_callback])
<train_model>
lotshape = {"IR3": 1, "IR2": 2, "IR1": 3, "Reg": 4}
landcontour = {"Low":1, "HLS": 2, "Bnk":3, "Lvl": 4}
utilities = {"ELO": 1, "NoSeWa": 2, "NoSewr": 3, "AllPub": 4}
landslope = {"Sev": 1, "Mod": 2, "Gtl": 3}
general = {"None": 0, "Po": 1, "Fa": 2, "TA": 3, "Gd": 4, "Ex": 5}
bsmtexposure = {"None": 0, "No": 0, "Mn": 1, "Av": 2, "Gd": 3}
bsmtfintype = {"None": 0, "Unf": 1, "LwQ": 2, "Rec": 3, "BLQ": 4, "ALQ": 5, "GLQ": 6}
electrical = {"Mix": 1, "FuseP": 2, "FuseF": 3, "FuseA": 4, "SBrkr": 5}
functional = {"Typ": 1, "Min1": 2, "Min2": 3, "Mod": 4, "Maj1": 5, "Maj2": 6, "Sev": 7, "Sal": 8}
garagefinish = {"None": 0, "Unf": 1, "RFn": 2, "Fin": 3}
fence = {"None": 0, "MnWw": 1, "GdWo": 2, "MnPrv": 3, "GdPrv": 4}
dff.replace({"LotShape": lotshape, "LandContour": landcontour, "Utilities": utilities, "LandSlope": landslope,
"BsmtExposure": bsmtexposure, "BsmtFinType1": bsmtfintype, "BsmtFinType2":bsmtfintype, "Electrical": electrical,
"Functional": functional, "GarageFinish": garagefinish, "Fence": fence},
inplace = True)
 for col in ["ExterQual", "ExterCond", "BsmtQual", "BsmtCond", "HeatingQC", "KitchenQual",
"FireplaceQu", "GarageQual", "GarageCond", "PoolQC"]:
dff[col] = dff[col].replace(general )
if VALIDATION:
history2 = model2.fit(get_training_dataset() , steps_per_epoch=STEPS_PER_EPOCH, epochs=40, validation_data=get_validation_dataset() , callbacks = [lr_callback, es_callback])
 else:
history2 = model2.fit(get_training_dataset() , steps_per_epoch=STEPS_PER_EPOCH, epochs=30, callbacks = [lr_callback] )<predict_on_test>
dff["BldgType"] = dff["BldgType"].apply(lambda x: "2Fam" if x in ["2fmCon", "Duplex"] else x)
 dff["SaleType"] = dff["SaleType"].apply(lambda x: "WD" if x.endswith("WD")else x)
 dff["SaleType"] = dff["SaleType"].apply(lambda x: "Contract" if x.startswith("Con")else x)
 dff["SaleType"] = dff["SaleType"].apply(lambda x: "Oth" if x == "COD" else x)
 dff["SaleCondition"] = dff["SaleCondition"].apply(lambda x: "Abnormal_Adjland" if x in ["Abnorml", "AdjLand"] else x)
 dff["SaleCondition"] = dff["SaleCondition"].apply(lambda x: "Alloca_Family" if x in ["Alloca", "Family"] else x)
 dff["SaleCondition"] = dff["SaleCondition"].apply(lambda x: "Other" if x in ["Abnormal_Adjland", "Alloca_Family"] else x)
 dff["GarageType"] = dff["GarageType"].apply(lambda x: "Carport_None" if x in ["CarPort", "None"] else x)
 dff["GarageType"] = dff["GarageType"].apply(lambda x: "Basement_2Types" if x in ["Basment", "2Types"] else x)
 dff["LotConfig"] = dff["LotConfig"].apply(lambda x: "CulDSac_FR3" if x in ["CulDSac", "FR3"] else x)
 dff["RoofStyle"] = dff["RoofStyle"].apply(lambda x: "Other" if x not in ["Gable"] else x)
 dff["RoofMatl"] = dff["RoofMatl"].apply(lambda x: "Other" if x != "CompShg" else x)
 dff["MasVnrType"] = dff["MasVnrType"].apply(lambda x: "None_BrkCmn" if x in ["None", "BrkCmn"] else x)
 dff["Foundation"] = dff["Foundation"].apply(lambda x: "BrkTil_Stone" if x in ["BrkTil", "Stone"] else x)
 dff["Foundation"] = dff["Foundation"].apply(lambda x: "BrkTil_Stone_Slab" if x in ["BrkTil_Stone", "Slab"] else x)
 dff["Foundation"] = dff["Foundation"].apply(lambda x: "PConc_Wood" if x in ["PConc", "Wood"] else x)
 dff["Heating"] = dff["Heating"].apply(lambda x: "Other" if x != "GasA" else x )
if VALIDATION:
cmdataset = get_validation_dataset(ordered=True)
 images_ds = cmdataset.map(lambda image, label: image)
 labels_ds = cmdataset.map(lambda image, label: label ).unbatch()
cm_correct_labels = next(iter(labels_ds.batch(NUM_VALIDATION_IMAGES)) ).numpy()
cm_probabilities =(model1.predict(images_ds)*0.3)+model2.predict(images_ds)*0.7
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_test_metric>
dff["FrontageRatio"] =(dff["LotFrontage"] / dff["LotArea"])
 dff["HQFloor"] = dff["1stFlrSF"] + dff["2ndFlrSF"]
dff["FloorAreaRatio"] = dff["GrLivArea"] / dff["LotArea"]
dff["TotalArea"] = dff["TotalBsmtSF"] + dff["GrLivArea"]
dff["TotalPorch"] = dff["WoodDeckSF"] + dff["OpenPorchSF"] + dff["EnclosedPorch"] + dff["3SsnPorch"] + dff["ScreenPorch"]
dff["WeightedBsmtFinSF1"] = dff["BsmtFinSF1"] * dff["BsmtFinType1"]
dff["WeightedBsmtFinSF2"] = dff["BsmtFinSF2"] * dff["BsmtFinType2"]
dff["WeightedTotalBasement"] = dff["WeightedBsmtFinSF1"] + dff["BsmtFinSF2"] * dff["BsmtFinType2"] + dff["BsmtUnfSF"]
dff["TotalFullBath"] = dff["BsmtFullBath"] + dff["FullBath"]
dff["TotalHalfBath"] = dff["BsmtHalfBath"] + dff["HalfBath"]
dff["TotalBsmtBath"] = dff["BsmtFullBath"] + 0.5 * dff["BsmtHalfBath"]
dff["TotalBath"] = dff["TotalFullBath"] + 0.5 *(dff["BsmtHalfBath"] + dff["HalfBath"])+ dff["BsmtFullBath"] + 0.5 * dff["BsmtHalfBath"]
dff["HasPool"] = dff["PoolArea"].apply(lambda x: 0 if x == 0 else 1)
 dff["Has2ndFlr"] = dff["2ndFlrSF"].apply(lambda x: 0 if x == 0 else 1)
 dff["HasBsmt"] = dff["TotalBsmtSF"].apply(lambda x: 0 if x == 0 else 1)
 dff["HasFireplace"] = dff["Fireplaces"].apply(lambda x: 0 if x == 0 else 1)
 dff["HasGarage"] = dff["GarageArea"].apply(lambda x: 0 if x == 0 else 1)
 dff["HasLowQual"] = dff["LowQualFinSF"].apply(lambda x: 0 if x == 0 else 1)
 dff["HasPorch"] = dff["TotalPorch"].apply(lambda x: 0 if x == 0 else 1)
 dff["HasMiscVal"] = dff["MiscVal"].apply(lambda x: 0 if x == 0 else 1)
 dff["HasWoodDeck"] = dff["WoodDeckSF"].apply(lambda x: 0 if x == 0 else 1)
 dff["HasOpenPorch"] = dff["OpenPorchSF"].apply(lambda x: 0 if x == 0 else 1)
 dff["HasEnclosedPorch"] = dff["EnclosedPorch"].apply(lambda x: 0 if x == 0 else 1)
 dff["Has3SsnPorch"] = dff["3SsnPorch"].apply(lambda x: 0 if x == 0 else 1)
 dff["HasScreenPorch"] = dff["ScreenPorch"].apply(lambda x: 0 if x == 0 else 1)
 dff["TotalPorchType"] = dff["HasWoodDeck"] + dff["HasOpenPorch"] + dff["HasEnclosedPorch"] + dff["Has3SsnPorch"] + dff["HasScreenPorch"]
dff["TotalPorchType"] = dff["TotalPorchType"].apply(lambda x: 3 if x >=3 else x )
if VALIDATION:
cmat = confusion_matrix(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)))
 score = f1_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
 precision = precision_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
 recall = recall_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
 display_confusion_matrix(cmat, score, precision, recall)
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score, precision, recall))<predict_on_test>
dff["RestorationAge"] = dff["YearRemodAdd"] - dff["YearBuilt"]
dff["RestorationAge"] = dff["RestorationAge"].apply(lambda x: 0 if x < 0 else x)
 dff["HasRestoration"] = dff["RestorationAge"].apply(lambda x: 0 if x == 0 else 1)
 dff["YearAfterRestoration"] = dff["YrSold"] - dff["YearRemodAdd"]
dff["YearAfterRestoration"] = dff["YearAfterRestoration"].apply(lambda x: 0 if x < 0 else x)
 dff["BuildAge"] = dff["YrSold"] - dff["YearBuilt"]
dff["BuildAge"] = dff["BuildAge"].apply(lambda x: 0 if x < 0 else x)
 dff["IsNewHouse"] = dff["BuildAge"].apply(lambda x: 1 if x == 0 else 0)
 def year_map(year):
year = 1 if year <= 1895 else\ 
(2 if year <= 1916 else\ 
(3 if year <= 1919 else\ 
(4 if year <= 1929 else\ 
(5 if year <= 1941 else\ 
(6 if year <= 1945 else\ 
(7 if year <= 1964 else\ 
(8 if year <= 1980 else\ 
(9 if year <= 1991 else\ 
(10 if year < 2008 else 11)))))))))
 return year
dff["YearBuilt_bins"] = dff["YearBuilt"].apply(lambda year: year_map(year))
dff["YearRemodAdd_bins"] = dff["YearRemodAdd"].apply(lambda year: year_map(year))
dff["GarageYrBlt_bins"] = dff["GarageYrBlt"].apply(lambda year: year_map(year))
dff["YrSold"] = dff["YrSold"].astype(str)
 dff["MoSold"] = dff["MoSold"].astype(str)
 dff["Season"] = dff["MoSold"].apply(lambda x: "Winter" if x in ["12", "1", "2"] else\ 
("Spring" if x in ["3", "4", "5"] else\ 
("Summer" if x in ["6", "7", "8"] else "Fall")) )
test_ds = get_test_dataset(ordered=True)
 print('Computing predictions...')
 test_images_ds = test_ds.map(lambda image, idnum: image)
 probabilities =(model1.predict(test_images_ds)*0.3)+model2.predict(test_images_ds)*0.7
predictions = np.argmax(probabilities, axis=-1)
 print(predictions)
 print('Generating submission.csv file...')
 test_ids_ds = test_ds.map(lambda image, idnum: idnum ).unbatch()
test_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES)) ).numpy().astype('U')
 np.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')
 !head submission.csv<define_variables>
dff["OverallValue"] = dff["OverallQual"] * dff["OverallCond"]
dff["ExterValue"] = dff["ExterQual"] * dff["ExterCond"]
dff["BsmtValue"] =(( dff["BsmtQual"] + dff["BsmtFinType1"] + dff["BsmtFinType2"])* dff["BsmtCond"])/ 2
dff["KitchenValue"] = dff["KitchenAbvGr"] * dff["KitchenQual"]
dff["FireplaceValue"] = dff["Fireplaces"] * dff["FireplaceQu"]
dff["GarageValue"] = dff["GarageQual"] * dff["GarageCond"]
dff["TotalValue"] = dff["OverallValue"] + dff["ExterValue"] + dff["BsmtValue"] + dff["KitchenValue"] + dff["FireplaceValue"] + dff["GarageValue"] +\
dff["HeatingQC"] + dff["Utilities"] + dff["Electrical"] - dff["Functional"] + dff["PoolQC"]
dff["TotalQual"] = dff["OverallQual"] + dff["ExterQual"] + dff["BsmtQual"] + dff["KitchenQual"] + dff["FireplaceQu"] + dff["GarageQual"] +\
dff["HeatingQC"] + dff["PoolQC"]
dff["TotalCond"] = dff["OverallCond"] + dff["ExterCond"] + dff["BsmtCond"] + dff["GarageCond"]
dff["TotalQualCond"] = dff["TotalQual"] + dff["TotalCond"]
if VALIDATION:
dataset = get_validation_dataset()
dataset = dataset.unbatch().batch(20)
 batch = iter(dataset )<predict_on_test>
dff["BsmtSFxValue"] = dff["TotalBsmtSF"] * dff["BsmtValue"]
dff["BsmtSFxQual"] = dff["TotalBsmtSF"] * dff["BsmtQual"]
dff["TotalAreaXOverallValue"] = dff["TotalArea"] * dff["OverallValue"]
dff["TotalAreaXOverallQual"] = dff["TotalArea"] * dff["OverallQual"]
dff["GarageAreaXGarageValue"] = dff["GarageArea"] * dff["GarageValue"]
dff["GarageAreaXGarageQual"] = dff["GarageArea"] * dff["GarageQual"]
if VALIDATION:
images, labels = next(batch)
 probabilities =(model1.predict(images)*0.3)+model2.predict(images)*0.7
predictions = np.argmax(probabilities, axis=-1)
 display_batch_of_images(( images, labels), predictions )<install_modules>
dff2 = dff.copy()
num_cols2, cat_cols2, ord_cols2 = col_types(dff2 )
!pip install -q efficientnet<import_modules>
dff2["LotShape"] = dff2["LotShape"].apply(lambda x: 1 if x in [1, 2] else(2 if x == 3 else 3))
dff2["LandSlope"] = dff2["LandSlope"].apply(lambda x: 1 if x in [1, 2] else(2 if x == 3 else 3))
dff2["OverallCond"] = dff2["OverallCond"].apply(lambda x: 1 if x in [1, 2, 3] else x-1)
 dff2["OverallQual"] = dff2["OverallQual"].apply(lambda x: 1 if x in [1, 2] else x-1)
 dff2["ExterCond"] = dff2["ExterCond"].apply(lambda x: 1 if x in [1, 2] else(2 if x == 3 else 3))
dff2["BsmtQual"] = dff2["BsmtQual"].apply(lambda x: 0 if x in [0, 1, 2] else(1 if x == 3 else(2 if x == 4 else 3)))
 dff2["BsmtCond"] = dff2["BsmtCond"].apply(lambda x: 0 if x in [0, 1, 2] else(1 if x == 3 else 2))
dff2["BsmtFinType1"] = dff2["BsmtFinType1"].apply(lambda x: 1 if x in [1, 2, 3, 4, 5] else(2 if x == 6 else x))
dff2["BsmtFinType2"] = dff2["BsmtFinType2"].apply(lambda x: 1 if x in [1, 2, 3, 4, 5] else(2 if x == 6 else x))
dff2["HeatingQC"] = dff2["HeatingQC"].apply(lambda x: 1 if x in [1, 2] else(2 if x in [3, 4] else 3))
dff2["Electrical"] = dff2["Electrical"].apply(lambda x: 1 if x in [1, 2] else x-3)
 dff2["BsmtFullBath"] = dff2["BsmtFullBath"].apply(lambda x: 2 if x >= 2 else x)
 dff2["FullBath"] = dff2["FullBath"].apply(lambda x: 1 if x <= 1 else(3 if x >= 3 else x))
dff2["HalfBath"] = dff2["HalfBath"].apply(lambda x: 1 if x >= 1 else 0)
 dff2["BedroomAbvGr"] = dff2["BedroomAbvGr"].apply(lambda x: 1 if x <=1 else(5 if x >= 5 else x))
dff2["KitchenAbvGr"] = dff2["KitchenAbvGr"].apply(lambda x: 1 if x <= 1 else(2 if x >= 2 else x))
dff2["TotRmsAbvGrd"] = dff2["TotRmsAbvGrd"].apply(lambda x: 3 if x <= 4 else(10 if x >= 11 else x-1))
dff2["Functional"] = dff2["Functional"].apply(lambda x: 1 if x == 1 else 2)
 dff2["Fireplaces"] = dff2["Fireplaces"].apply(lambda x: 2 if x >= 2 else x)
 dff2["GarageCars"] = dff2["GarageCars"].apply(lambda x: 3 if x >= 3 else x)
 dff2["GarageQual"] = dff2["GarageQual"].apply(lambda x: 1 if x <= 2 else(2 if x == 3 else 3))
dff2["GarageCond"] = dff2["GarageCond"].apply(lambda x: 1 if x <= 2 else 2)
 dff2["Fence"] = dff2["Fence"].apply(lambda x: 1 if x in [1, 3] else x )
print("Tensorflow version " + tf.__version__)
<choose_model_class>
dff3 = dff2.copy()
dff3
AUTO = tf.data.experimental.AUTOTUNE
tpu = tf.distribute.cluster_resolver.TPUClusterResolver()
tf.config.experimental_connect_to_cluster(tpu)
 tf.tpu.experimental.initialize_tpu_system(tpu)
 strategy = tf.distribute.experimental.TPUStrategy(tpu)
 GCS_DS_PATH = KaggleDatasets().get_gcs_path('flower-classification')
 img_size=512
IMAGE_SIZE = [img_size, img_size]
EPOCHS = 15
BATCH_SIZE = 16 * strategy.num_replicas_in_sync<init_hyperparams>
for col in cat_cols2:
print(col, dff3[col].value_counts().size )
LR_START = 0.00001
LR_MAX = 0.00005 * strategy.num_replicas_in_sync
LR_MIN = 0.00001
LR_RAMPUP_EPOCHS = 5
LR_SUSTAIN_EPOCHS = 0
LR_EXP_DECAY =.8
def lrfn(epoch):
if epoch < LR_RAMPUP_EPOCHS:
lr =(LR_MAX - LR_START)/ LR_RAMPUP_EPOCHS * epoch + LR_START
elif epoch < LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS:
lr = LR_MAX
else:
lr =(LR_MAX - LR_MIN)* LR_EXP_DECAY**(epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS)+ LR_MIN
return lr
lr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=True)
 rng = [i for i in range(EPOCHS)]
y = [lrfn(x)for x in rng]
plt.plot(rng, y)
 print("Learning rate schedule: {:.3g} to {:.3g} to {:.3g}".format(y[0], max(y), y[-1]))<define_variables>
target_encoding = ["MSSubClass", "Neighborhood", "Exterior1st", "Exterior2nd", "Condition1", "Condition2", "HouseStyle"]
for col in target_encoding:
feature_name = col + "Rank"
dff3.loc[:, feature_name] = dff3[col].map(dff3.groupby(col ).SalePrice.median())
 dff3.loc[:, feature_name] = dff3.loc[:, feature_name].rank(method = "dense" )
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')
 TRAINING_FILENAMES=TRAINING_FILENAMES
VALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec')
 TEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec')
 SKIP_VALIDATION = True
if SKIP_VALIDATION:
TRAINING_FILENAMES = TRAINING_FILENAMES + VALIDATION_FILENAMES<define_variables>
dff3["Exterior"] = np.where(( dff3["Exterior1st"] != dff3["Exterior2nd"]), "Mixed", dff3["Exterior1st"])
 dff3["No2ndExt"] = dff3["Exterior"].apply(lambda x: 0 if x == "Mixed" else 1 )
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>
drop_cols = ["MSSubClass", "Neighborhood", "Condition1", "Condition2", "Exterior1st", "Exterior2nd", "PoolArea", "PoolQC",
"WoodDeckSF", "OpenPorchSF", "EnclosedPorch", "3SsnPorch", "ScreenPorch", "LowQualFinSF", "MiscVal", "2ndFlrSF",
"HouseStyle","YrSold", "MoSold", "YearBuilt", "YearRemodAdd", "GarageYrBlt", "Exterior", "Utilities", "Street"]
dff3.drop(drop_cols, axis = 1, inplace = True )
def random_blockout(img, sl=0.1, sh=0.2, rl=0.4):
h, w, c = img_size, img_size, 3
origin_area = tf.cast(h*w, tf.float32)
 e_size_l = tf.cast(tf.round(tf.sqrt(origin_area * sl * rl)) , tf.int32)
 e_size_h = tf.cast(tf.round(tf.sqrt(origin_area * sh / rl)) , tf.int32)
 e_height_h = tf.minimum(e_size_h, h)
 e_width_h = tf.minimum(e_size_h, w)
 erase_height = tf.random.uniform(shape=[], minval=e_size_l, maxval=e_height_h, dtype=tf.int32)
 erase_width = tf.random.uniform(shape=[], minval=e_size_l, maxval=e_width_h, dtype=tf.int32)
 erase_area = tf.zeros(shape=[erase_height, erase_width, c])
 erase_area = tf.cast(erase_area, tf.uint8)
 pad_h = h - erase_height
pad_top = tf.random.uniform(shape=[], minval=0, maxval=pad_h, dtype=tf.int32)
 pad_bottom = pad_h - pad_top
pad_w = w - erase_width
pad_left = tf.random.uniform(shape=[], minval=0, maxval=pad_w, dtype=tf.int32)
 pad_right = pad_w - pad_left
erase_mask = tf.pad([erase_area], [[0,0],[pad_top, pad_bottom], [pad_left, pad_right], [0,0]], constant_values=1)
 erase_mask = tf.squeeze(erase_mask, axis=0)
 erased_img = tf.multiply(tf.cast(img,tf.float32), tf.cast(erase_mask, tf.float32))
return tf.cast(erased_img, img.dtype )<categorify>
num_, cat_, ord_ = col_types(dff3)
 def prep_data(df, cat_cols, target):
dummies = pd.get_dummies(df[cat_cols], drop_first = True)
 data = pd.concat([df, dummies], axis = 1 ).drop(cat_cols, axis = 1)
 train = data[data[target].notnull() ]
test = data[data[target].isnull() ]
return train, test
train, test = prep_data(dff3, cat_, "SalePrice")
 target = "SalePrice"
predictors = [x for x in train.columns if x not in ["Id", "SalePrice"]]
def decode_image(image_data):
image = tf.image.decode_jpeg(image_data, channels=3)
 image = tf.cast(image, tf.float32)/ 255.0
image = tf.reshape(image, [*IMAGE_SIZE, 3])
 return image
def read_labeled_tfrecord(example):
LABELED_TFREC_FORMAT = {
"image": tf.io.FixedLenFeature([], tf.string),
"class": tf.io.FixedLenFeature([], tf.int64),
}
example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)
 image = decode_image(example['image'])
 label = tf.cast(example['class'], tf.int32)
 return image, label
def read_unlabeled_tfrecord(example):
UNLABELED_TFREC_FORMAT = {
"image": tf.io.FixedLenFeature([], tf.string),
"id": tf.io.FixedLenFeature([], tf.string),
}
example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT)
 image = decode_image(example['image'])
 idnum = example['id']
return image, idnum
def load_dataset(filenames, labeled=True, ordered=False):
ignore_order = tf.data.Options()
if not ordered:
ignore_order.experimental_deterministic = False
dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO)
 dataset = dataset.with_options(ignore_order)
 dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls=AUTO)
 return dataset
def data_augment(image, label):
image = tf.image.random_flip_left_right(image)
 image= random_blockout(image)
 return image, label
def get_training_dataset() :
dataset = load_dataset(TRAINING_FILENAMES, labeled=True)
 dataset = dataset.map(data_augment, num_parallel_calls=AUTO)
 dataset = dataset.repeat()
dataset = dataset.shuffle(2048)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.prefetch(AUTO)
 return dataset
def get_validation_dataset(ordered=False):
dataset = load_dataset(VALIDATION_FILENAMES, labeled=True, ordered=ordered)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.cache()
dataset = dataset.prefetch(AUTO)
 return dataset
def get_test_dataset(ordered=False):
dataset = load_dataset(TEST_FILENAMES, labeled=False, ordered=ordered)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.prefetch(AUTO)
 return dataset
def count_data_items(filenames):
n = [int(re.compile(r"-([0-9]*)\." ).search(filename ).group(1)) for filename in filenames]
return np.sum(n)
 NUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)
 NUM_VALIDATION_IMAGES =(1 - SKIP_VALIDATION)* count_data_items(VALIDATION_FILENAMES)
 NUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)
 STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE
print('Dataset: {} training images, {} validation images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))<choose_model_class>
high_skew = skewed[skewed.TrainSkewness_AfterYeoJohnson.abs() > 1].Feature.tolist()
print(high_skew)
 train.drop(high_skew, axis = 1, inplace = True)
 test.drop(high_skew, axis = 1, inplace = True )
with strategy.scope() :
enet = efn.EfficientNetB7(
 input_shape=(img_size, img_size, 3),
weights='imagenet',
include_top=False 
)
 model = tf.keras.Sequential([
enet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model.compile(
 optimizer=tf.keras.optimizers.Adam(lr=0.0001),
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 model.summary()<train_model>
train[target] = np.log1p(train[target])
 feature_distribution(train, target, test = False)
 train[target].skew()
history = model.fit(
 get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS,
callbacks=[lr_callback],
validation_data=None if SKIP_VALIDATION else get_validation_dataset() 
)
 test_ds = get_test_dataset(ordered=True)
 print('Computing predictions...')
 test_images_ds = test_ds.map(lambda image, idnum: image)
 preds1=model.predict(test_images_ds)
 del model
gc.collect()
tf.tpu.experimental.initialize_tpu_system(tpu )<choose_model_class>
target = "SalePrice"
predictors = [x for x in train.columns if x not in ["Id", "SalePrice"]]
with strategy.scope() :
Inet = InceptionResNetV2(
 input_shape=(img_size, img_size, 3),
weights='imagenet',
include_top=False 
)
 model2 = tf.keras.Sequential([
Inet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model2.compile(
 optimizer=tf.keras.optimizers.Adam(lr=0.0001),
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 model2.summary()<train_model>
scaler = RobustScaler()
train[predictors] = scaler.fit_transform(train[predictors])
 test[predictors] = scaler.transform(test[predictors] )
history2 = model2.fit(
 get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS,
callbacks=[lr_callback],
validation_data=None if SKIP_VALIDATION else get_validation_dataset() 
)
 preds2=model2.predict(test_images_ds)
 del model2
gc.collect()
tf.tpu.experimental.initialize_tpu_system(tpu )<choose_model_class>
X_train = train[predictors]
y_train = train[target]
X_test = test[predictors]
print(X_train.shape)
 print(X_test.shape )
with strategy.scope() :
desnet=DenseNet201(
 weights='imagenet',
include_top=False 
)
 model3 = tf.keras.Sequential([
desnet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model3.compile(
 optimizer=tf.keras.optimizers.Adam(lr=0.0001),
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
<train_model>
selector = VarianceThreshold(0.01)
 selector.fit(X_train)
 X_train = X_train[X_train.columns[selector.get_support() ]]
selector.transform(X_test)
 X_test = X_test[X_test.columns[selector.get_support() ]]
print(X_train.shape)
 print(X_test.shape)
 X_test
history3 = model3.fit(
 get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS,
callbacks=[lr_callback],
validation_data=None if SKIP_VALIDATION else get_validation_dataset() 
)
 preds3=model3.predict(test_images_ds)
 del model3
gc.collect()
tf.tpu.experimental.initialize_tpu_system(tpu )<choose_model_class>
test_id = test[["Id"]]
with strategy.scope() :
enet = efn.EfficientNetB6(
 input_shape=(img_size, img_size, 3),
weights='imagenet',
include_top=False 
)
 model4 = tf.keras.Sequential([
enet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model4.compile(
 optimizer=tf.keras.optimizers.Adam(lr=0.0001),
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy']
)<train_model>
kf = KFold(n_splits = 10, shuffle = True, random_state = 42)
 def rmse_cv(model, X = X_train, y = y_train):
return np.sqrt(-cross_val_score(model, X, y, scoring = 'neg_mean_squared_error', cv = kf)).mean()
history4 = model4.fit(
 get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS,
callbacks=[lr_callback],
validation_data=None if SKIP_VALIDATION else get_validation_dataset() 
)
 preds4=model4.predict(test_images_ds)
 del model4
gc.collect()
tf.tpu.experimental.initialize_tpu_system(tpu )<train_model>
lgb_model = lgb.LGBMRegressor(colsample_bytree=0.25, learning_rate=0.01,
max_depth=13, min_child_samples=7, n_estimators=10000,
num_leaves=20, objective='regression', random_state=42,
subsample=0.9330025956033094, subsample_freq=1)
 xgb_model = xgb.XGBRegressor(colsample_bytree=0.25, gamma=0.0, learning_rate=0.01, max_depth=3,
n_estimators=15000, n_jobs=-1, random_state=42,
reg_alpha=0.24206673672530965, reg_lambda=0.40464485640717085, subsample=1.0)
 gbr_model = GradientBoostingRegressor(alpha=0.8979588317644014,
learning_rate=0.01, loss='huber',
max_depth=13, max_features=0.1, min_samples_split=109,
n_estimators=10000, n_iter_no_change=100, random_state=42)
 svr_model = SVR(C=0.7682824405204463, coef0=0.0001, degree=2, epsilon=0.0001, gamma=0.0042151786393578635, max_iter=10000)
 lasso_model = Lasso(alpha=0.00012609086150256233, max_iter=5000, random_state=42)
 ridge_model = Ridge(alpha=2.651347536470113, max_iter=5000, random_state=42)
 enet_model = ElasticNet(alpha=0.0002286518512853544, l1_ratio=0.6510386358323069, max_iter=5000, random_state=42 )
preds1=np.load('.. /input/tpu-enet-b7-densenet-random-cut/probs.npz')
 preds1['a'].shape<load_pretrained>
%%time
models = {
"LGBMRegressor": lgb_model,
"XGBRegressor": xgb_model,
"GradientBoostingRegressor": gbr_model,
"SVR": svr_model,
"Lasso": lasso_model,
"Ridge": ridge_model,
}
oof_df = pd.DataFrame()
predictions_df = pd.DataFrame()
for name, model in models.items() :
print("For model ", name, "
")
 i = 1
oof = np.zeros(len(X_train))
predictions = np.zeros(len(X_test))
for train_ix, test_ix in kf.split(X_train.values):
print("Out of fold predictions generating for fold ", i)
 train_X, train_y = X_train.values[train_ix], y_train[train_ix]
test_X, test_y = X_train.values[test_ix], y_train[test_ix]
if name == "LGBMRegressor":
model.fit(train_X, train_y,
eval_set = [(test_X, test_y)],
eval_metric = "rmse",
early_stopping_rounds=200,
verbose=0)
 elif name == "XGBRegressor":
model.fit(train_X, train_y,
eval_set = [(test_X, test_y)],
eval_metric = "rmse",
early_stopping_rounds=250,
verbose=0)
 else:
model.fit(train_X, train_y)
 oof[test_ix] = oof[test_ix] + model.predict(X_train.values[test_ix])
 predictions = predictions + model.predict(X_test.values)
 i = i + 1
oof_df[name] = oof
predictions_df[name] = predictions / 10
print("
Done
" )
preds2=np.load('.. /input/kernel4-aug/probs.npz')
 preds2['a'].shape<load_pretrained>
oof = np.zeros(len(X_train))
predictions = np.zeros(len(X_test))
i = 1
for train_ix, test_ix in kf.split(oof_df):
print("Out of fold predictions generating for fold ", i)
 train_X, train_y = oof_df.values[train_ix], y_train[train_ix]
test_X, test_y = oof_df.values[test_ix], y_train[test_ix]
model = gbr_model
model.fit(train_X, train_y)
 oof[test_ix] = oof[test_ix] + model.predict(oof_df.values[test_ix])
 predictions = predictions + model.predict(predictions_df)
 i = i + 1
oof_stacked = oof
stack_preds = predictions / 10
<load_pretrained><EOS> 
preds =(4 * stack_preds +
predictions_df["LGBMRegressor"] +
predictions_df["XGBRegressor"] +
2 * predictions_df["GradientBoostingRegressor"] +
predictions_df["SVR"] +
predictions_df["Lasso"])/ 10
sub = pd.DataFrame({"Id": test_id.Id, "SalePrice": np.expm1(preds)})
 sub.to_csv("BlendedModel120121.csv", index = False)
 sub