Kaggle competition: House Prices - Advanced Regression Techniques
AUTO = tf.data.experimental.AUTOTUNE<choose_model_class>
%matplotlib inline
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 )<define_variables>
raw_train = pd.read_csv('.. /input/house-prices-advanced-regression-techniques/train.csv',index_col='Id')
 raw_test = pd.read_csv('.. /input/house-prices-advanced-regression-techniques/test.csv',index_col='Id')
 raw_train.info()
raw_test.info()
GCS_DS_PATH = KaggleDatasets().get_gcs_path()
IMAGE_SIZE = [512, 512]
EPOCHS = 50
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>
train = raw_train.copy()
test = raw_test.copy()
train_test = pd.concat([train.drop(columns=['SalePrice']),test] )
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.corr() ['SalePrice'].sort_values(key=abs,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_flip_left_right(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))<choose_model_class>
train_test = train_test.drop(train[(train['GrLivArea']>4000)&(train['SalePrice']<300000)].index)
 train = train.drop(train[(train['GrLivArea']>4000)&(train['SalePrice']<300000)].index )
with strategy.scope() :
enet = efn.EfficientNetB7(
 input_shape=(812, 812, 3),
weights='imagenet',
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.isnull().sum().sort_values(ascending=False ).head(20 )
scheduler = tf.keras.callbacks.ReduceLROnPlateau(patience=3, verbose=1)
 history = model.fit(
 get_training_dataset() ,
steps_per_epoch=STEPS_PER_EPOCH,
epochs=EPOCHS,
callbacks=[scheduler],
validation_data=get_validation_dataset()
)<save_to_csv>
for col in ['PoolQC','MiscFeature','Alley','Fence','BsmtQual','BsmtCond','BsmtExposure',
'BsmtFinType1','BsmtFinType2','FireplaceQu','GarageType','GarageFinish',
'GarageQual','GarageCond','MasVnrType']:
train_test[col].fillna('None',inplace=True)
 for col in ['Functional','Electrical','KitchenQual','Exterior1st','Exterior2nd','SaleType','MSZoning','Utilities']:
train_test[col].fillna(train_test[col].mode() [0],inplace=True)
 for col in ['GarageYrBlt', 'GarageArea', 'GarageCars','MasVnrArea','BsmtFinSF1',
'BsmtUnfSF','BsmtFinSF2','BsmtHalfBath','BsmtHalfBath','BsmtFullBath','TotalBsmtSF']:
train_test[col].fillna(0,inplace=True )
test_ds = get_test_dataset(ordered=True)
 print('Computing predictions...')
 test_images_ds = test_ds.map(lambda image, idnum: image)
 probabilities = model.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='')
<set_options>
train.corr() ['LotFrontage'].sort_values(key=abs, ascending=False )
warnings.filterwarnings('ignore')
 os.environ["WANDB_API_KEY"] = "0"<choose_model_class>
LF_df =train_test[['LotFrontage','1stFlrSF','LotArea','GrLivArea', 'TotalBsmtSF', 'MSSubClass', 'TotRmsAbvGrd','GarageArea','GarageCars']]
LF_df_notnull = LF_df.loc[train_test['LotFrontage'].notnull() ]
LF_df_isnull = LF_df.loc[(train_test['LotFrontage'].isnull())]
Xtr_LF = pd.get_dummies(LF_df_notnull.drop(columns=['LotFrontage']))
Xte_LF = pd.get_dummies(LF_df_isnull.drop(columns=['LotFrontage']))
Y_LF = LF_df_notnull.LotFrontage
RFR = RandomForestRegressor(n_estimators=60, n_jobs=-1)
 RFR.fit(Xtr_LF,Y_LF)
 predict = RFR.predict(Xte_LF)
 train_test.loc[train_test['LotFrontage'].isnull() , ['LotFrontage']]= predict
RFR.score(Xtr_LF,Y_LF )
def Init_TPU() :
try:
resolver = tf.distribute.cluster_resolver.TPUClusterResolver()
tf.config.experimental_connect_to_cluster(resolver)
 tf.tpu.experimental.initialize_tpu_system(resolver)
 strategy = tf.distribute.experimental.TPUStrategy(resolver)
 REPLICAS = strategy.num_replicas_in_sync
