Kaggle competition: House Prices - Advanced Regression Techniques
<SOS> metric: rmsle Kaggle data source: house-prices-advanced-regression-techniques<create_dataframe>
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import scipy
from sklearn.preprocessing import RobustScaler
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import Lasso
from sklearn.linear_model import Ridge
from sklearn.linear_model import ElasticNet
from sklearn.kernel_ridge import KernelRidge
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor
import xgboost as xgb
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
num_folds = 11
features = [c for c in train.columns if c not in ['ID_code', 'target']]
folds = KFold(n_splits=num_folds, random_state=2319)
 oof = np.zeros(len(train))
getVal = np.zeros(len(train))
predictions = np.zeros(len(target))
feature_importance_df = pd.DataFrame()<split>
df_train = pd.read_csv('.. /input/train.csv')
 df_test = pd.read_csv('.. /input/test.csv' )
for fold_,(trn_idx, val_idx)in enumerate(folds.split(train.values, target.values)) :
X_train, y_train = train.iloc[trn_idx][features], target.iloc[trn_idx]
X_valid, y_valid = train.iloc[val_idx][features], target.iloc[val_idx]
X_tr, y_tr = augment(X_train.values, y_train.values)
 X_tr = pd.DataFrame(X_tr)
 print("Fold idx:{}".format(fold_ + 1))
trn_data = lgb.Dataset(X_tr, label=y_tr)
 val_data = lgb.Dataset(X_valid, label=y_valid)
 clf = lgb.train(param, trn_data, 1000000, valid_sets = [trn_data, val_data], verbose_eval=5000, early_stopping_rounds = 4000)
 oof[val_idx] = clf.predict(train.iloc[val_idx][features], num_iteration=clf.best_iteration)
 getVal[val_idx]+= clf.predict(train.iloc[val_idx][features], num_iteration=clf.best_iteration)/ folds.n_splits
fold_importance_df = pd.DataFrame()
fold_importance_df["feature"] = features
fold_importance_df["importance"] = clf.feature_importance()
fold_importance_df["fold"] = fold_ + 1
feature_importance_df = pd.concat([feature_importance_df, fold_importance_df], axis=0)
 predictions += clf.predict(test[features], num_iteration=clf.best_iteration)/ folds.n_splits<compute_test_metric>
df_train['DataType'], df_test['DataType'] = 'training', 'testing'
df_test.insert(df_test.shape[1] - 1, 'SalePrice', np.nan)
 df_data = pd.concat([df_train, df_test], ignore_index=True )
