Kaggle competition: House Prices - Advanced Regression Techniques
lr = 3e-2<train_model>
%matplotlib inline
pd.set_option('display.max_rows', 100)
 pd.set_option('display.max_columns', 500)
learn.fit_one_cycle(1, slice(lr))<save_model>
train = pd.read_csv(".. /input/train.csv")
 test = pd.read_csv(".. /input/test.csv" )
learn.save('stage-1-rn50-test' )<find_best_params>
train = pd.read_csv(".. /input/train.csv")
 test = pd.read_csv(".. /input/test.csv" )
learn.lr_find()<train_model>
train.drop(train[(train['GrLivArea'] > 4000)&(train['SalePrice'] < 200000)].index,inplace=True )
learn.fit_one_cycle(2, slice(3e-5, lr/5))<save_model>
train.dtypes.value_counts()
learn.save('stage-2-rn50-test' )<predict_on_test>
test.dtypes.value_counts()
preds,_ = learn.get_preds(DatasetType.Test )<save_to_csv>
train.drop('Id',axis=1,inplace=True)
 Submission = test[['Id']]
test.drop('Id',axis=1,inplace=True )
pred_labels = [' '.join(list([str(i)for i in np.nonzero(row>0.2)[0]])) for row in np.array(preds)]
df = pd.DataFrame({'Id':test_ids,'Predicted':pred_labels})
 df.to_csv('submission.csv', header=True, index=False )<set_options>
