Kaggle competition: House Prices - Advanced Regression Techniques
<SOS> metric: rmsle Kaggle data source: house-prices-advanced-regression-techniques<train_model>
!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 )
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'))<categorify>
!pip install --upgrade lightgbm
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.'] )<train_model>
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()
training_dataset = get_training_dataset()
training_dataset = training_dataset.unbatch().batch(20)
 train_batch = iter(training_dataset )<define_variables>
df = pd.concat([train, test])
 df
test_dataset = get_test_dataset()
test_dataset = test_dataset.unbatch().batch(20)
 test_batch = iter(test_dataset )<randomize_order>
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
EPOCHS = 20
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)
 es_callback = tf.keras.callbacks.EarlyStopping(min_delta=0, patience=10, verbose=1, mode='auto', restore_best_weights=True)
 rng = [i for i in range(25 if EPOCHS<25 else EPOCHS)]
y = [lrfn(x)for x in rng]
plt.plot(rng, y)
 print("Learning rate schedule: {:.3g} to {:.3g} to {:.3g}".format(y[0], max(y), y[-1]))<choose_model_class>
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 )
with strategy.scope() :
dn201 = tf.keras.applications.DenseNet201(weights='imagenet', include_top=False, input_shape=[*IMAGE_SIZE, 3])
 dn201.trainable = True
model1 = tf.keras.Sequential([
dn201,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model1.compile(
 optimizer = tf.keras.optimizers.Adam(learning_rate=0.001),
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 model1.summary() 
<choose_model_class>
df[(df.GarageFinish.isnull())&(df.GarageType.notnull())]
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),
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 model2.summary()<choose_model_class>
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"
<train_model>
df[df.GarageYrBlt == df.YearBuilt].shape[0]
history1 = model1.fit(
 get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS,
validation_data= None if not VALIDATION else get_validation_dataset() ,
callbacks = [lr_callback] )<train_model>
df.loc[(df.GarageYrBlt.isnull())&(df.GarageType.notnull()), "GarageYrBlt"] = df.loc[(df.GarageYrBlt.isnull())&(df.GarageType.notnull())].YearBuilt
history2 = model2.fit(
 get_training_dataset() ,
steps_per_epoch=128,
epochs=EPOCHS,
validation_data= None if not VALIDATION else get_validation_dataset() ,
callbacks = [lr_callback] )<predict_on_test>
df[(df.GarageType == "Detchd")&(df.YearBuilt < 1930)&(df.YearRemodAdd < 2000)&(df.YearRemodAdd > 1980)&(df.GarageCars == 1)].GarageArea.median()
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()
m = model1.predict(images_ds)
 m2 = model2.predict(images_ds)
 scores = []
for alpha in np.linspace(0,1,100):
cm_probabilities = alpha*m+(1-alpha)*m2
cm_predictions = np.argmax(cm_probabilities, axis=-1)
 scores.append(f1_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro'))
print("Correct labels: ", cm_correct_labels.shape, cm_correct_labels)
 print("Predicted labels: ", cm_predictions.shape, cm_predictions)
 plt.plot(scores)
 best_alpha = np.argmax(scores)/100
cm_probabilities = best_alpha*m+(1-best_alpha)*m2
cm_predictions = np.argmax(cm_probabilities, axis=-1)
 else:
best_alpha = 0.44
print(best_alpha )<compute_test_metric>
df.loc[(df.GarageArea.isnull())&(df.GarageType.notnull()), "GarageArea"] = 234
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>
num_cols, cat_cols, ord_cols = col_types(df )
TTA_NUM = 10
probabilities = []
for i in range(TTA_NUM):
')
 test_ds = get_test_dataset(ordered=True)
 test_images_ds = test_ds.map(lambda image, idnum: image)
 probabilities.append(model1.predict(test_images_ds,verbose =1))<feature_engineering>
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 )
prob1 = np.mean(probabilities,axis =0 )<predict_on_test>
df.loc[(df.MasVnrArea.isnull())&(df.MasVnrType == "None"), "MasVnrArea"] = 0
TTA_NUM = 10
probabilities = []
for i in range(TTA_NUM):
print('TTA Number: ',i)
 test_ds = get_test_dataset(ordered=True)
 test_images_ds = test_ds.map(lambda image, idnum: image)
 probabilities.append(model2.predict(test_images_ds,verbose =1)) 
<feature_engineering>
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 )
prob2 = np.mean(probabilities,axis =0)
 prob2<save_to_csv>
print(df.MSZoning.value_counts())
 df[df.MSZoning.isnull() ]
print('Generating submission.csv file...')
 test_ids_ds = test_ds.map(lambda image, idnum: idnum ).unbatch()
test_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES)) ).numpy().astype('U')
 np.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')
 !head submission.csv<import_modules>
