Kaggle competition: House Prices - Advanced Regression Techniques
<SOS> metric: rmsle Kaggle data source: house-prices-advanced-regression-techniques<choose_model_class>
pd.options.display.max_columns = 100
pd.options.display.max_rows = 100
set_matplotlib_formats('retina')
 warnings.filterwarnings('ignore')
 %matplotlib inline
def create_model(n_out):
input_shape=(WINDOW_SIZE,WINDOW_SIZE, IMAGE_CHANNELS)
 input_tensor = Input(shape=(WINDOW_SIZE, WINDOW_SIZE, IMAGE_CHANNELS))
base_model = InceptionV3(include_top=False,
weights='imagenet',
input_shape=input_shape 
)
 bn = BatchNormalization()(input_tensor)
 x = base_model(bn)
 x = Conv2D(32, kernel_size=(1,1), activation='relu' )(x)
 x = Flatten()(x)
 x = Dropout(0.5 )(x)
 x = Dense(1024, activation='relu' )(x)
 x = Dropout(0.5 )(x)
 output = Dense(n_out, activation='sigmoid' )(x)
 model = Model(input_tensor, output)
 return model
model = create_model(n_out=NUM_CLASSES )<choose_model_class>
train_data = pd.read_csv(".. /input/house-prices-advanced-regression-techniques/train.csv")
 test_data = pd.read_csv(".. /input/house-prices-advanced-regression-techniques/test.csv" )
epochs = 10; batch_size = 16
checkpoint = ModelCheckpoint('.. /working/InceptionV3.h5', monitor='val_loss', verbose=1,
save_best_only=True, mode='min', save_weights_only = True)
 reduceLROnPlat = ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=3,
verbose=1, mode='auto', epsilon=0.0001)
 early = EarlyStopping(monitor="val_loss",
mode="min",
patience=6)
 callbacks_list = [checkpoint, early, reduceLROnPlat]
indexes = np.arange(train_dataset_info.shape[0])
 np.random.shuffle(indexes)
 train_indexes, valid_indexes = train_test_split(indexes, test_size=0.15, random_state=8)
 train_generator = data_generator.get_dataset(
 train_dataset_info[train_indexes], batch_size,(IMAGE_SIZE,IMAGE_SIZE,IMAGE_CHANNELS), augument=True)
 validation_generator = data_generator.get_dataset(
 train_dataset_info[valid_indexes], 32,(IMAGE_SIZE,IMAGE_SIZE,IMAGE_CHANNELS), augument=False)
<import_modules>
sales_correlation = correlation_matrix_train["SalePrice"].sort_values()
sales_correlation
print(keras.__version__)
 SVG(model_to_dot(model ).create(prog='dot', format='svg')) 
<choose_model_class>
low_correlation = [index for index, value in sales_correlation.items() if value < 0.1 and value > -0.1 and index != 'Id']
for layer in model.layers:
layer.trainable = False
model.layers[-1].trainable = True
model.layers[-2].trainable = True
model.layers[-3].trainable = True
model.layers[-4].trainable = True
model.layers[-5].trainable = True
model.layers[-6].trainable = True
model.compile(
 loss='binary_crossentropy',
optimizer=Adam(1e-03),
metrics=['acc'])
 train_images, train_labels = train_generator.make_one_shot_iterator().get_next()
val_images, val_labels = validation_generator.make_one_shot_iterator().get_next() 
<train_model>
null_check = train_data.isna().sum()
for layer in model.layers:
layer.trainable = True
model.compile(loss='binary_crossentropy',
optimizer=Adam(lr=1e-4),
metrics=['accuracy'])
<load_from_csv>
null_columns = [index for index,value in null_check.items() if value >= train_data.shape[0]*0.8]
submit = pd.read_csv(path_to_train+'/sample_submission.csv')
 predicted = []
draw_predict = []
model.load_weights('.. /input/sliding-window-inception-v3-weights/InceptionV3.h5')
 def iter_image_slices(image):