train_missing = pd.DataFrame(train.isna().sum() [train.isna().sum() !=0].sort_values())
 train_missing.columns = ['
train_missing['Percent_Missing'] = train.isna().sum() [train.isna().sum() !=0]/len(train)
 train_missing
%matplotlib inline 
<load_pretrained>
test_missing = pd.DataFrame(test.isna().sum() [test.isna().sum() !=0].sort_values())
 test_missing.columns = ['
test_missing['Percent_Missing'] = test.isna().sum() [test.isna().sum() !=0]/len(test)
 test_missing
try:
shutil.copytree(".. /input/keras-pretrained-models", "/tmp/.keras/models")
 except FileExistsError:
pass<import_modules>
train.drop(['PoolQC','MiscFeature','Alley','Fence','FireplaceQu'],axis=1,inplace=True)
 test.drop(['PoolQC','MiscFeature','Alley','Fence','FireplaceQu'],axis=1,inplace=True )
Conv1D, Conv2D, Conv3D, \
Conv2DTranspose, \
AveragePooling1D, AveragePooling2D, \
MaxPooling1D, MaxPooling2D, MaxPooling3D, \
GlobalAveragePooling1D, \
GlobalMaxPooling1D, GlobalMaxPooling2D, GlobalMaxPooling3D, \
LocallyConnected1D, LocallyConnected2D, \
concatenate, Flatten, Average, Activation, \
RepeatVector, Permute, Reshape, Dot, \
multiply, dot, add, \
PReLU, \
Bidirectional, TimeDistributed, \
SpatialDropout1D, \
BatchNormalization 
<import_modules>
for col in train.columns:
if train[col].dtype == "object":
print("Cardinality of %s variable in Train Data:"%col,train[col].nunique())
 print("Cardinality of %s variable in Test Data:"%col,test[col].nunique())
 print("
" )
from PIL import Image
from zipfile import ZipFile
import h5py
import cv2
from tqdm import tqdm<define_variables>
train.drop(train.index[[691,1182]],inplace=True)
 train['SalePrice'] = np.log(train['SalePrice'] )
src_dir = '.. /input/human-protein-atlas-image-classification'<load_from_csv>
train['MSSubClass'] = train['MSSubClass'].astype(str)
 test['MSSubClass'] = test['MSSubClass'].astype(str )
train_labels = pd.read_csv(os.path.join(src_dir, "train.csv"))
print(train_labels.shape)
 train_labels.head(10 )<load_from_csv>
test['MSZoning'].fillna(test['MSZoning'].value_counts(dropna=False ).index[0],inplace=True )
test_labels = pd.read_csv(os.path.join(src_dir, "sample_submission.csv"))
print(test_labels.shape)
 test_labels.head()<define_variables>
train['LotFrontage'] = train.groupby('Neighborhood')['LotFrontage'].transform(lambda x: x.fillna(x.median()))
test['LotFrontage'] = test.groupby('Neighborhood')['LotFrontage'].transform(lambda x: x.fillna(x.median()))
SH =(256, 256)
 ID_LIST_TRAIN = train_labels.Id.tolist()<data_type_conversions>
train['Street'].value_counts(dropna=False )
def get_arr(Id, test=False):
if test:
arr = get_arr0(Id, test=True)
 else:
arr = get_arr0(Id)
 arr = cv2.resize(arr, SH ).astype('float32')
 return arr<split>
test['Street'].value_counts(dropna=False )
y_cat_train_dic = {}
for icat in range(28):
target = str(icat)
 y_cat_train_5 = np.array([int(target in ee.split())for ee in train_labels.Target.tolist() ])
 y_cat_train_dic[icat] = y_cat_train_5<feature_engineering>
train.drop('Street',axis=1,inplace=True)
 test.drop('Street',axis=1,inplace=True )
up_sample = {}
for k in y_cat_train_dic:
v = y_cat_train_dic[k].sum()
up_sample[k] = np.ceil(( train_labels.shape[0]/28)/ v)
 up_sample<sort_values>
train['Utilities'].value_counts(dropna=False )
up_sample2 = list(zip(*sorted(list(up_sample.items()), key=lambda x: x[0])))[1]
up_sample2 = np.array(up_sample2)
 up_sample2<define_variables>
test['Utilities'].value_counts(dropna=False )
class Seq(object):
sections = None
index = None
def __init__(self, df, extend=False, aug=False, test=False, batch_size=32):
self.shaffle = None
self.extend = extend
self.aug = aug
self.test = test
self.batch_size = batch_size
self.df = df
self.ids = self.df.Id.tolist()
self.reversed = sorted(range(SH[0]), reverse=True)
 self.initialize_it()
self.len = 1
for _ in self.it:
self.len += 1
self.initialize_it()
def initialize_it(self):
if self.shaffle:

 raise NotImplementedError
self.it = iter(range(0, len(self.ids), self.batch_size))
self.idx_next = self.it.__next__()
def __len__(self):
return self.len
def __iter__(self):
return self
def __next__(self):
idx = self.idx_next
self.ids_part = self.ids[idx:(( idx+self.batch_size)if idx+self.batch_size<len(self.ids)else len(self.ids)) ]
res = self.getpart(self.ids_part)
 try:
self.idx_next = self.it.__next__()
except StopIteration:
self.initialize_it()
return res
def __getitem__(self, id0):
arr, tgts = self.get_data(id0)
 cat = self.convert_tgts(tgts)
 return arr, cat
k_list = list(range(4))
def random_transform(self, arr):
k = random.choice(self.k_list)
 arr0 = np.rot90(arr, k=k)
 if random.randint(0,1):
arr0 = arr0[self.reversed,:,:]
if random.randint(0,1):
arr0 = arr0[:,self.reversed,:]
return arr0
def convert_tgts(self, tgts):
try:
cats = to_categorical(tgts, num_classes=28)
 cat = cats.sum(axis=0)
 except TypeError:
cat = np.zeros(( 28,))
return cat
def get_data(self, id0):
arr = get_arr(id0, test=self.test)
 try:
y0 =(self.df.Target[self.df.Id == id0] ).tolist() [0]
y1 = y0.split()
y = [int(ee)for ee in y1]
except AttributeError:
y = None
return arr, y
def getpart(self, ids):
xs = []
ys = []
for id0 in ids:
self.extend_data(id0, xs, ys)
 x = np.stack(xs)
 y = np.stack(ys)
 x_dummy = np.zeros(( len(x), 1))
x_ret = {
'input': x,
'input_cls': y,
}
y_ret = {
'path_fit_cls_img': x_dummy,
'path_cls_img_cls': y,
'path_fit_imgA': x_dummy,
'path_fit_img_cls_img': x_dummy,
'path_cls_cls': y,
'path_img_cls': y,
'path_img_img_cls': y,
'path_fit_cls_img_imgE': x_dummy,
}
return(x_ret, y_ret)
 def split(self, arr, sections=sections):
res0 = np.vsplit(arr, sections)
 res = [np.hsplit(ee, sections)for ee in res0]
res = list(chain.from_iterable(res))
return res
def extend_data(self, id0, xs, ys):
arr0, cat = self[id0]
if self.extend:
mm = up_sample2[cat==1].max()
mm = int(mm)
 for ii in range(mm):
if self.aug:
img = self.random_transform(arr0)
 else:
img = arr0
xs.append(img.flatten())
 ys.append(cat)
 else:
if self.aug:
img = self.random_transform(arr0)
 else:
img = arr0
xs.append(img.flatten())
 ys.append(cat )<import_modules>
train.drop('Utilities',axis=1,inplace=True)
 test.drop('Utilities',axis=1,inplace=True )
from keras import applications<categorify>
train.drop('LandSlope',axis=1,inplace=True)
 test.drop('LandSlope',axis=1,inplace=True )
def make_trainable_false(model_resnet, trainable=False):
layers = model_resnet.layers
for ilayer in layers:
ilayer.trainable = trainable
return<choose_model_class>
train.groupby('Neighborhood')['SalePrice'].agg(['count','min','max','mean'] ).sort_values(by='count' )
def make_model_cnvt(img_dim, img_shape):

 inp = Input(shape=(img_dim,))
oup = Reshape(img_shape )(inp)
 oup = Conv2D(3,
kernel_size=1,
strides=1,
padding='same',
activation='tanh',
kernel_regularizer=regularizers.l2(1e-4))(oup)
 model_cnvt = Model(inp, oup, name='model_cnvt')
 return model_cnvt<choose_model_class>
train.groupby('Condition1')['SalePrice'].agg(['count','min','max','mean'] ).sort_values(by='count' )
def make_model_classifier(input_dim=1536):
inp_cls = Input(( input_dim,))
oup_cls = Dense(28 )(inp_cls)
 oup_cls = Activation('sigmoid' )(oup_cls)
 model_classifier = Model(inp_cls, oup_cls, name='classifier')
 return model_classifier<choose_model_class>
train.drop('Condition2',axis=1,inplace=True)
 test.drop('Condition2',axis=1,inplace=True )
def make_model(img_dim, model_cnvt, model_resnet, model_classifier):

 inp = Input(shape=(img_dim,), name='input')
 oup = model_cnvt(inp)
 oup = model_resnet(oup)
 oup = model_classifier(oup)
 oup = Activation('linear', name='path_cls_cls' )(oup)
 model = Model(inp, oup, name='model')
 model.compile(loss='binary_crossentropy',
optimizer='adam',
metrics=['categorical_accuracy', 'binary_accuracy'])
 return {
'model_classifier': model_classifier,
'model_resnet': model_resnet,
'model_cnvt': model_cnvt,
'model': model
}<train_on_grid>
test['BldgType'].value_counts(dropna=False )
model_cnvt = make_model_cnvt(img_dim, img_shape)
 model_cnvt.summary()<categorify>
train['HouseStyle'].value_counts(dropna=False )
model_cnvt.layers[2].get_weights()<load_pretrained>
test['HouseStyle'].value_counts(dropna=False )
model_cnvt.load_weights('.. /input/keras-inceptionresnetv2-resize139x139-005focal/model_5_cnvt.h5')
 model_cnvt.layers[2].get_weights()<choose_model_class>
train.groupby('OverallQual')['SalePrice'].agg(['count','min','max','mean'] ).sort_values(by='count' )
model_resnet = applications.inception_resnet_v2.InceptionResNetV2(
 include_top=False,
weights='imagenet',
input_tensor=None,
input_shape=list(SH)+ [3],
pooling='avg',
classes=None )<load_pretrained>
model_resnet.layers[1].get_weights() [0][0]<load_pretrained>
train.groupby('OverallCond')['SalePrice'].agg(['count','min','max','mean'] ).sort_values(by='count' )
model_resnet.load_weights('.. /input/keras-inceptionresnetv2-resize139x139-005focal/model_5_resnet.h5')
 model_resnet.layers[1].get_weights() [0][0]<load_pretrained>
train['YearBuilt'].value_counts(dropna=False ).sort_values(ascending=False ).head()
model_classifier.layers[1].get_weights() [0][0]<load_pretrained>
train['YearRemodAdd'].value_counts(dropna=False ).sort_values(ascending=False ).head()
model_classifier.load_weights('.. /input/keras-inceptionresnetv2-resize139x139-005focal/model_5_classifier.h5')
 model_classifier.layers[1].get_weights() [0][0]<categorify>
train['RoofMatl'].value_counts(dropna=False )
THRESHOLD = 0.5
K_epsilon = K.epsilon()
def f1(y_true, y_pred):
y_pred = K.cast(K.greater(K.clip(y_pred, 0, 1), THRESHOLD), K.floatx())
 tp = K.sum(K.cast(y_true*y_pred, 'float'), axis=0)
 tn = K.sum(K.cast(( 1-y_true)*(1-y_pred), 'float'), axis=0)
 fp = K.sum(K.cast(( 1-y_true)*y_pred, 'float'), axis=0)
 fn = K.sum(K.cast(y_true*(1-y_pred), 'float'), axis=0)
 p = tp /(tp + fp + K_epsilon)
 r = tp /(tp + fn + K_epsilon)
 f1 = 2*p*r /(p+r+K_epsilon)
 f1 = tf.where(tf.is_nan(f1), tf.zeros_like(f1), f1)
 return K.mean(f1)
 def f1_loss(y_true, y_pred):
tp = K.sum(K.cast(y_true*y_pred, 'float'), axis=0)
 tn = K.sum(K.cast(( 1-y_true)*(1-y_pred), 'float'), axis=0)
 fp = K.sum(K.cast(( 1-y_true)*y_pred, 'float'), axis=0)
 fn = K.sum(K.cast(y_true*(1-y_pred), 'float'), axis=0)
 p = tp /(tp + fp + K_epsilon)
 r = tp /(tp + fn + K_epsilon)
 f1 = 2*p*r /(p+r+K_epsilon)
 f1 = tf.where(tf.is_nan(f1), tf.zeros_like(f1), f1)
 return 1-K.mean(f1 )<choose_model_class>
test['RoofMatl'].value_counts(dropna=False )
models['model'].compile(loss=f1_loss,
optimizer='adam',
metrics=['categorical_accuracy', 'binary_accuracy', f1] )<train_model>
train['Exterior1st'].value_counts(dropna=False )
seq = Seq(train_labels, extend=False, aug=True, batch_size=32)
 print(len(seq))
hst = models['model'].fit_generator(seq, epochs=3,
steps_per_epoch=len(seq),
callbacks=[] )<predict_on_test>
test['Exterior1st'].value_counts(dropna=False )
seq = Seq(train_labels, extend=False, aug=False, batch_size=32)
 print(len(seq))
xs, ys = next(seq)
 print(xs['input'].shape)
 y_pred = models['model_cnvt'].predict(xs['input'])
 print(y_pred.shape )<prepare_x_and_y>
test['Exterior1st'].fillna(test['Exterior1st'].value_counts(dropna=False ).index[0],inplace=True )
Image.fromarray(np.uint8(( y_pred[0]+1)/2*255))<prepare_output>
train['Exterior1st'].nunique() ,test['Exterior1st'].nunique()
seq_pred = Seq(train_labels, test=False, aug=False, batch_size=128)
 len(seq_pred )<predict_on_test>
train['Exterior2nd'].value_counts(dropna=False )
pred = models['model'].predict_generator(seq_pred, steps=len(seq_pred), verbose=1 )<compute_test_metric>
test['Exterior2nd'].value_counts(dropna=False )
def calc_threshold(pred):
threshold_dic = {}
for idx in tqdm(range(28)) :
m = 0
for ii in range(100):
threshold0 = ii*0.01
f1_val = f1_score(y_cat_train_dic[idx], threshold0<(pred[:,idx]))
if m < f1_val:
threshold_dic[idx] = threshold0+0.005
m = f1_val
return threshold_dic<set_options>
test['Exterior2nd'].fillna(test['Exterior2nd'].value_counts(dropna=False ).index[0],inplace=True )
threshold_dic = calc_threshold(pred)
 threshold_dic<concatenate>
train['Exterior2nd'].nunique() ,test['Exterior2nd'].nunique()
seq_test = Seq(test_labels, test=True, aug=False, batch_size=128)
 seq_test<predict_on_test>
train['MasVnrType'].fillna("None",inplace=True)
 test['MasVnrType'].fillna("None",inplace=True )
pred_test = models['model'].predict_generator(seq_test, steps=len(seq_test), verbose=1 )<save_to_csv>
train['MasVnrArea'].fillna(0,inplace=True)
 test['MasVnrArea'].fillna(0,inplace=True )
def make_test(pred):
test_labels1 = test_labels.copy()
test_labels1['Predicted'] = [str(ee)for ee in np.argmax(pred, axis=1)]
print(test_labels1.head())
 test_labels2 = test_labels1.copy()
for ii in range(test_labels2.shape[0]):
threshold = list(zip(*sorted(list(threshold_dic.items()), key=lambda x:x[0], reverse=False)))[1]
idx = threshold < pred[ii,:]
tgt = test_labels2['Predicted'][ii]
tgt = [tgt] + [str(ee)for ee in np.arange(28)[idx]]
tgt = set(tgt)
 tgt = ' '.join(tgt)
 test_labels2['Predicted'][ii] = tgt
print(test_labels2.head())
 return test_labels1, test_labels2<categorify>
train.groupby('ExterQual')['SalePrice'].agg(['count','min','max','mean'] ).sort_values(by='count' )
test_labels1_1, test_labels1_2 = make_test(pred_test )<save_to_csv>
train.groupby('ExterCond')['SalePrice'].agg(['count','min','max','mean'] ).sort_values(by='count' )
test_labels1_2.to_csv('InceptionResNetV1_2.csv', index=False )<categorify>
train.groupby('Foundation')['SalePrice'].agg(['count','min','max','mean'] ).sort_values(by='count' )
No = 1
models['model_cnvt'].save_weights('model_{}_cnvt.h5'.format(No))
models['model_resnet'].save_weights('model_{}_resnet.h5'.format(No))
models['model_classifier'].save_weights('model_{}_classifier.h5'.format(No))<train_model>
train['BsmtQual'].fillna("No_Basement",inplace=True)
 test['BsmtQual'].fillna("No_Basement",inplace=True )
ls -la<train_model>
train.groupby('BsmtQual')['SalePrice'].agg(['count','min','max','mean'] ).sort_values(by='count' )
seq = Seq(train_labels, extend=False, aug=True, batch_size=32)
 print(len(seq))
hst = models['model'].fit_generator(seq, epochs=2,
steps_per_epoch=len(seq),
callbacks=[] )<predict_on_test>
train['BsmtCond'].value_counts(dropna=False )
seq_pred = Seq(train_labels, test=False, aug=False, batch_size=128)
 len(seq_pred)
 pred = models['model'].predict_generator(seq_pred, steps=len(seq_pred), verbose=1)
 threshold_dic = calc_threshold(pred)
 threshold_dic<predict_on_test>
train['BsmtCond'].fillna("No_Basement",inplace=True)
 test['BsmtCond'].fillna("No_Basement",inplace=True )
seq_test = Seq(test_labels, test=True, aug=False, batch_size=128)
 seq_test
pred_test = models['model'].predict_generator(seq_test, steps=len(seq_test), verbose=1)
 test_labels2_1, test_labels2_2 = make_test(pred_test)
 test_labels2_2.head()<save_to_csv>
train['BsmtExposure'].fillna("No_Basement",inplace=True)
 test['BsmtExposure'].fillna("No_Basement",inplace=True )
test_labels2_2.to_csv('InceptionResNetV2_2.csv', index=False )<categorify>
train['BsmtFinType1'].fillna("No_Basement",inplace=True)
 test['BsmtFinType1'].fillna("No_Basement",inplace=True )
No = 2
models['model_cnvt'].save_weights('model_{}_cnvt.h5'.format(No))
models['model_resnet'].save_weights('model_{}_resnet.h5'.format(No))
models['model_classifier'].save_weights('model_{}_classifier.h5'.format(No))<train_model>
test['BsmtFinSF1'].fillna(0,inplace=True )
seq = Seq(train_labels, aug=True, batch_size=32)
 print(len(seq))
hst = models['model'].fit_generator(seq, epochs=2,
steps_per_epoch=len(seq),
callbacks=[] )<predict_on_test>
train['BsmtFinType2'].fillna("No_Basement",inplace=True)
 test['BsmtFinType2'].fillna("No_Basement",inplace=True )
seq_pred = Seq(train_labels, test=False, aug=False, batch_size=128)
 len(seq_pred)
 pred = models['model'].predict_generator(seq_pred, steps=len(seq_pred), verbose=1)
 threshold_dic = calc_threshold(pred)
 threshold_dic<predict_on_test>
test['BsmtFinSF2'].fillna(0,inplace=True )
seq_test = Seq(test_labels, test=True, aug=False, batch_size=128)
 seq_test
pred_test = models['model'].predict_generator(seq_test, steps=len(seq_test), verbose=1)
 test_labels3_1, test_labels3_2 = make_test(pred_test)
 test_labels3_2.head()<save_to_csv>
test['BsmtUnfSF'].fillna(0,inplace=True )
test_labels3_2.to_csv('InceptionResNetV3_2.csv', index=False )<categorify>
train['TotalBsmtSF'].isna().sum() ,test['TotalBsmtSF'].isna().sum()
No = 3
models['model_cnvt'].save_weights('model_{}_cnvt.h5'.format(No))
models['model_resnet'].save_weights('model_{}_resnet.h5'.format(No))
models['model_classifier'].save_weights('model_{}_classifier.h5'.format(No))<train_model>
test['TotalBsmtSF'].fillna(0,inplace=True )
def lr_schedule(epoch):
lr = 1e-4
print('Learning rate: ', lr)
 return lr<train_model>
train['Heating'].value_counts(dropna=False )
lr_scheduler = LearningRateScheduler(lr_schedule)
 callbacks = [lr_scheduler]
seq = Seq(train_labels, aug=True, batch_size=32)
 print(len(seq))
hst = models['model'].fit_generator(seq, epochs=2,
steps_per_epoch=len(seq),
callbacks=callbacks )<predict_on_test>
test['Heating'].value_counts(dropna=False )
seq_pred = Seq(train_labels, test=False, aug=False, batch_size=128)
 len(seq_pred)
 pred = models['model'].predict_generator(seq_pred, steps=len(seq_pred), verbose=1)
 threshold_dic = calc_threshold(pred)
 threshold_dic<predict_on_test>
train.groupby('Heating')['SalePrice'].agg(['count','min','max','mean'] )
seq_test = Seq(test_labels, test=True, aug=False, batch_size=128)
 seq_test
pred_test = models['model'].predict_generator(seq_test, steps=len(seq_test), verbose=1)
 test_labels4_1, test_labels4_2 = make_test(pred_test)
 test_labels4_2.head()<save_to_csv>
train['HeatingQC'].isna().sum() ,test['HeatingQC'].isna().sum()
test_labels4_2.to_csv('InceptionResNetV4_2.csv', index=False )<categorify>
train.groupby('CentralAir')['SalePrice'].agg(['count','min','max','mean'] ).sort_values(by='count' )
No = 4
models['model_cnvt'].save_weights('model_{}_cnvt.h5'.format(No))
models['model_resnet'].save_weights('model_{}_resnet.h5'.format(No))
models['model_classifier'].save_weights('model_{}_classifier.h5'.format(No))<train_model>
train['Electrical'].value_counts(dropna=False )
def lr_schedule(epoch):
lr = 1e-4
print('Learning rate: ', lr)
 return lr<train_model>
test['Electrical'].value_counts(dropna=False )
lr_scheduler = LearningRateScheduler(lr_schedule)
 callbacks = [lr_scheduler]
seq = Seq(train_labels, aug=True, batch_size=32)
 print(len(seq))
hst = models['model'].fit_generator(seq, epochs=2,
steps_per_epoch=len(seq),
callbacks=callbacks )<predict_on_test>
train['Electrical'].fillna(train['Electrical'].value_counts(dropna=False ).index[0],inplace=True )
seq_pred = Seq(train_labels, test=False, aug=False, batch_size=128)
 len(seq_pred)
 pred = models['model'].predict_generator(seq_pred, steps=len(seq_pred), verbose=1)
 threshold_dic = calc_threshold(pred)
 threshold_dic<predict_on_test>
train.drop(train.index[1300],inplace=True )
seq_test = Seq(test_labels, test=True, aug=False, batch_size=128)
 seq_test
pred_test = models['model'].predict_generator(seq_test, steps=len(seq_test), verbose=1)
 test_labels5_1, test_labels5_2 = make_test(pred_test)
 test_labels5_2.head()<save_to_csv>
len(train[train['2ndFlrSF'] == 0])/len(train )
test_labels5_2.to_csv('InceptionResNetV5_2.csv', index=False )<categorify>
train.drop('LowQualFinSF',axis=1,inplace=True)
 test.drop('LowQualFinSF',axis=1,inplace=True )
No = 5
models['model_cnvt'].save_weights('model_{}_cnvt.h5'.format(No))
models['model_resnet'].save_weights('model_{}_resnet.h5'.format(No))
models['model_classifier'].save_weights('model_{}_classifier.h5'.format(No))<train_model>
train['GrLivArea'].isna().sum() ,test['GrLivArea'].isna().sum()
ls -la<predict_on_test>
train.groupby('BsmtFullBath')['SalePrice'].agg(['count','min','max','mean'] ).sort_values(by='count' )
seq = Seq(train_labels, extend=False, aug=False, batch_size=32)
 print(len(seq))
xs, ys = next(seq)
 print(xs['input'].shape)
 y_pred = models['model_cnvt'].predict(xs['input'])
 print(y_pred.shape )<prepare_x_and_y>
test['BsmtFullBath'].fillna(0,inplace=True )
Image.fromarray(np.uint8(( y_pred[0]+1)/2*255))<import_modules>
test['BsmtHalfBath'].fillna(0,inplace=True )
print("Tensorflow version " + tf.__version__)
 AUTO = tf.data.experimental.AUTOTUNE<set_options>
train['HalfBath'].value_counts(dropna=False )
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 )<define_variables>
test['HalfBath'].value_counts(dropna=False )
GCS_DS_PATH = KaggleDatasets().get_gcs_path('flower-classification')
 PATH2 = KaggleDatasets().get_gcs_path('tf-flower-photo-tfrec' )<define_variables>
train.groupby('KitchenQual')['SalePrice'].agg(['count','min','max','mean'] ).sort_values(by='count' )
IMAGE_SIZE = [224, 224]
EPOCHS = 12
BATCH_SIZE =16 * strategy.num_replicas_in_sync
img_size=224
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')
 TRAINING_FILENAMES += tf.io.gfile.glob(PATH2 + '/imagenet/tfrecords-jpeg-224x224/*.tfrec')
 TRAINING_FILENAMES += tf.io.gfile.glob(PATH2 + '/inaturalist_1/tfrecords-jpeg-224x224/*.tfrec')
 TRAINING_FILENAMES += tf.io.gfile.glob(PATH2 + '/openimage/tfrecords-jpeg-224x224/*.tfrec')
 TRAINING_FILENAMES += tf.io.gfile.glob(PATH2 + '/oxford_102/tfrecords-jpeg-224x224/*.tfrec')
 TRAINING_FILENAMES += tf.io.gfile.glob(PATH2 + '/tf_flowers/tfrecords-jpeg-224x224/*.tfrec')
 VALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec')
 TEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec')
 TRAINING_FILENAMES=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']<categorify>
test['KitchenQual'].fillna(test['KitchenQual'].value_counts(dropna=False ).index[0],inplace=True )
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>
train['TotRmsAbvGrd'].value_counts(dropna=False ).sort_index()
def random_blockout(img, sl=0.1, sh=0.2, rl=0.4):
p=random.random()
if p>=0.25:
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)
 else:
return tf.cast(img, img.dtype )<categorify>
train['Functional'].value_counts(dropna=False ).sort_values()
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= random_blockout(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))<train_model>
test['Functional'].fillna(test['Functional'].value_counts(dropna=False ).index[0],inplace=True )
print("Training data shapes:")
 for image, label in get_training_dataset().take(3):
