Kaggle competition: House Prices - Advanced Regression Techniques
<SOS> metric: rmsle Kaggle data source: house-prices-advanced-regression-techniques<data_type_conversions>
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import pprint
from scipy import stats
from sklearn.model_selection import train_test_split, GridSearchCV, RandomizedSearchCV, PredefinedSplit, cross_val_score
from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler, FunctionTransformer
from sklearn.metrics import mean_squared_log_error, make_scorer
from hpsklearn import HyperoptEstimator, svr, svr_linear, svr_rbf, svr_poly, svr_sigmoid, knn_regression, ada_boost_regression, gradient_boosting_regression, random_forest_regression, extra_trees_regression, sgd_regression, xgboost_regression
for i,(train_idx, valid_idx)in enumerate(splits):
x_train_fold = torch.tensor(x_train[train_idx.astype(int)], dtype=torch.long ).cuda()
y_train_fold = torch.tensor(y_train[train_idx.astype(int), np.newaxis], dtype=torch.float32 ).cuda()
x_val_fold = torch.tensor(x_train[valid_idx.astype(int)], dtype=torch.long ).cuda()
y_val_fold = torch.tensor(y_train[valid_idx.astype(int), np.newaxis], dtype=torch.float32 ).cuda()
model = NeuralNet()
model.cuda()
loss_fn = torch.nn.BCEWithLogitsLoss(reduction='sum')
 step_size = 300
base_lr, max_lr = 0.001, 0.005
optimizer = AdamW(filter(lambda p: p.requires_grad, model.parameters()))
scheduler = CyclicLR(optimizer, base_lr=base_lr, max_lr=max_lr,
step_size=step_size, mode='exp_range',
gamma=0.99994)
 train = torch.utils.data.TensorDataset(x_train_fold, y_train_fold)
 valid = torch.utils.data.TensorDataset(x_val_fold, y_val_fold)
 train = MyDataset(train)
 valid = MyDataset(valid)
 train_loader = torch.utils.data.DataLoader(train, batch_size=batch_size, shuffle=True)
 valid_loader = torch.utils.data.DataLoader(valid, batch_size=batch_size, shuffle=False)
 print(f'Fold {i + 1}')
 for epoch in range(n_epochs):
start_time = time.time()
model.train()
avg_loss = 0.
 for i,(x_batch, y_batch, index)in enumerate(train_loader):
y_pred = model([x_batch])
 if scheduler:
scheduler.batch_step()
loss = loss_fn(y_pred, y_batch)
 optimizer.zero_grad()
loss.backward()
optimizer.step()
avg_loss += loss.item() / len(train_loader)
 model.eval()
valid_preds_fold = np.zeros(( x_val_fold.size(0)))
 avg_val_loss = 0.
 for i,(x_batch, y_batch, index)in enumerate(valid_loader):
y_pred = model([x_batch] ).detach()
avg_val_loss += loss_fn(y_pred, y_batch ).item() / len(valid_loader)
 valid_preds_fold[i * batch_size:(i+1)* batch_size] = sigmoid(y_pred.cpu().numpy())[:, 0]
elapsed_time = time.time() - start_time
print('Epoch {}/{} \t loss={:.4f} \t val_loss={:.4f} \t time={:.2f}s'.format(
 epoch + 1, n_epochs, avg_loss, avg_val_loss, elapsed_time))
avg_losses_f.append(avg_loss)
 avg_val_losses_f.append(avg_val_loss)
 for i,(x_batch,)in enumerate(test_loader):
y_pred = model([x_batch] ).detach()
test_preds_fold[i * batch_size:(i+1)* batch_size] = sigmoid(y_pred.cpu().numpy())[:, 0]
train_preds[valid_idx] = valid_preds_fold
test_preds += test_preds_fold / len(splits)
 print('All \t loss={:.4f} \t val_loss={:.4f} \t f1={:.4f} \t '.format(np.average(avg_losses_f),np.average(avg_val_losses_f),f1))<save_to_csv>
pd.set_option('display.max_columns', 100)
 pd.set_option("display.max_rows", 400)
 random_state = 42
