Kaggle competition: Petals to the Metal - Flower Classification on TPU
<SOS> metric: macrofscore Kaggle data source: petals-to-the-metal-flower-classification-on-tpu<define_search_space>
print("TF version ", tf.__version__)
 AUTO = tf.data.experimental.AUTOTUNE
parameters_DC = [{'max_depth':[50,100],'min_samples_split': [0.1,0.2,0.5,0.8,0.9]}]
paramaters_RF = [{'max_depth':[2,5,10,15,20,50],'min_samples_split': [0.1,0.2,0.5,0.8],'n_estimators':[100]}]
parameters_XGB =[{"learning_rate": [0.2,0.5,0.8,0.9] ,"max_depth": [1, 3,5, 10], "min_child_weight": [3,5,7,10,20],"gamma": [0.1, 0.2 ,0.4,0.7],'reg_alpha':[0, 0.001, 0.005, 0.01, 0.05],'n_estimator':[100,1000,2000,4000]}]
parameters_GBC =[{"learning_rate": [0.5, 0.25, 0.1, 0.05, 0.01] ,"max_depth": [ 3, 4, 5, 6], "min_samples_leaf" :[50,100,150],"n_estimators" : [16, 32, 64, 128]}]
parameters_ADA =[{'algorithm':['SAMME'],"base_estimator__criterion" : ["gini"],"base_estimator__splitter" : ["best", "random"],"n_estimators": [500,1000],"learning_rate": [ 0.01, 0.1, 1.0]}] 
<train_on_grid>
def seed_everything(seed=0):
np.random.seed(seed)
 tf.random.set_seed(seed)
 os.environ['PYTHONHASHSEED'] = str(seed)
 os.environ['TF_DETERMINISTIC_OPS'] = '1'
seed = 0
seed_everything(seed)
 warnings.filterwarnings("ignore" )
DC = DecisionTreeClassifier()
Grid_DC = GridSearchCV(DC, parameters_DC, cv=4,scoring="accuracy", n_jobs= 4,return_train_score=True, verbose = 1)
 Grid_DC.fit(X_train,y_train)
 DC_best = Grid_DC.best_estimator_
Grid_DC.best_score_<train_on_grid>
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 )
RF = RandomForestClassifier()
Grid_RF = GridSearchCV(RF, paramaters_RF, cv=4,scoring="accuracy", n_jobs= 4,return_train_score=True, verbose = 1)
 Grid_RF.fit(X_train,y_train)
 RF_best = Grid_RF.best_estimator_
Grid_RF.best_score_ 
<train_on_grid>
BATCH_SIZE = 16 * strategy.num_replicas_in_sync
WARMUP_EPOCHS = 3
WARMUP_LEARNING_RATE = 1e-4 * strategy.num_replicas_in_sync
EPOCHS = 20
LEARNING_RATE = 3e-5 * strategy.num_replicas_in_sync
HEIGHT = 512
WIDTH = 512
CHANNELS = 3
N_CLASSES = 104
ES_PATIENCE = 6
RLROP_PATIENCE = 3
DECAY_DROP = 0.3
XGB = XGBClassifier()
Grid_XGB = GridSearchCV(XGB, parameters_XGB, cv=4,scoring="accuracy", n_jobs= 4,return_train_score=True, verbose = 1)
 Grid_XGB.fit(X_train,y_train)
 XGB_best = Grid_XGB.best_estimator_
Grid_XGB.best_score_<train_on_grid>
model_path = 'DenseNet201_%sx%s.h5' %(HEIGHT, WIDTH)
 GCS_PATH = KaggleDatasets().get_gcs_path() + '/tfrecords-jpeg-%sx%s' %(HEIGHT, WIDTH)
 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' )
GBC = GradientBoostingClassifier()
Grid_GBC = GridSearchCV(GBC,parameters_GBC, cv=4, scoring="accuracy", n_jobs= 4, return_train_score=True,verbose = 1)
 Grid_GBC.fit(X_train,y_train)
 GBC_best = Grid_GBC.best_estimator_