print(image.numpy().shape, label.numpy().shape)
 print("Training data label examples:", label.numpy())
 print("Validation data shapes:")
 for image, label in get_validation_dataset().take(3):
print(image.numpy().shape, label.numpy().shape)
 print("Validation data label examples:", label.numpy())
 print("Test data shapes:")
 for image, idnum in get_test_dataset().take(3):
print(image.numpy().shape, idnum.numpy().shape)
 print("Test data IDs:", idnum.numpy().astype('U'))<train_model>
train['Fireplaces'].value_counts(dropna=False ).sort_index()
training_dataset = get_training_dataset()
training_dataset = training_dataset.unbatch().batch(20)
 training_dataset = training_dataset.shuffle(20)
 train_batch = iter(training_dataset )<define_variables>
train.groupby('Fireplaces')['SalePrice'].agg(['count','min','max','mean'] ).sort_values(by='count' )
display_batch_of_images(next(train_batch))<define_variables>
train['GarageType'].isna().sum() ,test['GarageType'].isna().sum()
test_dataset = get_test_dataset()
test_dataset = test_dataset.unbatch().batch(20)
 test_batch = iter(test_dataset )<define_variables>
train['GarageType'].fillna("No_Garage",inplace=True)
 test['GarageType'].fillna("No_Garage",inplace=True )
