Kaggle competition: House Prices - Advanced Regression Techniques
!pip install -q efficientnet<import_modules>
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib
import matplotlib.pyplot as plt
from scipy.stats import skew
import numpy as np
import pandas as pd
import re
import os
import efficientnet.tfkeras as efn
import tensorflow as tf
from tensorflow.keras.layers import Input, Dense
from tensorflow.keras.layers import GlobalAveragePooling2D
from tensorflow.keras.models import Sequential
from tensorflow.keras.callbacks import LearningRateScheduler
from kaggle_datasets import KaggleDatasets
from sklearn.metrics import confusion_matrix, f1_score
from sklearn.metrics import precision_score, recall_score
import seaborn as sea
import matplotlib.pyplot as plt<set_options>
train = pd.read_csv('.. /input/house-prices-advanced-regression-techniques/train.csv')
 test = pd.read_csv('.. /input/house-prices-advanced-regression-techniques/test.csv' )
sea.set_style("darkgrid")
 np.random.seed(3)
 tf.random.set_seed(6 )<define_variables>
features = ['GrLivArea','OverallQual','2ndFlrSF','TotalBsmtSF','1stFlrSF','GarageCars','YearBuilt', 'GarageArea','ExterQual',
'YearRemodAdd','FireplaceQu','GarageYrBlt','FullBath','MSSubClass','LotArea','Fireplaces','KitchenQual','MSZoning',
'GarageType','BsmtFinSF1','Neighborhood','BsmtQual','TotRmsAbvGrd','HalfBath','BldgType','GarageFinish',
'Foundation','BedroomAbvGr','HouseStyle','CentralAir','OpenPorchSF','HeatingQC','BsmtFinType1','BsmtUnfSF',
'GarageCond','GarageQual','KitchenAbvGr','OverallCond','BsmtCond','MasVnrArea','BsmtFullBath','Exterior1st',
'Exterior2nd','PavedDrive','WoodDeckSF','LandContour','MasVnrType','BsmtFinType2','Functional','Fence']
gcs_path = KaggleDatasets().get_gcs_path("tpu-getting-started")
 data_path = os.path.join(gcs_path, "tfrecords-jpeg-512x512/")
 train_path = os.path.join(gcs_path, "tfrecords-jpeg-512x512/train/")
 val_path = os.path.join(gcs_path, "tfrecords-jpeg-512x512/val/")
 test_path = os.path.join(gcs_path, "tfrecords-jpeg-512x512/test/" )<define_variables>
train = train[features + ['SalePrice']]
test = test[['Id'] + features]
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>
all_data = pd.concat(( train.loc[:, 'GrLivArea':'Fence'], test.loc[:,'GrLivArea':'Fence']))
def read_record(example):
features = {
"image": tf.io.FixedLenFeature([], tf.string),
"class": tf.io.FixedLenFeature([], tf.int64),
}
example = tf.io.parse_single_example(example, features)
 image = tf.image.decode_jpeg(example["image"], channels=3)
 image = tf.cast(image, tf.float32)/ 255.0
image = tf.reshape(image, [512,512,3])
 label = tf.cast(example["class"], tf.int32)
 return image, label
def read_record_test(example):
features = {
"image": tf.io.FixedLenFeature([], tf.string),
"id": tf.io.FixedLenFeature([], tf.string),
}
example = tf.io.parse_single_example(example, features)
 image = tf.image.decode_jpeg(example["image"], channels=3)
 image = tf.cast(image, tf.float32)/ 255.0
image = tf.reshape(image, [512,512,3])
 image_id = example["id"]
return image, image_id<create_dataframe>
matplotlib.rcParams['figure.figsize'] =(17.0, 7.0)
 prices = pd.DataFrame({"price": train['SalePrice'], "log(price+1)": np.log1p(train['SalePrice'])})
 prices.hist() ;
