Kaggle competition: Flower Classification with TPUs
<SOS> metric: MacroFScore Kaggle data source: flower-classification-with-tpus<set_options>
!pip install -q efficientnet
pd.set_option('display.max_columns', 500)
 pd.set_option('display.max_rows', 200)
 warnings.filterwarnings('ignore')
 SEED = 42
PATH = '.. /input/'<load_from_csv>
print("Tensorflow version " + tf.__version__)
def concat_df(train_data, test_data):
return pd.concat([train_data, test_data], sort=True ).reset_index(drop=True)
 def divide_df(all_data):
return all_data.loc[:1459], all_data.loc[1460:].drop(['SalePrice'], axis=1)
 df_train = pd.read_csv(PATH + 'train.csv')
 df_test = pd.read_csv(PATH + 'test.csv')
 df_all = concat_df(df_train, df_test)
 df_train.name = 'Training Set'
df_test.name = 'Test Set'
df_all.name = 'All Set'
dfs = [df_train, df_test]
print('Number of Training Examples = {}'.format(df_train.shape[0]))
print('Number of Test Examples = {}
'.format(df_test.shape[0]))
print('Training X Shape = {}'.format(df_train.shape))
print('Training y Shape = {}
'.format(df_train['SalePrice'].shape[0]))
print('Test X Shape = {}'.format(df_test.shape))
print('Test y Shape = {}
'.format(df_test.shape[0]))<count_missing_values>
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)
def display_missing(df):
for col in df.columns.tolist() :
if df[col].isnull().sum() :
print('{} column missing values: {}/{}'.format(col, df[col].isnull().sum() , len(df)))
 print('
')
 for df in dfs:
print('{}'.format(df.name))
display_missing(df )<categorify>
AUTO = tf.data.experimental.AUTOTUNE
IMAGE_SIZE = [512, 512]
EPOCHS = 25
FOLDS = 5
SEED = 777
BATCH_SIZE = 16 * strategy.num_replicas_in_sync
df_all['MasVnrArea'] = df_all['MasVnrArea'].fillna(0)
 df_all['MasVnrType'] = df_all['MasVnrType'].fillna('None')
 for feature in ['BsmtFinSF1', 'BsmtFinSF2', 'BsmtUnfSF', 'TotalBsmtSF', 'BsmtFullBath', 'BsmtHalfBath']:
df_all[feature] = df_all[feature].fillna(0)
 for feature in ['BsmtCond', 'BsmtExposure', 'BsmtFinType1', 'BsmtFinType2', 'BsmtQual']:
df_all[feature] = df_all[feature].fillna('None')
 for feature in ['GarageArea', 'GarageCars', 'GarageYrBlt']:
df_all[feature] = df_all[feature].fillna(0)
 for feature in ['GarageType', 'GarageFinish', 'GarageQual', 'GarageCond']:
df_all[feature] = df_all[feature].fillna('None')
 for feature in ['Alley', 'Fence', 'FireplaceQu', 'MiscFeature', 'PoolQC']:
df_all[feature] = df_all[feature].fillna('None')
 display_missing(df_all )<feature_engineering>
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:
tf.config.optimizer.set_jit(True)
 print('Accelerated Linear Algebra enabled' )
for feature in ['Electrical', 'Exterior1st', 'Exterior2nd', 'Functional', 'KitchenQual', 'MSZoning', 'SaleType', 'Utilities']:
df_all[feature] = df_all.groupby(['Neighborhood', 'MSSubClass'])[feature].apply(lambda x: x.fillna(x.mode() [0]))
df_all['LotFrontage'] = df_all.groupby(['Neighborhood'])['LotFrontage'].apply(lambda x: x.fillna(x.median()))
display_missing(df_all )<sort_values>
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']
df_train, df_test = divide_df(df_all)
 cols = ['GarageYrBlt', 'Id', 'MSSubClass', 'MoSold', 'YearBuilt', 'YearRemodAdd', 'YrSold']
df_train_corr = df_train.drop(cols, axis=1 ).corr().abs().unstack().sort_values(kind="quicksort", ascending=False ).reset_index()
df_train_corr.rename(columns={"level_0": "Feature 1", "level_1": "Feature 2", 0: 'Correlation Coefficient'}, inplace=True)
 df_train_corr.drop(df_train_corr.iloc[1::2].index, inplace=True)
 df_train_corr_nd = df_train_corr.drop(df_train_corr[df_train_corr['Correlation Coefficient'] == 1.0].index)
 df_test_corr = df_test.drop(cols, axis=1 ).corr().abs().unstack().sort_values(kind="quicksort", ascending=False ).reset_index()
df_test_corr.rename(columns={"level_0": "Feature 1", "level_1": "Feature 2", 0: 'Correlation Coefficient'}, inplace=True)
 df_test_corr.drop(df_test_corr.iloc[1::2].index, inplace=True)
 df_test_corr_nd = df_test_corr.drop(df_test_corr[df_test_corr['Correlation Coefficient'] == 1.0].index )<filter>
LR_START = 0.00001
LR_MAX = 0.00005 * strategy.num_replicas_in_sync
LR_MIN = 0.00001
LR_RAMPUP_EPOCHS = 10
LR_SUSTAIN_EPOCHS = 0
LR_EXP_DECAY =.8
def lrfn(epoch):
if epoch < LR_RAMPUP_EPOCHS:
lr =(LR_MAX - LR_START)/ LR_RAMPUP_EPOCHS * epoch + LR_START
elif epoch < LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS:
lr = LR_MAX
else:
lr =(LR_MAX - LR_MIN)* LR_EXP_DECAY**(epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS)+ LR_MIN
return lr
lr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=True)
 rng = [i for i in range(EPOCHS)]
y = [lrfn(x)for x in rng]
plt.plot(rng, y)
 print("Learning rate schedule: {:.3g} to {:.3g} to {:.3g}".format(y[0], max(y), y[-1]))
df_train_corr_nd[df_train_corr_nd['Feature 1'] == 'SalePrice']<define_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)
 image = tf.image.random_flip_up_down(image, seed=SEED)
 return image, label
def get_training_dataset(dataset, do_aug=True):
dataset = dataset.map(data_augment, num_parallel_calls=AUTO)
 if do_aug:
dataset = dataset.map(transform, num_parallel_calls=AUTO)
 dataset = dataset.repeat()
dataset = dataset.shuffle(2048)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.prefetch(AUTO)
 return dataset
def get_validation_dataset(dataset):
dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.cache()
dataset = dataset.prefetch(AUTO)
 return dataset
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 = int(count_data_items(TRAINING_FILENAMES)*(FOLDS - 1.0)/FOLDS)
 NUM_VALIDATION_IMAGES = int(count_data_items(TRAINING_FILENAMES)* 1.0/FOLDS)
 NUM_TEST_IMAGES = int(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))