for x_start, x_end, y_start, y_end in data_generator.slice_images() :
yield image[x_start:x_end, y_start:y_end, :]
for name in tqdm(submit['Id']):
path = os.path.join(path_to_train+'/test/', name)
 image = data_generator.load_image(path,(IMAGE_SIZE,IMAGE_SIZE,3)) /255.
 classes=set()
for s in iter_image_slices(image):
score_predict = model.predict(s[np.newaxis])[0]
draw_predict.append(score_predict)
 label_predict = np.arange(NUM_CLASSES)[score_predict>=0.2]
classes.update(label_predict)
 str_predict_label = ' '.join(str(l)for l in classes)
 predicted.append(str_predict_label)
 submit['Predicted'] = predicted
submit.to_csv('submit_InceptionV3.csv', index=False )<import_modules>
catagorical_variables = [index for index, value in train_data.dtypes.items() if value == "object"]
import numpy as np
import lightgbm as lgb
import pandas as pd
from kaggle.competitions import twosigmanews
import matplotlib.pyplot as plt
import random
from datetime import datetime, date
from xgboost import XGBClassifier
from sklearn import model_selection
from sklearn.metrics import mean_squared_error
import time<split>
catagorical_variables = [var for var in catagorical_variables if var not in null_columns and var not in low_correlation]
env = twosigmanews.make_env() 
(market_train_df, news_train_df)= env.get_training_data()
market_train, news_train = market_train_df.copy() , news_train_df.copy()<categorify>
combined_data = pd.concat([train_data,test_data] )
def mis_impute(data):
for i in data.columns:
if data[i].dtype == "object":
data[i] = data[i].fillna("other")
 elif(data[i].dtype == "int64" or data[i].dtype == "float64"):
data[i] = data[i].fillna(data[i].mean())
 else:
pass
return data
market_train_df = mis_impute(market_train_df)
 def data_prep(market_train):
market_train.time = market_train.time.dt.date
lbl = {k: v for v, k in enumerate(market_train['assetCode'].unique())}
market_train['assetCodeT'] = market_train['assetCode'].map(lbl)
 market_train = market_train.dropna(axis=0)
 return market_train
market_train = data_prep(market_train_df)
 print(market_train.shape )<feature_engineering>
modal_imputer = SimpleImputer(missing_values=np.nan, strategy='most_frequent')
 mean_imputer = SimpleImputer(missing_values=np.nan, strategy='mean' )
market_train = market_train.loc[market_train['time']>=date(2009, 1, 1)]
up = market_train.returnsOpenNextMktres10 >= 0
fcol = [c for c in market_train if c not in ['assetCode', 'assetCodes', 'assetCodesLen', 'assetName', 'audiences',
'firstCreated', 'headline', 'headlineTag', 'marketCommentary', 'provider',
'returnsOpenNextMktres10', 'sourceId', 'subjects', 'time', 'time_x', 'universe','sourceTimestamp']]
X = market_train[fcol].values
up = up.values
r = market_train.returnsOpenNextMktres10.values
mins = np.min(X, axis=0)
 maxs = np.max(X, axis=0)
 rng = maxs - mins
X = 1 -(( maxs - X)/ rng)
 assert X.shape[0] == up.shape[0] == r.shape[0]
X_train, X_test, up_train, up_test, r_train, r_test = model_selection.train_test_split(X, up, r, test_size=0.25, random_state=99)
 train_data = lgb.Dataset(X_train, label=up_train.astype(int))
test_data = lgb.Dataset(X_test, label=up_test.astype(int))<train_model>
combined_data["LotFrontage"] = mean_imputer.fit_transform(combined_data[["LotFrontage"]] )
<init_hyperparams>
combined_data["MSZoning"] = modal_imputer.fit_transform(combined_data[["MSZoning"]])
 combined_data["Utilities"] = modal_imputer.fit_transform(combined_data[["Utilities"]])
 combined_data["Exterior1st"] = modal_imputer.fit_transform(combined_data[["Exterior1st"]])
 combined_data["Exterior2nd"] = modal_imputer.fit_transform(combined_data[["Exterior2nd"]])
 combined_data["Electrical"] = modal_imputer.fit_transform(combined_data[["Electrical"]])
 combined_data["KitchenQual"] = modal_imputer.fit_transform(combined_data[["KitchenQual"]])
 combined_data["Functional"] = modal_imputer.fit_transform(combined_data[["Functional"]])
 combined_data["GarageType"] = modal_imputer.fit_transform(combined_data[["GarageType"]])
 combined_data["SaleType"] = modal_imputer.fit_transform(combined_data[["SaleType"]] )