print("Connected to TPU Successfully:
TPUs Initialised with Replicas:",REPLICAS)
 return strategy
except ValueError:
print("Connection to TPU Falied")
 print("Using default strategy for CPU and single GPU")
 strategy = tf.distribute.get_strategy()
return strategy
strategy=Init_TPU()<define_variables>
path = '.. /input/contradictory-my-dear-watson/'<load_from_csv>
train[['Neighborhood','SalePrice']].groupby('Neighborhood' ).mean().sort_values('SalePrice' )
train_url = os.path.join(path,'train.csv')
 train_data = pd.read_csv(train_url, header='infer')
 sample_sub_url = os.path.join(path,'sample_submission.csv')
 sample_sub = pd.read_csv(sample_sub_url, header='infer')
 test_url = os.path.join(path,'test.csv')
 test_data = pd.read_csv(test_url, header='infer' )<groupby>
train_test["oNeighborhood"] = train_test.Neighborhood.map({'MeadowV':1,
'IDOTRR':2, 'BrDale':2,
'OldTown':3, 'Edwards':3, 'BrkSide':3,
'Sawyer':4, 'Blueste':4, 'SWISU':4, 'NAmes':4,
'NPkVill':5, 'Mitchel':5,
'SawyerW':6, 'Gilbert':6, 'NWAmes':6,
'Blmngtn':7, 'CollgCr':7, 'ClearCr':7, 'Crawfor':7,
'Veenker':8, 'Somerst':8, 'Timber':8,
'StoneBr':9,
'NoRidge':10, 'NridgHt':10} )
print("Records per Label:
", train_data.groupby('label' ).size() )<groupby>
train_test['Has_pool'] = train_test['PoolArea'].apply(lambda x: 1 if x > 0 else 0)
 train_test['Has_2ndfloor'] = train_test['2ndFlrSF'].apply(lambda x: 1 if x > 0 else 0)
 train_test['Has_garage'] = train_test['GarageArea'].apply(lambda x: 1 if x > 0 else 0)
 train_test['Has_bsmt'] = train_test['TotalBsmtSF'].apply(lambda x: 1 if x > 0 else 0)
 train_test['Has_fireplace'] = train_test['Fireplaces'].apply(lambda x: 1 if x > 0 else 0)
 binary_features = ['Has_pool','Has_2ndfloor','Has_garage','Has_bsmt','Has_fireplace']
print("Records per Language:
", train_data.groupby('language' ).size() )<set_options>
gc.collect()<load_pretrained>
ordinal_features = ['FireplaceQu', 'BsmtQual', 'BsmtCond', 'GarageQual',
'GarageCond', 'ExterQual', 'ExterCond','HeatingQC',
'KitchenQual', 'BsmtFinType1', 'BsmtFinType2',
'Functional', 'BsmtExposure', 'GarageFinish',
'LandSlope','LotShape', 'PavedDrive', 'Street',
'CentralAir']
transformer_model = 'jplu/tf-xlm-roberta-large'
tokenizer = XLMRobertaTokenizer.from_pretrained(transformer_model )<data_type_conversions>
bin_map = {'TA':2,'Gd':3, 'Fa':1,'Ex':4,'Po':1,'None':0,'Y':1,'N':0,'Reg':3,'IR1':2,'IR2':1,'IR3':0,
"No" : 2, "Mn" : 2, "Av": 3,"Gd" : 4,"Unf" : 1, "LwQ": 2, "Rec" : 3,"BLQ" : 4, "ALQ" : 5, "GLQ" : 6,
'Typ':7, 'Min1':6, "Min2":5, 'Mod':4, "Maj1":3, "Maj2":2, "Sev":1, "Sal":0,'Grvl':0,'Pave':1
}
train_test['ExterQual'] = train_test['ExterQual'].map(bin_map)
 train_test['ExterCond'] = train_test['ExterCond'].map(bin_map)
 train_test['BsmtCond'] = train_test['BsmtCond'].map(bin_map)
 train_test['BsmtQual'] = train_test['BsmtQual'].map(bin_map)
 train_test['HeatingQC'] = train_test['HeatingQC'].map(bin_map)
 train_test['KitchenQual'] = train_test['KitchenQual'].map(bin_map)
 train_test['FireplaceQu'] = train_test['FireplaceQu'].map(bin_map)
 train_test['Functional'] = train_test['Functional'].map(bin_map)
 train_test['Street'] = train_test['Street'].map(bin_map)
 train_test['GarageQual'] = train_test['GarageQual'].map(bin_map)
 train_test['GarageCond'] = train_test['GarageCond'].map(bin_map)
 train_test['CentralAir'] = train_test['CentralAir'].map(bin_map)
 train_test['LotShape'] = train_test['LotShape'].map(bin_map)
 train_test['BsmtExposure'] = train_test['BsmtExposure'].map(bin_map)
 train_test['BsmtFinType1'] = train_test['BsmtFinType1'].map(bin_map)
 train_test['BsmtFinType2'] = train_test['BsmtFinType2'].map(bin_map)
 PavedDrive = {"N" : 0, "P" : 1, "Y" : 2}
train_test['PavedDrive'] = train_test['PavedDrive'].map(PavedDrive)
 GarageFinish = {'Fin':3, 'RFn':2, 'Unf':1, 'NA':0,'None':0}
train_test['GarageFinish'] = train_test['GarageFinish'].map(GarageFinish)
 LandSlope = {'Gtl':2, 'Mod':1, 'Sev':0}
train_test['LandSlope'] = train_test['LandSlope'].map(LandSlope)
 train_test["MSZoning"] = train_test.MSZoning.map({'C(all)':1, 'RH':2, 'RM':2, 'RL':3, 'FV':4})
 train_test["oCondition1"] = train_test.Condition1.map({'Artery':1,
'Feedr':2, 'RRAe':2,
'Norm':3, 'RRAn':3,
'PosN':4, 'RRNe':4,
'PosA':5 ,'RRNn':5} )
tokenizer.convert_tokens_to_ids(list(tokenizer.tokenize("Elementary, My Dear Watson!")) )<data_type_conversions>
train_test['Total_SF']=train_test['TotalBsmtSF'] + train_test['1stFlrSF'] + train_test['2ndFlrSF']
train_test['Total_sqr_footage'] =(train_test['BsmtFinSF1'] + train_test['BsmtFinSF2'] +
train_test['1stFlrSF'] + train_test['2ndFlrSF'])
 train_test['Total_Bathrooms'] =(train_test['FullBath'] +(0.5 * train_test['HalfBath'])+
train_test['BsmtFullBath'] +(0.5 * train_test['BsmtHalfBath']))
train_test['Total_porch_sf'] =(train_test['OpenPorchSF'] + train_test['3SsnPorch'] +
train_test['EnclosedPorch'] + train_test['ScreenPorch'] +
train_test['WoodDeckSF'])
 train_test["+_TotalHouse_OverallQual"] = train_test["Total_SF"] * train_test["OverallQual"]
train_test["+_GrLivArea_OverallQual"] = train_test["GrLivArea"] * train_test["OverallQual"]
train_test["+_oMSZoning_TotalHouse"] = train_test["MSZoning"] * train_test["Total_SF"]
train_test["+_oMSZoning_OverallQual"] = train_test["MSZoning"] + train_test["OverallQual"]
train_test["+_oNeighborhood_TotalHouse"] = train_test["oNeighborhood"] * train_test["Total_SF"]
train_test["+_oNeighborhood_OverallQual"] = train_test["oNeighborhood"] + train_test["OverallQual"]
train_test["+_oNeighborhood_YearBuilt"] = train_test["oNeighborhood"] + train_test["YearBuilt"]
train_test["+_BsmtFinSF1_OverallQual"] = train_test["BsmtFinSF1"] * train_test["OverallQual"]
train_test["-_oFunctional_TotalHouse"] = train_test["Functional"] * train_test["Total_SF"]
train_test["-_oFunctional_OverallQual"] = train_test["Functional"] + train_test["OverallQual"]
train_test["-_LotArea_OverallQual"] = train_test["LotArea"] * train_test["OverallQual"]
train_test["-_TotalHouse_LotArea"] = train_test["Total_SF"] + train_test["LotArea"]
train_test["-_oCondition1_TotalHouse"] = train_test["oCondition1"] * train_test["Total_SF"]
train_test["-_oCondition1_OverallQual"] = train_test["oCondition1"] + train_test["OverallQual"]
train_test["Bsmt"] = train_test["BsmtFinSF1"] + train_test["BsmtFinSF2"] + train_test["BsmtUnfSF"]
train_test["Rooms"] = train_test["FullBath"]+train_test["TotRmsAbvGrd"]
train_test["TotalPlace"] = train_test["TotalBsmtSF"] + train_test["1stFlrSF"] + train_test["2ndFlrSF"] + train_test["GarageArea"] +train_test["OpenPorchSF"]+train_test["EnclosedPorch"]+train_test["3SsnPorch"]+train_test["ScreenPorch"]
train = train_data[['premise','hypothesis']].values.tolist()
test = test_data[['premise','hypothesis']].values.tolist()<define_variables>
train_test_num = pd.DataFrame(train_test.select_dtypes(['float64','int32','int64']))
train_test_num.drop(columns=ordinal_features,inplace=True)
 train_test_num.drop(columns=binary_features,inplace=True )
max_len = 80
train_encode = tokenizer.batch_encode_plus(train, pad_to_max_length=True, max_length=max_len)
 test_encode = tokenizer.batch_encode_plus(test, pad_to_max_length=True, max_length=max_len )<split>
train_test_skewed = train_test_num.apply(lambda x:skew(x)).sort_values(key=abs,ascending=False)
 train_test_skewed_df = pd.DataFrame({'Skew':train_test_skewed})
 train_test_skewed_df
test_size = 0.1
x_train, x_val, y_train, y_val = train_test_split(train_encode['input_ids'], train_data.label.values, test_size=test_size)
 x_test = test_encode['input_ids']<set_options>
skewed_features = train_test_skewed_df[train_test_skewed_df.Skew>0.5].index
lmbd = 0.15
for sk in skewed_features:
if sk not in ['SalePrice','SalePrice_log']:
train_test[sk] = boxcox1p(train_test[sk], lmbd )
gc.collect()<define_variables>
train_test = pd.get_dummies(train_test)
 train_test.isna().sum().sort_values(ascending=False )
AUTO = tf.data.experimental.AUTOTUNE
batch_size = 16 * strategy.num_replicas_in_sync
train_ds =(tf.data.Dataset.from_tensor_slices(( x_train, y_train)).repeat().shuffle(2048 ).batch(batch_size ).prefetch(AUTO))
val_ds =(tf.data.Dataset.from_tensor_slices(( x_val, y_val)).batch(batch_size ).prefetch(AUTO))
test_ds =(tf.data.Dataset.from_tensor_slices(x_test ).batch(batch_size))<set_options>
lasso_model = Lasso(alpha=0.0001 ).fit(train_test[:1458],train.SalePrice_log)
 ft_im_df = pd.DataFrame({"Feature Importance":lasso_model.coef_}, index=train_test.columns)
 ft_im_df.sort_values('Feature Importance', key=abs,ascending=False ).head(20 )
gc.collect()<categorify>
CV = KFold(n_splits=5,shuffle=True,random_state=42)
 rb_scaler = RobustScaler()
def build_model(strategy,transformer):
with strategy.scope() :
transformer_encoder = TFXLMRobertaModel.from_pretrained(transformer)
 input_layer = Input(shape=(max_len,), dtype=tf.int32, name="input_layer")
 sequence_output = transformer_encoder(input_layer)[0]
cls_token = sequence_output[:, 0, :]
output_layer = Dense(3, activation='softmax' )(cls_token)
 model = Model(inputs=input_layer, outputs=output_layer)
 model.compile(
 Adam(lr=1e-5),
loss='sparse_categorical_crossentropy',
metrics=['accuracy'] 
)
 return model
model = build_model(strategy,transformer_model )<train_model>
def rmse(model,x,y):
return -(cross_val_score(model, x, y,cv=CV,scoring='neg_root_mean_squared_error',n_jobs=-1))
epochs = 30
n_steps = len(train_data)// batch_size
model.fit(train_ds,
steps_per_epoch = n_steps,
validation_data = val_ds,
epochs = epochs )<set_options>
train_test = rb_scaler.fit_transform(train_test)
 X = train_test[:1458]
X_test = train_test[1458:]
Y = train.SalePrice_log
X.shape
gc.collect()<predict_on_test>
pca = PCA(n_components=0.9999)
 train_test_pc = pca.fit_transform(train_test)
 X_PC = train_test_pc[:1458]
X_test_PC = train_test_pc[1458:]
X_PC.shape
prediction = model.predict(test_ds, verbose=0)
 sample_sub['prediction'] = prediction.argmax(axis=1 )<save_to_csv>
n_trials = 500
sample_sub.to_csv("submission.csv", index=False )<load_from_csv>
ridge_best_params = {'alpha': 36.31161037749121}
ridge_best_model = Ridge(**ridge_best_params )
df_submit = pd.read_csv(".. /input/mberttrain10epochs/submission(1 ).csv")
<save_to_csv>
lasso_best_params = {'alpha': 0.0007350225758112973}
lasso_best_model = Lasso(**lasso_best_params )
df_submit.to_csv("submission.csv", index=False)
 df_submit.head()<install_modules>
elastic_best_params = {'alpha': 0.004962477837834253, 'l1_ratio': 0.1}
elastic_best_model = ElasticNet(**elastic_best_params )
pip install pyspellchecker<import_modules>
SVR_best_params = {'epsilon': 0.0007028077160999125, 'kernel': 'rbf',
'gamma': 0.0001032023906441773, 'C': 20.673761351762828}
SVR_best_model = SVR(**SVR_best_params )
import pandas as pd
from spellchecker import SpellChecker
import regex as re<set_options>
KNR_best_params = {'alpha': 0.017852963690058583, 'kernel': 'polynomial',
'gamma': 0.00010010824404031089, 'degree': 4}
KNR_best_model = KernelRidge(**KNR_best_params )
warnings.filterwarnings("ignore" )<load_from_csv>
Bayesian_best_params = {'alpha_1': 9.974811163419825e-06, 'alpha_2': 5.050535825995536e-06,
'lambda_1': 9.97006607898247e-06, 'lambda_2': 1.004807953151607e-08}
Bayesian_best_model = BayesianRidge(**Bayesian_best_params )
train = pd.read_csv('.. /input/contradictory-my-dear-watson/train.csv')
 test = pd.read_csv('.. /input/contradictory-my-dear-watson/test.csv' )<filter>
eng = train.loc[train.language == 'English']<load_pretrained>
MLP_best_model = MLPRegressor(random_state=42,
solver='adam',
activation='tanh',
alpha= 2.9344049246725894,
hidden_layer_sizes=(120),
max_iter=1000,
learning_rate='adaptive',
batch_size=300,
learning_rate_init=0.5,
early_stopping=True )
spell = SpellChecker()
spell.word_frequency.load_text_file('.. /input/english-words/words_alpha.txt')
 spell.word_frequency.load_words([''] )<feature_engineering>
eng['premise_misspelled'] = eng.premise.apply(lambda sentence: tuple(spell.unknown(re.split('[!\:;,.\-\% \b\s() "/$0-9]',re.sub('['\[\]]', '', sentence)))) )<filter>
XGB_best_params= {'n_estimators': 230, 'learning_rate': 0.05064350395549183,
'max_depth': 2, 'booster': 'gblinear', 'gamma': 0.0005562582585578549,
'reg_alpha': 0.0010013453661588325, 'reg_lambda': 0.0010065125775610678,
'colsample_bytree': 0.6000000000000001, 'subsample': 1.0}
XGB_best_model = XGBRegressor(**XGB_best_params,objective='reg:squaredlogerror',
random_state=42,n_jobs=-1 )
misspelled_df = eng.loc[eng.premise_misspelled !=() ]
list(misspelled_df.premise_misspelled )<create_dataframe>
pd.set_option('display.max_colwidth', -1 )<filter>
LGBM_best_params={'boosting_type': 'gbdt', 'num_leaves': 10,
'learning_rate': 0.0623344941102757, 'n_estimators': 350,
'max_depth': 6, 'min_samples_split': 0.003721770553125834,
'min_samples_leaf': 2, 'reg_alpha': 0.011733455705754578,
'reg_lambda': 0.0692034942836032, 'colsample_bytree': 0.6000000000000001,
'subsample': 0.9}
LGBM_best_model = LGBMRegressor(**LGBM_best_params,random_state=42,n_jobs=-1 )
err1 = misspelled_df.loc[eng.premise.str.contains('\?\?', case = False)]
err2 = misspelled_df.loc[eng.premise.str.contains("\xad", case = False)]
print(len(err1), len(err2))<remove_duplicates>
def model_eval() :
rmse_mean = []
std = []
rmser = []
regressors=['Lasso','Ridge','Elastic_Net',
'Kernel_Ridge','SVR','Bayesian',
'MLP','XGB','LGBM']
models=[lasso_best_model,ridge_best_model,
elastic_best_model,KNR_best_model,
SVR_best_model,Bayesian_best_model,
MLP_best_model,XGB_best_model,
LGBM_best_model]
for model in models:
cv_result = rmse(model,X_PC,Y)
 rmse_mean.append(cv_result.mean())
 std.append(cv_result.std())
 rmser.append(cv_result)
 performance_df=pd.DataFrame({'CV_Mean':rmse_mean,'Std':std},index=regressors)
 return performance_df
performance_df = model_eval()
performance_df.sort_values('CV_Mean' )
reduced_1 = pd.concat([misspelled_df, err1, err1] ).drop_duplicates(keep=False)
 reduced_2 = pd.concat([reduced_1, err2, err2] ).drop_duplicates(keep=False )<categorify>
stacking = StackingRegressor(estimators=[('SVR',SVR_best_model), 
('Kernel_ridge',KNR_best_model), 
('ElasticNet',elastic_best_model), 
('Ridge',ridge_best_model), 
('Lasso', lasso_best_model), 
('Bayesian',Bayesian_best_model), 
('MLP',MLP_best_model), 
('LGBM',LGBM_best_model), 
('XGB',XGB_best_model)],
final_estimator=KernelRidge() ,
cv=5,
n_jobs=-1)
 cv_result = rmse(stacking,X_PC,Y)
 stk_acc = cv_result.mean()
stk_std = cv_result.std()
performance_df.loc['Stacking'] = {'CV_Mean':stk_acc, 'Std':stk_std}
performance_df.sort_values(by=['CV_Mean'] )
correction = err1.premise.apply(lambda sentence: re.sub('\?\?', 'e', sentence))
correct_rhone = correction.apply(lambda sentence: re.sub('Rhene', 'Rhone', sentence))
correct_ataturk = correct_rhone.apply(lambda sentence: re.sub('Ataterk', 'Ataturk', sentence))
correct_madrileno = correct_ataturk.apply(lambda sentence: re.sub('Madrileeo', 'Madrileno', sentence))
correct_alacahoyuk = correct_madrileno.apply(lambda sentence: re.sub('Alacaheyek', 'Alacahoyuk', sentence))
correct_alcudia = correct_alacahoyuk.apply(lambda sentence: re.sub('Alcedia', 'Alcudia', sentence))
correction1 = correct_alcudia<feature_engineering>
stack_y = stacking.fit(X_PC,Y ).predict(X_test_PC)
 elastic_y = elastic_best_model.fit(X_PC,Y ).predict(X_test_PC)
 ridge_y = ridge_best_model.fit(X_PC,Y ).predict(X_test_PC)
 lasso_y = lasso_best_model.fit(X_PC,Y ).predict(X_test_PC)
 SVR_y = SVR_best_model.fit(X_PC,Y ).predict(X_test_PC)
 KNR_y = KNR_best_model.fit(X_PC,Y ).predict(X_test_PC)
 Bayesian_y = Bayesian_best_model.fit(X_PC,Y ).predict(X_test_PC)
 XGB_y = XGB_best_model.fit(X_PC,Y ).predict(X_test_PC)
 blend = 0.0 * stack_y + 0.1 * elastic_y + 0.9*ridge_y + 0.0*lasso_y+ 0.0*SVR_y
for i in correction1.index:
eng.loc[eng.index == i, 'premise'] = correction1.loc[correction1.index == i]<filter>
sub_pre = np.exp(blend)
 sub_pre = np.around(sub_pre,decimals=-1)
 sub_pre
<feature_engineering><EOS> 
sub_pd = pd.DataFrame({'Id':test.index,'SalePrice':sub_pre})
 sub_pd.to_csv('submit.csv' ,index=False )