display_batch_of_images(next(test_batch))<choose_model_class>
train.groupby('GarageType')['SalePrice'].agg(['count','min','max','mean'] ).sort_values(by='count' )
def lrfn(epoch):
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
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=1 )<import_modules>
train['GarageYrBlt'].isna().sum() ,test['GarageYrBlt'].isna().sum()
<install_modules>
train['GarageYrBlt'].fillna(0,inplace=True)
 test['GarageYrBlt'].fillna(0,inplace=True )
!pip install -U efficientnet 
<choose_model_class>
train['GarageYrBlt'].value_counts().sort_values(ascending=False ).head()
with strategy.scope() :
pretrained_model = efn.EfficientNetB6(weights='noisy-student', include_top=False ,input_shape=[*IMAGE_SIZE, 3])
 pretrained_model.trainable = True
model = tf.keras.Sequential([
pretrained_model,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model.compile(
 optimizer=tf.keras.optimizers.Adam() ,
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 model.summary()<train_model>
test.loc[1132,'GarageYrBlt'] = 2007
history = model.fit(get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
epochs=40,
validation_data=None,
callbacks = [lr_callback]
)<load_pretrained>
train['GarageFinish'].isna().sum() ,test['GarageFinish'].isna().sum()
model.save_weights('enetb6.h5' )<choose_model_class>
train['GarageFinish'].fillna("No_Garage",inplace=True)
 test['GarageFinish'].fillna("No_Garage",inplace=True )
<train_model>
train.groupby('GarageFinish')['SalePrice'].agg(['count','min','max','mean'] ).sort_values(by='count' )
<choose_model_class>
train['GarageCars'].isna().sum() ,test['GarageCars'].isna().sum()
<install_modules>
test['GarageCars'].fillna(0,inplace=True )
!pip install -q efficientnet<import_modules>
train['GarageArea'].isna().sum() ,test['GarageArea'].isna().sum()
print("Tensorflow version " + tf.__version__)
<set_options>
test['GarageArea'].fillna(0,inplace=True )
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 = 20
BATCH_SIZE = 16 * strategy.num_replicas_in_sync<init_hyperparams>
train['GarageQual'].isna().sum() ,test['GarageQual'].isna().sum()
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
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]))<define_variables>
train['GarageQual'].fillna("No_Garage",inplace=True)
 test['GarageQual'].fillna("No_Garage",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 = True
if SKIP_VALIDATION:
TRAINING_FILENAMES = TRAINING_FILENAMES + VALIDATION_FILENAMES
VALIDATION_MISMATCHES_IDS = []<define_variables>
train['GarageQual'].value_counts().sort_values(ascending=False )
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>
test['GarageQual'].value_counts().sort_values(ascending=False )
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.'] )<normalization>
train.groupby('GarageQual')['SalePrice'].agg(['count','min','max','mean'] ).sort_values(by='count' )
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))
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>
train['GarageCond'].isna().sum() ,test['GarageCond'].isna().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)
 return image, label