print("
>> CV score: {:<8.5f}".format(roc_auc_score(target, oof)) )<save_to_csv>
col_convert = ['MSSubClass']
df_data[col_convert] = df_data[col_convert].astype('object' )
submission = pd.DataFrame({"ID_code": test.ID_code.values})
 submission["target"] = predictions
submission.to_csv("submission.csv", index=False )<load_from_csv>
df_data['SalePrice'] = np.log1p(df_data['SalePrice'] )
df_train = pd.read_csv('.. /input/train.csv')
 df_test = pd.read_csv('.. /input/test.csv' )<prepare_x_and_y>
df_data['MiscVal'] = np.log1p(df_data['MiscVal'] )
train_df = df_train.copy()
test_df = df_test.copy()
train_df.drop(columns=["ID_code", "target"], inplace=True)
 test_df.drop(columns=["ID_code"], inplace=True)
 target = df_train.target<randomize_order>
df_data['LotFrontage'] = df_data['LotFrontage'].fillna(df_data.groupby(['Neighborhood'])['LotFrontage'].transform('mean'))
df_data.loc[(df_data['LotFrontage'] > 200)&(df_data['DataType'] == 'trainnig'), 'DataType'] = 'excluded'
def augment_train(df_train, y_train):
t0 = df_train[y_train == 0].copy()
t1 = df_train[y_train == 1].copy()
i = 0
N = 3
for I in range(2):
for col in df_train.columns:
i = i + 1000
np.random.seed(i)
 np.random.shuffle(t0[col].values)
 np.random.shuffle(t1[col].values)
 df_train = pd.concat([df_train, t0.copy() ])
 df_train = pd.concat([df_train, t1.copy() ])
 y_train = pd.concat([y_train, pd.Series([0] * t0.shape[0]), pd.Series([1] * t1.shape[0])])
 return df_train, y_train<choose_model_class>
df_data.loc[(df_data['LotArea'] > 100000)&(df_data['DataType'] == 'training'), 'DataType'] = 'excluded'
model = CatBoostClassifier(subsample=0.36,
custom_loss='Logloss',
random_strength = 0,
max_depth=3,
eval_metric="AUC",
learning_rate=0.01,
iterations=60000,
bootstrap_type='Bernoulli',
l2_leaf_reg=0.3,
task_type="GPU",
random_seed=432013,
od_type="Iter",
border_count=128
)<split>
df_data.loc[(df_data['BsmtFinSF1'] > 4000)&(df_data['DataType'] == 'training'), 'DataType'] = 'excluded'
def run_cat(model, trt, tst, tar,n_splits=11, plot=False):
kf = KFold(n_splits=n_splits, random_state=432013, shuffle=True)
 oof = np.zeros(len(trt))
feature_importance_df = pd.DataFrame()
y_valid_pred = 0 * tar
y_test_pred = 0
for n_fold,(train_index, valid_index)in enumerate(kf.split(trt, tar)) :
y_train, y_valid = tar.iloc[train_index], tar.iloc[valid_index]
X_train, X_valid = trt.iloc[train_index,:], trt.iloc[valid_index,:]
X_train, y_train = augment_train(X_train, y_train)
 _train = Pool(X_train, label=y_train)
 _valid = Pool(X_valid, label=y_valid)
 print("Fold ", n_fold)
 fit_model = model.fit(_train,
verbose_eval=1000,
early_stopping_rounds=1000,
eval_set=[_valid],
use_best_model=True,
plot=False, 
)
 pred = fit_model.predict_proba(X_valid)[:,1]
oof[valid_index] = pred
print("auc = ", roc_auc_score(y_valid, pred))
y_valid_pred.iloc[valid_index] = pred
y_test_pred += fit_model.predict_proba(tst)[:,1]
y_test_pred /= n_splits
print("average auc:", roc_auc_score(tar, oof))
return y_test_pred, oof<concatenate>
df_data.loc[(df_data['TotalBsmtSF'] > 5000)&(df_data['DataType'] == 'training'), 'DataType'] = 'excluded'
y_test_pred, oof = run_cat(model,train_df, test_df, target )<save_to_csv>
df_data.loc[(df_data['1stFlrSF'] > 4000)&(df_data['DataType'] == 'training'), 'DataType'] = 'excluded'
submission = pd.read_csv(".. /input/sample_submission.csv")
 submission['target'] = y_test_pred
pd.Series(oof ).to_csv("Cat_oof.csv", index = False)
 submission.to_csv('submission.csv', index=False )<set_options>
df_data.loc[(df_data['GrLivArea'] > 4500)&(df_data['DataType'] == 'training'), 'DataType'] = 'excluded'
warnings.filterwarnings('ignore')
<compute_test_metric>
df_data.loc[(df_data['OpenPorchSF'] > 500)&(df_data['SalePrice'] < 11)&(df_data['DataType'] == 'training'), 'DataType'] = 'excluded'
def focal_loss(alpha=0.25,gamma=5.0):
def focal_crossentropy(y_true, y_pred):
bce = K.binary_crossentropy(y_true, y_pred)
 y_pred = K.clip(y_pred, K.epsilon() , 1.- K.epsilon())
 p_t =(y_true*y_pred)+(( 1-y_true)*(1-y_pred))
alpha_t = y_true*alpha +(( 1-alpha)*(1-y_true))
return K.mean(alpha_t*K.pow(( 1-p_t), gamma)*bce, axis=-1)
 return focal_crossentropy
def auc(y_true, y_pred):
auc = tf.metrics.auc(y_true, y_pred,num_thresholds=10000)[1]
K.get_session().run(tf.local_variables_initializer())
 return auc<set_options>
col_convert = ['LotArea', 'MasVnrArea', 'BsmtFinSF1', 'BsmtFinSF2', 'BsmtUnfSF', 'TotalBsmtSF',
'1stFlrSF', '2ndFlrSF', 'LowQualFinSF', 'GrLivArea', 'GarageArea',
'WoodDeckSF', 'OpenPorchSF', 'EnclosedPorch', '3SsnPorch', 'ScreenPorch', 'PoolArea']
df_data[col_convert] = df_data[col_convert].fillna(0)
 df_data['TotalSF'] = df_data['TotalBsmtSF'] + df_data['GrLivArea']
df_data['TotalPorch'] = df_data['OpenPorchSF'] + df_data['EnclosedPorch'] + df_data['3SsnPorch'] + df_data['ScreenPorch']
df_data['TotalArea'] = df_data['TotalSF'] + df_data['TotalPorch'] + df_data['GarageArea'] + df_data['WoodDeckSF']
K.tensorflow_backend._get_available_gpus()<load_from_csv>
col_convert = ['BsmtFullBath', 'BsmtHalfBath', 'FullBath', 'HalfBath',
'BedroomAbvGr', 'KitchenAbvGr', 'TotRmsAbvGrd']
df_data[col_convert] = df_data[col_convert].fillna(0)
 df_data['TotalBathBsmt'] = df_data['BsmtFullBath'] + 0.5 * df_data['BsmtHalfBath']
df_data['TotalBathAbvGrd'] = df_data['FullBath'] + 0.5 * df_data['HalfBath']
df_data['TotalRmsAbvGrdIncBath'] = df_data['TotRmsAbvGrd'] + df_data['TotalBathAbvGrd']
df_data['TotalRms'] = df_data['TotalRmsAbvGrdIncBath'] + df_data['TotalBathBsmt']
test_df = pd.read_csv(".. /input/test.csv")
 train_df = pd.read_csv(".. /input/train.csv")
 submission = pd.read_csv(".. /input/sample_submission.csv" )<concatenate>
df_data['AreaPerRmsBsmt'] = df_data['TotalBsmtSF'] /(df_data['TotalBathBsmt'] + 1)
 df_data['AreaPerRmsGrLivAbvGrd'] = df_data['GrLivArea'] /(df_data['TotalRmsAbvGrdIncBath'] + 1)
 df_data['AreaPerRmsTotal'] = df_data['TotalSF'] /(df_data['TotalRms'] + 1 )
train_df = train_df.assign(isTrain = True)
 test_df = test_df.assign(isTrain=False)
 full_df = pd.concat([train_df,test_df],sort=False )<normalization>
col_convert = ['ExterQual', 'ExterCond', 'BsmtQual', 'BsmtCond', 'HeatingQC',
'KitchenQual', 'FireplaceQu', 'GarageQual', 'GarageCond', 'PoolQC']
df_data[col_convert] = df_data[col_convert].replace('Ex', 5 ).replace('Gd', 4 ).replace('TA', 3 ).replace('Fa', 2 ).replace('Po', 1 ).replace('NA', 0)
 df_data[col_convert] = df_data[col_convert].fillna(0 ).astype(int)
 df_data['ExterQualCond'] = df_data['ExterQual'] * df_data['ExterCond']
df_data['BsmtQualCond'] = df_data['BsmtQual'] * df_data['BsmtCond']
df_data['GarageQualCond'] = df_data['GarageQual'] * df_data['GarageCond']
df_data['OverallQualCond'] = df_data['OverallQual'] * df_data['OverallCond']
scaler = MinMaxScaler()
X=scaler.fit_transform(full_df.loc[:,'var_0':'var_199'].values,range(-1,1))<prepare_x_and_y>
col_convert = ['BsmtExposure']
df_data[col_convert] = df_data[col_convert].replace('Gd', 4 ).replace('Av', 3 ).replace('Mn', 2 ).replace('No', 1 ).replace('NA', 0)
 df_data[col_convert] = df_data[col_convert].fillna(0 ).astype(int )
x = X[full_df.isTrain]
y = full_df[full_df.isTrain].target
x_test = X[~full_df.isTrain]<categorify>
col_convert = ['BsmtFinType1', 'BsmtFinType2']
df_data[col_convert] = df_data[col_convert].replace('GLQ', 6 ).replace('ALQ', 5 ).replace('BLQ', 4 ).replace('Rec', 3 ).replace('LwQ', 2 ).replace('Unf', 1 ).replace('NA', 0)
 df_data[col_convert] = df_data[col_convert].fillna(0 ).astype(int )
input_data = Input(shape=(X.shape[1],))
encoded = Dense(128, activation='relu' )(input_data)
 encoded = Dense(4, activation='relu' )(encoded)
 encoded = Dense(128, activation='relu' )(encoded)
 decoded = Dense(X.shape[1], activation='tanh' )(encoded)
 autoencoder = Model(input_data, decoded)
 autoencoder.compile(optimizer='adam', loss='mean_squared_error' )<categorify>
col_convert = ['GarageFinish']
df_data[col_convert] = df_data[col_convert].replace('Fin', 3 ).replace('RFn', 2 ).replace('Unf', 1 ).replace('NA', 0)
 df_data[col_convert] = df_data[col_convert].fillna(0 ).astype(int )
autoencoder.fit(X,X, epochs=10, batch_size=512, shuffle=True )<predict_on_test>
col_convert = ['Fence']
df_data[col_convert] = df_data[col_convert].replace('GdPrv', 4 ).replace('MnPrv', 3 ).replace('GdWo', 2 ).replace('MnWw', 1 ).replace('NA', 0)
 df_data[col_convert] = df_data[col_convert].fillna(0 ).astype(int )
x = np.insert(x,-1,np.mean(np.power(x - autoencoder.predict(x), 2), axis=1),axis=1)
 x_test = np.insert(x_test,-1,np.mean(np.power(x_test - autoencoder.predict(x_test), 2), axis=1),axis=1 )<define_variables>
df_data['GarageYrBlt'] = df_data['GarageYrBlt'].fillna(df_data['YearBuilt'])
 df_data['YearBuiltRemod'] = df_data['YearRemodAdd'] - df_data['YearBuilt']
df_data['YearBuiltSold'] = df_data['YrSold'] - df_data['YearBuilt']
df_data['YearRemodSold'] = df_data['YrSold'] - df_data['YearRemodAdd']
df_data['YearGarageSold'] = df_data['YrSold'] - df_data['GarageYrBlt']
folds = StratifiedKFold(n_splits=10, shuffle=False, random_state=42)
 oof = np.zeros(len(train_df))
predictions = np.zeros(len(test_df))<init_hyperparams>
df_data['Utilities'] = df_data['Utilities'].fillna('ELO' )
param = {
'bagging_freq': 5,
'bagging_fraction': 0.33,
'boost_from_average':'false',
'boost': 'gbdt',
'feature_fraction': 0.04,
'learning_rate': 0.01,
'max_depth': -1,
'metric':'auc',
'min_data_in_leaf': 80,
'min_sum_hessian_in_leaf': 10.0,
'num_leaves': 13,
'num_threads': 8,
'tree_learner': 'serial',
'objective': 'binary',
'verbosity': 1
}<predict_on_test>
df_data['SaleType'] = df_data['SaleType'].fillna('Oth' )
for fold_,(trn_idx, val_idx)in enumerate(folds.split(x, y)) :
print("Fold {}".format(fold_))
trn_data = lgb.Dataset(x[trn_idx], label=y[trn_idx])
 val_data = lgb.Dataset(x[val_idx], label=y[val_idx])
 clf = lgb.train(param, trn_data, 1000000, valid_sets = [trn_data, val_data], verbose_eval=2500, early_stopping_rounds = 100)
 oof[val_idx] = clf.predict(x[val_idx], num_iteration=clf.best_iteration)
 predictions += clf.predict(x_test, num_iteration=clf.best_iteration)/ folds.n_splits
print("CV score: {:<8.5f}".format(roc_auc_score(y, oof)) )<save_to_csv>
col_fillnas = ['MSZoning', 'Exterior1st', 'Exterior2nd', 'MasVnrType', 'Electrical', 'Functional']
for col_fillna in col_fillnas: df_data[col_fillna] = df_data[col_fillna].fillna(df_data[col_fillna].value_counts().idxmax() )
submission = test_df.loc[:,['ID_code','target']]
submission['target'] = predictions
submission.to_csv("submission_16.csv", index=False )<load_from_csv>
col_fillnas = ['Alley', 'GarageType']
for col_fillna in col_fillnas: df_data[col_fillna] = df_data[col_fillna].fillna('NA' )
training = pd.read_csv(".. /input/train.csv", index_col=0)
 test = pd.read_csv(".. /input/test.csv", index_col=0)
 print(training.shape)
 print(test.shape)
 training = training.replace(-999999,np.nan)
 training=training.replace(9999999999,np.nan)
 X = training.iloc[:,:-1]
y = training.TARGET
X_train, X_test, y_train, y_test = cross_validation.train_test_split(X, y, stratify=y, test_size=0.3)
 ratio = float(np.sum(y == 1)) / np.sum(y==0)
 X_train, X_test, y_train, y_test = cross_validation.train_test_split(X, y, stratify=y, test_size=0.3)
 xgbooster = xgb.XGBClassifier(missing=np.nan,
max_depth = 5,
n_estimators=1000,
learning_rate=0.1,
nthread=4,
subsample=1.0,
colsample_bytree=0.5,
min_child_weight = 3,
scale_pos_weight = ratio,
reg_alpha=0.03,
seed=234)
 scorestrain=[]
scorescv=[]
iterations=[]
for i in range(1000,len(X_train),3000):
print(i)
 xgbooster.fit(X_train[:i], y_train[:i], early_stopping_rounds=50, eval_metric="auc",
eval_set=[(X_test, y_test)])
 scorestrain.append(roc_auc_score(y_train[:i], xgbooster.predict_proba(X_train[:i], ntree_limit=xgbooster.best_iteration)[:,1]))
scorescv.append(roc_auc_score(y_test,xgbooster.predict_proba(X_test,ntree_limit=xgbooster.best_iteration)[:,1]))
iterations.append(i)

plt.figure(figsize=(15,10))
plt.plot(iterations,scorestrain,'r')
 plt.plot(iterations,scorescv, 'b')
 plt.ylim(0.8,0.9)
 plt.xlim(1000,55000)
 plt.xlabel('
plt.ylabel('AUC')
 plt.legend(['Training Set','CV set'],loc='lower right')
<define_variables>
col_fillnas = ['GarageCars', 'MiscFeature']
df_data[col_fillnas] = df_data[col_fillnas].fillna(0 )
package_dir = ".. /input/ppbert/pytorch-pretrained-bert/pytorch-pretrained-BERT"
sys.path.append(package_dir )<import_modules>
col_number = df_data.select_dtypes(include=['number'] ).columns.drop(['MiscVal', 'SalePrice', 'YearBuiltRemod', 'YearBuiltSold', 'YearRemodSold', 'YearGarageSold'] ).tolist()
for col_transform in col_number:
skewness = scipy.stats.skew(df_data[col_transform].dropna())
 if skewness > 0.75: df_data[col_transform] = np.log1p(df_data[col_transform] )
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import fastai
from fastai.train import Learner
from fastai.train import DataBunch
from fastai.callbacks import *
from fastai.basic_data import DatasetType
import fastprogress
from fastprogress import force_console_behavior
import numpy as np
from pprint import pprint
import pandas as pd
import os
import time
import gc
import random
from tqdm._tqdm_notebook import tqdm_notebook as tqdm
from keras.preprocessing import text, sequence
import torch
from torch import nn
from torch.utils import data
from torch.nn import functional as F
import torch.utils.data
from tqdm import tqdm
import warnings
from pytorch_pretrained_bert import BertTokenizer, BertForSequenceClassification, BertAdam
from pytorch_pretrained_bert import BertConfig
from nltk.tokenize.treebank import TreebankWordTokenizer
from scipy.stats import rankdata
from gensim.models import KeyedVectors<string_transform>
df_data['SalePrice'] = df_data['SalePrice'].fillna(0 )
def convert_lines(example, max_seq_length,tokenizer):
max_seq_length -=2
all_tokens = []
longer = 0
for text in tqdm(example):
tokens_a = tokenizer.tokenize(text)
 if len(tokens_a)>max_seq_length:
tokens_a = tokens_a[:max_seq_length]
longer += 1
one_token = tokenizer.convert_tokens_to_ids(["[CLS]"]+tokens_a+["[SEP]"])+[0] *(max_seq_length - len(tokens_a))
all_tokens.append(one_token)
 return np.array(all_tokens)
 def is_interactive() :
return 'SHLVL' not in os.environ
def seed_everything(seed=123):
random.seed(seed)
 os.environ['PYTHONHASHSEED'] = str(seed)
 np.random.seed(seed)
 torch.manual_seed(seed)
 torch.cuda.manual_seed(seed)
 torch.backends.cudnn.deterministic = True
def get_coefs(word, *arr):
return word, np.asarray(arr, dtype='float32')
 def load_embeddings(path):
emb_arr = KeyedVectors.load(path)
 return emb_arr
def build_matrix(word_index, path):
embedding_index = load_embeddings(path)
 embedding_matrix = np.zeros(( max_features + 1, 300))
unknown_words = []
for word, i in word_index.items() :
if i <= max_features:
try:
embedding_matrix[i] = embedding_index[word]
except KeyError:
try:
embedding_matrix[i] = embedding_index[word.lower() ]
except KeyError:
try:
embedding_matrix[i] = embedding_index[word.title() ]
except KeyError:
unknown_words.append(word)
 return embedding_matrix, unknown_words
def sigmoid(x):
return 1 /(1 + np.exp(-x))
class SpatialDropout(nn.Dropout2d):
def forward(self, x):
x = x.unsqueeze(2)
 x = x.permute(0, 3, 2, 1)
 x = super(SpatialDropout, self ).forward(x)
 x = x.permute(0, 3, 2, 1)
 x = x.squeeze(2)
 return x
def train_model(learn,test,output_dim,lr=0.001,
batch_size=512, n_epochs=4,
enable_checkpoint_ensemble=True):
all_test_preds = []
checkpoint_weights = [2 ** epoch for epoch in range(n_epochs)]
test_loader = torch.utils.data.DataLoader(test, batch_size=batch_size, shuffle=False)
 n = len(learn.data.train_dl)
 phases = [(TrainingPhase(n ).schedule_hp('lr', lr *(0.3**(i)))) for i in range(n_epochs)]
sched = GeneralScheduler(learn, phases)
 learn.callbacks.append(sched)
 for epoch in range(n_epochs):
learn.fit(1)
 test_preds = np.zeros(( len(test), output_dim))
for i, x_batch in enumerate(test_loader):
X = x_batch[0].cuda()
y_pred = sigmoid(learn.model(X ).detach().cpu().numpy())
 test_preds[i * batch_size:(i+1)* batch_size, :] = y_pred
all_test_preds.append(test_preds)
 if enable_checkpoint_ensemble:
test_preds = np.average(all_test_preds, weights=checkpoint_weights, axis=0)
 else:
test_preds = all_test_preds[-1]
return test_preds
def handle_punctuation(x):
x = x.translate(remove_dict)
 x = x.translate(isolate_dict)
 return x
def handle_contractions(x):
x = tokenizer.tokenize(x)
 return x
def fix_quote(x):
x = [x_[1:] if x_.startswith("'")else x_ for x_ in x]
x = ' '.join(x)
 return x
def preprocess(x):
x = handle_punctuation(x)
 x = handle_contractions(x)
 x = fix_quote(x)
 return x
class SequenceBucketCollator() :
def __init__(self, choose_length, sequence_index, length_index, label_index=None):
self.choose_length = choose_length
self.sequence_index = sequence_index
self.length_index = length_index
self.label_index = label_index
def __call__(self, batch):
batch = [torch.stack(x)for x in list(zip(*batch)) ]
sequences = batch[self.sequence_index]
lengths = batch[self.length_index]
length = self.choose_length(lengths)
 mask = torch.arange(start=maxlen, end=0, step=-1)< length
padded_sequences = sequences[:, mask]
batch[self.sequence_index] = padded_sequences
if self.label_index is not None:
return [x for i, x in enumerate(batch)if i != self.label_index], batch[self.label_index]
return batch
class NeuralNet(nn.Module):
def __init__(self, embedding_matrix, num_aux_targets):
super(NeuralNet, self ).__init__()
embed_size = embedding_matrix.shape[1]
self.embedding = nn.Embedding(max_features, embed_size)
 self.embedding.weight = nn.Parameter(torch.tensor(embedding_matrix, dtype=torch.float32))
self.embedding.weight.requires_grad = False
self.embedding_dropout = SpatialDropout(0.3)
 self.lstm1 = nn.LSTM(embed_size, LSTM_UNITS, bidirectional=True, batch_first=True)
 self.lstm2 = nn.LSTM(LSTM_UNITS * 2, LSTM_UNITS, bidirectional=True, batch_first=True)
 self.linear1 = nn.Linear(DENSE_HIDDEN_UNITS, DENSE_HIDDEN_UNITS)
 self.linear2 = nn.Linear(DENSE_HIDDEN_UNITS, DENSE_HIDDEN_UNITS)
 self.linear_out = nn.Linear(DENSE_HIDDEN_UNITS, 1)
 self.linear_aux_out = nn.Linear(DENSE_HIDDEN_UNITS, num_aux_targets)
 def forward(self, x, lengths=None):
h_embedding = self.embedding(x.long())
 h_embedding = self.embedding_dropout(h_embedding)
 h_lstm1, _ = self.lstm1(h_embedding)
 h_lstm2, _ = self.lstm2(h_lstm1)
 avg_pool = torch.mean(h_lstm2, 1)
 max_pool, _ = torch.max(h_lstm2, 1)
 h_conc = torch.cat(( max_pool, avg_pool), 1)
 h_conc_linear1 = F.relu(self.linear1(h_conc))
h_conc_linear2 = F.relu(self.linear2(h_conc))
hidden = h_conc + h_conc_linear1 + h_conc_linear2
result = self.linear_out(hidden)
 aux_result = self.linear_aux_out(hidden)
 out = torch.cat([result, aux_result], 1)
 return out
def custom_loss(data, targets):
bce_loss_1 = nn.BCEWithLogitsLoss(weight=targets[:,1:2] )(data[:,:1],targets[:,:1])
 bce_loss_2 = nn.BCEWithLogitsLoss()(data[:,1:],targets[:,2:])
 return(bce_loss_1 * loss_weight)+ bce_loss_2
def reduce_mem_usage(df):
start_mem = df.memory_usage().sum() / 1024**2
print('Memory usage of dataframe is {:.2f} MB'.format(start_mem))
for col in df.columns:
col_type = df[col].dtype
if col_type != object:
c_min = df[col].min()
c_max = df[col].max()
if str(col_type)[:3] == 'int':
if c_min > np.iinfo(np.int8 ).min and c_max < np.iinfo(np.int8 ).max:
df[col] = df[col].astype(np.int8)
 elif c_min > np.iinfo(np.int16 ).min and c_max < np.iinfo(np.int16 ).max:
df[col] = df[col].astype(np.int16)
 elif c_min > np.iinfo(np.int32 ).min and c_max < np.iinfo(np.int32 ).max:
df[col] = df[col].astype(np.int32)
 elif c_min > np.iinfo(np.int64 ).min and c_max < np.iinfo(np.int64 ).max:
df[col] = df[col].astype(np.int64)
 else:
if c_min > np.finfo(np.float16 ).min and c_max < np.finfo(np.float16 ).max:
df[col] = df[col].astype(np.float16)
 elif c_min > np.finfo(np.float32 ).min and c_max < np.finfo(np.float32 ).max:
df[col] = df[col].astype(np.float32)
 else:
df[col] = df[col].astype(np.float64)
 else:
df[col] = df[col].astype('category')
 end_mem = df.memory_usage().sum() / 1024**2
print('Memory usage after optimization is: {:.2f} MB'.format(end_mem))
print('Decreased by {:.1f}%'.format(100 *(start_mem - end_mem)/ start_mem))
return df
def ensemble_predictions(predictions, weights, type_="linear"):
assert np.isclose(np.sum(weights), 1.0)
 if type_ == "linear":
res = np.average(predictions, weights=weights, axis=0)
 elif type_ == "harmonic":
res = np.average([1 / p for p in predictions], weights=weights, axis=0)
 return 1 / res
elif type_ == "geometric":
numerator = np.average(
 [np.log(p)for p in predictions], weights=weights, axis=0 
)
 res = np.exp(numerator / sum(weights))
return res
elif type_ == "rank":
res = np.average([rankdata(p)for p in predictions], weights=weights, axis=0)
 return res /(len(res)+ 1)
 return res<set_options>
df_data = pd.get_dummies(df_data, columns=None, drop_first=True )
warnings.filterwarnings(action='once')
 device = torch.device('cuda')
 MAX_SEQUENCE_LENGTH = 300
SEED = 1234
BATCH_SIZE = 512
BERT_MODEL_PATH = '.. /input/bert-pretrained-models/uncased_l-12_h-768_a-12/uncased_L-12_H-768_A-12/'
np.random.seed(SEED)
 torch.manual_seed(SEED)
 torch.cuda.manual_seed(SEED)
 torch.backends.cudnn.deterministic = True
bert_config = BertConfig('.. /input/bert-inference/bert-inference/bert_config.json')
 tokenizer = BertTokenizer.from_pretrained(BERT_MODEL_PATH, cache_dir=None,do_lower_case=True)
 tqdm.pandas()
CRAWL_EMBEDDING_PATH = '.. /input/gensim-embeddings-dataset/crawl-300d-2M.gensim'
GLOVE_EMBEDDING_PATH = '.. /input/gensim-embeddings-dataset/glove.840B.300d.gensim'
NUM_MODELS = 2
LSTM_UNITS = 128
DENSE_HIDDEN_UNITS = 4 * LSTM_UNITS
MAX_LEN = 220
if not is_interactive() :
def nop(it, *a, **k):
return it
tqdm = nop
fastprogress.fastprogress.NO_BAR = True
master_bar, progress_bar = force_console_behavior()
fastai.basic_train.master_bar, fastai.basic_train.progress_bar = master_bar, progress_bar
seed_everything()<load_from_csv>
x = df_data[df_data['DataType_training'] == 1].drop(['Id', 'SalePrice', 'DataType_training', 'DataType_testing'], axis=1)
 y = df_data.loc[df_data['DataType_training'] == 1, 'SalePrice']
test_df = pd.read_csv(".. /input/jigsaw-unintended-bias-in-toxicity-classification/test.csv")
 test_df['comment_text'] = test_df['comment_text'].astype(str)
 X_test = convert_lines(test_df["comment_text"].fillna("DUMMY_VALUE"), MAX_SEQUENCE_LENGTH, tokenizer )<load_pretrained>
lassoreg = Lasso(alpha=1e-5 ).fit(x, y)
 feat = pd.DataFrame(data=lassoreg.coef_, index=x.columns, columns=['FeatureImportances'] ).sort_values(['FeatureImportances'], ascending=False )
model = BertForSequenceClassification(bert_config, num_labels=1)
 model.load_state_dict(torch.load(".. /input/bert-inference/bert-inference/bert_pytorch.bin"))
model.to(device)
 for param in model.parameters() :
param.requires_grad = False
model.eval()<categorify>
x = df_data.loc[df_data['DataType_training'] == 1, model_feat]
y = df_data.loc[df_data['DataType_training'] == 1, 'SalePrice']
test_preds = np.zeros(( len(X_test)))
 test = torch.utils.data.TensorDataset(torch.tensor(X_test, dtype=torch.long))
test_loader = torch.utils.data.DataLoader(test, batch_size=512, shuffle=False)
 tk0 = tqdm(test_loader)
 for i,(x_batch,)in enumerate(tk0):
pred = model(x_batch.to(device), attention_mask=(x_batch > 0 ).to(device), labels=None)
 test_preds[i * 512:(i + 1)* 512] = pred[:, 0].detach().cpu().squeeze().numpy()
test_pred = torch.sigmoid(torch.tensor(test_preds)).numpy().ravel()<create_dataframe>
scaler = RobustScaler()
x = scaler.fit_transform(x )
submission_bert_plain = pd.DataFrame.from_dict({
'id': test_df['id'],
'prediction': test_pred
} )<load_from_csv>
x_train, x_validate, y_train, y_validate = train_test_split(x, y, test_size=0.25, random_state=58 )
train_df = reduce_mem_usage(pd.read_csv('.. /input/jigsaw-unintended-bias-in-toxicity-classification/train.csv'))<define_variables>
model_linreg = LinearRegression()
model_linreg.fit(x_train, y_train)
 model_linreg_ypredict = model_linreg.predict(x_validate)
 model_linreg_rmse = mean_squared_error(y_validate, model_linreg_ypredict)** 0.5
model_linreg_cvscores = np.sqrt(np.abs(cross_val_score(model_linreg, x, y, cv=5, scoring='neg_mean_squared_error')))
 print('linear regression
root mean squared error: %0.4f, cross validation score: %0.4f(+/- %0.4f)' %(model_linreg_rmse, model_linreg_cvscores.mean() , 2 * model_linreg_cvscores.std()))
symbols_to_isolate = '.,?!-;*"…:—() %
symbols_to_delete = '
🍕\r🐵😑\xa0\ue014\t\uf818\uf04a\xad😢🐶️\uf0e0😜😎👊\u200b\u200e😁عدويهصقأناخلىبمغر😍💖💵Е👎😀😂\u202a\u202c🔥😄🏻💥ᴍʏʀᴇɴᴅᴏᴀᴋʜᴜʟᴛᴄᴘʙғᴊᴡɢ😋👏שלוםבי😱‼\x81エンジ故障\u2009🚌ᴵ͞🌟😊😳😧🙀😐😕\u200f👍😮😃😘אעכח💩💯⛽🚄🏼ஜ😖ᴠ🚲‐😟😈💪🙏🎯🌹😇💔😡\x7f👌ἐὶήιὲκἀίῃἴξ🙄Ｈ😠\ufeff\u2028😉😤⛺🙂\u3000تحكسة👮💙فزط😏🍾🎉😞\u2008🏾😅😭👻😥😔😓🏽🎆🍻🍽🎶🌺🤔😪\x08‑🐰🐇🐱🙆😨🙃💕𝘊𝘦𝘳𝘢𝘵𝘰𝘤𝘺𝘴𝘪𝘧𝘮𝘣💗💚地獄谷улкнПоАН🐾🐕😆ה🔗🚽歌舞伎🙈😴🏿🤗🇺🇸мυтѕ⤵🏆🎃😩\u200a🌠🐟💫💰💎эпрд\x95🖐🙅⛲🍰🤐👆🙌\u2002💛🙁👀🙊🙉\u2004ˢᵒʳʸᴼᴷᴺʷᵗʰᵉᵘ\x13🚬🤓\ue602😵άοόςέὸתמדףנרךצט😒͝🆕👅👥👄🔄🔤👉👤👶👲🔛🎓\uf0b7\uf04c\x9f\x10成都😣⏺😌🤑🌏😯ех😲Ἰᾶὁ💞🚓🔔📚🏀👐\u202d💤🍇\ue613小土豆🏡❔⁉\u202f👠》कर्मा🇹🇼🌸蔡英文🌞🎲レクサス😛外国人关系Сб💋💀🎄💜🤢َِьыгя不是\x9c\x9d🗑\u2005💃📣👿༼つ༽😰ḷЗз▱ц￼🤣卖温哥华议会下降你失去所有的钱加拿大坏税骗子🐝ツ🎅\x85🍺آإشء🎵🌎͟ἔ油别克🤡🤥😬🤧й\u2003🚀🤴ʲшчИОРФДЯМюж😝🖑ὐύύ特殊作戦群щ💨圆明园קℐ🏈😺🌍⏏ệ🍔🐮🍁🍆🍑🌮🌯🤦\u200d𝓒𝓲𝓿𝓵안영하세요ЖљКћ🍀😫🤤ῦ我出生在了可以说普通话汉语好极🎼🕺🍸🥂🗽🎇🎊🆘🤠👩🖒🚪天一家⚲\u2006⚭⚆⬭⬯⏖新✀╌🇫🇷🇩🇪🇮🇬🇧😷🇨🇦ХШ🌐\x1f杀鸡给猴看ʁ𝗪𝗵𝗲𝗻𝘆𝗼𝘂𝗿𝗮𝗹𝗶𝘇𝗯𝘁𝗰𝘀𝘅𝗽𝘄𝗱📺ϖ\u2000үսᴦᎥһͺ\u2007հ\u2001ɩｙｅ൦ｌƽｈ𝐓𝐡𝐞𝐫𝐮𝐝𝐚𝐃𝐜𝐩𝐭𝐢𝐨𝐧Ƅᴨןᑯ໐ΤᏧ௦Іᴑ܁𝐬𝐰𝐲𝐛𝐦𝐯𝐑𝐙𝐣𝐇𝐂𝐘𝟎ԜТᗞ౦〔Ꭻ𝐳𝐔𝐱𝟔𝟓𝐅🐋ﬃ💘💓ё𝘥𝘯𝘶💐🌋🌄🌅𝙬𝙖𝙨𝙤𝙣𝙡𝙮𝙘𝙠𝙚𝙙𝙜𝙧𝙥𝙩𝙪𝙗𝙞𝙝𝙛👺🐷ℋ𝐀𝐥𝐪🚶𝙢Ἱ🤘ͦ💸ج패티Ｗ𝙇ᵻ👂👃ɜ🎫\uf0a7БУі🚢🚂ગુજરાતીῆ🏃𝓬𝓻𝓴𝓮𝓽𝓼☘﴾̯﴿₽\ue807𝑻𝒆𝒍𝒕𝒉𝒓𝒖𝒂𝒏𝒅𝒔𝒎𝒗𝒊👽😙\u200cЛ‒🎾👹⎌🏒⛸公寓养宠物吗🏄🐀🚑🤷操美𝒑𝒚𝒐𝑴🤙🐒欢迎来到阿拉斯ספ𝙫🐈𝒌𝙊𝙭𝙆𝙋𝙍𝘼𝙅ﷻ🦄巨收赢得白鬼愤怒要买额ẽ🚗🐳𝟏𝐟𝟖𝟑𝟕𝒄𝟗𝐠𝙄𝙃👇锟斤拷𝗢𝟳𝟱𝟬⦁マルハニチロ株式社⛷한국어ㄸㅓ니͜ʖ𝘿𝙔₵𝒩ℯ𝒾𝓁𝒶𝓉𝓇𝓊𝓃𝓈𝓅ℴ𝒻𝒽𝓀𝓌𝒸𝓎𝙏ζ𝙟𝘃𝗺𝟮𝟭𝟯𝟲👋🦊多伦🐽🎻🎹⛓🏹🍷🦆为和中友谊祝贺与其想象对法如直接问用自己猜本传教士没积唯认识基督徒曾经让相信耶稣复活死怪他但当们聊些政治题时候战胜因圣把全堂结婚孩恐惧且栗谓这样还♾🎸🤕🤒⛑🎁批判检讨🏝🦁🙋😶쥐스탱트뤼도석유가격인상이경제황을렵게만들지않록잘관리해야합다캐나에서대마초와화약금의품런성분갈때는반드시허된사용🔫👁凸ὰ💲🗯𝙈Ἄ𝒇𝒈𝒘𝒃𝑬𝑶𝕾𝖙𝖗𝖆𝖎𝖌𝖍𝖕𝖊𝖔𝖑𝖉𝖓𝖐𝖜𝖞𝖚𝖇𝕿𝖘𝖄𝖛𝖒𝖋𝖂𝕴𝖟𝖈𝕸👑🚿💡知彼百\uf005𝙀𝒛𝑲𝑳𝑾𝒋𝟒😦𝙒𝘾𝘽🏐𝘩𝘨ὼṑ𝑱𝑹𝑫𝑵𝑪🇰🇵👾ᓇᒧᔭᐃᐧᐦᑳᐨᓃᓂᑲᐸᑭᑎᓀᐣ🐄🎈🔨🐎🤞🐸💟🎰🌝🛳点击查版🍭𝑥𝑦𝑧ＮＧ👣\uf020っ🏉ф💭🎥Ξ🐴👨🤳🦍\x0b🍩𝑯𝒒😗𝟐🏂👳🍗🕉🐲چی𝑮𝗕𝗴🍒ꜥⲣⲏ🐑⏰鉄リ事件ї💊「」\uf203\uf09a\uf222\ue608\uf202\uf099\uf469\ue607\uf410\ue600燻製シ虚偽屁理屈Г𝑩𝑰𝒀𝑺🌤𝗳𝗜𝗙𝗦𝗧🍊ὺἈἡχῖΛ⤏🇳𝒙ψՁմեռայինրւդձ冬至ὀ𝒁🔹🤚🍎𝑷🐂💅𝘬𝘱𝘸𝘷𝘐𝘭𝘓𝘖𝘹𝘲𝘫کΒώ💢ΜΟΝΑΕ🇱♲𝝈↴💒⊘Ȼ🚴🖕🖤🥘📍👈➕🚫🎨🌑🐻𝐎𝐍𝐊𝑭🤖🎎😼🕷ｇｒｎｔｉｄｕｆｂｋ𝟰🇴🇭🇻🇲𝗞𝗭𝗘𝗤👼📉🍟🍦🌈🔭《🐊🐍\uf10aლڡ🐦\U0001f92f\U0001f92a🐡💳ἱ🙇𝗸𝗟𝗠𝗷🥜さようなら🔼'<feature_engineering>
model_lassoreg = Lasso(alpha=0.001, max_iter=1024)
 model_lassoreg.fit(x_train, y_train)
 model_lassoreg_ypredict = model_lassoreg.predict(x_validate)
 model_lassoreg_rmse = mean_squared_error(y_validate, model_lassoreg_ypredict)** 0.5
model_lassoreg_cvscores = np.sqrt(np.abs(cross_val_score(model_lassoreg, x, y, cv=5, scoring='neg_mean_squared_error')))
 print('lasso regression
root mean squared error: %0.4f, cross validation score: %0.4f(+/- %0.4f)' %(model_lassoreg_rmse, model_lassoreg_cvscores.mean() , 2 * model_lassoreg_cvscores.std()))
tokenizer = TreebankWordTokenizer()
isolate_dict = {ord(c):f' {c} ' for c in symbols_to_isolate}
remove_dict = {ord(c):f'' for c in symbols_to_delete}<prepare_x_and_y>
params = {'alpha': np.logspace(-4, 4, base=10, num=9),
'max_iter': [1024],
}
model_lassoreg_cv = GridSearchCV(model_lassoreg, params, iid=False, cv=5)
 model_lassoreg_cv.fit(x_train, y_train)
 model_lassoreg_cv_ypredict = model_lassoreg_cv.predict(x_validate)
 model_lassoreg_cv_rmse = mean_squared_error(y_validate, model_lassoreg_cv_ypredict)** 0.5
model_lassoreg_cv_cvscores = np.sqrt(np.abs(cross_val_score(model_lassoreg_cv, x, y, cv=5, scoring='neg_mean_squared_error')))
 print('lasso regression grid search
root mean squared error: %0.4f, cross validation score: %0.4f(+/- %0.4f)' %(model_lassoreg_cv_rmse, model_lassoreg_cv_cvscores.mean() , 2 * model_lassoreg_cv_cvscores.std()))
print(' best parameters: %s' %model_lassoreg_cv.best_params_ )
x_train = train_df['comment_text'].progress_apply(lambda x:preprocess(x))
y_aux_train = train_df[['target', 'severe_toxicity', 'obscene', 'identity_attack', 'insult', 'threat']]
x_test = test_df['comment_text'].progress_apply(lambda x:preprocess(x))
identity_columns = [
'male', 'female', 'homosexual_gay_or_lesbian', 'christian', 'jewish',
'muslim', 'black', 'white', 'psychiatric_or_mental_illness']
weights = np.ones(( len(x_train),)) / 4
weights +=(train_df[identity_columns].fillna(0 ).values>=0.5 ).sum(axis=1 ).astype(bool ).astype(np.int)/ 4
weights +=(((train_df['target'].values>=0.5 ).astype(bool ).astype(np.int)+ 
(train_df[identity_columns].fillna(0 ).values<0.5 ).sum(axis=1 ).astype(bool ).astype(np.int)) > 1 ).astype(bool ).astype(np.int)/ 4
weights +=(((train_df['target'].values<0.5 ).astype(bool ).astype(np.int)+ 
(train_df[identity_columns].fillna(0 ).values>=0.5 ).sum(axis=1 ).astype(bool ).astype(np.int)) > 1 ).astype(bool ).astype(np.int)/ 4
loss_weight = 1.0 / weights.mean()
y_train = np.vstack([(train_df['target'].values>=0.5 ).astype(np.int),weights] ).T
max_features = 410047<string_transform>
model_ridgereg = Ridge(alpha=10)
 model_ridgereg.fit(x_train, y_train)
 model_ridgereg_ypredict = model_ridgereg.predict(x_validate)
 model_ridgereg_rmse = mean_squared_error(y_validate, model_ridgereg_ypredict)** 0.5
model_ridgereg_cvscores = np.sqrt(np.abs(cross_val_score(model_ridgereg, x, y, cv=5, scoring='neg_mean_squared_error')))
 print('ridge regression
root mean squared error: %0.4f, cross validation score: %0.4f(+/- %0.4f)' %(model_ridgereg_rmse, model_ridgereg_cvscores.mean() , 2 * model_ridgereg_cvscores.std()))
tokenizer = text.Tokenizer(num_words = max_features, filters='',lower=False )<train_model>
params = {'alpha': np.logspace(-4, 4, base=10, num=9)}
model_ridgereg_cv = GridSearchCV(model_ridgereg, params, iid=False, cv=5)
 model_ridgereg_cv.fit(x_train, y_train)
 model_ridgereg_cv_ypredict = model_ridgereg_cv.predict(x_validate)
 model_ridgereg_cv_rmse = mean_squared_error(y_validate, model_ridgereg_cv_ypredict)** 0.5
model_ridgereg_cv_cvscores = np.sqrt(np.abs(cross_val_score(model_ridgereg_cv, x, y, cv=5, scoring='neg_mean_squared_error')))
 print('ridge regression grid search
root mean squared error: %0.4f, cross validation score: %0.4f(+/- %0.4f)' %(model_ridgereg_cv_rmse, model_ridgereg_cv_cvscores.mean() , 2 * model_ridgereg_cv_cvscores.std()))
print(' best parameters: %s' %model_ridgereg_cv.best_params_ )
tokenizer.fit_on_texts(list(x_train)+ list(x_test))
crawl_matrix, unknown_words_crawl = build_matrix(tokenizer.word_index, CRAWL_EMBEDDING_PATH)
 print('n unknown words(crawl): ', len(unknown_words_crawl))
glove_matrix, unknown_words_glove = build_matrix(tokenizer.word_index, GLOVE_EMBEDDING_PATH)
 print('n unknown words(glove): ', len(unknown_words_glove))
max_features = max_features or len(tokenizer.word_index)+ 1
max_features
embedding_matrix = np.concatenate([crawl_matrix, glove_matrix], axis=-1)
 embedding_matrix.shape
del crawl_matrix
del glove_matrix
gc.collect()
y_train_torch = torch.tensor(np.hstack([y_train, y_aux_train]), dtype=torch.float32 )<string_transform>
model_elasticnetreg = ElasticNet(alpha=0.1, l1_ratio=0.1, max_iter=1024)
 model_elasticnetreg.fit(x_train, y_train)
 model_elasticnetreg_ypredict = model_elasticnetreg.predict(x_validate)
 model_elasticnetreg_rmse = mean_squared_error(y_validate, model_elasticnetreg_ypredict)** 0.5
model_elasticnetreg_cvscores = np.sqrt(np.abs(cross_val_score(model_elasticnetreg, x, y, cv=5, scoring='neg_mean_squared_error')))
 print('elastic net regression
root mean squared error: %0.4f, cross validation score: %0.4f(+/- %0.4f)' %(model_elasticnetreg_rmse, model_elasticnetreg_cvscores.mean() , 2 * model_elasticnetreg_cvscores.std()))
x_train = tokenizer.texts_to_sequences(x_train)
 x_test = tokenizer.texts_to_sequences(x_test )<categorify>
params = {'alpha': np.logspace(-4, 4, base=10, num=9),
'l1_ratio': np.linspace(0.1, 0.9, num=5),
'max_iter': [1024],
}
model_elasticnetreg_cv = GridSearchCV(model_elasticnetreg, params, iid=False, cv=5)
 model_elasticnetreg_cv.fit(x_train, y_train)
 model_elasticnetreg_cv_ypredict = model_elasticnetreg_cv.predict(x_validate)
 model_elasticnetreg_cv_rmse = mean_squared_error(y_validate, model_elasticnetreg_cv_ypredict)** 0.5
model_elasticnetreg_cv_cvscores = np.sqrt(np.abs(cross_val_score(model_elasticnetreg_cv, x, y, cv=5, scoring='neg_mean_squared_error')))
 print('elastic net regression grid search
root mean squared error: %0.4f, cross validation score: %0.4f(+/- %0.4f)' %(model_elasticnetreg_cv_rmse, model_elasticnetreg_cv_cvscores.mean() , 2 * model_elasticnetreg_cv_cvscores.std()))
print(' best parameters: %s' %model_elasticnetreg_cv.best_params_ )
lengths = torch.from_numpy(np.array([len(x)for x in x_train]))
maxlen = 300
x_train_padded = torch.from_numpy(sequence.pad_sequences(x_train, maxlen=maxlen))<categorify>
model_kernelridgereg = KernelRidge(alpha=0.1, kernel='polynomial', degree=2)
 model_kernelridgereg.fit(x_train, y_train)
 model_kernelridgereg_ypredict = model_kernelridgereg.predict(x_validate)
 model_kernelridgereg_rmse = mean_squared_error(y_validate, model_kernelridgereg_ypredict)** 0.5
model_kernelridgereg_cvscores = np.sqrt(np.abs(cross_val_score(model_kernelridgereg, x, y, cv=5, scoring='neg_mean_squared_error')))
 print('kernel ridge regression
root mean squared error: %0.4f, cross validation score: %0.4f(+/- %0.4f)' %(model_kernelridgereg_rmse, model_kernelridgereg_cvscores.mean() , 2 * model_kernelridgereg_cvscores.std()))
test_lengths = torch.from_numpy(np.array([len(x)for x in x_test]))
x_test_padded = torch.from_numpy(sequence.pad_sequences(x_test, maxlen=maxlen))<create_dataframe>
params = {'alpha': np.logspace(-4, 4, base=10, num=9),
'degree': [1, 2, 3, 4, 5],
}
model_kernelridgereg_cv = GridSearchCV(model_kernelridgereg, params, iid=False, cv=5)
 model_kernelridgereg_cv.fit(x_train, y_train)
 model_kernelridgereg_cv_ypredict = model_kernelridgereg_cv.predict(x_validate)
 model_kernelridgereg_cv_rmse = mean_squared_error(y_validate, model_kernelridgereg_cv_ypredict)** 0.5
model_kernelridgereg_cv_cvscores = np.sqrt(np.abs(cross_val_score(model_kernelridgereg_cv, x, y, cv=5, scoring='neg_mean_squared_error')))
 print('kernel ridge regression grid search
root mean squared error: %0.4f, cross validation score: %0.4f(+/- %0.4f)' %(model_kernelridgereg_cv_rmse, model_kernelridgereg_cv_cvscores.mean() , 2 * model_kernelridgereg_cv_cvscores.std()))
print(' best parameters: %s' %model_kernelridgereg_cv.best_params_ )
batch_size = 512
test_dataset = data.TensorDataset(x_test_padded, test_lengths)
 train_dataset = data.TensorDataset(x_train_padded, lengths, y_train_torch)
 valid_dataset = data.Subset(train_dataset, indices=[0, 1])
 train_collator = SequenceBucketCollator(lambda lenghts: lenghts.max() ,
sequence_index=0,
length_index=1,
label_index=2)
 test_collator = SequenceBucketCollator(lambda lenghts: lenghts.max() , sequence_index=0, length_index=1)
 train_loader = data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True, collate_fn=train_collator)
 valid_loader = data.DataLoader(valid_dataset, batch_size=batch_size, shuffle=False, collate_fn=train_collator)
 test_loader = data.DataLoader(test_dataset, batch_size=batch_size, shuffle=False, collate_fn=test_collator)
 databunch = DataBunch(train_dl=train_loader, valid_dl=valid_loader, collate_fn=train_collator )<choose_model_class>
model_treereg = DecisionTreeRegressor(splitter='best', min_samples_split=5)
 model_treereg.fit(x_train, y_train)
 model_treereg_ypredict = model_treereg.predict(x_validate)
 model_treereg_rmse = mean_squared_error(y_validate, model_treereg_ypredict)** 0.5
model_treereg_cvscores = np.sqrt(np.abs(cross_val_score(model_treereg, x, y, cv=5, scoring='neg_mean_squared_error')))
 print('decision tree regression
root mean squared error: %0.4f, cross validation score: %0.4f(+/- %0.4f)' %(model_treereg_rmse, model_treereg_cvscores.mean() , 2 * model_treereg_cvscores.std()))
all_test_preds = []
for model_idx in range(NUM_MODELS):
print('Model ', model_idx)
 seed_everything(1 + model_idx)
 model = NeuralNet(embedding_matrix, y_aux_train.shape[-1])
 learn = Learner(databunch, model, loss_func=custom_loss)
 test_preds = train_model(learn,test_dataset,output_dim=7)
 all_test_preds.append(test_preds )<create_dataframe>
model_forestreg = RandomForestRegressor(n_estimators=100, min_samples_split=3, random_state=58)
 model_forestreg.fit(x_train, y_train)
 model_forestreg_ypredict = model_forestreg.predict(x_validate)
 model_forestreg_rmse = mean_squared_error(y_validate, model_forestreg_ypredict)** 0.5
model_forestreg_cvscores = np.sqrt(np.abs(cross_val_score(model_forestreg, x, y, cv=5, scoring='neg_mean_squared_error')))
 print('random forest regression
root mean squared error: %0.4f, cross validation score: %0.4f(+/- %0.4f)' %(model_forestreg_rmse, model_forestreg_cvscores.mean() , 2 * model_forestreg_cvscores.std()))
submission_lstm = pd.DataFrame.from_dict({
'id': test_df['id'],
'prediction': np.mean(all_test_preds, axis=0)[:, 0]
} )<save_to_csv>
params = {'n_estimators': [100],
'max_depth': [10, 20, None],
'min_samples_split': [3, 5, 7, 9],
'random_state': [58],
}
model_forestreg_cv = GridSearchCV(model_forestreg, params, iid=False, cv=5)
 model_forestreg_cv.fit(x_train, y_train)
 model_forestreg_cv_ypredict = model_forestreg_cv.predict(x_validate)
 model_forestreg_cv_rmse = mean_squared_error(y_validate, model_forestreg_cv_ypredict)** 0.5
model_forestreg_cv_cvscores = np.sqrt(np.abs(cross_val_score(model_forestreg_cv, x, y, cv=5, scoring='neg_mean_squared_error')))
 print('random forest regression grid search
root mean squared error: %0.4f, cross validation score: %0.4f(+/- %0.4f)' %(model_forestreg_cv_rmse, model_forestreg_cv_cvscores.mean() , 2 * model_forestreg_cv_cvscores.std()))
print(' best parameters: %s' %model_forestreg_cv.best_params_ )
submission = pd.read_csv(
 ".. /input/jigsaw-unintended-bias-in-toxicity-classification/sample_submission.csv" 
)
 weights = [0.265, 0.735]
submission["prediction"] = ensemble_predictions(
 [(submission_bert_plain.prediction.values)*(submission_bert_plain.prediction.values), submission_lstm.prediction.values],
weights,
type_="rank", 
)
 submission.to_csv("submission.csv", index=False )<set_options>
model_xgbreg = xgb.XGBRegressor(max_depth=5, learning_rate=0.1, n_estimators=1000, objective='reg:linear', booster='gbtree',
gamma=0, subsample=0.9, colsample_bytree=0.9, reg_alpha=0.1, reg_lambda=0.9, random_state=58)
 model_xgbreg.fit(x_train, y_train, eval_set=[(x_train, y_train),(x_validate, y_validate)], early_stopping_rounds=50, verbose=False, callbacks=[xgb.callback.print_evaluation(period=50)])
 model_xgbreg_ypredict = model_xgbreg.predict(x_validate)
 model_xgbreg_rmse = mean_squared_error(y_validate, model_xgbreg_ypredict)** 0.5
model_xgbreg_cvscores = np.sqrt(np.abs(cross_val_score(model_xgbreg, x, y, cv=5, scoring='neg_mean_squared_error')))
 print('xgboost regression
root mean squared error: %0.4f, cross validation score: %0.4f(+/- %0.4f)' %(model_xgbreg_rmse, model_xgbreg_cvscores.mean() , 2 * model_xgbreg_cvscores.std()))
plt.style.use("ggplot")
<load_from_csv>
final_model = model_kernelridgereg
x_test = df_data.loc[df_data['DataType_testing'] == 1, model_feat]
x_test = scaler.transform(x_test)
 y_test = pd.DataFrame(final_model.predict(x_test), columns=['SalePrice'], index=df_data.loc[df_data['DataType_testing'] == 1, 'Id'])
 y_test['SalePrice'] = np.expm1(y_test['SalePrice'] )
<statistical_test><EOS> 
out = pd.DataFrame({'Id': y_test.index, 'SalePrice': y_test['SalePrice']})
 out.to_csv('submission.csv', index=False )