Kaggle competition: House Prices - Advanced Regression Techniques
<SOS> metric: rmsle Kaggle data source: house-prices-advanced-regression-techniques<save_to_csv>
plt.style.use(['dark_background'])
 params = {'legend.fontsize': 'x-large',
'figure.figsize':(15, 5),
'axes.labelsize': 'small',
'axes.titlesize':'small',
'xtick.labelsize':'small',
'ytick.labelsize':'small'}
plt.rcParams.update(params )
search_result = threshold_search(y_train, train_preds)
 sub['prediction'] = test_preds.mean(1)> search_result['threshold']
sub.to_csv("submission.csv", index=False )<define_variables>
test = pd.read_csv(".. /input/house-prices-advanced-regression-techniques/test.csv")
 train = pd.read_csv(".. /input/house-prices-advanced-regression-techniques/train.csv" )
embed_size = 300
max_features = 95000
maxlen = 70<import_modules>
train['MSSubClass'] = train['MSSubClass'].apply(str)
 train['YrSold'] = train['YrSold'].astype(str)
 train['MoSold'] = train['MoSold'].astype(str)
 train['GarageYrBlt'] = train['GarageYrBlt'].astype(str)
 test['MSSubClass'] = test['MSSubClass'].apply(str)
 test['YrSold'] = test['YrSold'].astype(str)
 test['MoSold'] = test['MoSold'].astype(str)
 test['GarageYrBlt'] = test['GarageYrBlt'].astype(str )
import os
import time
import numpy as np
import pandas as pd
from tqdm import tqdm
import math
from sklearn.model_selection import train_test_split
from sklearn import metrics
from sklearn.model_selection import GridSearchCV, StratifiedKFold
from sklearn.metrics import f1_score, roc_auc_score
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.layers import Dense, Input, CuDNNLSTM, Embedding, Dropout, Activation, CuDNNGRU, Conv1D
from keras.layers import Bidirectional, GlobalMaxPool1D, GlobalMaxPooling1D, GlobalAveragePooling1D
from keras.layers import Input, Embedding, Dense, Conv2D, MaxPool2D, concatenate
from keras.layers import Reshape, Flatten, Concatenate, Dropout, SpatialDropout1D
from keras.optimizers import Adam
from keras.models import Model
from keras import backend as K
from keras.engine.topology import Layer
from keras import initializers, regularizers, constraints, optimizers, layers
from keras.layers import concatenate<load_from_csv>
def dbscan_outliers(var1,var2,dbscan_eps,dbscan_minsample,get_cluster_num):
plt.figure(figsize=(8,8))
scaler = RobustScaler()
scale_var1 = scaler.fit_transform(pd.DataFrame(( train[var1])) ).reshape(1,-1)[0]
scale_var2 = scaler.fit_transform(pd.DataFrame(( train[var2])) ).reshape(1,-1)[0]
df_temp = pd.DataFrame({"var1":scale_var1 , "var2":scale_var2})
 clustering = DBSCAN(eps=dbscan_eps, min_samples=dbscan_minsample ).fit(df_temp.values)
 df_temp["c"] = clustering.labels_
df_temp.index = train.index
sns.scatterplot(scale_var1,scale_var2, hue=clustering.labels_)
 return df_temp[df_temp["c"]==get_cluster_num].index