submission = pd.read_csv(SAMPLE_SUBMISSION, index_col='id')
 submission['prediction'] = test_preds
submission.reset_index(drop=False, inplace=True)
 submission.to_csv('submission.csv', index=False )<import_modules>
df_train = pd.read_csv('.. /input/house-prices-advanced-regression-techniques/train.csv')
 df_test = pd.read_csv('.. /input/house-prices-advanced-regression-techniques/test.csv')
 df_target = df_train[['SalePrice']]
df = df_train.append(df_test)
 df.drop(columns=['Id'], inplace=True )
import numpy as np
import pandas as pd
from keras.models import Model
from keras.layers import Input, Dense, Embedding, SpatialDropout1D, Dropout, add, concatenate
from keras.layers import CuDNNLSTM, CuDNNGRU, Bidirectional, GlobalMaxPooling1D, GlobalAveragePooling1D
from keras.optimizers import Adam
from keras.preprocessing import text, sequence
from keras.callbacks import LearningRateScheduler<define_variables>
def mount_df_info(df):
df_info = df.dtypes.to_frame(name='type')
 df_info['count_null'] = df.isnull().values.sum(axis=0)
 df_info['nunique'] = df.nunique().values
df_info['count_zeros'] =(df == 0 ).values.sum(axis=0)
 df_info['max_value'] = df.max()
df_info['min_value'] = df.min()
return df_info
EMBEDDING_FILES = [
'.. /input/fasttext-crawl-300d-2m/crawl-300d-2M.vec',
'.. /input/glove840b300dtxt/glove.840B.300d.txt'
]
NUM_MODELS = 2
MAX_FEATURES = 100000
BATCH_SIZE = 512*3
LSTM_UNITS = 128
DENSE_HIDDEN_UNITS = 4 * LSTM_UNITS
EPOCHS = 1
MAX_LEN = 220 
<compute_test_metric>
df_info = mount_df_info(df)
 df_info.sort_values(by='count_null', ascending=False ).head()
def get_coefs(word, *arr):
return word, np.asarray(arr, dtype='float32' )<load_pretrained>
columns = ['PoolQC', 'MiscFeature', 'Alley', 'Fence', 'FireplaceQu']
df[columns] = df[columns].fillna('nan')
 df_info = mount_df_info(df)
 df_info.sort_values(by='count_null', ascending=False ).head()
def load_embeddings(path):
with open(path)as f:
return dict(get_coefs(*line.strip().split(' ')) for line in f )<categorify>
df.loc[df[df['GarageYrBlt'] == 2207].index, 'GarageYrBlt'] = 2010
df['GarageYrBlt'] = df['GarageYrBlt'].fillna(0 ).astype(int)
 columns = ['GarageCond', 'GarageFinish', 'GarageQual', 'GarageType']
df[columns] = df[columns].fillna('nan')
 df_info = mount_df_info(df)
 df_info.sort_values(by='count_null', ascending=False ).head()
def build_matrix(word_index, path):
embedding_index = load_embeddings(path)
 embedding_matrix = np.zeros(( len(word_index)+ 1, 300))
for word, i in word_index.items() :
try:
embedding_matrix[i] = embedding_index[word]
except KeyError:
pass
return embedding_matrix<choose_model_class>
columns = ['BsmtCond', 'BsmtExposure', 'BsmtQual', 'BsmtFinType2', 'BsmtFinType1']
df[columns] = df[columns].fillna('nan')
 df_info = mount_df_info(df)
 df_info.sort_values(by='count_null', ascending=False ).head()