def get_training_dataset() :
dataset = load_dataset(TRAINING_FILENAMES, labeled=True)
 dataset = dataset.filter(lambda image, label, idnum: tf.reduce_sum(tf.cast(idnum == VALIDATION_MISMATCHES_IDS, tf.int32)) ==0)
 dataset = dataset.map(lambda image, label, idnum: [image, label])
 dataset = dataset.map(transform, num_parallel_calls=AUTO)
 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.filter(lambda image, label, idnum: tf.reduce_sum(tf.cast(idnum == VALIDATION_MISMATCHES_IDS, tf.int32)) ==0)
 dataset = dataset.map(lambda image, label, idnum: [image, label])
 dataset = dataset.batch(BATCH_SIZE)
 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):
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):
dataset = load_dataset(filenames,labeled = False)
 dataset = dataset.map(lambda image, idnum: idnum)
 dataset = dataset.filter(lambda idnum: tf.reduce_sum(tf.cast(idnum == VALIDATION_MISMATCHES_IDS, tf.int32)) ==0)
 uids = next(iter(dataset.batch(21000)) ).numpy().astype('U')
 return len(np.unique(uids))
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
print('Dataset: {} training images, {} validation images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))<create_dataframe>
train['GarageCond'].fillna("No_Garage",inplace=True)
 test['GarageCond'].fillna("No_Garage",inplace=True )
if len(VALIDATION_MISMATCHES_IDS)>0:
dataset = load_dataset(TRAINING_FILENAMES,labeled = True)
 dataset = dataset.filter(lambda image, label, idnum: tf.reduce_sum(tf.cast(idnum == VALIDATION_MISMATCHES_IDS, tf.int32)) >0)
 dataset = dataset.map(lambda image, label, idnum: [image, label])
 imgs = next(iter(dataset.batch(len(VALIDATION_MISMATCHES_IDS))))
display_batch_of_images(imgs )<choose_model_class>
train['PavedDrive'].isna().sum() ,test['PavedDrive'].isna().sum()
with strategy.scope() :
enet = efn.EfficientNetB7(
 input_shape=(512, 512, 3),
weights='noisy-student',
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>
train['PavedDrive'].value_counts()
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()
)<choose_model_class>
test['PavedDrive'].value_counts()
with strategy.scope() :
rnet = DenseNet201(
 input_shape=(512, 512, 3),
weights='imagenet',
include_top=False 
)
 model2 = tf.keras.Sequential([
rnet,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model2.compile(
 optimizer=tf.keras.optimizers.Adam(lr=0.0001),
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 model2.summary()<train_model>
train['WoodDeckSF'].isna().sum() ,test['WoodDeckSF'].isna().sum()
history2 = model2.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()
)<predict_on_test>
train['OpenPorchSF'].isna().sum() ,test['OpenPorchSF'].isna().sum()
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.51<define_variables>
train['EnclosedPorch'].isna().sum() ,test['EnclosedPorch'].isna().sum()
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 = 2 )<compute_test_metric>
train['3SsnPorch'].isna().sum() ,test['3SsnPorch'].isna().sum()
if not SKIP_VALIDATION:
cmat = confusion_matrix(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)))
 score = f1_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
 precision = precision_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
 recall = recall_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
 display_confusion_matrix(cmat, score, precision, recall)
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score, precision, recall))<save_to_csv>
train['ScreenPorch'].isna().sum() ,test['ScreenPorch'].isna().sum()
test_ds = get_test_dataset(ordered=True)
 print('Computing predictions...')
 test_images_ds = test_ds.map(lambda image, idnum: image)
 probabilities = best_alpha*model.predict(test_images_ds)+(1-best_alpha)*model2.predict(test_images_ds)
 predictions = np.argmax(probabilities, axis=-1)
 print(predictions)
 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='' )<install_modules>
