Kaggle competition: House Prices - Advanced Regression Techniques
<SOS> metric: rmsle Kaggle data source: house-prices-advanced-regression-techniques<load_pretrained>
warnings.filterwarnings("ignore")
 pd.set_option('display.max_columns', 5000)
 pd.set_option('display.max_rows', 5000)
 for dirname, _, filenames in os.walk('/kaggle/input'):
for filename in filenames:
print(os.path.join(dirname, filename))
preds51=np.load('.. /input/5-kfold-efficentne-e7-p1/probs.npz')
 preds51['a'].shape<load_pretrained>
train=pd.read_csv('/kaggle/input/house-prices-advanced-regression-techniques/train.csv')
 test=pd.read_csv('/kaggle/input/house-prices-advanced-regression-techniques/test.csv')
 sample_sub=pd.read_csv('/kaggle/input/house-prices-advanced-regression-techniques/sample_submission.csv' )
preds52=np.load('.. /input/5-kfold-efficentne-e7-p2/probs.npz')
 preds52['a'].shape<load_pretrained>
train[train.SalePrice>300000]
preds53=np.load('.. /input/5-kfold-efficentne-e7-p3/probs.npz')
 preds53['a'].shape<load_pretrained>
corr_dict=correlation_train['SalePrice'].sort_values(ascending=False ).to_dict()
important_columns=[]
for key,value in corr_dict.items() :
if(( value>0.1)&(value<0.8)) |(value<=-0.1):
important_columns.append(key)
 important_columns
preds54=np.load('.. /input/5-kfold-efficentne-e7-p4/probs.npz')
 preds54['a'].shape<load_pretrained>
train_test=pd.concat([train,test],axis=0,sort=False)
 train_test.head()
preds55=np.load('.. /input/5-kfold-efficentne-e7-p5/probs.npz')
 preds55['a'].shape<prepare_output>
pd.set_option('display.max_rows', 5000)
 train_test_null_info=pd.DataFrame(train_test.isnull().sum() ,columns=['Count of NaN'])
 train_test_dtype_info=pd.DataFrame(train_test.dtypes,columns=['DataTypes'])
 train_tes_info=pd.concat([train_test_null_info,train_test_dtype_info],axis=1)
 train_tes_info
preds55=(preds51['a']+preds52['a']+preds53['a']+preds54['a']+preds55['a'])/5<prepare_output>
train_test.loc[train_test['Fireplaces']==0,'FireplaceQu']='Nothing'
train_test['LotFrontage'] = train_test['LotFrontage'].fillna(train_test.groupby('1stFlrSF')['LotFrontage'].transform('mean'))
train_test['LotFrontage'].interpolate(method='linear',inplace=True)
 train_test['LotFrontage']=train_test['LotFrontage'].astype(int)
 train_test['MasVnrArea'] = train_test['MasVnrArea'].fillna(train_test.groupby('MasVnrType')['MasVnrArea'].transform('mean'))
train_test['MasVnrArea'].interpolate(method='linear',inplace=True)
 train_test['MasVnrArea']=train_test['MasVnrArea'].astype(int)
 train_test["Fence"] = train_test["Fence"].fillna("None")
 train_test["FireplaceQu"] = train_test["FireplaceQu"].fillna("None")
 train_test["Alley"] = train_test["Alley"].fillna("None")
 train_test["PoolQC"] = train_test["PoolQC"].fillna("None")
 train_test["MiscFeature"] = train_test["MiscFeature"].fillna("None")
 train_test.loc[train_test['BsmtFinSF1']==0,'BsmtFinType1']='Unf'
train_test.loc[train_test['BsmtFinSF2']==0,'BsmtQual']='TA'
train_test['YrBltRmd']=train_test['YearBuilt']+train_test['YearRemodAdd']
train_test['Total_Square_Feet'] =(train_test['BsmtFinSF1'] + train_test['BsmtFinSF2'] + train_test['1stFlrSF'] + train_test['2ndFlrSF'] + train_test['TotalBsmtSF'])
 train_test['Total_Bath'] =(train_test['FullBath'] +(0.5 * train_test['HalfBath'])+ train_test['BsmtFullBath'] +(0.5 * train_test['BsmtHalfBath']))
train_test['Total_Porch_Area'] =(train_test['OpenPorchSF'] + train_test['3SsnPorch'] + train_test['EnclosedPorch'] + train_test['ScreenPorch'] + train_test['WoodDeckSF'])
 train_test['exists_pool'] = train_test['PoolArea'].apply(lambda x: 1 if x > 0 else 0)
 train_test['exists_garage'] = train_test['GarageArea'].apply(lambda x: 1 if x > 0 else 0)
 train_test['exists_fireplace'] = train_test['Fireplaces'].apply(lambda x: 1 if x > 0 else 0)
 train_test['exists_bsmt'] = train_test['TotalBsmtSF'].apply(lambda x: 1 if x > 0 else 0)
 train_test['old_house'] = train_test['YearBuilt'].apply(lambda x: 1 if x <1990 else 0)
 for i in train_test.columns:
if 'SalePrice' not in i:
if 'object' in str(train_test[str(i)].dtype):
train_test[str(i)]=train_test[str(i)].fillna(method='ffill')
preds55=0.65*preds4['a']+0.35*preds55<drop_column>
columns =('FireplaceQu', 'BsmtQual', 'BsmtCond', 'GarageQual', 'GarageCond', 'ExterQual', 'ExterCond','HeatingQC', 'PoolQC', 'KitchenQual', 'BsmtFinType1', 'YrSold', 'MoSold', 'BsmtFinType2', 'Functional', 'Fence', 'BsmtExposure', 'GarageFinish', 'LandSlope', 'LotShape', 'PavedDrive', 'Street', 'Alley', 'CentralAir', 'MSSubClass', 'OverallCond')
 for col in columns:
lbl_enc = LabelEncoder()
lbl_enc.fit(list(train_test[col].values))
train_test[col] = lbl_enc.transform(list(train_test[col].values))
del preds1,preds2,preds3,preds4,preds55
gc.collect()<load_pretrained>
numeric_features = train_test.dtypes[train_test.dtypes != "object"].index
skewed_features = train_test[numeric_features].apply(lambda x: skew(x)).sort_values(ascending=False)
 print(skewed_features )
preds6=np.load('.. /input/flowertpuwin-densenet201/probs.npz')
 preds6['a'].shape<load_pretrained>
high_skewness = skewed_features[abs(skewed_features)> 0.9]
skewed_features = high_skewness.index
preds7=np.load('.. /input/flowertpuwin-densenet201/probs.npz')
 preds7['a'].shape 
<load_pretrained>
print(high_skewness)
 print('
Variables with high skewness:
',skewed_features )
preds8=np.load('.. /input/tpu-enet-b7-incepention-b6-new/probs.npz')
 preds8['a'].shape 
<prepare_output>
for feature in skewed_features:
train_test[feature] = boxcox1p(train_test[feature], boxcox_normmax(train_test[feature] + 1))
preds=np.argmax(preds, axis=1)
 preds.shape<load_from_csv>
train_test=pd.get_dummies(train_test,dtype='int8' )
submission = pd.read_csv('/kaggle/input/flower-blending-v1/submission.csv')
 submission.head()<prepare_output>
train_test_null_info=pd.DataFrame(train_test.isnull().sum() ,columns=['Count of NaN'])
 train_test_dtype_info=pd.DataFrame(train_test.dtypes,columns=['DataTypes'])
 train_test_info=pd.concat([train_test_null_info,train_test_dtype_info],axis=1)
 train_test_info
submission1=submission.copy()
submission1['label']=preds
submission1.head()<save_to_csv>
train=train_test[0:1460]
test=train_test[1460:2919]
submission1.to_csv('submission.csv', index=False)
<feature_engineering>
corr_dict2=corr_new_train['SalePrice'].sort_values(ascending=False ).to_dict()
corr_dict2
submission1['y']=submission['label']
submission1.corr()<install_modules>
best_columns=[]
for key,value in corr_dict2.items() :
if(( value>=0.3175)&(value<0.9)) |(value<=-0.315):
best_columns.append(key)
 best_columns
!pip install -q efficientnet<import_modules>
train['SalePrice_Log1p'] = np.log1p(train.SalePrice )
print("Tensorflow version " + tf.__version__ )<set_options>
print(len(train[(train.KitchenQual==3)&(train.SalePrice>360000)].index))
AUTO = tf.data.experimental.AUTOTUNE
try:
tpu = tf.distribute.cluster_resolver.TPUClusterResolver()
print('Running on TPU ', tpu.master())
 except ValueError:
tpu = None
if tpu:
tf.config.experimental_connect_to_cluster(tpu)
 tf.tpu.experimental.initialize_tpu_system(tpu)
 strategy = tf.distribute.experimental.TPUStrategy(tpu)
 else:
strategy = tf.distribute.get_strategy()
print("REPLICAS: ", strategy.num_replicas_in_sync)
 if tpu:
BATCH_SIZE_MULT = 2
else:
BATCH_SIZE_MULT = 1
GCS_DS_PATH = KaggleDatasets().get_gcs_path('flower-classification')
 print(GCS_DS_PATH)
 IMAGE_SIZE = [331, 331]
img_size=IMAGE_SIZE[0]
EPOCHS = 3
BATCH_SIZE = 16 * strategy.num_replicas_in_sync * BATCH_SIZE_MULT
DO_TTA = False 
<set_options>
dbscan = DBSCAN(eps=1400, min_samples=20 ).fit(train_pca)
 core_samples_mask = np.zeros_like(dbscan.labels_, dtype=bool)
 core_samples_mask[dbscan.core_sample_indices_] = True
labels=dbscan.labels_
n_clusters_ = len(set(labels)) -(1 if -1 in labels else 0 )
if not tpu:
MIXED_PRECISION = False
XLA_ACCELERATE = False
else:
MIXED_PRECISION = True
XLA_ACCELERATE = True
if MIXED_PRECISION:
if tpu: policy = tf.keras.mixed_precision.experimental.Policy('mixed_bfloat16')
 else: policy = tf.keras.mixed_precision.experimental.Policy('mixed_float16')
 mixed_precision.set_policy(policy)
 print('Mixed precision enabled')
 if XLA_ACCELERATE:
if not tpu:
tf.config.optimizer.set_jit(True)
 print('Accelerated Linear Algebra enabled' )<init_hyperparams>
labels=pd.DataFrame(labels,columns=['Classes'])
 print(labels[labels['Classes']==-1] )
LR_START = 0.00001
LR_MAX = 0.00005 * strategy.num_replicas_in_sync
LR_MIN = 0.00001
LR_RAMPUP_EPOCHS = 5
LR_SUSTAIN_EPOCHS = 0
LR_EXP_DECAY =.8
LR_MULTIPLIER = 1.0
@tf.function
def lrfn(epoch):
if epoch < LR_RAMPUP_EPOCHS:
lr =(LR_MAX - LR_START)/ LR_RAMPUP_EPOCHS * epoch + LR_START
elif epoch < LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS:
lr = LR_MAX
else:
lr =(LR_MAX - LR_MIN)* LR_EXP_DECAY**(epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS)+ LR_MIN
return lr * LR_MULTIPLIER
lr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=True)
 rng = [i for i in range(EPOCHS)]