df.groupby("Neighborhood" ).MSZoning.value_counts()
FileLinks('.' )<define_variables>
df.loc[(df.MSZoning.isnull())&(df.Neighborhood == "IDOTRR"), "MSZoning"] = "C(all)"
df.loc[(df.MSZoning.isnull())&(df.Neighborhood == "Mitchel"), "MSZoning"] = "RL"
if VALIDATION:
dataset = get_validation_dataset()
dataset = dataset.unbatch().batch(20)
 batch = iter(dataset )<predict_on_test>
df.KitchenQual.value_counts()
if VALIDATION:
images, labels = next(batch)
 probabilities =(model1.predict(images)*0.50505)+model2.predict(images)*0.44444+model3.predict(images)*0.05050
predictions = np.argmax(probabilities, axis=-1)
 display_batch_of_images(( images, labels), predictions )<install_modules>
print(df.groupby(["OverallQual", "KitchenAbvGr"] ).KitchenQual.value_counts())
 df.loc[(df.KitchenQual.isnull())&(df.OverallQual == 5)&(df.KitchenAbvGr == 1), "KitchenQual"] = "TA"
!pip install -q efficientnet<set_options>
print(df.SaleType.value_counts())
 df[df.SaleType.isnull() ]
print('TensorFlow version', tf.__version__)
 AUTO = tf.data.experimental.AUTOTUNE<define_variables>
print(df.groupby(["Neighborhood", "SaleCondition"] ).SaleType.value_counts())
 df.loc[(df.SaleType.isnull())&(df.Neighborhood == "Sawyer")&(df.SaleCondition == "Normal"), "SaleType"] = "WD"
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]
EPOCHS = 20
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 = TENSORFLOW_FILES
print('----')
 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']<init_hyperparams>
print(df.Electrical.value_counts())
 df[df.Electrical.isnull() ]
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(30)]
y = [lrfn(x)for x in rng]
plt.plot(rng, y)
 print(y )<categorify>
df[(df.YearBuilt > 2005)].Electrical.value_counts()
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>
df.Electrical.fillna("SBrkr", inplace=True )
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>
print(df.Exterior1st.value_counts())
 df[df.Exterior1st.isnull() ]
training_dataset = get_training_dataset()
training_dataset = training_dataset.unbatch().batch(20)
 train_batch = iter(training_dataset)
<create_dataframe>
print(df[(df.RoofMatl == "Tar&Grv")].Exterior1st.value_counts())
 df.Exterior1st.fillna("Plywood", inplace=True )
test_dataset = get_test_dataset()
test_dataset = test_dataset.unbatch().batch(20)
 test_batch = iter(test_dataset)
<define_variables>
print(df[(df.RoofMatl == "Tar&Grv")].Exterior2nd.value_counts())
 df.Exterior2nd.fillna("Plywood", inplace=True )
test_dataset = get_test_dataset()
test_dataset = test_dataset.unbatch().batch(20)
 test_batch = iter(test_dataset )<choose_model_class>
print(df.Functional.value_counts())
 df[df.Functional.isnull() ]
early_stop = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=20, restore_best_weights = True )<choose_model_class>
df[(df.Neighborhood == "IDOTRR")&(df.OverallQual < 5)&(df.YearRemodAdd < 1960)&(df.ExterQual == "Fa")].Functional.value_counts()
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>
df.Functional.fillna("Mod", inplace = True )
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>
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"))
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>
df.Utilities.fillna(df.Utilities.mode() [0], inplace=True)
 missing(df )
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>
df["MSSubClass"] = df["MSSubClass"].astype("str" )
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>
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"
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>
dff = df.copy()
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>
num_cols, cat_cols, ord_cols = col_types(dff)
 for col in dff.columns:
print("For column: ", col + "
")
 print(dff[col].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>
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 )
no_of_models = 2
models = [0] * no_of_models
start_model = 0
end_model = 2
model_indx_0 = start_model
model_indx_1 = start_model + 1 
<define_variables>
dff["MSZoning"] = dff["MSZoning"].apply(lambda x: "R" if x.startswith("R")else x )
val_probabilities = [0] * no_of_models
test_probabilities = [0] * no_of_models
all_probabilities = [0] * no_of_models<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 )
with strategy.scope() :
for j in range(no_of_models):
models[j] = create_EfficientNet_model()
models[0].summary()<load_pretrained>
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 )
models[0].load_weights('/kaggle/input/tpu-multitier-training-with-external-datasets-1/20200507_1057_models_0.h5')
 models[1].load_weights('/kaggle/input/tpu-multitier-training-with-external-datasets-1/20200507_1057_models_1.h5' )<load_pretrained>
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 )
def write_history(j):
history_dict = [0] * no_of_models
for i in range(j + 1):
if(historys[i] != 0):
history_dict[i] = historys[i].history
filename = './' + this_run_file_prefix + 'model_history_' + str(j)+ '.pkl'
pklfile = open(filename, 'ab')
 pickle.dump(history_dict, pklfile)
 pklfile.close()<define_variables>
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 )
EPOCHS = 20
historys = [0] * no_of_models
finished_models = 0
for j in range(start_model, end_model):
start_training = datetime.now()
print(start_training)
 time_from_start_program_tdelta = start_training - start_time
if time_from_start_program_tdelta > end_training_by_tdelta:
print(j, 'time limit for doing training over, get out')
 break
print('LR_EXP_DECAY:', LR_EXP_DECAY, '.LR_MAX:', LR_MAX)
 historys[j] = models[j].fit(get_training_dataset() , steps_per_epoch = STEPS_PER_EPOCH, epochs = EPOCHS, validation_data = get_validation_dataset() , callbacks = [lr_callback, early_stop])
 write_history(j)
 filename = this_run_file_prefix + 'models_' + str(j)+ '.h5'
models[j].save(filename)
 gc.collect()
finished_models = j + 1
print(datetime.now())
<categorify>
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 )
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()<create_dataframe>
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)
 test_images_ds = test_ds.map(lambda image, idnum: image)
<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"]
dataset = get_validation_dataset()
dataset = dataset.unbatch().batch(20)
 batch = iter(dataset)
 images, labels = next(batch )<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"]
print(datetime.now())
 for j in range(start_model, end_model):
val_probabilities[j] = models[j].predict(images_ds)
 test_probabilities[j] = models[j].predict(test_images_ds)
 all_probabilities[j] = models[j].predict(images)
 print(datetime.now())
<find_best_params>
dff2 = dff.copy()
num_cols2, cat_cols2, ord_cols2 = col_types(dff2 )
for j in range(start_model, finished_models):
display_training_curves(historys[j].history['loss'], historys[j].history['val_loss'], 'loss', 211)
 display_training_curves(historys[j].history['sparse_categorical_accuracy'], historys[j].history['val_sparse_categorical_accuracy'], 'accuracy', 212)
 for j in range(start_model, finished_models):
print('model number:', j, ', Train Accuracy:', max(historys[j].history['sparse_categorical_accuracy']), ', Validation Accuracy:', max(historys[j].history['val_sparse_categorical_accuracy']))
for j in range(start_model, finished_models):
print('model number:', j, ', Train Loss:', min(historys[j].history['loss']), ', Validation Loss:', min(historys[j].history['val_loss'])) 
<define_variables>
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 )
cm_probabilities = np.zeros(( val_probabilities[0].shape))
for j in range(no_of_models):
cm_probabilities = cm_probabilities + val_probabilities[j]
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>
dff3 = dff2.copy()
dff3
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>
for col in cat_cols2:
print(col, dff3[col].value_counts().size )
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>
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" )
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 = '')
<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 )
probabilities = np.zeros(( test_probabilities[0].shape))
for j in range(no_of_models):
probabilities = probabilities + test_probabilities[j]
filename = this_run_file_prefix + 'submission.csv'
create_submission_file(filename, probabilities)
 create_submission_file('submission.csv', probabilities)