AUTO = tf.data.experimental.AUTOTUNE
def get_size(filenames):
data_size = 0
for i in range(len(filenames)) :
count = re.search(r"-[0-9][0-9][0-9]\.", filenames[i] ).group()
data_size = data_size + int(count[1:4])
 return data_size
def prepare_dataset(flag, order = False):
filenames = tf.io.gfile.glob(os.path.join(data_path, flag)+"/*.tfrec")
 data_size = get_size(filenames)
 dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO)
 ignore_order = tf.data.Options()
if order == False:
ignore_order.experimental_deterministic = False
else:
ignore_order.experimental_deterministic = True
dataset = dataset.with_options(ignore_order)
 if flag == "test":
dataset = dataset.map(read_record_test, num_parallel_calls=AUTO)
 else:
dataset = dataset.map(read_record, num_parallel_calls=AUTO)
 return dataset, data_size
train_dataset, train_size = prepare_dataset("train")
 val_dataset, val_size = prepare_dataset("val")
 test_dataset, test_size = prepare_dataset("test")
 print("Size of Training Dataset\t: ", train_size)
 print("Size of Validation Dataset\t: ", val_size)
 print("Size of Test Dataset\t\t: ", test_size )<normalization>
train['SalePrice'] = np.log1p(train['SalePrice'])
 numeric_feats = all_data.dtypes[all_data.dtypes != "object"].index
skewed_feats = train[numeric_feats].apply(lambda x: skew(x.dropna()))
skewed_feats = skewed_feats[skewed_feats > 0.75]
skewed_feats = skewed_feats.index
all_data[skewed_feats] = np.log1p(all_data[skewed_feats] )
def augment(image, label):
cont_low = 0.8
cont_high = 1.2
cont_factor = tf.random.uniform([], minval=cont_low,
maxval=cont_high,
dtype=tf.float32)
 trn_image = tf.image.adjust_contrast(image, cont_factor)
 return trn_image, label<define_variables>
for feature in all_data.select_dtypes(exclude=['object'] ).columns:
all_data[feature].fillna(all_data[feature].median() , inplace = True)
 for feature in all_data.select_dtypes(include=['object'] ).columns:
all_data[feature].fillna(all_data[feature].value_counts().idxmax() , inplace = True )
batch_size = 16 * tpu_strategy.num_replicas_in_sync
train_dataset = train_dataset.map(augment,
num_parallel_calls = AUTO)
 train_dataset = train_dataset.repeat().shuffle(3000)\ 
.batch(batch_size ).prefetch(AUTO)
 val_dataset = val_dataset.batch(batch_size ).prefetch(AUTO)
 test_dataset = test_dataset.batch(batch_size ).prefetch(AUTO )<choose_model_class>
all_data = pd.get_dummies(all_data ).reset_index(drop=True)
 all_data
with tpu_strategy.scope() :
base_model = efn.EfficientNetB5(include_top=False,
input_shape=(512,512,3),
weights='imagenet')
 base_model.trainable = True
model = Sequential(name="Flower_Detector")
 model.add(base_model)
 model.add(GlobalAveragePooling2D(name="GAP"))
model.add(Dense(104, activation="softmax", name="Probs"))
model.compile(optimizer=tf.keras.optimizers.Adam() ,
loss="sparse_categorical_crossentropy",
metrics=["sparse_categorical_accuracy"])
 model.summary()<train_model>
X_train = all_data[:train.shape[0]]
X_test = all_data[train.shape[0]:]
y = train.SalePrice
step_per_epoch = train_size // batch_size
history = model.fit(train_dataset,
validation_data=val_dataset,
steps_per_epoch=step_per_epoch,
epochs=epoch,
callbacks=[lrs] )<predict_on_test>
def rmse_cv(model):
rmse= np.sqrt(-cross_val_score(model, X_train, y, scoring='neg_mean_squared_error', cv = 5))
return(rmse )
val_dataset, val_size = prepare_dataset("val", True)
 val_dataset = val_dataset.batch(batch_size ).prefetch(AUTO)
 val_image_dataset = val_dataset.map(lambda image,label: image)
 val_label_dataset = val_dataset.map(lambda image,label: label ).unbatch()