def build_model(embedding_matrix, num_aux_targets):
words = Input(shape=(MAX_LEN,))
x = Embedding(*embedding_matrix.shape, weights=[embedding_matrix], trainable=False )(words)
 x = SpatialDropout1D(0.3 )(x)
 x2 = Bidirectional(CuDNNLSTM(LSTM_UNITS, return_sequences=True))(x)
 x2 = Bidirectional(CuDNNLSTM(LSTM_UNITS, return_sequences=True))(x2)
 x1 = Bidirectional(CuDNNGRU(LSTM_UNITS, return_sequences=True))(x)
 x1 = Bidirectional(CuDNNGRU(LSTM_UNITS, return_sequences=True))(x1)
 x = add([x1, x2])
 hidden = concatenate([
GlobalMaxPooling1D()(x),
GlobalAveragePooling1D()(x),
])
 hidden = add([hidden, Dense(DENSE_HIDDEN_UNITS, activation='relu' )(hidden)])
 hidden = add([hidden, Dense(DENSE_HIDDEN_UNITS, activation='relu' )(hidden)])
 result = Dense(1, activation='sigmoid' )(hidden)
 aux_result = Dense(num_aux_targets, activation='sigmoid' )(hidden)
 model = Model(inputs=words, outputs=[result, aux_result])
 model.compile(
 loss='binary_crossentropy',
optimizer=Adam(clipnorm=0.1),
metrics=['accuracy'])
 return model<load_from_csv>
columns_disc = ['MSSubClass', 'MSZoning', 'Street', 'Alley', 'LotShape', 'LandContour', 'Utilities', 'LotConfig',
'LandSlope', 'Neighborhood', 'Condition1', 'Condition2', 'BldgType', 'HouseStyle', 'RoofStyle',
'RoofMatl', 'Exterior1st', 'Exterior2nd', 'MasVnrType', 'Foundation', 'BsmtExposure', 'BsmtFinType1',
'BsmtFinType2', 'Heating', 'CentralAir', 'Electrical', 'Functional', 'GarageType', 'GarageFinish',
'PavedDrive', 'Fence', 'MiscFeature', 'SaleType', 'SaleCondition']
columns_disc_qual = ['ExterQual', 'ExterCond', 'BsmtQual', 'BsmtCond', 'HeatingQC', 'KitchenQual', 'FireplaceQu',
'GarageQual', 'GarageCond', 'PoolQC']
columns_cont = ['LotFrontage', 'LotArea', 'OverallQual', 'OverallCond', 'MasVnrArea', 'BsmtFinSF1', 'BsmtFinSF2', 'BsmtUnfSF',
'TotalBsmtSF', '1stFlrSF', '2ndFlrSF', 'LowQualFinSF', 'GrLivArea', 'BsmtFullBath', 'BsmtHalfBath', 'FullBath',
'HalfBath', 'BedroomAbvGr', 'KitchenAbvGr', 'TotRmsAbvGrd', 'Fireplaces', 'GarageCars', 'GarageArea', 'WoodDeckSF',
'OpenPorchSF', 'EnclosedPorch', '3SsnPorch', 'ScreenPorch', 'PoolArea', 'MiscVal']
columns_year = ['YearBuilt', 'GarageYrBlt', 'YearRemodAdd', 'YrSold', 'MoSold']
print('Columns disc', len(columns_disc))
print('Columns disc to cont', len(columns_disc_qual))
print('Columns cont', len(columns_cont))
print('Columns year', len(columns_year))
train = pd.read_csv('.. /input/jigsaw-unintended-bias-in-toxicity-classification/train.csv')
 test = pd.read_csv('.. /input/jigsaw-unintended-bias-in-toxicity-classification/test.csv' )<prepare_x_and_y>
columns_disc = columns_disc + columns_disc_qual
x_train = train['comment_text'].fillna('' ).values
y_train = np.where(train['target'] >= 0.5, 1, 0)
 y_aux_train = train[['target', 'severe_toxicity', 'obscene', 'identity_attack', 'insult', 'threat']]
x_test = test['comment_text'].fillna('' ).values<train_model>
df_corr_disc = pd.DataFrame(columns=['feature', 'value', 'corr_with_sale_prices', 'count'])
 for _feature in columns_disc:
df_temp = pd.get_dummies(df_train[_feature])
 for _column in df_temp.columns:
_corr = stats.pointbiserialr(df_temp[_column], df_train['SalePrice'])
 df_corr_disc = df_corr_disc.append({'feature': _feature, 'value': _column, 'corr_with_sale_prices': _corr[0], 'count': sum(df_temp[_column])}, ignore_index=True)
 df_corr_disc.sort_values(by='corr_with_sale_prices' )