<find_best_params>
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 combine_two(correct_labels, probability_0, probability_1):
print('Start.', datetime.now())
 alphas0_to_try = np.linspace(0, 1, 101)
 best_score = -1
best_alpha0 = -1
best_alpha1 = -1
best_precision = -1
best_recall = -1
best_val_predictions = None
for alpha0 in alphas0_to_try:
alpha1 = 1.0 - alpha0
probabilities = alpha0 * probability_0 + alpha1 * probability_1
predictions = np.argmax(probabilities, axis = -1)
 score, precision, recall = getFitPrecisionRecall(correct_labels, predictions)
 if score > best_score:
best_alpha0 = alpha0
best_alpha1 = alpha1
best_score = score
best_precision = precision
best_recall = recall
best_val_predictions = predictions
return best_alpha0, best_alpha1, best_val_predictions, best_score, best_precision, best_recall<define_search_space>
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 combine_three(correct_labels, probability_0, probability_1, probability_2):
print('Start.', datetime.now())
 alphas0_to_try = np.linspace(0, 1, 101)
 alphas1_to_try = np.linspace(0, 1, 101)
 best_score = -1
best_alpha0 = -1
best_alpha1 = -1
best_alpha2 = -1
best_precision = -1
best_recall = -1
best_val_predictions = None
for alpha0 in alphas0_to_try:
for alpha1 in alphas1_to_try:
if(alpha0 + alpha1)> 1.0:
break
alpha2 = 1.0 - alpha0 - alpha1
probabilities = alpha0 * probability_0 + alpha1 * probability_1 + alpha2 * probability_2
predictions = np.argmax(probabilities, axis = -1)
 score, precision, recall = getFitPrecisionRecall(correct_labels, predictions)
 if score > best_score:
best_alpha0 = alpha0
best_alpha1 = alpha1
best_alpha2 = alpha2
best_score = score
best_precision = precision
best_recall = recall
best_val_predictions = predictions
return best_alpha0, best_alpha1, best_alpha2, best_val_predictions, best_score, best_precision, best_recall<train_model>
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 )
def get_best_combination(no_models, cm_correct_labels, val_probabilities, test_probabilities):
best_fit_score = -10000.0
best_predictions = 0
choose_filename = ''
curr_predictions = np.argmax(val_probabilities[0], axis = -1)
 score, precision, recall = getFitPrecisionRecall(cm_correct_labels, curr_predictions)
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score, precision, recall))
filename = this_run_file_prefix + 'submission_0.csv'
if best_fit_score < score:
best_fit_score = score
best_predictions = curr_predictions
choose_filename = filename
create_submission_file('./submission.csv', test_probabilities[0])
 create_submission_file(filename, test_probabilities[0])
 if no_models > 1:
curr_predictions = np.argmax(val_probabilities[1], axis = -1)
 score, precision, recall = getFitPrecisionRecall(cm_correct_labels, curr_predictions)
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score, precision, recall))
filename = this_run_file_prefix + 'submission_1.csv'
if best_fit_score < score:
best_fit_score = score
best_predictions = curr_predictions
choose_filename = filename
create_submission_file('./submission.csv', test_probabilities[1])
 create_submission_file(filename, test_probabilities[1])
 if no_models > 2:
curr_predictions = np.argmax(val_probabilities[2], axis = -1)
 score, precision, recall = getFitPrecisionRecall(cm_correct_labels, curr_predictions)
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score, precision, recall))
filename = this_run_file_prefix + 'submission_2.csv'
if best_fit_score < score:
best_fit_score = score
best_predictions = curr_predictions
choose_filename = filename
create_submission_file('./submission.csv', test_probabilities[2])
 create_submission_file(filename, test_probabilities[2])
 if no_models > 1:
best_alpha0, best_alpha1, best_val_predictions, best_score, best_precision, best_recall = combine_two(cm_correct_labels, val_probabilities[0], val_probabilities[1])
 print('For indx', [0, 1], 'best_alpha0:', best_alpha0, 'best_alpha1:', best_alpha1, '.', datetime.now())
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(best_score, best_precision, best_recall))
combined_probabilities = best_alpha0 * test_probabilities[0] + best_alpha1 * test_probabilities[1]
filename = this_run_file_prefix + 'submission_01.csv'
if best_fit_score < best_score:
best_fit_score = best_score
best_predictions = best_val_predictions
choose_filename = filename
create_submission_file('./submission.csv', combined_probabilities)
 create_submission_file(filename, combined_probabilities)
 if no_models > 2:
best_alpha0, best_alpha1, best_val_predictions, best_score, best_precision, best_recall = combine_two(cm_correct_labels, val_probabilities[0], val_probabilities[2])
 print('For indx', [0, 2], 'best_alpha0:', best_alpha0, 'best_alpha1:', best_alpha1, '.', datetime.now())
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(best_score, best_precision, best_recall))
combined_probabilities = best_alpha0 * test_probabilities[0] + best_alpha1 * test_probabilities[2]
filename = this_run_file_prefix + 'submission_02.csv'
if best_fit_score < best_score:
best_fit_score = best_score
best_predictions = best_val_predictions
choose_filename = filename
create_submission_file('./submission.csv', combined_probabilities)
 create_submission_file(filename, combined_probabilities)
 best_alpha0, best_alpha1, best_val_predictions, best_score, best_precision, best_recall = combine_two(cm_correct_labels, val_probabilities[1], val_probabilities[2])
 print('For indx', [1, 2], 'best_alpha0:', best_alpha0, 'best_alpha1:', best_alpha1, '.', datetime.now())
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(best_score, best_precision, best_recall))
combined_probabilities = best_alpha0 * test_probabilities[1] + best_alpha1 * test_probabilities[2]
filename = this_run_file_prefix + 'submission_12.csv'
if best_fit_score < best_score:
best_fit_score = best_score
best_predictions = best_val_predictions
choose_filename = filename
create_submission_file('./submission.csv', combined_probabilities)
 create_submission_file(filename, combined_probabilities)
 best_alpha0, best_alpha1, best_alpha2, best_val_predictions, best_score, best_precision, best_recall = combine_three(cm_correct_labels, val_probabilities[0], val_probabilities[1], val_probabilities[2])
 print('For indx', [0, 1, 2], 'best_alpha0:', best_alpha0, 'best_alpha1:', best_alpha1, 'best_alpha2:', best_alpha2, '.', datetime.now())
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(best_score, best_precision, best_recall))
combined_probabilities = best_alpha0 * test_probabilities[0] + best_alpha1 * test_probabilities[1] + best_alpha2 * test_probabilities[2]
filename = this_run_file_prefix + 'submission_012.csv'
if best_fit_score < best_score:
best_fit_score = best_score
best_predictions = best_val_predictions
choose_filename = filename
create_submission_file('./submission.csv', combined_probabilities)
 create_submission_file(filename, combined_probabilities)
 cmat = confusion_matrix(cm_correct_labels, best_predictions, labels = range(len(CLASSES)))
 cmat =(cmat.T / cmat.sum(axis = -1)).T
display_confusion_matrix(cmat, best_fit_score, precision, recall)
 print('Best score from all combination was', best_fit_score, '.For submission file used is', choose_filename)
 return best_predictions 
<categorify>
train[target] = np.log1p(train[target])
 feature_distribution(train, target, test = False)
 train[target].skew()
best_predictions = cm_predictions
if no_of_models > 1:
bp = get_best_combination(no_of_models, cm_correct_labels, val_probabilities, test_probabilities)
 best_predictions = bp 