train['PoolArea'].isna().sum() ,test['PoolArea'].isna().sum()
!pip install -q -U --pre efficientnet<set_options>
train['MoSold'].isna().sum() ,test['MoSold'].isna().sum()
print("Tensorflow version " + tf.__version__)
 AUTO = tf.data.experimental.AUTOTUNE<set_options>
train.groupby('MoSold')['SalePrice'].agg(['count','min','max','mean'] ).sort_index()
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)
 IMAGE_SIZE = [224, 224]
else:
strategy = tf.distribute.get_strategy()
IMAGE_SIZE = [224, 224]
print("REPLICAS: ", strategy.num_replicas_in_sync )<define_variables>
train['MoSold'] = train['MoSold'].astype(str)
 test['MoSold'] = test['MoSold'].astype(str )
GCS_DS_PATH = KaggleDatasets().get_gcs_path()<define_variables>
train['YrSold'].isna().sum() ,test['YrSold'].isna().sum()
IMAGE_SIZE = [512, 512]
EPOCHS = 40
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', GCS_PATH + '/val/?[8-9]-*.tfrec'])
 VALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/val/?[0-7]-*.tfrec')
 TEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec')
 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['YrSold'].value_counts().sort_values(ascending=False ).head(10 )
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>
train.groupby(['MoSold','YrSold'])['SalePrice'].count().sort_values(ascending=False )
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_saturation(image, 0.8, 1)
 randint = tf.random.uniform([1], minval=0, maxval=3, dtype=tf.int32, seed=None, name=None)[0]
image = tf.image.rot90(image,randint)
 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))<train_model>
train['YrSold'] = train['YrSold'].astype(str)
 test['YrSold'] = test['YrSold'].astype(str )
print("Training data shapes:")
 for image, label in get_training_dataset().take(3):
print(image.numpy().shape, label.numpy().shape)
 print("Training data label examples:", label.numpy())
 print("Validation data shapes:")
 for image, label in get_validation_dataset().take(3):