Grid_GBC.best_score_<train_on_grid>
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'
]
ADA = AdaBoostClassifier(DC_best)
 Grid_ADA = GridSearchCV(ADA,parameters_ADA, cv=4, scoring="accuracy", n_jobs= 4, return_train_score=True,verbose = 1)
 Grid_ADA.fit(X_train,y_train)
 ADA_best = Grid_ADA.best_estimator_
Grid_ADA.best_score_<define_search_space>
AUTO = tf.data.experimental.AUTOTUNE
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, [HEIGHT, WIDTH, 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_TREC_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
parameters_SVM = {'C': [0.1, 1, 10,50,100], 'gamma' : [0.001, 0.01, 0.1, 1,10]} 
<train_on_grid>
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
SVMC =SVC(probability=True)
 Grid_SVC = GridSearchCV(SVMC, parameters_SVM, scoring="accuracy", return_train_score=True,verbose = 1,cv=2)
 Grid_SVC.fit(X_train, y_train)
 SVM_best = Grid_SVC.best_estimator_
Grid_SVC.best_score_<train_model>
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
voting = VotingClassifier(estimators=[('ADA', ADA_best),('DC', DC_best),('RF', RF_best),('GBC',GBC_best),('XGB',XGB_best),('SVC',SVM_best)],weights=[3,0,0,1,3,3], voting='hard', n_jobs=4)
 voting_result = voting.fit(X_train, y_train )<compute_test_metric>
def get_training_dataset_preview(ordered=True):
dataset = load_dataset(TRAINING_FILENAMES, labeled=True, ordered = ordered)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.cache()
dataset = dataset.prefetch(AUTO)
 return dataset
voting.score(X_test,y_test )<predict_on_test>
def get_validation_dataset(ordered=True):
dataset = load_dataset(VALIDATION_FILENAMES, labeled=True, ordered=ordered)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.cache()
dataset = dataset.prefetch(AUTO)
 return dataset
pred = voting.predict(test )<load_from_csv>
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
test_2 = pd.read_csv('.. /input/test.csv' , header = 0, dtype={'Age': np.float64} )<create_dataframe>
def count_data_items(filenames):
n = [int(re.compile(r"-([0-9]*)\." ).search(filename ).group(1)) for filename in filenames]
return np.sum(n )
result = pd.DataFrame(pred,columns=['Survived'])
 submission13 = result.join(test_2['PassengerId'] ).iloc[:,::-1]<save_to_csv>
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 dataset_to_numpy_util(dataset, N):
dataset = dataset.unbatch().batch(N)
 for images, labels in dataset:
numpy_images = images.numpy()
numpy_labels = labels.numpy()
break;
return numpy_images, numpy_labels
def title_from_label_and_target(label, correct_label):
label = np.argmax(label, axis=-1)
 correct =(label == correct_label)
 return "{} [{}{}{}]".format(CLASSES[label], str(correct), ', shoud be ' if not correct else '',
CLASSES[correct_label] if not correct else ''), correct
def display_one_flower_eval(image, title, subplot, red=False):
plt.subplot(subplot)
 plt.axis('off')
 plt.imshow(image)
 plt.title(title, fontsize=14, color='red' if red else 'black')
 return subplot+1
def display_9_images_with_predictions(images, predictions, labels):
subplot=331
plt.figure(figsize=(13,13))
for i, image in enumerate(images):
title, correct = title_from_label_and_target(predictions[i], labels[i])
 subplot = display_one_flower_eval(image, title, subplot, not correct)
 if i >= 8:
break;
plt.tight_layout()
plt.subplots_adjust(wspace=0.1, hspace=0.1)
 plt.show()
submission13.to_csv('submission13.csv', index=False )<load_from_csv>
AUTO = tf.data.experimental.AUTOTUNE
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, [HEIGHT, WIDTH, 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, seed=seed)
 image = tf.image.random_flip_up_down(image, seed=seed)
 image = tf.image.random_saturation(image, lower=0, upper=2, seed=seed)
 image = tf.image.random_crop(image, size=[int(HEIGHT*.8), int(WIDTH*.8), CHANNELS], seed=seed)
 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_training_dataset_preview(ordered=True):
dataset = load_dataset(TRAINING_FILENAMES, labeled=True, ordered=ordered)
 dataset = dataset.batch(BATCH_SIZE)
 dataset = dataset.cache()
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 )
warnings.filterwarnings("ignore")
 train_file = '.. /input/train.csv'