def load_and_prec() :
train_df = pd.read_csv(".. /input/train.csv")
 test_df = pd.read_csv(".. /input/test.csv")
 print("Train shape : ",train_df.shape)
 print("Test shape : ",test_df.shape)
 train_X = train_df["question_text"].fillna("_
test_X = test_df["question_text"].fillna("_
tokenizer = Tokenizer(num_words=max_features)
 tokenizer.fit_on_texts(list(train_X))
train_X = tokenizer.texts_to_sequences(train_X)
 test_X = tokenizer.texts_to_sequences(test_X)
 train_X = pad_sequences(train_X, maxlen=maxlen)
 test_X = pad_sequences(test_X, maxlen=maxlen)
 train_y = train_df['target'].values
np.random.seed(2018)
 trn_idx = np.random.permutation(len(train_X))
train_X = train_X[trn_idx]
train_y = train_y[trn_idx]
return train_X, test_X, train_y, tokenizer.word_index<statistical_test>
dropindex = dbscan_outliers("GrLivArea","SalePrice",dbscan_eps=.7,dbscan_minsample=10,get_cluster_num=-1)
 print(f"Outliers droped {len(dropindex)}")
 train.drop(dropindex,inplace=True )
def load_glove(word_index):
EMBEDDING_FILE = '.. /input/embeddings/glove.840B.300d/glove.840B.300d.txt'
def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32')
 embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(EMBEDDING_FILE))
all_embs = np.stack(embeddings_index.values())
 emb_mean,emb_std = all_embs.mean() , all_embs.std()
embed_size = all_embs.shape[1]
nb_words = min(max_features, len(word_index))
embedding_matrix = np.random.normal(emb_mean, emb_std,(nb_words, embed_size))
for word, i in word_index.items() :
if i >= max_features: continue
embedding_vector = embeddings_index.get(word)
 if embedding_vector is not None: embedding_matrix[i] = embedding_vector
return embedding_matrix
def load_fasttext(word_index):
EMBEDDING_FILE = '.. /input/embeddings/wiki-news-300d-1M/wiki-news-300d-1M.vec'
def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32')
 embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(EMBEDDING_FILE)if len(o)>100)
 all_embs = np.stack(embeddings_index.values())
 emb_mean,emb_std = all_embs.mean() , all_embs.std()
embed_size = all_embs.shape[1]
nb_words = min(max_features, len(word_index))
embedding_matrix = np.random.normal(emb_mean, emb_std,(nb_words, embed_size))
for word, i in word_index.items() :
if i >= max_features: continue
embedding_vector = embeddings_index.get(word)
 if embedding_vector is not None: embedding_matrix[i] = embedding_vector
return embedding_matrix
def load_para(word_index):
EMBEDDING_FILE = '.. /input/embeddings/paragram_300_sl999/paragram_300_sl999.txt'
def get_coefs(word,*arr): return word, np.asarray(arr, dtype='float32')
 embeddings_index = dict(get_coefs(*o.split(" ")) for o in open(EMBEDDING_FILE, encoding="utf8", errors='ignore')if len(o)>100)
 all_embs = np.stack(embeddings_index.values())
 emb_mean,emb_std = all_embs.mean() , all_embs.std()
embed_size = all_embs.shape[1]
nb_words = min(max_features, len(word_index))
embedding_matrix = np.random.normal(emb_mean, emb_std,(nb_words, embed_size))
for word, i in word_index.items() :
if i >= max_features: continue
embedding_vector = embeddings_index.get(word)
 if embedding_vector is not None: embedding_matrix[i] = embedding_vector
return embedding_matrix<choose_model_class>
quantitative_cols = [col for col in train.columns if train.dtypes[col] != 'object']
quantitative_cols.remove('SalePrice')
 quantitative_cols.remove('Id')
 qualitative_cols = [col for col in train.columns if train.dtypes[col] == 'object']