x_1 = [0.19000424246380565, 2452, 212, 328, 202]
x_2 = [0.19016805202090095, 2583, 213, 312, 220]
params_1 = {
'task': 'train',
'boosting_type': 'dart',
'objective': 'binary',
'learning_rate': x_1[0],
'num_leaves': x_1[1],
'min_data_in_leaf': x_1[2],
'num_iteration': x_1[3],
'max_bin': x_1[4],
'verbose': 1
}
params_2 = {
'task': 'train',
'boosting_type': 'dart',
'objective': 'binary',
'learning_rate': x_2[0],
'num_leaves': x_2[1],
'min_data_in_leaf': x_2[2],
'num_iteration': x_2[3],
'max_bin': x_2[4],
'verbose': 1
}
gbm_1 = lgb.train(params_1,
train_data,
num_boost_round=100,
valid_sets=test_data,
early_stopping_rounds=5)
 gbm_2 = lgb.train(params_2,
train_data,
num_boost_round=100,
valid_sets=test_data,
early_stopping_rounds=5)
 days = env.get_prediction_days()
n_days = 0
prep_time = 0
prediction_time = 0
packaging_time = 0
for(market_obs_df, news_obs_df, predictions_template_df)in days:
n_days +=1
if(n_days%50==0):
print(n_days,end=' ')
 t = time.time()
market_obs_df = data_prep(market_obs_df)
 market_obs_df = market_obs_df[market_obs_df.assetCode.isin(predictions_template_df.assetCode)]
X_live = market_obs_df[fcol].values
X_live = 1 -(( maxs - X_live)/ rng)
 prep_time += time.time() - t
t = time.time()
lp =(gbm_1.predict(X_live)+ gbm_2.predict(X_live)) /2
prediction_time += time.time() -t
t = time.time()
confidence = lp
confidence =(confidence-confidence.min())/(confidence.max() -confidence.min())
 confidence = confidence * 2 - 1
preds = pd.DataFrame({'assetCode':market_obs_df['assetCode'],'confidence':confidence})
 predictions_template_df = predictions_template_df.merge(preds,how='left' ).drop('confidenceValue',axis=1 ).fillna(0 ).rename(columns={'confidence':'confidenceValue'})
 env.predict(predictions_template_df)
 packaging_time += time.time() - t
env.write_submission_file()
sub = pd.read_csv("submission.csv" )<install_modules>
combined_data["MasVnrType"] = combined_data["MasVnrType"].fillna("None")
 combined_data["MasVnrArea"] = combined_data["MasVnrArea"].fillna(0)
 combined_data["BsmtQual"] = combined_data["BsmtQual"].fillna("No Basement")
 combined_data["BsmtCond"] = combined_data["BsmtCond"].fillna("No Basement")
 combined_data["BsmtExposure"] = combined_data["BsmtExposure"].fillna("No Basement")
 combined_data["BsmtFinType1"] = combined_data["BsmtFinType1"].fillna("No Basement")
 combined_data["BsmtFinSF1"] = combined_data["BsmtFinSF1"].fillna(0)
 combined_data["BsmtFinType2"] = combined_data["BsmtFinType2"].fillna("No Basement")
 combined_data["BsmtUnfSF"] = combined_data["BsmtUnfSF"].fillna(0)
 combined_data["BsmtFullBath"] = combined_data["BsmtFullBath"].fillna(0)
 combined_data["FireplaceQu"] = combined_data["FireplaceQu"].fillna("No Fireplace")
 combined_data["GarageFinish"] = combined_data["GarageFinish"].fillna("No Garage")
 combined_data["GarageArea"] = combined_data["GarageArea"].fillna(0)
 combined_data["GarageQual"] = combined_data["GarageQual"].fillna("No Garage")
 combined_data["GarageCond"] = combined_data["GarageCond"].fillna("No Garage")
 combined_data["GarageYrBlt"] = combined_data["GarageYrBlt"].fillna(combined_data["YearBuilt"])
 combined_data["GarageCars"] = combined_data["GarageCars"].fillna(0)
 combined_data["TotalBsmtSF"] = combined_data["TotalBsmtSF"].fillna(0 )