y = [lrfn(x)for x in rng]
plt.plot(rng, y)
 print("Learning rate schedule: {:.3g} to {:.3g} to {:.3g}".format(y[0], max(y), y[-1])) 
<init_hyperparams>
train=pd.concat([train,labels],axis=1 )
LR_START2 = 0.00001
LR_MAX2 = 0.000025 * strategy.num_replicas_in_sync
LR_MIN2 = 0.00001
LR_RAMPUP_EPOCHS2 = 5
LR_SUSTAIN_EPOCHS2 = 0
LR_EXP_DECAY2 =.8
LR_MULTIPLIER = 1.0
@tf.function
def lrfn2(epoch):
if epoch < LR_RAMPUP_EPOCHS2:
lr =(LR_MAX2 - LR_START2)/ LR_RAMPUP_EPOCHS2 * epoch + LR_START2
elif epoch < LR_RAMPUP_EPOCHS2 + LR_SUSTAIN_EPOCHS2:
lr = LR_MAX2
else:
lr =(LR_MAX2 - LR_MIN2)* LR_EXP_DECAY2**(epoch - LR_RAMPUP_EPOCHS2 - LR_SUSTAIN_EPOCHS2)+ LR_MIN2
return lr
lr_callback2 = tf.keras.callbacks.LearningRateScheduler(lrfn2, verbose=True)
 rng = [i for i in range(EPOCHS)]
y = [lrfn2(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]))<normalization>
train[train.Classes==-1]
@tf.function
def lrfnCosineDecay(epoch):
if epoch < LR_RAMPUP_EPOCHS:
lr =(LR_MAX - LR_START)/ LR_RAMPUP_EPOCHS * epoch + LR_START
else:
lr = LR_MIN +(LR_MAX - LR_MIN)*(1 + math.cos(math.pi * epoch / EPOCHS)) / 2
return lr * LR_MULTIPLIER
rng = [i for i in range(EPOCHS)]
y = [lrfnCosineDecay(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]))
lr_callbackCosineDecay = tf.keras.callbacks.LearningRateScheduler(lrfnCosineDecay, verbose=True )<define_variables>
train.drop([197,810,1170,1182,1298,1386,1423],axis=0,inplace=True )
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')
 SKIP_VALIDATION = False