cat_features = ['Alley', 'BedroomAbvGr', 'BldgType', 'BsmtCond', 'BsmtExposure',
'BsmtFinType1', 'BsmtFinType2', 'BsmtFullBath', 'BsmtHalfBath', 'BsmtQual',
'CentralAir', 'Condition1', 'Condition2', 'Electrical', 'ExterCond',
'ExterQual', 'Exterior1st', 'Exterior2nd', 'Fence', 'FireplaceQu',
'Fireplaces', 'Foundation', 'FullBath', 'Functional', 'GarageCars',
'GarageCond', 'GarageFinish', 'GarageQual', 'GarageType', 'HalfBath',
'Heating', 'HeatingQC', 'KitchenAbvGr', 'KitchenQual', 'LandContour',
'LandSlope', 'LotConfig', 'LotShape', 'MSSubClass', 'MSZoning',
'MasVnrType', 'MiscFeature', 'MoSold', 'Neighborhood', 'OverallCond',
'OverallQual', 'PavedDrive', 'PoolQC', 'RoofMatl', 'RoofStyle',
'SaleCondition', 'SaleType', 'Street', 'TotRmsAbvGrd', 'Utilities', 'YrSold']
fig, axs = plt.subplots(ncols=2, nrows=28, figsize=(18, 120))
plt.subplots_adjust(right=1.5, top=1.5)
 for i, feature in enumerate(cat_features, 1):
plt.subplot(28, 2, i)
 sns.swarmplot(x=feature, y='SalePrice', data=df_train, palette='Set3')
 plt.xlabel('{}'.format(feature), size=25)
 plt.ylabel('SalePrice', size=25, labelpad=15)
 for j in range(2):
if df_train[feature].value_counts().shape[0] > 10:
plt.tick_params(axis='x', labelsize=7)
 else:
plt.tick_params(axis='x', labelsize=20)
 plt.tick_params(axis='y', labelsize=20)
 plt.show()<feature_engineering>
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))
df_all['YearBuiltRemod'] = df_all['YearBuilt'] + df_all['YearRemodAdd']
df_all['TotalSF'] = df_all['TotalBsmtSF'] + df_all['1stFlrSF'] + df_all['2ndFlrSF']
df_all['TotalSquareFootage'] = df_all['BsmtFinSF1'] + df_all['BsmtFinSF2'] + df_all['1stFlrSF'] + df_all['2ndFlrSF']
df_all['TotalBath'] = df_all['FullBath'] +(0.5 * df_all['HalfBath'])+ df_all['BsmtFullBath'] +(0.5 * df_all['BsmtHalfBath'])
 df_all['TotalPorchSF'] = df_all['OpenPorchSF'] + df_all['3SsnPorch'] + df_all['EnclosedPorch'] + df_all['ScreenPorch'] + df_all['WoodDeckSF']
df_all['OverallRating'] = df_all['OverallQual'] + df_all['OverallCond']
df_all['HasPool'] = df_all['PoolArea'].apply(lambda x: 1 if x > 0 else 0)
 df_all['Has2ndFloor'] = df_all['2ndFlrSF'].apply(lambda x: 1 if x > 0 else 0)
 df_all['HasGarage'] = df_all['GarageArea'].apply(lambda x: 1 if x > 0 else 0)
 df_all['HasBsmt'] = df_all['TotalBsmtSF'].apply(lambda x: 1 if x > 0 else 0)
 df_all['HasFireplace'] = df_all['Fireplaces'].apply(lambda x: 1 if x > 0 else 0)
 df_all['NewHouse'] = 0
idx = df_all[df_all['YrSold'] == df_all['YearBuilt']].index
df_all.loc[idx, 'NewHouse'] = 1<drop_column>
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
df_all.drop(df_all[np.logical_and(df_all['OverallQual'] < 5, df_all['SalePrice'] > 200000)].index, inplace=True)
 df_all.drop(df_all[np.logical_and(df_all['GrLivArea'] > 4000, df_all['SalePrice'] < 300000)].index, inplace=True)
 df_all.reset_index(drop=True, inplace=True )<define_variables>
def get_model() :
with strategy.scope() :
enet = efn.EfficientNetB7(
 input_shape=(IMAGE_SIZE[0], IMAGE_SIZE[1], 3),
weights='imagenet',
include_top=False 
)
 enet.trainable = True