tokenizer = text.Tokenizer(num_words=MAX_FEATURES)
 tokenizer.fit_on_texts(list(x_train)+ list(x_test))<string_transform>
df_train['new_Fireplaces'] = df_train['Fireplaces'] * df_train['FireplaceQu'].map({'nan': 0, 'Po': 1, 'Fa': 2, 'TA': 3, 'Gd': 4, 'Ex': 5} ).astype(int)
 df['new_Fireplaces'] = df['Fireplaces'] * df['FireplaceQu'].map({'nan': 0, 'Po': 1, 'Fa': 2, 'TA': 3, 'Gd': 4, 'Ex': 5} ).astype(int)
 df_train[['new_Fireplaces', 'SalePrice']].corr(method='spearman' )
x_train = tokenizer.texts_to_sequences(x_train)
 x_test = tokenizer.texts_to_sequences(x_test)
 x_train = sequence.pad_sequences(x_train, maxlen=MAX_LEN)
 x_test = sequence.pad_sequences(x_test, maxlen=MAX_LEN )<concatenate>
df_temp = df_train[df_train['YearRemodAdd'] > df_train['YearBuilt']]
plt.hist(df_temp['YearRemodAdd'] - df_temp['YearBuilt'], bins=30)
 plt.show()
df_train['new_has_remod'] = df_train['YearRemodAdd'] > df_train['YearBuilt']
df_train['new_time_remod'] = df_train['YearRemodAdd'] - df_train['YearBuilt']
df['new_has_remod'] = df['YearRemodAdd'] > df['YearBuilt']
df['new_time_remod'] = df['YearRemodAdd'] - df['YearBuilt']
print(stats.pointbiserialr(df_train['new_has_remod'], df_train['SalePrice']))
df_train[['new_time_remod', 'SalePrice']].corr(method='spearman' )
embedding_matrix = np.concatenate(
 [build_matrix(tokenizer.word_index, f)for f in EMBEDDING_FILES], axis=-1 )<define_variables>
df_train['new_garage_after_build'] = df_train['GarageYrBlt'] > df_train['YearBuilt']
df['new_garage_after_build'] = df['GarageYrBlt'] > df['YearBuilt']
print(stats.pointbiserialr(df_train['new_garage_after_build'], df_train['SalePrice']))
checkpoint_predictions = []
weights = []<train_model>
df_train['new_totalSF'] = df_train['TotalBsmtSF'] + df_train['1stFlrSF'] + df_train['2ndFlrSF'] + df_train['GarageArea']
df['new_totalSF'] = df['TotalBsmtSF'] + df['1stFlrSF'] + df['2ndFlrSF'] + df['GarageArea']
df_train[['new_totalSF', 'TotalBsmtSF', '1stFlrSF', '2ndFlrSF', 'GarageArea', 'SalePrice']].corr(method='spearman' )
for model_idx in range(NUM_MODELS):
model = build_model(embedding_matrix, y_aux_train.shape[-1])
 for global_epoch in range(EPOCHS):
model.fit(
 x_train,
[y_train, y_aux_train],
batch_size=BATCH_SIZE,
epochs=1,
callbacks=[
LearningRateScheduler(lambda epoch: 1e-3 *(0.6 ** global_epoch))
] 
)
 checkpoint_predictions.append(model.predict(x_test, batch_size=2048)[0].flatten())
 weights.append(2 ** global_epoch )<prepare_output>
df_train['BsmtFullBath'] = df_train['BsmtFullBath'].astype(int)
 df['BsmtFullBath'] = df['BsmtFullBath'].astype(int)
 df_train['BsmtHalfBath'] = df_train['BsmtHalfBath'].astype(int)
 df['BsmtHalfBath'] = df['BsmtHalfBath'].astype(int)
 df_train['new_others_room'] = df_train['TotRmsAbvGrd'] - df_train['BedroomAbvGr'] - df_train['KitchenAbvGr']