print(f"Quantitative columns({len(quantitative_cols)}): {quantitative_cols}", end="
"*2)
 print(f"Quanlitative columns({len(qualitative_cols)}): {qualitative_cols}")
class Attention(Layer):
def __init__(self, step_dim,
W_regularizer=None, b_regularizer=None,
W_constraint=None, b_constraint=None,
bias=True, **kwargs):
self.supports_masking = True
self.init = initializers.get('glorot_uniform')
 self.W_regularizer = regularizers.get(W_regularizer)
 self.b_regularizer = regularizers.get(b_regularizer)
 self.W_constraint = constraints.get(W_constraint)
 self.b_constraint = constraints.get(b_constraint)
 self.bias = bias
self.step_dim = step_dim
self.features_dim = 0
super(Attention, self ).__init__(**kwargs)
 def build(self, input_shape):
assert len(input_shape)== 3
self.W = self.add_weight(( input_shape[-1],),
initializer=self.init,
name='{}_W'.format(self.name),
regularizer=self.W_regularizer,
constraint=self.W_constraint)
 self.features_dim = input_shape[-1]
if self.bias:
self.b = self.add_weight(( input_shape[1],),
initializer='zero',
name='{}_b'.format(self.name),
regularizer=self.b_regularizer,
constraint=self.b_constraint)
 else:
self.b = None
self.built = True
def compute_mask(self, input, input_mask=None):
return None
def call(self, x, mask=None):
features_dim = self.features_dim
step_dim = self.step_dim
eij = K.reshape(K.dot(K.reshape(x,(-1, features_dim)) ,
K.reshape(self.W,(features_dim, 1))),(-1, step_dim))
if self.bias:
eij += self.b
eij = K.tanh(eij)
 a = K.exp(eij)
 if mask is not None:
a *= K.cast(mask, K.floatx())
 a /= K.cast(K.sum(a, axis=1, keepdims=True)+ K.epsilon() , K.floatx())
 a = K.expand_dims(a)
 weighted_input = x * a
return K.sum(weighted_input, axis=1)
 def compute_output_shape(self, input_shape):
return input_shape[0], self.features_dim<choose_model_class>
all_data = pd.concat(( train.loc[:,'MSSubClass':'SaleCondition'],
test.loc[:,'MSSubClass':'SaleCondition']))
def model_lstm_atten(embedding_matrix):
inp = Input(shape=(maxlen,))
x = Embedding(max_features, embed_size, weights=[embedding_matrix], trainable=False )(inp)
 x = Bidirectional(CuDNNLSTM(40, return_sequences=True))(x)
 x = Bidirectional(CuDNNGRU(40, return_sequences=True))(x)
 atten = Attention(maxlen )(x)
 avg_pool = GlobalAveragePooling1D()(x)
 max_pool = GlobalMaxPooling1D()(x)
 conc = concatenate([atten, avg_pool, max_pool])
 conc = Dense(64, activation="relu" )(conc)
 conc = Dropout(0.1 )(conc)
 outp = Dense(1, activation="sigmoid" )(conc)
 model = Model(inputs=inp, outputs=outp)
 model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
 return model<predict_on_test>
all_data["PoolQC"].fillna("NoPool", inplace=True)
 all_data["MiscFeature"].fillna("NOMiscFeature", inplace=True)
 all_data["Alley"].fillna("NOAlley", inplace=True)
 all_data["Fence"].fillna("NOFence", inplace=True)
 all_data["FireplaceQu"].fillna("NOFireplaceQu", inplace=True)
 all_data["GarageCond"].fillna("NOGarageCond", inplace=True)
 all_data["GarageQual"].fillna("NOGarageQual", inplace=True)
 all_data["GarageYrBlt"].fillna("NOGarageYrBlt", inplace=True)
 all_data["GarageFinish"].fillna("NOGarageFinish", inplace=True)
 all_data["GarageType"].fillna("NOGarageType", inplace=True)
 all_data["BsmtCond"].fillna("NOBsmtCond", inplace=True)
 all_data["BsmtExposure"].fillna("NOBsmtExposure", inplace=True)
 all_data["BsmtQual"].fillna("NOBsmtQual", inplace=True)
 all_data["BsmtFinType2"].fillna("NOBsmtFinType2", inplace=True)
 all_data["BsmtFinType1"].fillna("NOBsmtFinType1", inplace=True)
 all_data["LotFrontage"] = all_data.groupby("Neighborhood")["LotFrontage"].transform(lambda x: x.fillna(x.median()))
all_data["BsmtFinSF2"] = all_data.groupby("Neighborhood")["BsmtFinSF2"].transform(lambda x: x.fillna(x.median()))
all_data["BsmtFinSF1"] = all_data.groupby("Neighborhood")["BsmtFinSF1"].transform(lambda x: x.fillna(x.median()))
all_data["MasVnrType"] = all_data.groupby("Neighborhood")["MasVnrType"].transform(lambda x: x.fillna(x.mode().values[0]))
all_data["MasVnrArea"] = all_data.groupby("Neighborhood")["MasVnrArea"].transform(lambda x: x.fillna(x.mean()))
all_data["MSZoning"] = all_data.groupby("Neighborhood")["MSZoning"].transform(lambda x: x.fillna(x.mode().values[0]))
all_data["Exterior2nd"] = all_data.groupby("Neighborhood")["Exterior2nd"].transform(lambda x: x.fillna(x.mode().values[0]))
all_data["BsmtUnfSF"] = all_data.groupby("Neighborhood")["BsmtUnfSF"].transform(lambda x: x.fillna(x.median()))
all_data["TotalBsmtSF"] = all_data.groupby("Neighborhood")["TotalBsmtSF"].transform(lambda x: x.fillna(x.median()))
all_data["Exterior1st"] = all_data.groupby("Neighborhood")["Exterior1st"].transform(lambda x: x.fillna(x.mode().values[0]))
all_data["SaleType"] = all_data.groupby("Neighborhood")["SaleType"].transform(lambda x: x.fillna(x.mode().values[0]))
all_data["Electrical"] = all_data.groupby("Neighborhood")["Electrical"].transform(lambda x: x.fillna(x.mode().values[0]))
all_data["KitchenQual"] = all_data.groupby("Neighborhood")["KitchenQual"].transform(lambda x: x.fillna(x.mode().values[0]))
all_data["GarageArea"] = all_data.groupby("Neighborhood")["GarageArea"].transform(lambda x: x.fillna(x.median()))
all_data["GarageCars"] = all_data.groupby("Neighborhood")["GarageCars"].transform(lambda x: x.fillna(x.mode().values[0]))
all_data["Functional"] = all_data["Functional"].fillna("Typ")
 all_data["BsmtHalfBath"].fillna(0, inplace=True)
 all_data["BsmtFullBath"].fillna(0, inplace=True)
 all_data = all_data.drop(['Utilities'], axis=1)
def train_pred(model, train_X, train_y, val_X, val_y, epochs=2):
for e in range(epochs):
model.fit(train_X, train_y, batch_size=512, epochs=1, validation_data=(val_X, val_y))
pred_val_y = model.predict([val_X], batch_size=1024, verbose=0)
 best_thresh = 0.5
best_score = 0.0
for thresh in np.arange(0.1, 0.501, 0.01):
thresh = np.round(thresh, 2)
 score = metrics.f1_score(val_y,(pred_val_y > thresh ).astype(int))
if score > best_score:
best_thresh = thresh
best_score = score
print("Val F1 Score: {:.4f}".format(best_score))
pred_test_y = model.predict([test_X], batch_size=1024, verbose=0)
 return pred_val_y, pred_test_y, best_score<split>
all_data = pd.get_dummies(all_data )
train_X, test_X, train_y, word_index = load_and_prec()
embedding_matrix_1 = load_glove(word_index)
 embedding_matrix_3 = load_para(word_index )<normalization>
X_train = all_data[:train.shape[0]]
X_test = all_data[train.shape[0]:]
y = train.SalePrice
embedding_matrix = np.mean([embedding_matrix_1, embedding_matrix_3], axis = 0)
 np.shape(embedding_matrix )<compute_train_metric>
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import make_pipeline
from sklearn.pipeline import Pipeline
from sklearn.model_selection import KFold
def threshold_search(y_true, y_proba):
best_threshold = 0
best_score = 0
for threshold in [i * 0.01 for i in range(100)]:
score = f1_score(y_true=y_true, y_pred=y_proba > threshold)
 if score > best_score:
best_threshold = threshold
best_score = score
search_result = {'threshold': best_threshold, 'f1': best_score}
return search_result<predict_on_test>
kf = KFold(n_splits=12, random_state=42, shuffle=True)
 ridge_alphas = [1e-8, 9e-4, 7e-4, 5e-4, 3e-4, 1e-4, 1e-3, 5e-2, 1e-2, 0.1, 0.3, 1, 3, 5, 10, 15, 18, 20, 30, 50, 75, 100]
param_grid = {'model__alpha':ridge_alphas}
ridge = Pipeline(steps=[('standardscaler', RobustScaler()), 
('model', Ridge(max_iter=1e7)) ])
 search_ridge = GridSearchCV(ridge, param_grid,cv=kf,scoring="neg_mean_squared_error")
 search_ridge.fit(X_train, y)
 np.sqrt(search_ridge.best_score_*-1 )
DATA_SPLIT_SEED = 2018
train_meta = np.zeros(train_y.shape)
 test_meta = np.zeros(test_X.shape[0])
 splits = list(StratifiedKFold(n_splits=5, shuffle=True, random_state=DATA_SPLIT_SEED ).split(train_X, train_y))
for idx,(train_idx, valid_idx)in enumerate(splits):
X_train = train_X[train_idx]
y_train = train_y[train_idx]
X_val = train_X[valid_idx]
y_val = train_y[valid_idx]
model = model_lstm_atten(embedding_matrix)
 pred_val_y, pred_test_y, best_score = train_pred(model, X_train, y_train, X_val, y_val, epochs = 4)
 train_meta[valid_idx] = pred_val_y.reshape(-1)
 test_meta += pred_test_y.reshape(-1)/ len(splits )<save_to_csv>
cv_result = pd.DataFrame(search_ridge.cv_results_["params"])
 cv_result["score"] = np.sqrt(search_ridge.cv_results_["mean_test_score"]*-1)
 cv_result.plot(x="model__alpha",y="score");
search_result = threshold_search(train_y, train_meta)
 print(search_result)
 sub = pd.read_csv('.. /input/sample_submission.csv')
 sub.prediction = test_meta > search_result['threshold']
sub.to_csv("submission.csv", index=False )<import_modules>
alphas = np.array([ 0.01,0.005,0.001,0.0001,0.00001])
 param_grid = {'model__alpha':alphas}
lasso = Pipeline(steps=[('standardscaler', RobustScaler()), 
('model', Lasso(max_iter=1e5)) ])
 search_lasso = GridSearchCV(lasso, param_grid,cv=10,scoring="neg_mean_squared_error")
 search_lasso.fit(X_train, y)
 np.sqrt(search_lasso.best_score_*-1 )
import logging
from nltk import word_tokenize
import pandas as pd
import numpy as np
import gc
import os
import torch
from torch import nn
from torch.autograd import Variable
import torch.nn.functional as F
from torch.nn.utils.rnn import pad_sequence
from sklearn.metrics import f1_score
from torch import optim
import torchtext
import random<load_from_csv>
cv_result = pd.DataFrame(search_lasso.cv_results_["params"])
 cv_result["score"] = np.sqrt(search_lasso.cv_results_["mean_test_score"]*-1)
 cv_result.plot(x="model__alpha",y="score" )
text = torchtext.data.Field(lower=True, batch_first=True, tokenize=word_tokenize)
 qid = torchtext.data.Field()
target = torchtext.data.Field(sequential=False, use_vocab=False, is_target=True)
 train = torchtext.data.TabularDataset(path='.. /input/train.csv', format='csv',
fields={'question_text':('text',text),
'target':('target',target)})
 test = torchtext.data.TabularDataset(path='.. /input/test.csv', format='csv',
fields={'qid':('qid', qid),
'question_text':('text', text)} )<find_best_params>
lasso_coef = pd.DataFrame(search_lasso.best_estimator_["model"].coef_,columns=["coef"])
 lasso_coef["col"] = X_train.columns
<split><EOS> 
pred = search_lasso.best_estimator_.predict(X_test)
 df_result = pd.DataFrame(np.expm1(pred),columns=["SalePrice"])
 df_result["Id"] = test.Id
df_result.to_csv("submit.csv",index=False)