print(image.numpy().shape, label.numpy().shape)
 print("Validation data label examples:", label.numpy())
 print("Test data shapes:")
 for image, idnum in get_test_dataset().take(3):
print(image.numpy().shape, idnum.numpy().shape)
 print("Test data IDs:", idnum.numpy().astype('U'))<train_model>
train['SaleType'].isna().sum() ,test['SaleType'].isna().sum()
training_dataset = get_training_dataset()
training_dataset = training_dataset.unbatch().batch(20)
 train_batch = iter(training_dataset )<define_variables>
test['SaleType'].fillna(test['SaleType'].value_counts().index[0],inplace=True )
display_batch_of_images(next(train_batch))<define_variables>
train['SaleCondition'].isna().sum() ,test['SaleCondition'].isna().sum()
test_dataset = get_test_dataset()
test_dataset = test_dataset.unbatch().batch(20)
 test_batch = iter(test_dataset )<define_variables>
train['Total_Bathrooms'] =(train['FullBath'] +(0.5*train['HalfBath'])+ train['BsmtFullBath'] +(0.5*train['BsmtHalfBath']))
train['Total_porch_sf'] =(train['OpenPorchSF'] + train['3SsnPorch'] + train['EnclosedPorch'] + train['ScreenPorch'] + train['WoodDeckSF'])
 test['Total_Bathrooms'] =(test['FullBath'] +(0.5*test['HalfBath'])+ test['BsmtFullBath'] +(0.5*test['BsmtHalfBath']))
test['Total_porch_sf'] =(test['OpenPorchSF'] + test['3SsnPorch'] + test['EnclosedPorch'] + test['ScreenPorch'] + test['WoodDeckSF'] )
display_batch_of_images(next(test_batch))<choose_model_class>
train.isna().sum() [train.isna().sum() !=0]
def get_model_xception() :
with strategy.scope() :
pretrained_model = tf.keras.applications.Xception(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=tf.keras.optimizers.Nadam(learning_rate=0.0008, beta_1=0.9, beta_2=0.999),
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 return model<choose_model_class>
test.isna().sum() [test.isna().sum() !=0]
def get_model_inception_resnet_v2() :
with strategy.scope() :
pretrained_model = tf.keras.applications.InceptionResNetV2(weights='imagenet', include_top=False ,input_shape=[*IMAGE_SIZE, 3])
 pretrained_model.trainable = True

 model = tf.keras.Sequential([
pretrained_model,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model.compile(
 optimizer=tf.keras.optimizers.Nadam(learning_rate=0.0005, beta_1=0.9, beta_2=0.999),
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 return model<choose_model_class>
for col in train.columns:
if train[col].dtype == "object":
print("Cardinality of %s variable in Training Data:"%col,train[col].nunique())
 print("Cardinality of %s variable in Testing Data:"%col,test[col].nunique())
 print("
" )
def get_model_densenet() :
with strategy.scope() :
pretrained_model = tf.keras.applications.DenseNet201(weights='imagenet', include_top=False ,input_shape=[*IMAGE_SIZE, 3])
 pretrained_model.trainable = True
model = tf.keras.Sequential([
pretrained_model,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model.compile(
 optimizer=tf.keras.optimizers.Nadam(learning_rate=0.001, beta_1=0.9, beta_2=0.999),
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 return model<choose_model_class>
train.corr() ['SalePrice'].sort_values(ascending=False )
def get_model_efficientnet_b7() :
with strategy.scope() :
pretrained_model = efn.EfficientNetB7(weights='noisy-student', include_top=False, input_shape=[*IMAGE_SIZE, 3])
 pretrained_model.trainable = True
model = tf.keras.Sequential([
pretrained_model,
tf.keras.layers.GlobalAveragePooling2D() ,
tf.keras.layers.Dense(len(CLASSES), activation='softmax')
 ])
 model.compile(
 optimizer=tf.keras.optimizers.Nadam(learning_rate=0.001, beta_1=0.9, beta_2=0.999),
loss = 'sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy'] 
)
 return model<choose_model_class>
train.drop(['GarageCars','TotRmsAbvGrd','1stFlrSF'],axis=1,inplace=True)
 test.drop(['GarageCars','TotRmsAbvGrd','1stFlrSF'],axis=1,inplace=True )
reduce_lr = tf.keras.callbacks.ReduceLROnPlateau(
 monitor='val_loss', patience=3, verbose=1, factor=0.3, min_lr=1e-06
)<choose_model_class>
train.corr() ['SalePrice'].sort_values(ascending=False )
es = tf.keras.callbacks.EarlyStopping(
 monitor='val_loss', min_delta=0, patience=10, verbose=1, mode='auto',
baseline=None, restore_best_weights=True
)<find_best_params>
trn = train.copy()
tst = test.copy()
histories = []
models = []
gc.collect()
models.append(get_model_efficientnet_b7())
 models.append(get_model_xception())
 models.append(get_model_inception_resnet_v2())
 models.append(get_model_inception_resnet_v2())
<train_model>
y = train['SalePrice']
train.drop('SalePrice',inplace=True,axis=1)
 len_train = len(train)
 full_data = pd.concat([train,test],axis=0 ).reset_index(drop=True)
 full_data = pd.get_dummies(full_data)
 train = full_data[:len_train]
test = full_data[len_train:]
for m in models:
h = m.fit(get_training_dataset() , steps_per_epoch=STEPS_PER_EPOCH, epochs=EPOCHS, validation_data=get_validation_dataset() ,callbacks=[reduce_lr,es])
 histories.append(h)
 gc.collect()<predict_on_test>
overfit = []
for col in train.columns:
counts = train[col].value_counts()
zeros = counts.iloc[0]
if zeros / len(train)* 100 >99:
overfit.append(col)
 print(len(overfit))
def ens_predict(models,images):
return np.average([models[i].predict(images)for i in range(len(models)) ], axis = 0 )<predict_on_test>
train.drop(overfit,axis=1,inplace=True)
 test.drop(overfit,axis=1,inplace=True )
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()
for m in models:
cm_probabilities = m.predict(images_ds)
 cm_predictions = np.argmax(cm_probabilities, axis=-1)
 print("Correct labels: ", cm_correct_labels.shape, cm_correct_labels)
 print("Predicted labels: ", cm_predictions.shape, cm_predictions)
 cm_probabilities = ens_predict(models,images_ds)
 cm_predictions = np.argmax(cm_probabilities, axis=-1)
 print("Correct labels: ", cm_correct_labels.shape, cm_correct_labels)
 print("Predicted labels: ", cm_predictions.shape, cm_predictions )<compute_train_metric>
X = train
cmat = confusion_matrix(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)))
 score = f1_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
 precision = precision_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
 recall = recall_score(cm_correct_labels, cm_predictions, labels=range(len(CLASSES)) , average='macro')
 cmat =(cmat.T / cmat.sum(axis=1)).T
display_confusion_matrix(cmat, score, precision, recall)
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score, precision, recall))<save_to_csv>
X_Train,X_Test,y_Train,y_Test = train_test_split(X,y,test_size=0.25)
 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 )
test_ds = get_test_dataset(ordered=True)
 print('Computing predictions...')
 test_images_ds = test_ds.map(lambda image, idnum: image)
 probabilities = ens_predict(models,test_images_ds)
 predictions = np.argmax(probabilities, axis=-1)
 print(predictions)
 print('Generating submission.csv file...')
 test_ids_ds = test_ds.map(lambda image, idnum: idnum ).unbatch()
test_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES)) ).numpy().astype('U')
 np.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')
 !head submission.csv<define_variables>