df['new_others_room'] = df['TotRmsAbvGrd'] - df['BedroomAbvGr'] - df['KitchenAbvGr']
df_train['new_all_room'] = df_train['TotRmsAbvGrd'] + df_train['BsmtFullBath'] + df_train['BsmtHalfBath'] + df_train['FullBath'] + df_train['HalfBath']
df['new_all_room'] = df['TotRmsAbvGrd'] + df['BsmtFullBath'] + df['BsmtHalfBath'] + df['FullBath'] + df['HalfBath']
df_train[['TotRmsAbvGrd', 'BedroomAbvGr', 'KitchenAbvGr', 'BsmtFullBath', 'BsmtHalfBath', 'FullBath', 'HalfBath', 'new_others_room', 'new_all_room', 'SalePrice']].corr(method='spearman' )
predictions = np.average(checkpoint_predictions, weights=weights, axis=0 )<create_dataframe>
_df_temp = pd.DataFrame()
for _columns in columns_disc_qual:
_df_temp[_columns] = df[_columns].map({'nan': 0, 'Po': 1, 'Fa': 2, 'TA': 3, 'Gd': 4, 'Ex': 5} ).astype(int)
 df['new_overall'] = _df_temp[columns_disc_qual].sum(axis=1)/ len(columns_disc_qual )
submission = pd.DataFrame.from_dict({
'id': test['id'],
'prediction': predictions
})
<save_to_csv>
columns_disc = ['MSSubClass', 'MSZoning', 'Street', 'Alley', 'LotShape', 'LandContour', 'Utilities', 'LotConfig',
'LandSlope', 'Neighborhood', 'Condition1', 'Condition2', 'BldgType', 'HouseStyle', 'RoofStyle',
'RoofMatl', 'Exterior1st', 'Exterior2nd', 'MasVnrType', 'Foundation', 'BsmtExposure', 'BsmtFinType1',
'BsmtFinType2', 'Heating', 'CentralAir', 'Electrical', 'Functional', 'GarageType', 'GarageFinish',
'PavedDrive', 'Fence', 'MiscFeature', 'SaleType', 'SaleCondition', 'MoSold',
'ExterQual', 'ExterCond', 'BsmtQual', 'BsmtCond', 'HeatingQC', 'KitchenQual', 'FireplaceQu',
'GarageQual', 'GarageCond', 'PoolQC',
'new_has_remod', 'new_garage_after_build']
columns_cont = ['LotFrontage', 'LotArea', 'OverallQual', 'OverallCond', 'MasVnrArea', 'BsmtFinSF1', 'BsmtFinSF2', 'BsmtUnfSF',
'TotalBsmtSF', '1stFlrSF', '2ndFlrSF', 'LowQualFinSF', 'GrLivArea', 'BsmtFullBath', 'BsmtHalfBath', 'FullBath',
'HalfBath', 'BedroomAbvGr', 'KitchenAbvGr', 'TotRmsAbvGrd', 'Fireplaces', 'GarageCars', 'GarageArea', 'WoodDeckSF',
'OpenPorchSF', 'EnclosedPorch', '3SsnPorch', 'ScreenPorch', 'PoolArea', 'MiscVal',
'new_Fireplaces', 'new_time_remod', 'new_time_sold', 'new_totalSF', 'new_others_room', 'new_all_room', 'new_overall']
columns_year = ['YearBuilt', 'GarageYrBlt', 'YearRemodAdd', 'YrSold']
print('Columns disc', len(columns_disc))
print('Columns cont', len(columns_cont))
print('Columns year', len(columns_year))
submission.to_csv('submission.csv', index=False )<save_to_csv>
columns_cont = columns_cont + columns_year
submission.to_csv('submission.csv', index=False )<import_modules>
oneHot = OneHotEncoder(handle_unknown='ignore')
 df_onehot = oneHot.fit_transform(df[columns_disc] )