<define_variables>
target = "SalePrice"
predictors = [x for x in train.columns if x not in ["Id", "SalePrice"]]
probabilities = np.zeros(( all_probabilities[0].shape))
for j in range(no_of_models):
probabilities = probabilities + all_probabilities[j]
predictions = np.argmax(probabilities, axis =-1)
 display_batch_of_images(( images, labels), predictions )<load_pretrained>
scaler = RobustScaler()
train[predictors] = scaler.fit_transform(train[predictors])
 test[predictors] = scaler.transform(test[predictors] )
val_probs = [cm_correct_labels, cm_predictions, val_probabilities[0], val_probabilities[1], test_probabilities[0], test_probabilities[1]]
filename = this_run_file_prefix + 'tests_vals_01.pkl'
pklfile = open(filename, 'ab')
 pickle.dump(val_probs, pklfile)
 pklfile.close()<categorify>
X_train = train[predictors]
y_train = train[target]
X_test = test[predictors]
print(X_train.shape)
 print(X_test.shape )
use_correct_labels = cm_correct_labels
use_val_predictions = best_predictions<define_variables>
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
correct_labels_cnt = 0
incorrect_labels_cnt = 0
correct_labels = []
incorrect_labels = []
vals_actual_true = {}
vals_tp = {}
vals_fn = {}
vals_fp = {}
for i in range(len(CLASSES)) :
vals_actual_true[i] = 0
vals_tp[i] = 0
vals_fn[i] = 0
vals_fp[i] = 0
for i in range(len(use_correct_labels)) :
correct_label = use_correct_labels[i]
predict_label = use_val_predictions[i]
vals_actual_true[correct_label] = vals_actual_true[correct_label] + 1
if use_val_predictions[i] != use_correct_labels[i]:
incorrect_labels_cnt = incorrect_labels_cnt + 1
incorrect_labels.append(i)
 vals_fn[correct_label] = vals_fn[correct_label] + 1
vals_fp[predict_label] = vals_fp[predict_label] + 1
else:
correct_labels_cnt = correct_labels_cnt + 1
correct_labels.append(i)
 vals_tp[correct_label] = vals_tp[correct_label] + 1
print('Number of correct_labels is {}, incorrect_labels is {}'.format(correct_labels_cnt, incorrect_labels_cnt))
print('Incorrect labels', incorrect_labels)
<define_variables>
test_id = test[["Id"]]
def display_my_batch_of_images(databatch, rows = 0, cols = 0, predictions=None):

 images, labels = databatch
if labels is None:
labels = [None for _ in enumerate(images)]
if rows == 0 or cols == 0:
rows = int(math.sqrt(len(images)))
 cols =(len(images)+ rows - 1)//rows
print('Total number of images is {}, rows is {}, cols is {}'.format(len(images), rows, cols))
FIGSIZE = 20.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()<define_variables>
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()
disp_labels = []
disp_predictions = []
for i in range(54):
if i >= incorrect_labels_cnt:
break
id = incorrect_labels[i]
disp_labels.append(use_correct_labels[id])
 disp_predictions.append(use_val_predictions[id])
 print(disp_labels)
 print(disp_predictions )<split>
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 )
display_my_batch_of_images(( disp_images, disp_labels), rows = 9, cols = 6, predictions = disp_predictions )<load_from_csv>
%%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
" )
val_ids = list(range(len(use_correct_labels)))
 filename = this_run_file_prefix + 'validation_results.csv'
np.savetxt(filename, np.rec.fromarrays([val_ids, use_correct_labels, use_val_predictions]), fmt = ['%d', '%d', '%d'], delimiter = ',', header = 'id,correct_label,predicted_label', comments = '')
 cls_ids = list(range(len(CLASSES)))
 filename = this_run_file_prefix + 'validation_statistics.csv'
np.savetxt(filename, np.rec.fromarrays([cls_ids, list(vals_actual_true.values()), list(vals_tp.values()), list(vals_fn.values()), list(vals_fp.values())]), fmt = ['%d', '%d', '%d', '%d', '%d'], delimiter = ',', header = 'cls_id,actual_true,true_positive,false_negative,false_positive', comments = '' )<import_modules>
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
<install_modules><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