!pip install -q efficientnet<set_options>
for col in low_correlation:
del combined_data[col]
print('TensorFlow version', tf.__version__)
 AUTO = tf.data.experimental.AUTOTUNE<load_from_csv>
for col in null_columns:
del combined_data[col]
<define_variables>
high_correlation = correlation_matrix_train.abs().unstack().sort_values(kind="quicksort", ascending=False)
 high_correlation[correlation_matrix_train.shape[0]:].where(lambda x : x >= 0.75 ).dropna()
start_time = datetime.now()
print('Time now is', start_time)
 end_training_by_tdelta = timedelta(seconds=8400)
 this_run_file_prefix = start_time.strftime('%Y%m%d_%H%M_')
 print(this_run_file_prefix)
 IMAGE_SIZE = [224, 224]
EPOCHS = 12
BATCH_SIZE = 16 * strategy.num_replicas_in_sync
GCS_PATH_SELECT = {
192: GCS_DS_PATH + '/tfrecords-jpeg-192x192',
224: GCS_DS_PATH + '/tfrecords-jpeg-224x224',
331: GCS_DS_PATH + '/tfrecords-jpeg-331x331',
512: GCS_DS_PATH + '/tfrecords-jpeg-512x512'
}
GCS_PATH = GCS_PATH_SELECT[IMAGE_SIZE[0]]
TRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/train/*.tfrec')
 VALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec')
 TEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec')
 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>
combined_data = pd.get_dummies(combined_data, columns=catagorical_variables, prefix=catagorical_variables, drop_first=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>
new_train = combined_data.iloc[:train_shape[0]]
new_test = combined_data.iloc[train_shape[0]:]
def decode_image(image_data):
image = tf.image.decode_jpeg(image_data, channels = 3)
 image = tf.cast(image, tf.float32)/ 255.0
image = tf.reshape(image, [*IMAGE_SIZE, 3])
 return image
def read_labeled_tfrecord(example):
LABELED_TFREC_FORMAT = {
'image': tf.io.FixedLenFeature([], tf.string),
'class': tf.io.FixedLenFeature([], tf.int64),
}
example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)
 image = decode_image(example['image'])
 label = tf.cast(example['class'], tf.int32)
 return image, label
def read_unlabeled_tfrecord(example):
UNLABELED_TFREC_FORMAT = {
'image': tf.io.FixedLenFeature([], tf.string),
'id': tf.io.FixedLenFeature([], tf.string),
}
example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT)
 image = decode_image(example['image'])
 idnum = example['id']
return image, idnum
def load_dataset(filenames, labeled = True, ordered = False):
ignore_order = tf.data.Options()
if not ordered:
ignore_order.experimental_deterministic = False
dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads = AUTO)
 dataset = dataset.with_options(ignore_order)
 dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls = AUTO)
 return dataset
def data_augment(image, label):
image = tf.image.random_flip_left_right(image)
 image = tf.image.random_saturation(image, 0, 2)
 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)) 
<categorify>
X = new_train.drop(['Id', 'SalePrice'], axis=1)
 y = new_train["SalePrice"].values
columns = list(X.columns )
<create_dataframe>
test_ids = new_test.iloc[:,0].values
test_set = new_test.iloc[:,1:]
test_set = test_set.drop(['SalePrice'], axis=1 )
test_ds = get_test_dataset(ordered = True)
 test_images_ds = test_ds.map(lambda image, idnum: image )<define_variables>
sc = StandardScaler()
X = sc.fit_transform(X)
 test_set = sc.transform(test_set )
start_time = datetime.now()
this_run_file_prefix = start_time.strftime('%Y%m%d_%H%M_')
 start_model = 0
model_indx_0 = start_model
model_indx_1 = start_model + 1
test_vals_pickle_outputs = ['/kaggle/input/all-previous-4/97731.pkl',
'/kaggle/input/all-previous-4/97606.pkl',
'/kaggle/input/all-previous-4/97611.pkl',
'/kaggle/input/all-previous-4/97659.pkl']<load_pretrained>
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2, random_state=0 )
def get_results_from_pickle(filename):
pklfile = open(filename, 'rb')
 test_results = pickle.load(pklfile)
 pklfile.close()
return test_results 
<categorify>
param_grid_rf = {
'max_depth': [100, 200, 300],
'min_samples_leaf': [1, 2, 3],
'min_samples_split': [1, 2, 3],
'n_estimators': [1000, 1200]
}
rf_regressor = RandomForestRegressor()
grid_search_rf = GridSearchCV(estimator = rf_regressor, param_grid = param_grid_rf,
cv = 3, n_jobs = -1, verbose = 2)
 grid_search_rf.fit(X_train,y_train )
no_of_models = len(test_vals_pickle_outputs)
 cm_correct_labels_results = [0] * no_of_models
cm_predictions_results = [0] * no_of_models
test_ids_results = [0] * no_of_models
val_probabilities = [0] * no_of_models
test_probabilities = [0] * no_of_models
for i in range(no_of_models):
test_results = get_results_from_pickle(test_vals_pickle_outputs[i])
 [cm_correct_labels_results[i], cm_predictions_results[i], test_ids_results[i], val_probabilities[i], test_probabilities[i]] = test_results 
<define_variables>
grid_search_rf.best_params_
cm_probabilities = np.zeros(( val_probabilities[0].shape))
for j in range(no_of_models):
cm_probabilities = cm_probabilities + val_probabilities[j]
cm_predictions = np.argmax(cm_probabilities, axis = -1)
 print('Correct labels: ', cm_correct_labels_results[0].shape, cm_correct_labels_results[0])
 print('Predicted labels: ', cm_predictions.shape, cm_predictions )<compute_train_metric>
best_grid_rf = grid_search_rf.best_estimator_
best_grid_rf
def getFitPrecisionRecall(correct_labels, predictions):
score = f1_score(correct_labels, predictions, labels = range(len(CLASSES)) , average = 'macro')
 precision = precision_score(correct_labels, predictions, labels = range(len(CLASSES)) , average = 'macro')
 recall = recall_score(correct_labels, predictions, labels = range(len(CLASSES)) , average = 'macro')
 return score, precision, recall 
<find_best_params>
importances = list(rf_regressor.feature_importances_)
 feature_importances = [(feature, round(importance, 4)) for feature, importance in zip(columns, importances)]
feature_importances = sorted(feature_importances, key = lambda x: x[1], reverse = True)
 feature_importances
for j in range(no_of_models):
model_predictions = np.argmax(val_probabilities[j], axis = -1)
 score, precision, recall = getFitPrecisionRecall(cm_correct_labels_results[0], model_predictions)
 print('For model: {}, f1 score: {:.4f}, precision: {:.4f}, recall: {:.4f}'.format(j, score, precision, recall))<compute_train_metric>
y_pred_rf = rf_regressor.predict(X_test )
cmat = confusion_matrix(cm_correct_labels_results[0], cm_predictions, labels = range(len(CLASSES)))
 score, precision, recall = getFitPrecisionRecall(cm_correct_labels_results[0], cm_predictions)
 cmat =(cmat.T / cmat.sum(axis = -1)).T
display_confusion_matrix(cmat, score, precision, recall)
 print('f1 score: {:.6f}, precision: {:.6f}, recall: {:.6f}'.format(score, precision, recall))<categorify>
print(f"R Squared Value: {r2_score(y_test,y_pred_rf)}" )
def create_submission_file_not_the_right_way(filename, probabilities, test_ids):
predictions = np.argmax(probabilities, axis = -1)
 print('Generating submission file...', filename)
 np.savetxt(filename, np.rec.fromarrays([test_ids, predictions]), fmt = ['%s', '%d'], delimiter = ',', header = 'id,label', comments = '')
 def create_submission_file(filename, probabilities):
predictions = np.argmax(probabilities, axis = -1)
 print('Generating submission file...', filename)
 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(filename, np.rec.fromarrays([test_ids, predictions]), fmt = ['%s', '%d'], delimiter = ',', header = 'id,label', comments = '')
<find_best_params>
param_grid_xg = {
'learning_rate': [0.01, 0.02],
'subsample': [0.6, 0.7, 0.8],
'colsample_bytree': [0.6, 0.7, 0.8],
'n_estimators': [800, 1000, 1500, 2000]
}
xg_regressor = XGBRegressor()
grid_search_xg = GridSearchCV(estimator = xg_regressor, param_grid = param_grid_xg,
cv = 3, n_jobs = -1, verbose = 2)
 grid_search_xg.fit(X_train,y_train )
def combine_two(correct_labels, probability_0, probability_1):
print('Start.', datetime.now())
 alphas0_to_try = np.linspace(0, 1, 101)
 best_score = -1
best_alpha0 = -1
best_alpha1 = -1
best_precision = -1
best_recall = -1
best_val_predictions = None
for alpha0 in alphas0_to_try:
alpha1 = 1.0 - alpha0
probabilities = alpha0 * probability_0 + alpha1 * probability_1
predictions = np.argmax(probabilities, axis = -1)
 score, precision, recall = getFitPrecisionRecall(correct_labels, predictions)
 if score > best_score:
best_alpha0 = alpha0
best_alpha1 = alpha1
best_score = score
best_precision = precision
best_recall = recall
best_val_predictions = predictions
return best_alpha0, best_alpha1, best_val_predictions, best_score, best_precision, best_recall<define_search_space>
grid_search_xg.best_params_
def combine_three(correct_labels, probability_0, probability_1, probability_2):
print('Start.', datetime.now())
 alphas0_to_try = np.linspace(0, 1, 101)
 alphas1_to_try = np.linspace(0, 1, 101)
 best_score = -1
best_alpha0 = -1
best_alpha1 = -1
best_alpha2 = -1
best_precision = -1
best_recall = -1
best_val_predictions = None
for alpha0 in alphas0_to_try:
for alpha1 in alphas1_to_try:
if(alpha0 + alpha1)> 1.0:
break
alpha2 = 1.0 - alpha0 - alpha1
probabilities = alpha0 * probability_0 + alpha1 * probability_1 + alpha2 * probability_2
predictions = np.argmax(probabilities, axis = -1)
 score, precision, recall = getFitPrecisionRecall(correct_labels, predictions)
 if score > best_score:
best_alpha0 = alpha0
best_alpha1 = alpha1
best_alpha2 = alpha2
best_score = score
best_precision = precision
best_recall = recall
best_val_predictions = predictions
return best_alpha0, best_alpha1, best_alpha2, best_val_predictions, best_score, best_precision, best_recall<save_to_csv>
best_grid_xg = grid_search_xg.best_estimator_
best_grid_xg
probabilities = np.zeros(( test_probabilities[0].shape))
for j in range(no_of_models):
probabilities = probabilities + test_probabilities[j]
create_submission_file_not_the_right_way('submission.csv', probabilities, test_ids_results[0])
<train_model>
xg_regressor = best_grid_xg
xg_regressor.fit(X_train,y_train )
def get_best_combination(no_models, cm_correct_labels, val_probabilities, test_probabilities):
best_fit_score = -10000.0
best_predictions = 0
choose_filename = ''
curr_predictions = np.argmax(val_probabilities[0], axis = -1)
 score, precision, recall = getFitPrecisionRecall(cm_correct_labels, curr_predictions)
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score, precision, recall))
filename = this_run_file_prefix + 'submission_0.csv'
if best_fit_score < score:
best_fit_score = score
best_predictions = curr_predictions
choose_filename = filename
create_submission_file('./submission.csv', test_probabilities[0])
 create_submission_file(filename, test_probabilities[0])
 if no_models > 1:
curr_predictions = np.argmax(val_probabilities[1], axis = -1)
 score, precision, recall = getFitPrecisionRecall(cm_correct_labels, curr_predictions)
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score, precision, recall))
filename = this_run_file_prefix + 'submission_1.csv'
if best_fit_score < score:
best_fit_score = score
best_predictions = curr_predictions
choose_filename = filename
create_submission_file('./submission.csv', test_probabilities[1])
 create_submission_file(filename, test_probabilities[1])
 if no_models > 2:
curr_predictions = np.argmax(val_probabilities[2], axis = -1)
 score, precision, recall = getFitPrecisionRecall(cm_correct_labels, curr_predictions)
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(score, precision, recall))
filename = this_run_file_prefix + 'submission_2.csv'
if best_fit_score < score:
best_fit_score = score
best_predictions = curr_predictions
choose_filename = filename
create_submission_file('./submission.csv', test_probabilities[2])
 create_submission_file(filename, test_probabilities[2])
 if no_models > 1:
best_alpha0, best_alpha1, best_val_predictions, best_score, best_precision, best_recall = combine_two(cm_correct_labels, val_probabilities[0], val_probabilities[1])
 print('For indx', [0, 1], 'best_alpha0:', best_alpha0, 'best_alpha1:', best_alpha1, '.', datetime.now())
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(best_score, best_precision, best_recall))
combined_probabilities = best_alpha0 * test_probabilities[0] + best_alpha1 * test_probabilities[1]
filename = this_run_file_prefix + 'submission_01.csv'
if best_fit_score < best_score:
best_fit_score = best_score
best_predictions = best_val_predictions
choose_filename = filename
create_submission_file('./submission.csv', combined_probabilities)
 create_submission_file(filename, combined_probabilities)
 if no_models > 2:
best_alpha0, best_alpha1, best_val_predictions, best_score, best_precision, best_recall = combine_two(cm_correct_labels, val_probabilities[0], val_probabilities[2])
 print('For indx', [0, 2], 'best_alpha0:', best_alpha0, 'best_alpha1:', best_alpha1, '.', datetime.now())
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(best_score, best_precision, best_recall))
combined_probabilities = best_alpha0 * test_probabilities[0] + best_alpha1 * test_probabilities[2]
filename = this_run_file_prefix + 'submission_02.csv'
if best_fit_score < best_score:
best_fit_score = best_score
best_predictions = best_val_predictions
choose_filename = filename
create_submission_file('./submission.csv', combined_probabilities)
 create_submission_file(filename, combined_probabilities)
 best_alpha0, best_alpha1, best_val_predictions, best_score, best_precision, best_recall = combine_two(cm_correct_labels, val_probabilities[1], val_probabilities[2])
 print('For indx', [1, 2], 'best_alpha0:', best_alpha0, 'best_alpha1:', best_alpha1, '.', datetime.now())
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(best_score, best_precision, best_recall))
combined_probabilities = best_alpha0 * test_probabilities[1] + best_alpha1 * test_probabilities[2]
filename = this_run_file_prefix + 'submission_12.csv'
if best_fit_score < best_score:
best_fit_score = best_score
best_predictions = best_val_predictions
choose_filename = filename
create_submission_file('./submission.csv', combined_probabilities)
 create_submission_file(filename, combined_probabilities)
 best_alpha0, best_alpha1, best_alpha2, best_val_predictions, best_score, best_precision, best_recall = combine_three(cm_correct_labels, val_probabilities[0], val_probabilities[1], val_probabilities[2])
 print('For indx', [0, 1, 2], 'best_alpha0:', best_alpha0, 'best_alpha1:', best_alpha1, 'best_alpha2:', best_alpha2, '.', datetime.now())
 print('f1 score: {:.3f}, precision: {:.3f}, recall: {:.3f}'.format(best_score, best_precision, best_recall))
combined_probabilities = best_alpha0 * test_probabilities[0] + best_alpha1 * test_probabilities[1] + best_alpha2 * test_probabilities[2]
filename = this_run_file_prefix + 'submission_012.csv'
if best_fit_score < best_score:
best_fit_score = best_score
best_predictions = best_val_predictions
choose_filename = filename
create_submission_file('./submission.csv', combined_probabilities)
 create_submission_file(filename, combined_probabilities)
 cmat = confusion_matrix(cm_correct_labels, best_predictions, labels = range(len(CLASSES)))
 cmat =(cmat.T / cmat.sum(axis = -1)).T
display_confusion_matrix(cmat, score, precision, recall)
 print('Best score from all combination was', best_fit_score, '.For submission file used is', choose_filename)
 return best_fit_score, best_predictions 
<choose_model_class>
y_pred_xg = xg_regressor.predict(X_test )
best_predictions = cm_predictions
run_this = False
if no_of_models > 1 and run_this:
bp = get_best_combination(no_of_models, cm_correct_labels_results[0], val_probabilities, test_probabilities)
 best_predictions = bp 
<define_variables>
print(f"R Squared Value: {r2_score(y_test,y_pred_xg)}" )
use_correct_labels = cm_correct_labels_results[0]
use_val_predictions = best_predictions<define_variables>
rf_regressor.fit(X,y )
correct_labels_cnt = 0
incorrect_labels_cnt = 0
correct_labels = []
incorrect_labels = []
vals_actual_true = {}
vals_tp = {}
vals_fn = {}
vals_fp = {}
for i in range(len(CLASSES)) :
vals_actual_true[i] = 0
vals_tp[i] = 0
vals_fn[i] = 0
vals_fp[i] = 0
for i in range(len(use_correct_labels)) :
correct_label = use_correct_labels[i]
predict_label = use_val_predictions[i]
vals_actual_true[correct_label] = vals_actual_true[correct_label] + 1
if use_val_predictions[i] != use_correct_labels[i]:
incorrect_labels_cnt = incorrect_labels_cnt + 1
incorrect_labels.append(i)
 vals_fn[correct_label] = vals_fn[correct_label] + 1
vals_fp[predict_label] = vals_fp[predict_label] + 1
else:
correct_labels_cnt = correct_labels_cnt + 1
correct_labels.append(i)
 vals_tp[correct_label] = vals_tp[correct_label] + 1
print('Number of correct_labels is {}, incorrect_labels is {}'.format(correct_labels_cnt, incorrect_labels_cnt))
print('Incorrect labels', incorrect_labels)
<set_options>
xg_regressor.fit(X,y )
!pip install -q efficientnet
print("Tensorflow version " + tf.__version__)
 AUTO = tf.data.experimental.AUTOTUNE<set_options>
test_pred_rf = rf_regressor.predict(test_set ).round(2 )
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>
results_rf = pd.DataFrame(
 {'Id': test_ids,
'SalePrice': test_pred_rf
} )
GCS_DS_PATH = KaggleDatasets().get_gcs_path('flower-classification-with-tpus')
 IMAGE_SIZE = [512, 512]
BATCH_SIZE = 16 * strategy.num_replicas_in_sync
GCS_PATH_SELECT = {
192: GCS_DS_PATH + '/tfrecords-jpeg-192x192',
224: GCS_DS_PATH + '/tfrecords-jpeg-224x224',
331: GCS_DS_PATH + '/tfrecords-jpeg-331x331',
512: GCS_DS_PATH + '/tfrecords-jpeg-512x512'
}
GCS_PATH = GCS_PATH_SELECT[IMAGE_SIZE[0]]
TRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/train/*.tfrec')
 VALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec')
 TEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec' )<define_variables>
results_rf.to_csv("random_forest_prediction.csv", index=False )
<define_variables>
test_pred_xg = xg_regressor.predict(test_set ).round(2 )
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']<define_variables>
results_xg = pd.DataFrame(
 {'Id': test_ids,
'SalePrice': test_pred_xg
} )
<categorify><EOS> 
results_xg.to_csv("xgboost_prediction.csv", index=False )