import gc
import re
import operator
import numpy as np
import pandas as pd
from gensim.models import KeyedVectors
from sklearn import model_selection
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.layers import Embedding, Input, Dense, CuDNNGRU,concatenate, Dropout, Bidirectional,CuDNNLSTM, SpatialDropout1D, Conv1D, GlobalAveragePooling1D, GlobalMaxPooling1D
from keras.optimizers import RMSprop, Adam
from keras.models import Model
from keras.callbacks import EarlyStopping
import seaborn as sns<load_from_csv>
df_disc = pd.DataFrame.sparse.from_spmatrix(df_onehot, columns=oneHot.get_feature_names(df[columns_disc].columns)).astype(bool ).reset_index()
df_cont = df[columns_cont].reset_index()
df_processed = pd.concat([df_cont, df_disc], sort=False, axis=1 ).drop(columns=['index'] )
train = pd.read_csv(".. /input/jigsaw-unintended-bias-in-toxicity-classification/train.csv")
 test = pd.read_csv(".. /input/jigsaw-unintended-bias-in-toxicity-classification/test.csv")
 print("Train shape : ",train.shape)
 print("Test shape : ",test.shape)
 train.head() 
<concatenate>
standard = StandardScaler()
df_processed[columns_cont] = standard.fit_transform(df_processed[columns_cont])
 transformer = FunctionTransformer(np.log1p)
 df_target = transformer.transform(df_target )
df = pd.concat([train[['id','comment_text']], test], axis=0)
 del(train, test)
 gc.collect()<load_pretrained>
def rmsqle(y, y_pred):
return np.sqrt(mean_squared_log_error(np.expm1(np.abs(y)) , np.expm1(np.abs(y_pred))))
ft_common_crawl = '.. /input/fasttext-crawl-300d-2m/crawl-300d-2M.vec'
embeddings_index = KeyedVectors.load_word2vec_format(ft_common_crawl )<set_options>
def evaluate(model, _X_test, _y_test):
_y_pred = model.predict(_X_test)
 return rmsqle(_y_test, _y_pred )
gc.collect()<feature_engineering>
def write_submission(_result):
df_to_submit = pd.read_csv('.. /input/house-prices-advanced-regression-techniques/sample_submission.csv')
 df_to_submit['SalePrice'] = np.expm1(_result)
 df_to_submit.to_csv('/kaggle/working/to_submit.csv', index=False)
 df_to_submit.head()
def build_vocab(texts):
sentences = texts.apply(lambda x: x.split() ).values
vocab = {}
for sentence in sentences:
for word in sentence:
try:
vocab[word] += 1
except KeyError:
vocab[word] = 1
return vocab<categorify>
rmsqle_score = make_scorer(rmsqle, greater_is_better=False )
def check_coverage(vocab, embeddings_index):
known_words = {}
unknown_words = {}
nb_known_words = 0
nb_unknown_words = 0
for word in vocab.keys() :
try:
known_words[word] = embeddings_index[word]
nb_known_words += vocab[word]
except:
unknown_words[word] = vocab[word]
nb_unknown_words += vocab[word]
pass
print('Found embeddings for {:.3%} of vocab'.format(len(known_words)/ len(vocab)))
 print('Found embeddings for {:.3%} of all text'.format(nb_known_words /(nb_known_words + nb_unknown_words)))
 unknown_words = sorted(unknown_words.items() , key=operator.itemgetter(1)) [::-1]
return unknown_words<feature_engineering>
columns_to_drop = ['MSSubClass_150', 'Utilities_nan', 'Functional_nan']
df_train.drop(columns=columns_to_drop, inplace=True)
 df_test.drop(columns=columns_to_drop, inplace=True )
df['comment_text'] = df['comment_text'].apply(lambda x: x.lower())
 gc.collect()<compute_train_metric>
X_train, X_test, y_train, y_test = train_test_split(df_train, df_target, test_size=0.25, random_state=random_state )
vocab = build_vocab(df['comment_text'])
 oov = check_coverage(vocab, embeddings_index)
 oov[:10]<set_options>
from xgboost import XGBRegressor, plot_importance
from lightgbm import LGBMRegressor
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
gc.collect()<define_variables>
xgb = XGBRegressor(colsample_bytree=0.4603, gamma=0.0468,
learning_rate=0.05, max_depth=3,
min_child_weight=1.7817, n_estimators=2200,
reg_alpha=0.4640, reg_lambda=0.8571,
subsample=0.5213,
random_state=7, nthread = -1)
 xgb.fit(X_train, y_train)
 print(rmsqle(xgb.predict(X_test), y_test))