val_labels = next(iter(val_label_dataset.batch(val_size)) ).numpy()
val_probs = model.predict(val_image_dataset)
 val_preds = np.argmax(val_probs, axis=-1 )<compute_train_metric>
alphas = [0.0005, 0.001, 0.01, 0.03, 0.05, 0.1]
l1_ratios = [1.5, 1.1, 1, 0.9, 0.8, 0.7, 0.5]
con_mat = confusion_matrix(val_labels, val_preds,
labels=range(len(classes)))
 prec = precision_score(val_labels, val_preds,
labels=range(len(classes)) ,
average='macro')
 rec = recall_score(val_labels, val_preds,
labels=range(len(classes)) ,
average='macro')
 f1 = f1_score(val_labels, val_preds,
labels=range(len(classes)) ,
average='macro')
 plt.figure(figsize=(10,10))
ax = plt.gca()
ax.matshow(con_mat, cmap='Greens')
 ax.set_xticks(range(len(classes)))
 ax.set_xticklabels(classes, fontdict={'fontsize': 6})
 plt.setp(ax.get_xticklabels() , rotation=65, ha="left",
rotation_mode="anchor")
 ax.set_yticks(range(len(classes)))
 ax.set_yticklabels(classes, fontdict={'fontsize': 6})
 plt.setp(ax.get_yticklabels() , rotation=25, ha="right",
rotation_mode="anchor")
 plt.show()
print('Precision \t: {:.4f}'.format(prec))
print('Recall \t\t: {:.4f}'.format(rec))
print('F1 score \t: {:.4f}'.format(f1))<predict_on_test>
cv_elastic = [rmse_cv(ElasticNet(alpha = alpha, l1_ratio=l1_ratio)).mean()
for(alpha, l1_ratio)in product(alphas, l1_ratios)]
test_dataset, test_size = prepare_dataset("test", True)
 test_dataset = test_dataset.batch(batch_size ).prefetch(AUTO)
 test_image_dataset = test_dataset.map(lambda image,idnum: image)
 test_id_dataset = test_dataset.map(lambda image,idnum: idnum ).unbatch()
test_ids = next(iter(test_id_dataset.batch(test_size)) ).numpy().astype('U')
 test_probs = model.predict(test_image_dataset)
 test_preds = np.argmax(test_probs, axis=-1 )<install_modules>
elastic = ElasticNet(alpha=0.0005, l1_ratio=0.9 )
!pip install -q efficientnet<import_modules>
elastic.fit(X_train, y )
print("Tensorflow version " + tf.__version__ )<set_options>
rmse = np.sqrt(np.mean(( preds['true']-preds['preds'])**2))
print('RMSE: {0:.4f}'.format(rmse))
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()
IMAGE_SIZE = [512, 512]
EPOCHS = 50
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' )<define_variables>
print('R^2 train: %.3f' % r2_score(preds['true'], preds['preds']))
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>
print("Elastic Net picked " + str(sum(coef != 0)) + " variables and eliminated the other " + str(sum(coef == 0)) + " variables" )
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))<choose_model_class>
preds = elastic.predict(X_test)
 preds
with strategy.scope() :
enet = efn.EfficientNetB7(
 input_shape=(812, 812, 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>
preds = np.expm1(elastic.predict(X_test))
preds
scheduler = tf.keras.callbacks.ReduceLROnPlateau(patience=3, verbose=1)
 history = model.fit(
 get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS,
callbacks=[scheduler],
validation_data=get_validation_dataset()
)<save_to_csv>
solution = pd.DataFrame({"id":test.Id, "SalePrice":preds})
 solution.to_csv("elastic.csv", index = False )