data = pd.read_csv(train_file, delimiter=',')
 test_file = '.. /input/test.csv'
tdata = pd.read_csv(test_file, delimiter=',')
 train_data = data[['Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Cabin', 'Fare', 'Survived', 'Name', 'Ticket']]
test_data = tdata[['Pclass', 'Sex', 'Age', 'SibSp', 'Parch', 'Cabin', 'Fare', 'Name', 'Ticket']]
def update_name(df):
df['Lname'] = df.Name.apply(lambda x: x.split(',')[0])
 return df
def update_sex(df):
df.Sex = df.Sex.str[0]
return df
def update_cabin(df):
df.Cabin = df.Cabin.fillna('N')
 df.Cabin = df.Cabin.str[0]
return df
def update_fare(df):
df.Fare = df.Fare.fillna(0)
 bins =(-1, 0, 8, 15, 31, 60, 513)
 bin_names = [0, 1, 2, 3, 4, 5]
df.Fare = pd.cut(df.Fare, bins, labels=bin_names)
 return df
def update_age(df):
df.Age = df.Age.fillna(0)
 bins =(-1, 0, 5, 12, 20, 28, 38, 60, 90)
 bin_names = [0, 1, 2, 3, 4, 5, 6, 7]
df.Age = pd.cut(df.Age, bins, labels=bin_names)
 return df
def update_columns(df):
df = update_name(df)
 df = update_sex(df)
 df = update_cabin(df)
 df = update_fare(df)
 df = update_age(df)
 df = df.drop(['Name'], axis=1)
 return df
train_data = update_columns(train_data)
 test_data = update_columns(test_data)
 def encode_features(df):
features = ['Sex', 'Ticket', 'Cabin', 'Lname']
df_combined = df[features]
for feature in features:
le = preprocessing.LabelEncoder()
le = le.fit(df_combined[feature])
 df[feature] = le.transform(df[feature])
 return df
train_data = encode_features(train_data)
 test_data = encode_features(test_data)
 X_all = train_data.drop(['Survived'], axis=1)
 y_all = train_data['Survived']<save_to_csv>
NUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)
 train_dataset = get_training_dataset_preview(ordered=True)
 y_train = next(iter(train_dataset.unbatch().map(lambda image, label: label ).batch(NUM_TRAINING_IMAGES)) ).numpy()
print('Number of training images %d' % NUM_TRAINING_IMAGES )
clf = RandomForestClassifier(n_estimators=100, max_depth=2, random_state=100)
 clf.fit(X_all, y_all)
 test_predictions = clf.predict(test_data)
 preds = {'PassengerId': tdata['PassengerId'], 'Survived': test_predictions}
df = pd.DataFrame(data=preds)
 df.to_csv('preds.csv', sep=',', index=False )<import_modules>
NUM_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES)
 valid_dataset = get_validation_dataset(ordered=True)
 y_valid = next(iter(valid_dataset.unbatch().map(lambda image, label: label ).batch(NUM_VALIDATION_IMAGES)) ).numpy()
print('Number of validation images %d' % NUM_VALIDATION_IMAGES )
from sklearn.linear_model import ElasticNet, Lasso, BayesianRidge, LassoLarsIC
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
from sklearn.kernel_ridge import KernelRidge
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import RobustScaler
from sklearn.base import BaseEstimator, TransformerMixin, RegressorMixin, clone
from sklearn.model_selection import KFold, cross_val_score, train_test_split
from sklearn.metrics import mean_squared_error
import xgboost as xgb
import lightgbm as lgb<load_from_csv>
NUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)
 print('Number of test images %d' % NUM_TEST_IMAGES)
 test_dataset = get_test_dataset(ordered=True )