contraction_mapping = {"ain't": "is not", "aren't": "are not","can't": "cannot", "'cause": "because", "could've": "could have", "couldn't": "could not", "didn't": "did not", "doesn't": "does not", "don't": "do not", "hadn't": "had not", "hasn't": "has not", "haven't": "have not", "he'd": "he would","he'll": "he will", "he's": "he is", "how'd": "how did", "how'd'y": "how do you", "how'll": "how will", "how's": "how is", "I'd": "I would", "I'd've": "I would have", "I'll": "I will", "I'll've": "I will have","I'm": "I am", "I've": "I have", "i'd": "i would", "i'd've": "i would have", "i'll": "i will", "i'll've": "i will have","i'm": "i am", "i've": "i have", "isn't": "is not", "it'd": "it would", "it'd've": "it would have", "it'll": "it will", "it'll've": "it will have","it's": "it is", "let's": "let us", "ma'am": "madam", "mayn't": "may not", "might've": "might have","mightn't": "might not","mightn't've": "might not have", "must've": "must have", "mustn't": "must not", "mustn't've": "must not have", "needn't": "need not", "needn't've": "need not have","o'clock": "of the clock", "oughtn't": "ought not", "oughtn't've": "ought not have", "shan't": "shall not", "sha'n't": "shall not", "shan't've": "shall not have", "she'd": "she would", "she'd've": "she would have", "she'll": "she will", "she'll've": "she will have", "she's": "she is", "should've": "should have", "shouldn't": "should not", "shouldn't've": "should not have", "so've": "so have","so's": "so as", "this's": "this is","that'd": "that would", "that'd've": "that would have", "that's": "that is", "there'd": "there would", "there'd've": "there would have", "there's": "there is", "here's": "here is","they'd": "they would", "they'd've": "they would have", "they'll": "they will", "they'll've": "they will have", "they're": "they are", "they've": "they have", "to've": "to have", "wasn't": "was not", "we'd": "we would", "we'd've": "we would have", "we'll": "we will", "we'll've": "we will have", "we're": "we are", "we've": "we have", "weren't": "were not", "what'll": "what will", "what'll've": "what will have", "what're": "what are", "what's": "what is", "what've": "what have", "when's": "when is", "when've": "when have", "where'd": "where did", "where's": "where is", "where've": "where have", "who'll": "who will", "who'll've": "who will have", "who's": "who is", "who've": "who have", "why's": "why is", "why've": "why have", "will've": "will have", "won't": "will not", "won't've": "will not have", "would've": "would have", "wouldn't": "would not", "wouldn't've": "would not have", "y'all": "you all", "y'all'd": "you all would","y'all'd've": "you all would have","y'all're": "you all are","y'all've": "you all have","you'd": "you would", "you'd've": "you would have", "you'll": "you will", "you'll've": "you will have", "you're": "you are", "you've": "you have" }<set_options>
lgbm = LGBMRegressor(objective='regression',num_leaves=5,
learning_rate=0.05, n_estimators=720,
max_bin = 55, bagging_fraction = 0.8,
bagging_freq = 5, feature_fraction = 0.2319,
feature_fraction_seed=9, bagging_seed=9,
min_data_in_leaf =6, min_sum_hessian_in_leaf = 11)
 lgbm.fit(X_train, y_train)
 print(rmsqle(lgbm.predict(X_test), y_test))
del(vocab,oov)
 gc.collect()<define_variables>
gradient = GradientBoostingRegressor(n_estimators=3000, learning_rate=0.05,
max_depth=4, max_features='sqrt',
min_samples_leaf=15, min_samples_split=10,
loss='huber', random_state =5)
 gradient.fit(X_train, y_train)
 print(rmsqle(gradient.predict(X_test), y_test))
<string_transform><EOS> 
predict_xgb = xgb.predict(df_test)
 predict_lgbm = lgbm.predict(df_test)
 predict_gradient = gradient.predict(df_test)
 predict_final =(predict_lgbm * 0.30 + predict_xgb * 0.50 + predict_gradient * 0.20)
 write_submission(predict_final )