Kaggle competition: House Prices - Advanced Regression Techniques
<SOS> metric: rmsle Kaggle data source: house-prices-advanced-regression-techniques<predict_on_test>
!pip install --upgrade seaborn
def predict_and_save(input_ds, generator_model, output_path):
i = 1
for img in input_ds:
prediction = generator_model(img, training=False)[0].numpy()
prediction =(prediction * 127.5 + 127.5 ).astype(np.uint8)
 im = PIL.Image.fromarray(prediction)
 im.save(f'{output_path}{str(i)}.jpg')
 i += 1<define_variables>
Train = pd.read_csv('.. /input/house-prices-advanced-regression-techniques/train.csv')
 Train = Train.set_index('Id')
 Test = pd.read_csv('.. /input/house-prices-advanced-regression-techniques/test.csv')
 Test = Test.set_index('Id')
 preprocessing_path = '.. /input/house-price-eda'
train_scale = pd.read_csv(f'{preprocessing_path}/train_scaled.csv')
 train_scale = train_scale.set_index('Id')
 test_scale = pd.read_csv(f'{preprocessing_path}/test_scaled.csv')
 try:
test_scale = test_scale.rename(columns={'Unnamed: 0':'Id'})
 except:
pass
test_scale = test_scale.set_index('Id')
 Train = Train.loc[train_scale.index]
listing = glob.glob(f'{preprocessing_path}/*_one_hot_pickle')
 for model_file in listing:
col = model_file.split('_one_')[0]
col = col.split('/')[-1]
enc = pickle.load(open(model_file, 'rb'))
new_cols = pd.DataFrame(enc.transform(Train[[col]] ).toarray() ,
columns=f'{col}_' + enc.categories_[0])
 new_cols.index = Train.index
Train = pd.concat([Train, new_cols], axis = 1)
 Train = Train.drop(col, axis = 1)
 for log_col in train_scale.columns[train_scale.columns.str.endswith('log')]:
col = log_col.split('_log')[0]
Train[log_col] = np.log(Train[col])
 Train = Train.drop(col, axis = 1)
 Train = Train[train_scale.columns]
for model_file in listing:
col = model_file.split('_one_')[0]
col = col.split('/')[-1]
enc = pickle.load(open(model_file, 'rb'))
new_cols = pd.DataFrame(enc.transform(Test[[col]] ).toarray() ,
columns=f'{col}_' + enc.categories_[0])
 new_cols.index = Test.index
Test = pd.concat([Test, new_cols], axis = 1)
 Test = Test.drop(col, axis = 1)
 for log_col in test_scale.columns[test_scale.columns.str.endswith('log')]:
col = log_col.split('_log')[0]
Test[log_col] = np.log(Test[col])
 Test = Test.drop(col, axis = 1)
 Test = Test[test_scale.columns]
os.makedirs('.. /images/')
 predict_and_save(load_dataset(PHOTO_FILENAMES ).batch(1), monet_generator, '.. /images/' )<load_pretrained>
meanMSSubClass_Saleprice = Train[['MSSubClass', 'SalePrice_log']].groupby('MSSubClass' ).mean()
shutil.make_archive('/kaggle/working/images/', 'zip', '.. /images')
 print(f"Generated samples: {len([name for name in os.listdir('.. /images/')if os.path.isfile(os.path.join('.. /images/', name)) ])}" )<install_modules>
for col in Test.columns:
if len(set(Train[col])) > 2 and '_log' not in col:
Train[f'{col}_log'] = np.log(Train[col] + 1)
 Train = Train.drop(col, axis = 1)
 Test[f'{col}_log'] = np.log(Test[col] + 1)
 Test = Test.drop(col, axis = 1 )
!pip install -q efficientnet<set_options>
print('TensorFlow version', tf.__version__)
 AUTO = tf.data.experimental.AUTOTUNE<define_variables>