dataset=pd.read_csv('/kaggle/input/house-prices-advanced-regression-techniques/train.csv' )<load_from_csv>
display_batch_of_images(next(iter(train_dataset.unbatch().batch(20))))
test=pd.read_csv('/kaggle/input/house-prices-advanced-regression-techniques/test.csv' )<count_missing_values>
display_batch_of_images(next(iter(valid_dataset.unbatch().batch(20))))
dataset['GarageYrBlt'].isna().sum()<count_missing_values>
display_batch_of_images(next(iter(test_dataset.unbatch().batch(20))))
dataset['TotRmsAbvGrd'].isna().sum()<count_missing_values>
def create_model(input_shape, N_CLASSES):
base_model = applications.DenseNet201(weights = 'imagenet',
include_top = False,
input_shape = input_shape)
 base_model.trainable = False
model = tf.keras.Sequential([
base_model,
layers.GlobalAveragePooling2D() ,
layers.Dense(N_CLASSES, activation='softmax')
 ])
 return model
dataset['GarageCars'].isna().sum()<drop_column>
with strategy.scope() :
model = create_model(( None, None, CHANNELS), N_CLASSES)
 metric_list = ['sparse_categorical_accuracy']
optimizer = optimizers.Adam(lr=WARMUP_LEARNING_RATE)
 model.compile(optimizer=optimizer,
loss = 'sparse_categorical_crossentropy',
metrics = metric_list)
 model.summary()
del dataset['GarageYrBlt']
del test['GarageYrBlt'] 
<import_modules>
STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE
warmup_history = model.fit(x=get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
validation_data=get_validation_dataset() ,
epochs=WARMUP_EPOCHS,
verbose=2 ).history
import scipy.stats<set_options>
LR_START = 0.00000001
LR_MIN = 0.000001
LR_MAX = LEARNING_RATE
LR_RAMPUP_EPOCHS = 3
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
rng = [i for i in range(EPOCHS)]
y = [lrfn(x)for x in rng]
sns.set(style='whitegrid')
 fig, ax = plt.subplots(figsize =(20, 6))
plt.plot(rng, y)
 print("Learning rate schedule : {:.3g} to {:.3g} to {:.3g}".format(y[0], max(y), y[-1]))
class column_similarity(object):
def __init__(self, data , filter_col):
num_columns=[]
cat_columns=[]
self.data=data.fillna('')
 for col in data.columns:
if self._check_numberic(data[col]):
num_columns.append(col)
 else:
cat_columns.append(col)
 self.cat_columns=np.array(cat_columns)
 self.num_columns=np.array(num_columns)
 self.cat_dist=None
self.num_dist=None
self.dist_reset()
def dist_reset(self):
if len(self.cat_columns)>0:
self.cat_dist=np.zeros(( len(self.cat_columns),len(self.cat_columns)))
 if len(self.num_columns)>0:
self.num_dist=np.zeros(( len(self.num_columns),len(self.num_columns)))
 def _check_numberic(self,data):
return pd.to_numeric(data[data.notna() ], errors='coerce' ).notnull().all()
def filtered_similarity(self,delimiter,threshold_chi,threshold_cor, filt=None):
self.dist_reset()
Cat_dist_frame=pd.DataFrame()
Num_dist_frame=pd.DataFrame()
chi_column1=[]
chi_column2=[]
chi_usecase1=[]
chi_usecase2=[]
chi_score=[]
if self.cat_columns is not None:
for i in range(len(self.cat_columns)) :
for j in range(i,len(self.cat_columns)) :
contingency_table=None
contingency_table=pd.crosstab(self.data[self.cat_columns[i]],self.data[self.cat_columns[j]])
 chi2, p, dof, ex=scipy.stats.chi2_contingency(contingency_table)
 self.cat_dist[i][j]=chi2
self.cat_dist[j][i]=chi2
if self.cat_dist[i][i]>0:
self.cat_dist[i]= self.cat_dist[i]/self.cat_dist[i][i]
selected_elems=list(np.where(self.cat_dist[i]>=threshold_chi)[0])
 if len(selected_elems)>0:
selected_elems.remove(i)
 chi_column1=chi_column1+[self.cat_columns[i]]*len(selected_elems)
 chi_column2=chi_column2+list(self.cat_columns[selected_elems])
 chi_score=chi_score+list(self.cat_dist[i][selected_elems])
 Cat_dist_frame['Column1']=[col.split(delimiter)[1] if delimiter in col else col for col in chi_column1]
Cat_dist_frame['Column2']=[col.split(delimiter)[1] if delimiter in col else col for col in chi_column2]
Cat_dist_frame['Score']=chi_score
return Cat_dist_frame.copy()
def similarity(self,delimiter='_',threshold_chi=0.0,threshold_cor=0.0):
global_Cat_dist_frame=self.filtered_similarity(delimiter,threshold_chi,threshold_cor)
 return global_Cat_dist_frame<compute_test_metric>
for layer in model.layers:
layer.trainable = True
checkpoint = ModelCheckpoint(model_path, monitor = 'val_loss', mode='min', save_best_only=True)
 es = EarlyStopping(monitor = 'val_loss', mode='min', patience=ES_PATIENCE,
restore_best_weights = True, verbose=1)
 lr_callback = LearningRateScheduler(lrfn, verbose=1)
 callback_list = [checkpoint, es, lr_callback]
optimizer = optimizers.Adam(lr=LEARNING_RATE)
 model.compile(optimizer = optimizer,
loss = 'sparse_categorical_crossentropy',
metrics = metric_list)
 model.summary()
sm=column_similarity(dataset,dataset.columns )<compute_test_metric>
history = model.fit(
 x = get_training_dataset() ,
steps_per_epoch = STEPS_PER_EPOCH,
validation_data = get_validation_dataset() ,
callbacks = callback_list,
epochs = EPOCHS,
verbose = 2
).history
similarity=sm.similarity()<drop_column>
x_train = train_dataset.map(lambda image, label : image)
 train_preds = model.predict(x_train)
 train_preds = np.argmax(train_preds, axis=-1)
 print(classification_report(y_train, train_preds, target_names=CLASSES))
<count_values>
x_valid = valid_dataset.map(lambda image, label : image)
 valid_preds = model.predict(x_valid)
 valid_preds = np.argmax(valid_preds, axis=-1)
 print(classification_report(y_valid, valid_preds, target_names=CLASSES))
dataset['GarageCond'].value_counts()<data_type_conversions>
x_train_samp, y_train_samp = dataset_to_numpy_util(train_dataset, 9)
 train_samp_preds = model.predict(x_train_samp, batch_size=9)
 display_9_images_with_predictions(x_train_samp, train_samp_preds, y_train_samp )
dataset['GarageFinish']=dataset['GarageFinish'].fillna('Unf')
 dataset['GarageCond']=dataset['GarageCond'].fillna('TA')
 test['GarageFinish']=dataset['GarageFinish'].fillna('Unf')
 test['GarageCond']=dataset['GarageCond'].fillna('TA' )<filter>
x_valid_samp, y_valid_samp = dataset_to_numpy_util(valid_dataset, 9)
 valid_samp_preds = model.predict(x_valid_samp, batch_size=9)
 display_9_images_with_predictions(x_valid_samp, valid_samp_preds, y_valid_samp )
cols_null=dataset.isna().sum(axis=0)
 cols_null=cols_null[cols_null>0]<sort_values>
x_test = test_dataset.map(lambda image, idnum:image)
 test_preds = model.predict(x_test)
 test_preds = np.argmax(test_preds, axis=-1 )
<drop_column><EOS> 
test_ids_ds = test_dataset.map(lambda image, idnum:idnum ).unbatch()
test_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES)) ).numpy().astype('U')
 submission = pd.DataFrame(test_ids, columns=['id'])
 submission['label'] = test_preds
submission.to_csv('submission.csv', index=False)
 display(submission.head(10))