if SKIP_VALIDATION:
TRAINING_FILENAMES = TRAINING_FILENAMES + VALIDATION_FILENAMES 
<define_variables>
"Looking at the SalePrice and SalePrice_Log1p visualizations"
train = train[train.GarageArea * train.GarageCars < 3700]
train = train[(train.FullBath +(train.HalfBath*0.5)+ train.BsmtFullBath +(train.BsmtHalfBath*0.5)) <5]
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>
train.isnull().sum()
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, figsize = 13.0):

 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 = figsize
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>
train.isnull().sum()
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 read_labeled_id_tfrecord(example):
LABELED_ID_TFREC_FORMAT = {
"image": tf.io.FixedLenFeature([], tf.string),
"class": tf.io.FixedLenFeature([], tf.int64),
"id": tf.io.FixedLenFeature([], tf.string),
}
example = tf.io.parse_single_example(example, LABELED_ID_TFREC_FORMAT)
 image = decode_image(example['image'])
 label = tf.cast(example['class'], tf.int32)
 idnum = example['id']
return image, label, 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_id_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls=AUTO)
 return dataset
def load_dataset_with_id(filenames, 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_id_tfrecord, num_parallel_calls=AUTO)
 return dataset
def data_augment(image, label):
image = tf.image.random_flip_left_right(image)
 image= random_blockout(image)
 return image, label
def get_training_dataset(do_aug=True,do_repeat=True):
dataset = load_dataset(TRAINING_FILENAMES, labeled=True)
 dataset = dataset.map(lambda image, label, idnum: [image, label])
 if do_repeat:
dataset = dataset.repeat()
if do_aug:
dataset = dataset.map(data_augment, num_parallel_calls=AUTO)
 if do_repeat:
dataset = dataset.shuffle(2048)
 dataset = dataset.batch(BATCH_SIZE, drop_remainder=True)
 dataset = dataset.prefetch(AUTO)
 return dataset
def get_validation_dataset(ordered=False, repeated=False):
dataset = load_dataset(VALIDATION_FILENAMES, labeled=True, ordered=ordered)
 dataset = dataset.map(lambda image, label, idnum: [image, label])
 if repeated:
dataset = dataset.repeat()
dataset = dataset.shuffle(2048)
 dataset = dataset.batch(BATCH_SIZE, drop_remainder=repeated)
 dataset = dataset.cache()
dataset = dataset.prefetch(AUTO)
 return dataset
def get_validation_dataset_with_id(ordered=False):
dataset = load_dataset_with_id(VALIDATION_FILENAMES, ordered=ordered)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.cache()
dataset = dataset.prefetch(AUTO)
 return dataset
def get_test_dataset(ordered=False, do_aug=False):
dataset = load_dataset(TEST_FILENAMES, labeled=False, ordered=ordered)
 if do_aug:
dataset = dataset.map(data_augment, num_parallel_calls=AUTO)
 dataset = dataset.map(transform, num_parallel_calls=AUTO)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.prefetch(AUTO)
 return dataset
def count_data_items(filenames):
n = [int(re.compile(r"-([0-9]*)\." ).search(filename ).group(1)) for filename in filenames]
return np.sum(n)
 def int_div_round_up(a, b):
return(a + b - 1)// b
NUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)
 NUM_VALIDATION_IMAGES =(1 - SKIP_VALIDATION)* count_data_items(VALIDATION_FILENAMES)
 NUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)
 STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE
VALIDATION_STEPS = int_div_round_up(NUM_VALIDATION_IMAGES, BATCH_SIZE)
 print('Dataset: {} training images, {} validation images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES)) 
<normalization>
test.isnull().sum()
def get_mat(rotation, shear, height_zoom, width_zoom, height_shift, width_shift):
rotation = math.pi * rotation / 180.
 shear = math.pi * shear / 180.
 c1 = tf.math.cos(rotation)
 s1 = tf.math.sin(rotation)
 one = tf.constant([1],dtype='float32')
 zero = tf.constant([0],dtype='float32')
 rotation_matrix = tf.reshape(tf.concat([c1,s1,zero, -s1,c1,zero, zero,zero,one],axis=0),[3,3])
 c2 = tf.math.cos(shear)
 s2 = tf.math.sin(shear)
 shear_matrix = tf.reshape(tf.concat([one,s2,zero, zero,c2,zero, zero,zero,one],axis=0),[3,3])
 zoom_matrix = tf.reshape(tf.concat([one/height_zoom,zero,zero, zero,one/width_zoom,zero, zero,zero,one],axis=0),[3,3])
 shift_matrix = tf.reshape(tf.concat([one,zero,height_shift, zero,one,width_shift, zero,zero,one],axis=0),[3,3])
 return K.dot(K.dot(rotation_matrix, shear_matrix), K.dot(zoom_matrix, shift_matrix))<categorify>
test.isnull().sum()
def transform(image,label):
DIM = IMAGE_SIZE[0]
XDIM = DIM%2
rot = 15.* tf.random.normal([1],dtype='float32')
 shr = 5.* tf.random.normal([1],dtype='float32')
 h_zoom = 1.0 + tf.random.normal([1],dtype='float32')/10.
 w_zoom = 1.0 + tf.random.normal([1],dtype='float32')/10.
 h_shift = 16.* tf.random.normal([1],dtype='float32')
 w_shift = 16.* tf.random.normal([1],dtype='float32')
 m = get_mat(rot,shr,h_zoom,w_zoom,h_shift,w_shift)
 x = tf.repeat(tf.range(DIM//2,-DIM//2,-1), DIM)
 y = tf.tile(tf.range(-DIM//2,DIM//2),[DIM])
 z = tf.ones([DIM*DIM],dtype='int32')
 idx = tf.stack([x,y,z])
 idx2 = K.dot(m,tf.cast(idx,dtype='float32'))
idx2 = K.cast(idx2,dtype='int32')
 idx2 = K.clip(idx2,-DIM//2+XDIM+1,DIM//2)
 idx3 = tf.stack([DIM//2-idx2[0,], DIM//2-1+idx2[1,]])
 d = tf.gather_nd(image,tf.transpose(idx3))
return tf.reshape(d,[DIM,DIM,3]),label<categorify>
del test['SalePrice']
def random_blockout(img, sl=0.1, sh=0.2, rl=0.4):
h, w, c = img_size, img_size, 3
origin_area = tf.cast(h*w, tf.float32)
 e_size_l = tf.cast(tf.round(tf.sqrt(origin_area * sl * rl)) , tf.int32)
 e_size_h = tf.cast(tf.round(tf.sqrt(origin_area * sh / rl)) , tf.int32)
 e_height_h = tf.minimum(e_size_h, h)
 e_width_h = tf.minimum(e_size_h, w)
 erase_height = tf.random.uniform(shape=[], minval=e_size_l, maxval=e_height_h, dtype=tf.int32)
 erase_width = tf.random.uniform(shape=[], minval=e_size_l, maxval=e_width_h, dtype=tf.int32)
 erase_area = tf.zeros(shape=[erase_height, erase_width, c])
 erase_area = tf.cast(erase_area, tf.uint8)
 pad_h = h - erase_height
pad_top = tf.random.uniform(shape=[], minval=0, maxval=pad_h, dtype=tf.int32)
 pad_bottom = pad_h - pad_top
pad_w = w - erase_width
pad_left = tf.random.uniform(shape=[], minval=0, maxval=pad_w, dtype=tf.int32)
 pad_right = pad_w - pad_left
erase_mask = tf.pad([erase_area], [[0,0],[pad_top, pad_bottom], [pad_left, pad_right], [0,0]], constant_values=1)
 erase_mask = tf.squeeze(erase_mask, axis=0)
 erased_img = tf.multiply(tf.cast(img,tf.float32), tf.cast(erase_mask, tf.float32))
return tf.cast(erased_img, img.dtype)
<define_variables>
X=train.drop(['SalePrice','SalePrice_Log1p','Classes'],axis=1)
 y=train.SalePrice_Log1p
training_dataset = get_training_dataset(do_aug=False)
 training_dataset = training_dataset.unbatch().batch(20)
 train_batch = iter(training_dataset )<define_variables>
def overfit_reducer(df):
overfit = []
for i in df.columns:
counts = df[i].value_counts()
zeros = counts.iloc[0]
if zeros / len(df)* 100 > 99.9:
overfit.append(i)
 overfit = list(overfit)
 return overfit
overfitted_features = overfit_reducer(X )
display_batch_of_images(next(train_batch))<load_pretrained>
std_scaler=StandardScaler()
rbst_scaler=RobustScaler()
power_transformer=PowerTransformer()
X_std=std_scaler.fit_transform(X)
 X_rbst=rbst_scaler.fit_transform(X)
 X_pwr=power_transformer.fit_transform(X)
 test_std=std_scaler.transform(test)
 test_rbst=rbst_scaler.transform(test)
 test_pwr=power_transformer.transform(test )
gc.enable()
def get_training_dataset_raw() :
dataset = load_dataset(TRAINING_FILENAMES, labeled=True, ordered=False)
 return dataset
raw_training_dataset = get_training_dataset_raw()
label_counter = Counter()
for images, labels, id in raw_training_dataset:
label_counter.update([labels.numpy() ])
 del raw_training_dataset
TARGET_NUM_PER_CLASS = 122
def get_weight_for_class(class_id):
counting = label_counter[class_id]
weight = TARGET_NUM_PER_CLASS / counting
return weight
weight_per_class = {class_id: get_weight_for_class(class_id)for class_id in range(104)}
weight_per_class_wo_id = {get_weight_for_class(class_id)for class_id in range(104)}<choose_model_class>
X_train,X_test,y_train,y_test=train_test_split(X_std,y,test_size=0.002,random_state=52)
 print('X_train Shape :',X_train.shape)
 print('X_test Shape :',X_test.shape)
 print('y_train Shape :',y_train.shape)
 print('y_test Shape :',y_test.shape )
with strategy.scope() :
enet = efn.EfficientNetB7(
 input_shape=(None,None,3),
weights='noisy-student',
include_top=False 
)
 model = tf.keras.Sequential([
enet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax',dtype='float32')
 ])
 model.compile(
 optimizer=tf.keras.optimizers.Adam(lr=0.0001),
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 model.summary()<train_model>
lgb_regressor=lgb.LGBMRegressor(objective='regression', num_leaves=5, learning_rate=0.035, n_estimators=2177, max_bin=50, bagging_fraction=0.65,bagging_freq=5, bagging_seed=7,
feature_fraction=0.201, feature_fraction_seed=7,n_jobs=-1)
 lgb_regressor.fit(X_train, y_train)
 y_head=lgb_regressor.predict(X_test)
 print('-'*10+'LGBM'+'-'*10)
 print('R square Accuracy: ',r2_score(y_test,y_head))
print('Mean Absolute Error Accuracy: ',mean_absolute_error(y_test,y_head))
print('Mean Squared Error Accuracy: ',mean_squared_error(y_test,y_head))
history = model.fit(
 get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS,
callbacks=[lr_callback],
validation_data=None if SKIP_VALIDATION else get_validation_dataset()
)<define_variables>
gb_reg = GradientBoostingRegressor(n_estimators=1992, learning_rate=0.03005, max_depth=4, max_features='sqrt', min_samples_leaf=15, min_samples_split=14, loss='huber', random_state =42)
 gb_reg.fit(X_train, y_train)
 y_head=gb_reg.predict(X_test)
 print('-'*10+'GBR'+'-'*10)
 print('R square Accuracy: ',r2_score(y_test,y_head))
print('Mean Absolute Error Accuracy: ',mean_absolute_error(y_test,y_head))
print('Mean Squared Error Accuracy: ',mean_squared_error(y_test,y_head))
IMAGE_SIZE = [512, 512]
img_size=IMAGE_SIZE[0]
EPOCHS = 3
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')
<train_model>
kfolds = KFold(n_splits=10, shuffle=True, random_state=42)
 alphas=[1e-9,1e-8,1e-7,1e-6]
ridgecv_reg= make_pipeline(RidgeCV(alphas=alphas, cv=kfolds))
ridgecv_reg.fit(X_train, y_train)
 y_head=ridgecv_reg.predict(X_test)
 print('-'*10+'RidgeCV'+'-'*10)
 print('R square Accuracy: ',r2_score(y_test,y_head))
print('Mean Absolute Error Accuracy: ',mean_absolute_error(y_test,y_head))
print('Mean Squared Error Accuracy: ',mean_squared_error(y_test,y_head))
history = model.fit(
 get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS,
callbacks=[lr_callback2],
validation_data=None if SKIP_VALIDATION else get_validation_dataset()
)<predict_on_test>
kfolds = KFold(n_splits=8, shuffle=True, random_state=42)
 lassocv_reg= make_pipeline(LassoCV(alphas=alphas, cv=kfolds))
lassocv_reg.fit(X_train, y_train)
 y_head=lassocv_reg.predict(X_test)
 print('-'*10+'LassoCV'+'-'*10)
 print('R square Accuracy: ',r2_score(y_test,y_head))
print('Mean Absolute Error Accuracy: ',mean_absolute_error(y_test,y_head))
print('Mean Squared Error Accuracy: ',mean_squared_error(y_test,y_head))
<define_variables>
kfolds = KFold(n_splits=8, shuffle=True, random_state=42)
 alphas=[0.0001, 0.0002, 0.0003, 0.0004, 0.0005, 0.0006]
l1ratio=[0.87, 0.9,0.92, 0.95,0.97, 0.99, 1]
elasticv_reg= make_pipeline(ElasticNetCV(alphas=alphas, cv=kfolds, l1_ratio=l1ratio))
elasticv_reg.fit(X_train, y_train)
 y_head=elasticv_reg.predict(X_test)
 print('-'*10+'ElasticNetCV'+'-'*10)
 print('R square Accuracy: ',r2_score(y_test,y_head))
print('Mean Absolute Error Accuracy: ',mean_absolute_error(y_test,y_head))
print('Mean Squared Error Accuracy: ',mean_squared_error(y_test,y_head))
IMAGE_SIZE = [331, 331]
img_size=IMAGE_SIZE[0]
EPOCHS = 3
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')
<choose_model_class>
estimators = [('lgbm', lgb_regressor), 
('gbr', gb_reg), 
('lasso', lassocv_reg), 
('ridge', ridgecv_reg), 
('elasticnet', elasticv_reg)]
stack_reg=StackingRegressor(estimators=estimators,final_estimator=ExtraTreesRegressor(n_estimators=50),n_jobs=-1)
 stack_reg.fit(X_train, y_train)
 y_head=stack_reg.predict(X_test)
 print('-'*10+'StackingRegressor'+'-'*10)
 print('R square Accuracy: ',r2_score(y_test,y_head))
print('Mean Absolute Error Accuracy: ',mean_absolute_error(y_test,y_head))
print('Mean Squared Error Accuracy: ',mean_squared_error(y_test,y_head))
with strategy.scope() :
pretrained_model = efn.EfficientNetB5(weights='noisy-student', include_top=False ,input_shape=(None,None,3))
model2 = tf.keras.Sequential([
pretrained_model,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax', dtype='float32')
 ])
 model2.summary()
class LRSchedule(tf.keras.optimizers.schedules.LearningRateSchedule):
def __call__(self, step):
return lrfn(epoch=step//STEPS_PER_EPOCH)
 optimizer = tf.keras.optimizers.Adam(learning_rate=LRSchedule())
 train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy()
valid_accuracy = tf.keras.metrics.SparseCategoricalAccuracy()
train_loss = tf.keras.metrics.Sum()
valid_loss = tf.keras.metrics.Sum()
loss_fn = tf.keras.losses.sparse_categorical_crossentropy<train_on_grid>
y_head=pd.DataFrame(y_head,columns=['Predict'])
 y_test.reset_index(drop=True,inplace=True)
 y_test_y_head=pd.concat([y_test,y_head],axis=1)
 y_test_y_head.head()
STEPS_PER_TPU_CALL = int(NUM_TRAINING_IMAGES/BATCH_SIZE)
 VALIDATION_STEPS_PER_TPU_CALL = 29
@tf.function
def train_step(data_iter):
def train_step_fn(images, labels):
with tf.GradientTape() as tape:
probabilities = model2(images, training=True)
 loss = loss_fn(labels, probabilities)
 grads = tape.gradient(loss, model2.trainable_variables)
 optimizer.apply_gradients(zip(grads, model2.trainable_variables))
train_accuracy.update_state(labels, probabilities)
 train_loss.update_state(loss)
 for _ in tf.range(STEPS_PER_TPU_CALL):
strategy.experimental_run_v2(train_step_fn, next(data_iter))
@tf.function
def valid_step(data_iter):
def valid_step_fn(images, labels):
probabilities = model2(images, training=False)
 loss = loss_fn(labels, probabilities)
 valid_accuracy.update_state(labels, probabilities)
 valid_loss.update_state(loss)
 for _ in tf.range(VALIDATION_STEPS_PER_TPU_CALL):
strategy.experimental_run_v2(valid_step_fn, next(data_iter))<train_model>
print('Count columns of test: ',len(test.columns))
print('Count columns of X: ',len(X.columns))
start_time = epoch_start_time = time.time()
train_dist_ds = strategy.experimental_distribute_dataset(get_training_dataset())
 valid_dist_ds = strategy.experimental_distribute_dataset(get_validation_dataset(repeated=True))
print("Training steps per epoch:", STEPS_PER_EPOCH, "in increments of", STEPS_PER_TPU_CALL)
 print("Validation images:", NUM_VALIDATION_IMAGES,
"Batch size:", BATCH_SIZE,
"Validation steps:", NUM_VALIDATION_IMAGES//BATCH_SIZE, "in increments of", VALIDATION_STEPS_PER_TPU_CALL)
 print("Repeated validation images:", int_div_round_up(NUM_VALIDATION_IMAGES, BATCH_SIZE*VALIDATION_STEPS_PER_TPU_CALL)*VALIDATION_STEPS_PER_TPU_CALL*BATCH_SIZE-NUM_VALIDATION_IMAGES)
 History = namedtuple('History', 'history')
 history = History(history={'loss': [], 'val_loss': [], 'sparse_categorical_accuracy': [], 'val_sparse_categorical_accuracy': []})
 epoch = 0
train_data_iter = iter(train_dist_ds)
 valid_data_iter = iter(valid_dist_ds)
 step = 0
epoch_steps = 0
while True:
train_step(train_data_iter)
 epoch_steps += STEPS_PER_TPU_CALL
step += STEPS_PER_TPU_CALL
print('=', end='', flush=True)
 if(step // STEPS_PER_EPOCH)> epoch:
print('|', end='', flush=True)
 valid_epoch_steps = 0
for _ in range(int_div_round_up(NUM_VALIDATION_IMAGES, BATCH_SIZE*VALIDATION_STEPS_PER_TPU_CALL)) :
valid_step(valid_data_iter)
 valid_epoch_steps += VALIDATION_STEPS_PER_TPU_CALL
print('=', end='', flush=True)
 history.history['sparse_categorical_accuracy'].append(train_accuracy.result().numpy())
 history.history['val_sparse_categorical_accuracy'].append(valid_accuracy.result().numpy())
 history.history['loss'].append(train_loss.result().numpy() /(BATCH_SIZE*epoch_steps))
history.history['val_loss'].append(valid_loss.result().numpy() /(BATCH_SIZE*valid_epoch_steps))
epoch_time = time.time() - epoch_start_time
print('
EPOCH {:d}/{:d}'.format(epoch+1, EPOCHS))
print('time: {:0.1f}s'.format(epoch_time),
'loss: {:0.4f}'.format(history.history['loss'][-1]),
'accuracy: {:0.4f}'.format(history.history['sparse_categorical_accuracy'][-1]),
'val_loss: {:0.4f}'.format(history.history['val_loss'][-1]),
'val_acc: {:0.4f}'.format(history.history['val_sparse_categorical_accuracy'][-1]),
'lr: {:0.4g}'.format(lrfn(epoch)) ,
'steps/val_steps: {:d}/{:d}'.format(epoch_steps, valid_epoch_steps), flush=True)
 epoch = step // STEPS_PER_EPOCH
epoch_steps = 0
epoch_start_time = time.time()
train_accuracy.reset_states()
valid_accuracy.reset_states()
valid_loss.reset_states()
train_loss.reset_states()
if epoch >= EPOCHS:
break
optimized_ctl_training_time = time.time() - start_time
print("OPTIMIZED CTL TRAINING TIME: {:0.1f}s".format(optimized_ctl_training_time))<define_variables>
test_pred_lgb=lgb_regressor.predict(test_pwr)
 test_pred_gb=gb_reg.predict(test_pwr)
 test_pred_elastic=elasticv_reg.predict(test_pwr)
 test_pred_ridge=ridgecv_reg.predict(test_pwr)
 test_pred_lasso=lassocv_reg.predict(test_pwr)
 test_pred_stack=stack_reg.predict(test_pwr )
IMAGE_SIZE = [512, 512]
img_size=IMAGE_SIZE[0]
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' )<predict_on_test>
test_pred_lgb=pd.DataFrame(test_pred_lgb,columns=['SalePrice'])
 test_pred_gb=pd.DataFrame(test_pred_gb,columns=['SalePrice'])
 test_pred_elastic=pd.DataFrame(test_pred_elastic,columns=['SalePrice'])
 test_pred_ridge=pd.DataFrame(test_pred_ridge,columns=['SalePrice'])
 test_pred_lasso=pd.DataFrame(test_pred_lasso,columns=['SalePrice'])
 test_pred_stack=pd.DataFrame(test_pred_stack,columns=['SalePrice'] )
if not SKIP_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 = model.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.5<find_best_params>
test_pred_lgb.SalePrice =np.floor(np.expm1(test_pred_lgb.SalePrice))
test_pred_gb.SalePrice =np.floor(np.expm1(test_pred_gb.SalePrice))
test_pred_elastic.SalePrice =np.floor(np.expm1(test_pred_elastic.SalePrice))
test_pred_ridge.SalePrice =np.floor(np.expm1(test_pred_ridge.SalePrice))
test_pred_lasso.SalePrice =np.floor(np.expm1(test_pred_lasso.SalePrice))
test_pred_stack.SalePrice =np.floor(np.expm1(test_pred_stack.SalePrice))
print(best_alpha)
<define_variables>
final_pred=(test_pred_stack*0.1665)+(test_pred_lgb*0.678)+(test_pred_ridge*0.1665)
 final_pred.head()
if not SKIP_VALIDATION:
cmdataset_with_id = get_validation_dataset_with_id(ordered=True)
 ids_ds = cmdataset_with_id.map(lambda image, label, idnum: idnum ).unbatch()
ids = next(iter(ids_ds.batch(NUM_VALIDATION_IMAGES)) ).numpy().astype('U')
 val_batch = iter(cmdataset.unbatch().batch(1))
noip = sum(cm_predictions!=cm_correct_labels)
 print('Number of incorrect predictions: ' + str(noip)+ '('+str(round(noip/NUM_VALIDATION_IMAGES*100,1)) +'%)')
 for fi in range(NUM_VALIDATION_IMAGES):
x = next(val_batch)
 if cm_predictions[fi] != cm_correct_labels[fi]:
print("Image id: '" + ids[fi] + "'")
 display_batch_of_images(x,np.array([cm_predictions[fi]]),figsize = 4 )<compute_test_metric>
sample_sub['SalePrice']=final_pred
<save_to_csv><EOS> 
sample_sub.to_csv('sample_submission.csv',index=False )