Train = Train.drop(1276 )
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 = [224, 224]
EPOCHS = 12
BATCH_SIZE = 16 * strategy.num_replicas_in_sync
GCS_PATH_SELECT = {
192: GCS_DS_PATH + '/tfrecords-jpeg-192x192',
224: GCS_DS_PATH + '/tfrecords-jpeg-224x224',
331: GCS_DS_PATH + '/tfrecords-jpeg-331x331',
512: GCS_DS_PATH + '/tfrecords-jpeg-512x512'
}
GCS_PATH = GCS_PATH_SELECT[IMAGE_SIZE[0]]
TRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/train/*.tfrec')
 VALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec')
 TEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec')
 MOREIMAGES_PATH_SELECT = {
192: '/tfrecords-jpeg-192x192',
224: '/tfrecords-jpeg-224x224',
331: '/tfrecords-jpeg-331x331',
512: '/tfrecords-jpeg-512x512'
}
MOREIMAGES_PATH = MOREIMAGES_PATH_SELECT[IMAGE_SIZE[0]]
IMAGENET_FILES = tf.io.gfile.glob(MORE_IMAGES_GCS_DS_PATH + '/imagenet' + MOREIMAGES_PATH + '/*.tfrec')
 INATURELIST_FILES = tf.io.gfile.glob(MORE_IMAGES_GCS_DS_PATH + '/inaturalist' + MOREIMAGES_PATH + '/*.tfrec')
 OPENIMAGE_FILES = tf.io.gfile.glob(MORE_IMAGES_GCS_DS_PATH + '/openimage' + MOREIMAGES_PATH + '/*.tfrec')
 OXFORD_FILES = tf.io.gfile.glob(MORE_IMAGES_GCS_DS_PATH + '/oxford_102' + MOREIMAGES_PATH + '/*.tfrec')
 TENSORFLOW_FILES = tf.io.gfile.glob(MORE_IMAGES_GCS_DS_PATH + '/tf_flowers' + MOREIMAGES_PATH + '/*.tfrec')
 ADDITIONAL_TRAINING_FILENAMES = IMAGENET_FILES + INATURELIST_FILES + OPENIMAGE_FILES + OXFORD_FILES + TENSORFLOW_FILES
print('----')
 TRAINING_FILENAMES = TRAINING_FILENAMES + ADDITIONAL_TRAINING_FILENAMES + VALIDATION_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>
corr = Train.corr() ['SalePrice_log']
Train_err = Train[corr[np.abs(corr)< 0.4].index]
Test_err = Test[corr[np.abs(corr)< 0.4].index]
Train = Train[corr[np.abs(corr)> 0.4].index]
Test = Test[corr[np.abs(corr)> 0.4].index.drop('SalePrice_log')]
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>
def getFoldValidation(length, K = 4):
diff = int(length/K)
 fraction = length % K
batchValidation = [[k*diff,(k + 1)*diff] for k in range(K)]
batchValidation[-1][1] = batchValidation[-1][1] + fraction - 1
return batchValidation
batchValidation = np.array(getFoldValidation(len(Train)) )
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>
def getTrainTestBatch() :
fold = 0
while fold < batchValidation.shape[0]:
train_batch = pd.concat([Train.iloc[batchValidation[i][0]:batchValidation[i][1]]
for i in range(batchValidation.shape[0])if i != fold])
 test_batch = Train.iloc[batchValidation[fold][0]:batchValidation[fold][1]]
yield train_batch, test_batch, fold
fold += 1
train_batch, test_batch, fold = next(getTrainTestBatch())
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>
def mse_loss(y_true, y_pred):
return K.sqrt(K.mean(( y_true - y_pred)**2))
def e_loss(y_true, y_pred):
return K.sqrt(K.mean(( np.e**y_true - np.e**y_pred)**2))
training_dataset = get_training_dataset()
training_dataset = training_dataset.unbatch().batch(20)
 train_batch = iter(training_dataset)
<create_dataframe>
class linearAndErrorModels(BaseEstimator, RegressorMixin, TransformerMixin):
def getErrorModel(self, epochs=150):
return xgb.XGBRegressor(colsample_bytree=0.4603, gamma=0.0468,
learning_rate=0.05, max_depth=50,
min_child_weight=1.7817, n_estimators=2200,
reg_alpha=0.4640, reg_lambda=0.8571,
subsample=0.5213,
random_state =7, nthread = -1)
 def __init__(self):
self.models = models
def fit(self, X_Train, X_Train_err, y, epochs=150):
baseModel = LinearRegression()
baseModel.fit(X_Train,Y_Train)
 predict_Train = baseModel.predict(X_Train)
 error_Train = Y_Train - predict_Train
X_Train_err['predict'] = predict_Train
self.X_Train_err = X_Train_err
self.errorModel = self.getErrorModel(epochs=epochs)
 self.errorModel.fit(X_Train_err, error_Train)
 predict_Train = self.errorModel.predict(X_Train_err)
 error_Train = error_Train.values.flatten() - predict_Train.flatten()
X_Train_err['predict_2'] = predict_Train
self.errorModel_2 = self.getErrorModel(epochs=epochs)
 self.errorModel_2.fit(X_Train_err, error_Train)
 self.baseModel = baseModel
return self
def predict(self, X_val, X_val_err):
predict = self.baseModel.predict(X_val)
 X_val_err['predict'] = predict
error = self.errorModel.predict(X_val_err)
 X_val_err['predict_2'] = error.flatten()
error_2 = self.errorModel_2.predict(X_val_err)
 predict = predict.flatten() + error.flatten()
return predict
test_dataset = get_test_dataset()
test_dataset = test_dataset.unbatch().batch(20)
 test_batch = iter(test_dataset)
<define_variables>
models = ['linear']
genarator = getTrainTestBatch()
Val_Report = {key : [] for key in models}
MSEs = np.array([])
 for train_batch, test_batch, fold in genarator:
sampling = train_batch.sample(frac=1)
 X_Train = sampling.drop('SalePrice_log', axis = 1)
 X_Train_err = Train_err.loc[X_Train.index]
Y_Train = sampling[['SalePrice_log']]
X_val = test_batch.drop('SalePrice_log', axis = 1)
 X_val_err = Train_err.loc[X_val.index]
Y_val = test_batch[['SalePrice_log']]
LAEM = linearAndErrorModels()
LAEM.fit(X_Train, X_Train_err, Y_Train, epochs = 1000)
 predict = LAEM.predict(X_val, X_val_err)
 MSE = mse_loss(K.constant(Y_val), K.constant(predict)).numpy()
MSEs = np.append(MSEs, MSE)
test_dataset = get_test_dataset()
test_dataset = test_dataset.unbatch().batch(20)
 test_batch = iter(test_dataset )<choose_model_class>
X_Train = Train.drop('SalePrice_log', axis = 1)
 X_Train_err = Train_err.loc[X_Train.index]
Y_Train = Train[['SalePrice_log']]
LAEM = linearAndErrorModels()
LAEM.fit(X_Train, X_Train_err, Y_Train )
early_stop = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=20, restore_best_weights = True )<choose_model_class>
predict = LAEM.predict(Test, Test_err )
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>
predict = pd.DataFrame(predict)
 predict.index = Test.index
predict.columns = ['SalePrice_log']
predict['SalePrice'] = np.e**(predict['SalePrice_log'])
 predict = predict.drop('SalePrice_log', axis = 1)
 predict
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>
predict.to_csv("submission.csv" )