lr = LinearRegression()
lr.fit(X_Train,y_Train)
 print("Linear Regression, Training Set RMSE:",rmse(y_Train,lr.predict(X_Train)))
 print("Linear Regression,Training R Squared:",calc_r2(lr,y_Train,X_Train))
print("
Linear Regression,Testing Set RMSE:",rmse(y_Test,lr.predict(X_Test)))
 print("Linear Regression,Testing R Squared:",calc_r2(lr,y_Test,X_Test))
print("
Linear Regression,Cross Validation Score:",cv_score(lr))
dataset = get_validation_dataset()
dataset = dataset.unbatch().batch(20)
 batch = iter(dataset )<predict_on_test>
lasso = Lasso(alpha=0.001,max_iter=5000)
 lasso.fit(X_Train,y_Train)
 print("Lasso Regression, Training Set RMSE:",rmse(y_Train,lasso.predict(X_Train)))
 print("Lasso Regression,Training R Squared:",calc_r2(lasso,y_Train,X_Train))
print("
Lasso Regression,Testing Set RMSE:",rmse(y_Test,lasso.predict(X_Test)))
 print("Lasso Regression,Testing R Squared:",calc_r2(lasso,y_Test,X_Test))
print("
Lasso Regression,Cross Validation Score:",cv_score(lasso))
images, labels = next(batch)
 probabilities = ens_predict(models,images)
 predictions = np.argmax(probabilities, axis=-1)
 display_batch_of_images(( images, labels), predictions )<set_options>
coeffs = pd.DataFrame(list(zip(X.columns, lasso.coef_)) , columns=['Predictors', 'Coefficients'])
 coeffs.sort_values(by='Coefficients',ascending=False )
np.random.seed(0)
 sns.set(style='white', context='notebook', palette='deep')
 for dirname, _, filenames in os.walk('/kaggle/input'):
for filename in filenames:
print(os.path.join(dirname, filename)) 
<load_from_csv>
scores = []
alpha = [0.001,0.005,0.01,0.05,0.1,0.5,1,2,5,10]
for i in alpha:
las = Lasso(alpha=i,max_iter=10000)
 las.fit(X_Train,y_Train)
 scores.append(rmse(y_Test,las.predict(X_Test)))
 print("Lasso Scores with Different Alpha Values
",scores )
train = pd.read_csv(".. /input/digit-recognizer/train.csv")
 test = pd.read_csv(".. /input/digit-recognizer/test.csv" )<split>
ridge = Ridge()
ridge.fit(X_Train,y_Train)
 print("Ridge Regression,Training Set RMSE:",rmse(y_Train,ridge.predict(X_Train)))
 print("Ridge Regression,Training R Squared:",calc_r2(ridge,y_Train,X_Train))
print("
Ridge Regression,Testing Set RMSE:",rmse(y_Test,ridge.predict(X_Test)))
 print("Ridge Regression,Testing R Squared:",calc_r2(ridge,y_Test,X_Test))
print("
Ridge Regression,Cross Validation Score:",cv_score(ridge))
tmp = train["label"]
X_train, X_test, y_train, y_test = train_test_split(train.drop(labels=["label"],axis=1),
tmp,
test_size = 0.01,
random_state = 0 )<categorify>
scores = []
alpha = [0.001,0.005,0.01,0.05,0.1,0.5,1,2,5,10]
for i in alpha:
ridge = Ridge(alpha=i)
 ridge.fit(X_Train,y_Train)
 scores.append(rmse(y_Test,ridge.predict(X_Test)))
 print("Ridge Scores with Different Alpha Values
",scores )
y_train = to_categorical(y_train, num_classes = 10)
 y_test = to_categorical(y_test, num_classes = 10)
 plt.imshow(X_train[0][:,:,0],cmap='gray' )<train_model>
en = ElasticNet(max_iter=5000)
 params = {"alpha":[0.0001,0.0002,0.001,0.005,0.01,0.05,0.1,0.5,1,2,5,10],
"l1_ratio":[0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1]}
grid = GridSearchCV(estimator=en,param_grid=params,cv=5,n_jobs=-1,scoring='neg_mean_squared_error')
 grid.fit(X,y )
epochs = 30
batchsize = 16
steps_per_epoch = X_train.shape[0] / batchsize
learning_rate_reduction = ReduceLROnPlateau(monitor='val_accuracy',
patience=3,
factor=0.5,
min_lr=0.00001)
 dataset = ImageDataGenerator()
dataset.fit(X_train )<choose_model_class>
grid.best_estimator_,grid.best_params_,grid.best_score_
<choose_model_class>
en = grid.best_estimator_
en.fit(X_Train,y_Train)
 print("Elastic Net Regression,Training Set RMSE:",rmse(y_Train,en.predict(X_Train)))
 print("Elastic Net Regression,Training R Squared:",calc_r2(en,y_Train,X_Train))
print("
Elastic Net Regression,Testing Set RMSE:",rmse(y_Test,en.predict(X_Test)))
 print("Elastic Net Regression,Testing R Squared:",calc_r2(en,y_Test,X_Test))
print("
Elastic Net Regression,Cross Validation Score:",cv_score(en))
<choose_model_class><EOS> 
en_submission = np.expm1(en.predict(test))
lasso_submission = np.expm1(lasso.predict(test))
ridge_submission = np.expm1(ridge.predict(test))
average =(en_submission+lasso_submission+ridge_submission)/3
Submission['SalePrice'] = average
Submission.to_csv("Stacked7.csv",index=None )