model = tf.keras.Sequential([
enet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax', dtype='float32')
 ])
 model.compile(
 optimizer='adam',
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 return model
bsmtcond_map = {'None': 0, 'Po': 1, 'Fa': 2, 'TA': 3, 'Gd': 4}
bsmtexposure_map = {'None': 0, 'No': 1, 'Mn': 2, 'Av': 3, 'Gd': 4}
bsmtfintype_map = {'None': 0, 'Unf': 1, 'LwQ': 2, 'Rec': 3, 'BLQ': 4, 'ALQ': 5, 'GLQ': 6}
bsmtqual_map = {'None': 0, 'Fa': 1, 'TA': 2, 'Gd': 3, 'Ex': 4}
centralair_map = {'Y': 1, 'N': 0}
extercond_map = {'Po': 1, 'Fa': 2, 'TA': 3, 'Gd': 4, 'Ex': 5}
exterqual_map = {'Fa': 1, 'TA': 2, 'Gd': 3, 'Ex': 4}
fireplacequ_map = {'None': 0, 'Po': 1, 'Fa': 2, 'TA': 3, 'Gd': 4, 'Ex': 5}
functional_map = {'Typ': 0, 'Min1': 1, 'Min2': 1, 'Mod': 2, 'Maj1': 3, 'Maj2': 3, 'Sev': 4}
garagecond_map = {'None': 0, 'Po': 1, 'Fa': 2, 'TA': 3, 'Gd': 4, 'Ex': 5}
garagefinish_map = {'None': 0, 'Unf': 1, 'RFn': 2, 'Fin': 3}
garagequal_map = {'None': 0, 'Po': 1, 'Fa': 2, 'TA': 3, 'Gd': 4, 'Ex': 5}
heatingqc_map = {'Po': 1, 'Fa': 2, 'TA': 3, 'Gd': 4, 'Ex': 5}
kitchenqual_map = {'Fa': 1, 'TA': 2, 'Gd': 3, 'Ex': 4}
landslope_map = {'Gtl': 1, 'Mod': 2, 'Sev': 3}
lotshape_map = {'Reg': 0, 'IR1': 1, 'IR2': 2, 'IR3': 3}
paveddrive_map = {'N': 0, 'P': 1, 'Y': 2}
df_all['BsmtCond'] = df_all['BsmtCond'].map(bsmtcond_map)
 df_all['BsmtExposure'] = df_all['BsmtExposure'].map(bsmtexposure_map)
 df_all['BsmtFinType1'] = df_all['BsmtFinType1'].map(bsmtfintype_map)
 df_all['BsmtFinType2'] = df_all['BsmtFinType2'].map(bsmtfintype_map)
 df_all['BsmtQual'] = df_all['BsmtQual'].map(bsmtqual_map)
 df_all['CentralAir'] = df_all['CentralAir'].map(centralair_map)
 df_all['ExterCond'] = df_all['ExterCond'].map(extercond_map)
 df_all['ExterQual'] = df_all['ExterQual'].map(exterqual_map)
 df_all['FireplaceQu'] = df_all['FireplaceQu'].map(fireplacequ_map)
 df_all['Functional'] = df_all['Functional'].map(functional_map)
 df_all['GarageCond'] = df_all['GarageCond'].map(garagecond_map)
 df_all['GarageFinish'] = df_all['GarageFinish'].map(garagefinish_map)
 df_all['GarageQual'] = df_all['GarageQual'].map(garagequal_map)
 df_all['HeatingQC'] = df_all['HeatingQC'].map(heatingqc_map)
 df_all['KitchenQual'] = df_all['KitchenQual'].map(kitchenqual_map)
 df_all['LandSlope'] = df_all['LandSlope'].map(landslope_map)
 df_all['LotShape'] = df_all['LotShape'].map(lotshape_map)
 df_all['PavedDrive'] = df_all['PavedDrive'].map(paveddrive_map)
 df_all.drop(columns=['Street', 'Utilities', 'PoolQC'], inplace=True )<categorify>
def train_cross_validate(test_images_ds, folds=5):
histories = []
probabilities = []
all_labels = []
all_prob = []
all_pred = []
early_stopping = tf.keras.callbacks.EarlyStopping(monitor = 'val_loss', patience = 5)
 kfold = KFold(folds, shuffle=True, random_state=SEED)
 for f,(trn_ind, val_ind)in enumerate(kfold.split(TRAINING_FILENAMES)) :
print()
print('
print('
print('
train_dataset = load_dataset(list(pd.DataFrame({'TRAINING_FILENAMES': TRAINING_FILENAMES} ).loc[trn_ind]['TRAINING_FILENAMES']), labeled = True)
 val_dataset = load_dataset(list(pd.DataFrame({'TRAINING_FILENAMES': TRAINING_FILENAMES} ).loc[val_ind]['TRAINING_FILENAMES']), labeled = True, ordered = True)
 model = get_model()
history = model.fit(
 get_training_dataset(train_dataset, do_aug=True),
steps_per_epoch = STEPS_PER_EPOCH,
epochs = EPOCHS,
callbacks = [lr_callback, early_stopping],
validation_data = get_validation_dataset(val_dataset),
verbose=2 
)
 probabilities.append(model.predict(test_images_ds))
histories.append(history)
 print('Inferring fold',f+1,'validation images...')
 VAL_FILES = list(pd.DataFrame({'TRAINING_FILENAMES': TRAINING_FILENAMES} ).loc[val_ind]['TRAINING_FILENAMES'])
 NUM_VALIDATION_IMAGES = count_data_items(VAL_FILES)
 cmdataset = get_validation_dataset(load_dataset(VAL_FILES, labeled = True, ordered = True))
images_ds = cmdataset.map(lambda image, label: image)
 labels_ds = cmdataset.map(lambda image, label: label ).unbatch()
all_labels.append(next(iter(labels_ds.batch(NUM_VALIDATION_IMAGES)) ).numpy())
 prob = model.predict(images_ds)
 all_prob.append(prob)
 all_pred.append(np.argmax(prob, axis=-1))
cm_correct_labels = np.concatenate(all_labels)
 cm_probabilities = np.concatenate(all_prob)
 cm_predictions = np.concatenate(all_pred)
 return histories, probabilities, cm_correct_labels, cm_predictions
nominal_features = ['Alley', 'BldgType', 'Condition1', 'Condition2', 'Electrical',
'Exterior1st', 'Exterior2nd', 'Fence', 'Foundation', 'GarageType',
'Heating', 'HouseStyle', 'LandContour', 'LotConfig', 'MSSubClass',
'MSZoning', 'MasVnrType', 'MiscFeature', 'MoSold', 'Neighborhood',
'RoofMatl', 'RoofStyle', 'SaleCondition', 'SaleType', 'YrSold']
encoded_features = []
for feature in nominal_features:
encoded_df = pd.get_dummies(df_all[feature])
 n = df_all[feature].nunique()
encoded_df.columns = ['{}_{}'.format(feature, col)for col in encoded_df.columns]
encoded_features.append(encoded_df)
 df_all = pd.concat([df_all, *encoded_features], axis=1)
 df_all.drop(columns=nominal_features, inplace=True )<prepare_x_and_y>
test_ds = get_test_dataset(ordered=True)
 test_images_ds = test_ds.map(lambda image, idnum: image)
 print('Start training %i folds'%FOLDS)
 histories, probabilities, cm_correct_labels, cm_pre = train_cross_validate(test_images_ds, folds = FOLDS)
 print('Computing predictions...')
 probabilities = np.average(probabilities, axis = 0)
 predictions = np.argmax(probabilities, axis=-1)
 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='')
sparse = []
for feature in df_all.columns:
counts = df_all[feature].value_counts()
zeros = counts.iloc[0]
if zeros / len(df_all)* 100 > 99.94:
sparse.append(feature)
 df_all.drop(columns=sparse, inplace=True)
 df_train, df_test = df_all.loc[:1456], df_all.loc[1457:].drop(['SalePrice'], axis=1)
 drop_cols = ['Id', 'Dataset']
X_train = df_train.drop(columns=drop_cols + ['SalePrice'] ).values
y_train = df_train['SalePrice'].values
X_test = df_test.drop(columns=drop_cols ).values
print('X_train shape: {}'.format(X_train.shape))
print('y_train shape: {}'.format(y_train.shape))
print('X_test shape: {}'.format(X_test.shape))<compute_train_metric>
cmat = confusion_matrix(cm_correct_labels, cm_pre, labels=range(len(CLASSES)))
 score = f1_score(cm_correct_labels, cm_pre, labels=range(len(CLASSES)) , average='macro')
 precision = precision_score(cm_correct_labels, cm_pre, labels=range(len(CLASSES)) , average='macro')
 recall = recall_score(cm_correct_labels, cm_pre, 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))
def rmse(y_train, y_pred):
return np.sqrt(mean_squared_error(y_train, y_pred))
def cv_rmse(model, X=X_train, y=y_train):
return np.sqrt(-cross_val_score(model, X, y, scoring='neg_mean_squared_error', cv=kf))
K = 10
kf = KFold(n_splits=K, shuffle=True, random_state=SEED )<choose_model_class>
def get_model_2() :
with strategy.scope() :
dnet = DenseNet201(
 input_shape=(IMAGE_SIZE[0], IMAGE_SIZE[1], 3),
weights='imagenet',
include_top=False 
)
 dnet.trainable = True
model = tf.keras.Sequential([
dnet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax', dtype='float32')
 ])
 model.compile(
 optimizer='adam',
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 return model
ridge = make_pipeline(RobustScaler() , RidgeCV(alphas=np.arange(14.5, 15.6, 0.1), cv=kf))
lasso = make_pipeline(RobustScaler() , LassoCV(alphas=np.arange(0.0001, 0.0009, 0.0001), random_state=SEED, cv=kf))
elasticnet = make_pipeline(RobustScaler() , ElasticNetCV(alphas=np.arange(0.0001, 0.0008, 0.0001), l1_ratio=np.arange(0.8, 1, 0.025), cv=kf))
svr = make_pipeline(RobustScaler() , SVR(C=20, epsilon=0.008, gamma=0.0003))
gbr = GradientBoostingRegressor(n_estimators=3000, learning_rate=0.01, max_depth=4, max_features='sqrt', min_samples_leaf=15, min_samples_split=10, loss='huber', random_state=SEED)
 lgbmr = LGBMRegressor(objective='regression',
num_leaves=4,
learning_rate=0.01,
n_estimators=5000,
max_bin=200,
bagging_fraction=0.75,
bagging_freq=5,
bagging_seed=SEED,
feature_fraction=0.2,
feature_fraction_seed=SEED,
verbose=0)
 xgbr = XGBRegressor(learning_rate=0.01,
n_estimators=3500,
max_depth=3,
gamma=0.001,
subsample=0.7,
colsample_bytree=0.7,
objective='reg:squarederror',
nthread=-1,
seed=SEED,
reg_alpha=0.0001)
 stack = StackingCVRegressor(regressors=(ridge, lasso, elasticnet, svr, gbr, lgbmr, xgbr), meta_regressor=xgbr, use_features_in_secondary=True)
 models = {'RidgeCV': ridge,
'LassoCV': lasso,
'ElasticNetCV': elasticnet,
'SupportVectorRegressor': svr,
'GradientBoostingRegressor': gbr,
'LightGBMRegressor': lgbmr,
'XGBoostRegressor': xgbr,
'StackingCVRegressor': stack}
predictions = {}
scores = {}
for name, model in models.items() :
start = datetime.now()
print('[{}] Running {}'.format(start, name))
model.fit(X_train, y_train)
 predictions[name] = np.expm1(model.predict(X_train))
score = cv_rmse(model, X=X_train, y=y_train)
 scores[name] =(score.mean() , score.std())
 end = datetime.now()
print('[{}] Finished Running {} in {:.2f}s'.format(end, name,(end - start ).total_seconds()))
print('[{}] {} Mean RMSE: {:.6f} / Std: {:.6f}
'.format(datetime.now() , name, scores[name][0], scores[name][1]))<compute_train_metric>
def train_cross_validate_2(test_images_ds, folds=5):
histories = []
probabilities = []
all_labels = []
all_prob = []
all_pred = []
early_stopping = tf.keras.callbacks.EarlyStopping(monitor = 'val_loss', patience = 5)
 kfold = KFold(folds, shuffle=True, random_state=SEED)
 for f,(trn_ind, val_ind)in enumerate(kfold.split(TRAINING_FILENAMES)) :
print()
print('
print('
print('
train_dataset = load_dataset(list(pd.DataFrame({'TRAINING_FILENAMES': TRAINING_FILENAMES} ).loc[trn_ind]['TRAINING_FILENAMES']), labeled = True)
 val_dataset = load_dataset(list(pd.DataFrame({'TRAINING_FILENAMES': TRAINING_FILENAMES} ).loc[val_ind]['TRAINING_FILENAMES']), labeled = True, ordered = True)
 model = get_model()
history = model.fit(
 get_training_dataset(train_dataset, do_aug=True),
steps_per_epoch = STEPS_PER_EPOCH,
epochs = EPOCHS,
callbacks = [lr_callback, early_stopping],
validation_data = get_validation_dataset(val_dataset),
verbose=2 
)
 probabilities.append(model.predict(test_images_ds))
histories.append(history)
 print('Inferring fold',f+1,'validation images...')
 VAL_FILES = list(pd.DataFrame({'TRAINING_FILENAMES': TRAINING_FILENAMES} ).loc[val_ind]['TRAINING_FILENAMES'])
 NUM_VALIDATION_IMAGES = count_data_items(VAL_FILES)
 cmdataset = get_validation_dataset(load_dataset(VAL_FILES, labeled = True, ordered = True))
images_ds = cmdataset.map(lambda image, label: image)
 labels_ds = cmdataset.map(lambda image, label: label ).unbatch()
all_labels.append(next(iter(labels_ds.batch(NUM_VALIDATION_IMAGES)) ).numpy())
 prob = model.predict(images_ds)
 all_prob.append(prob)
 all_pred.append(np.argmax(prob, axis=-1))
cm_correct_labels = np.concatenate(all_labels)
 cm_probabilities = np.concatenate(all_prob)
 cm_predictions = np.concatenate(all_pred)
 return histories, probabilities, cm_correct_labels, cm_predictions
def blend_predict(X):
return(( 0.1 * elasticnet.predict(X)) + 
(0.05 * lasso.predict(X)) + 
(0.1 * ridge.predict(X)) + 
(0.1 * svr.predict(X)) + 
(0.1 * gbr.predict(X)) + 
(0.15 * xgbr.predict(X)) + 
(0.1 * lgbmr.predict(X)) + 
(0.3 * stack.predict(X)))
 blended_score = rmse(y_train, blend_predict(X_train))
print('Blended Prediction RMSE: {}'.format(blended_score))<save_to_csv>
submission_df = pd.DataFrame(columns=['Id', 'SalePrice'])
 submission_df['Id'] = df_test['Id']
submission_df['SalePrice'] = np.expm1(blend_predict(X_test))
submission_df.to_csv('submissions.csv', header=True, index=False)
 submission_df.head(10 )<import_modules>
<load_from_csv><EOS>