Kaggle competition: House Prices - Advanced Regression Techniques
<SOS> metric: rmsle Kaggle data source: house-prices-advanced-regression-techniques<choose_model_class>
warnings.filterwarnings('ignore')
 %matplotlib inline
class ResNet34(nn.Module):
def __init__(self ,pretrained):
super(ResNet34,self ).__init__()
if pretrained is True:
self.model = pretrainedmodels.__dict__["resnet34"](pretrained="imagenet")
 else:
self.model = pretrainedmodels.__dict__["resnet34"](pretrained=None)
 self.layer0 = nn.Linear(512,168)
 self.layer1 = nn.Linear(512,11)
 self.layer2 = nn.Linear(512,7)
 def forward(self,x):
batch_size ,_,_,_ = x.shape
x = self.model.features(x)
 x = F.adaptive_avg_pool2d(x,1 ).reshape(batch_size, -1)
 layer0 = self.layer0(x)
 layer1 = self.layer1(x)
 layer2 = self.layer2(x)
 return layer0, layer1, layer2 
<normalization>
df_train = pd.read_csv('.. /input/train.csv')
 df_test = pd.read_csv('.. /input/test.csv' )
class BengaliDatasetTest:
def __init__(self, df, img_height, img_width, mean, std):
self.image_ids = df.image_id.values
self.img_arr = df.iloc[:, 1:].values
self.aug = albumentations.Compose([
albumentations.Resize(img_height, img_width, always_apply=True),
albumentations.Normalize(mean, std, always_apply=True)
 ])
 def __len__(self):
return len(self.image_ids)
 def __getitem__(self, item):
image = self.img_arr[item, :]
img_id = self.image_ids[item]
image = image.reshape(137, 236 ).astype(float)
 image = Image.fromarray(image ).convert("RGB")
 image = self.aug(image=np.array(image)) ["image"]
image = np.transpose(image,(2, 0, 1)).astype(np.float32)
 return {
"image": torch.tensor(image, dtype=torch.float),
"image_id": img_id
}<create_dataframe>
df_train['SalePrice'] = np.log1p(df_train['SalePrice'] )
def model_predict() :
g_pred, v_pred, c_pred = [], [], []
img_ids_list = []
for file_idx in range(4):
df = pd.read_parquet(f".. /input/bengaliai-cv19/test_image_data_{file_idx}.parquet")
 dataset = BengaliDatasetTest(df=df,
img_height=IMG_HEIGHT,
img_width=IMG_WIDTH,
mean=MODEL_MEAN,
std=MODEL_STD)
 data_loader = torch.utils.data.DataLoader(
 dataset=dataset,
batch_size= TEST_BATCH_SIZE,
shuffle=False,
num_workers=4 
)
 for bi, d in enumerate(data_loader):
image = d["image"]
img_id = d["image_id"]
image = image.to(DEVICE, dtype=torch.float)
 g, v, c = model(image)
 for ii, imid in enumerate(img_id):
g_pred.append(g[ii].cpu().detach().numpy())
 v_pred.append(v[ii].cpu().detach().numpy())
 c_pred.append(c[ii].cpu().detach().numpy())
 img_ids_list.append(imid)
 return g_pred, v_pred, c_pred, img_ids_list<choose_model_class>
data = pd.concat([df_train['SalePrice'], df_train['1stFlrSF']], axis=1)
 f, ax = plt.subplots(figsize=(8, 6))
fig = sns.regplot(x='1stFlrSF', y="SalePrice", data=data )
model = ResNet34(pretrained=False)
 TEST_BATCH_SIZE = 32
Start_fold=3
final_g_pred = []
final_v_pred = []
final_c_pred = []
final_img_ids = []
for i in range(Start_fold,5):
model.load_state_dict(torch.load(f".. /input/bengali-models/50 Epoch/resnet34_fold{i}.bin"))
model.to(DEVICE)
 model.eval()
g_pred, v_pred, c_pred, img_ids_list = model_predict()
final_g_pred.append(g_pred)
 final_v_pred.append(v_pred)
 final_c_pred.append(c_pred)
 if i == Start_fold:
final_img_ids.extend(img_ids_list )<prepare_output>
df_train = df_train[df_train['Id'] != 692][df_train['Id'] != 1183]
df_train = df_train.drop(df_train[(df_train['GrLivArea']>4000)&(df_train['SalePrice']<12.5)].index)
 df_train = df_train.drop(df_train[(df_train['LotArea']>150000)].index)
 df_train = df_train.drop(df_train[(df_train['GarageArea']>1200)&(df_train['SalePrice']<12.5)].index )
final_g = np.argmax(np.mean(np.array(final_g_pred), axis=0), axis=1)
 final_v = np.argmax(np.mean(np.array(final_v_pred), axis=0), axis=1)
 final_c = np.argmax(np.mean(np.array(final_c_pred), axis=0), axis=1)
 predictions = []
for ii, imid in enumerate(final_img_ids):
predictions.append(( f"{imid}_grapheme_root", final_g[ii]))
predictions.append(( f"{imid}_vowel_diacritic", final_v[ii]))
predictions.append(( f"{imid}_consonant_diacritic", final_c[ii])) 
<prepare_output>
del df_all['Utilities']
sub = pd.DataFrame(predictions,columns=["row_id","target"])
 print(sub )<save_to_csv>
df_all["PoolQC"] = df_all["PoolQC"].fillna("None")
 df_all["MiscFeature"] = df_all["MiscFeature"].fillna("None")
 df_all["Alley"] = df_all["Alley"].fillna("None")
 df_all["Fence"] = df_all["Fence"].fillna("None")
 df_all["FireplaceQu"] = df_all["FireplaceQu"].fillna("None")
 df_all['BsmtQual'] = df_all['BsmtQual'].fillna('None')
 df_all['BsmtCond'] = df_all['BsmtCond'].fillna('None')
 df_all['BsmtExposure'] = df_all['BsmtExposure'].fillna('None')
 df_all['BsmtFinType1'] = df_all['BsmtFinType1'].fillna('None')
 df_all['BsmtFinType2'] = df_all['BsmtFinType2'].fillna('None')
 df_all['GarageType'] = df_all['GarageType'].fillna('None')
 df_all['GarageFinish'] = df_all['GarageFinish'].fillna('None')
 df_all['GarageQual'] = df_all['GarageQual'].fillna('None')
 df_all['GarageCond'] = df_all['GarageCond'].fillna('None' )
sub.to_csv("submission.csv",index=False )<import_modules>
df_all['BsmtFinSF1'] = df_all['BsmtFinSF1'].fillna(0)
 df_all['BsmtFinSF2'] = df_all['BsmtFinSF2'].fillna(0)
 df_all['BsmtUnfSF'] = df_all['BsmtUnfSF'].fillna(0)
 df_all['TotalBsmtSF'] = df_all['TotalBsmtSF'].fillna(0)
 df_all['BsmtFullBath'] = df_all['BsmtFullBath'].fillna(0)
 df_all['BsmtHalfBath'] = df_all['BsmtHalfBath'].fillna(0)
 df_all['MasVnrArea'] = df_all['MasVnrArea'].fillna(0)
 df_all['GarageYrBlt'] = df_all['GarageYrBlt'].fillna(0)
 df_all['GarageCars'] = df_all['GarageCars'].fillna(0)
 df_all['GarageArea'] = df_all['GarageArea'].fillna(0 )
import torch
import numpy as np
from torch.utils.data import DataLoader
from torch.utils.data import Dataset
from torchvision import transforms as torchtransforms
import cv2
import torch.nn as nn
from tqdm import tqdm_notebook as tqdm
import torchvision
import torch.nn as nn
import torch.nn.functional as F
import time<define_variables>
df_all['MSZoning'] = df_all['MSZoning'].fillna(df_all['MSZoning'].mode() [0])
 df_all['Exterior1st'] = df_all['Exterior1st'].fillna(df_all['Exterior1st'].mode() [0])
 df_all['Exterior2nd'] = df_all['Exterior2nd'].fillna(df_all['Exterior2nd'].mode() [0])
 df_all['MasVnrType'] = df_all['MasVnrType'].fillna(df_all['MasVnrType'].mode() [0])
 df_all['Electrical'] = df_all['Electrical'].fillna(df_all['Electrical'].mode() [0])
 df_all['KitchenQual'] = df_all['KitchenQual'].fillna(df_all['KitchenQual'].mode() [0])
 df_all['Functional'] = df_all['Functional'].fillna(df_all['Functional'].mode() [0])
 df_all['SaleType'] = df_all['SaleType'].fillna(df_all['SaleType'].mode() [0] )
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
 print(device)
 modelpath = "/kaggle/input/se-resnext50-32x4d-fold2/se_resnext50_32x4d_fold2.pkl"
root_path="/kaggle/input/bengaliai-cv19"<categorify>
df_all["LotFrontage"] = df_all.groupby("Neighborhood")["LotFrontage"].transform(lambda x: x.fillna(x.median()))
simple_transform_valid = torchtransforms.Compose([
torchtransforms.ToTensor() ,
torchtransforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
 ] )<choose_model_class>
df_all['MSSubClass'] = df_all['MSSubClass'].apply(str)
 df_all['OverallCond'] = df_all['OverallCond'].astype(str )
__all__ = ['SENet', 'se_resnext50_32x4d']
class SEModule(nn.Module):
def __init__(self, channels, reduction):
super(SEModule, self ).__init__()
self.avg_pool = nn.AdaptiveAvgPool2d(1)
 self.fc1 = nn.Conv2d(channels, channels // reduction, kernel_size=1,
padding=0)
 self.relu = nn.ReLU(inplace=True)
 self.fc2 = nn.Conv2d(channels // reduction, channels, kernel_size=1,
padding=0)
 self.sigmoid = nn.Sigmoid()
def forward(self, x):
module_input = x
x = self.avg_pool(x)
 x = self.fc1(x)
 x = self.relu(x)
 x = self.fc2(x)
 x = self.sigmoid(x)
 return module_input * x
class Bottleneck(nn.Module):

 def forward(self, x):
residual = x
out = self.conv1(x)
 out = self.bn1(out)
 out = self.relu(out)
 out = self.conv2(out)
 out = self.bn2(out)
 out = self.relu(out)
 out = self.conv3(out)
 out = self.bn3(out)
 if self.downsample is not None:
residual = self.downsample(x)
 out = self.se_module(out)+ residual
out = self.relu(out)
 return out
class SEBottleneck(Bottleneck):

 expansion = 4
def __init__(self, inplanes, planes, groups, reduction, stride=1,
downsample=None):
super(SEBottleneck, self ).__init__()
self.conv1 = nn.Conv2d(inplanes, planes * 2, kernel_size=1, bias=False)
 self.bn1 = nn.BatchNorm2d(planes * 2)
 self.conv2 = nn.Conv2d(planes * 2, planes * 4, kernel_size=3,
stride=stride, padding=1, groups=groups,
bias=False)
 self.bn2 = nn.BatchNorm2d(planes * 4)
 self.conv3 = nn.Conv2d(planes * 4, planes * 4, kernel_size=1,
bias=False)
 self.bn3 = nn.BatchNorm2d(planes * 4)
 self.relu = nn.ReLU(inplace=True)
 self.se_module = SEModule(planes * 4, reduction=reduction)
 self.downsample = downsample
self.stride = stride
class SEResNetBottleneck(Bottleneck):

 expansion = 4
def __init__(self, inplanes, planes, groups, reduction, stride=1,
downsample=None):
super(SEResNetBottleneck, self ).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False,
stride=stride)
 self.bn1 = nn.BatchNorm2d(planes)
 self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, padding=1,
groups=groups, bias=False)
 self.bn2 = nn.BatchNorm2d(planes)
 self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)
 self.bn3 = nn.BatchNorm2d(planes * 4)
 self.relu = nn.ReLU(inplace=True)
 self.se_module = SEModule(planes * 4, reduction=reduction)
 self.downsample = downsample
self.stride = stride
class SEResNeXtBottleneck(Bottleneck):

 expansion = 4
def __init__(self, inplanes, planes, groups, reduction, stride=1,
downsample=None, base_width=4):
super(SEResNeXtBottleneck, self ).__init__()
width = math.floor(planes *(base_width / 64)) * groups
self.conv1 = nn.Conv2d(inplanes, width, kernel_size=1, bias=False,
stride=1)
 self.bn1 = nn.BatchNorm2d(width)
 self.conv2 = nn.Conv2d(width, width, kernel_size=3, stride=stride,
padding=1, groups=groups, bias=False)
 self.bn2 = nn.BatchNorm2d(width)
 self.conv3 = nn.Conv2d(width, planes * 4, kernel_size=1, bias=False)
 self.bn3 = nn.BatchNorm2d(planes * 4)
 self.relu = nn.ReLU(inplace=True)
 self.se_module = SEModule(planes * 4, reduction=reduction)
 self.downsample = downsample
self.stride = stride
class SENet(nn.Module):
def __init__(self, block, layers, groups, reduction, dropout_p=0.2,
inplanes=128, input_3x3=True, downsample_kernel_size=3,
downsample_padding=1, num_classes=1000):
super(SENet, self ).__init__()
self.inplanes = inplanes
if input_3x3:
layer0_modules = [ 
('conv1', nn.Conv2d(3, 64, 3, stride=2, padding=1,
bias=False)) , 
('bn1', nn.BatchNorm2d(64)) , 
('relu1', nn.ReLU(inplace=True)) , 
('conv2', nn.Conv2d(64, 64, 3, stride=1, padding=1,
bias=False)) , 
('bn2', nn.BatchNorm2d(64)) , 
('relu2', nn.ReLU(inplace=True)) , 
('conv3', nn.Conv2d(64, inplanes, 3, stride=1, padding=1,
bias=False)) , 
('bn3', nn.BatchNorm2d(inplanes)) , 
('relu3', nn.ReLU(inplace=True)) ,
]
else:
layer0_modules = [ 
('conv1', nn.Conv2d(3, inplanes, kernel_size=7, stride=2,
padding=3, bias=False)) , 
('bn1', nn.BatchNorm2d(inplanes)) , 
('relu1', nn.ReLU(inplace=True)) ,
]
layer0_modules.append(( 'pool', nn.MaxPool2d(3, stride=2,
ceil_mode=True)))
 self.layer0 = nn.Sequential(OrderedDict(layer0_modules))
self.layer1 = self._make_layer(
 block,
planes=64,
blocks=layers[0],
groups=groups,
reduction=reduction,
downsample_kernel_size=1,
downsample_padding=0 
)
 self.layer2 = self._make_layer(
 block,
planes=128,
blocks=layers[1],
stride=2,
groups=groups,
reduction=reduction,
downsample_kernel_size=downsample_kernel_size,
downsample_padding=downsample_padding 
)
 self.layer3 = self._make_layer(
 block,
planes=256,
blocks=layers[2],
stride=2,
groups=groups,
reduction=reduction,
downsample_kernel_size=downsample_kernel_size,
downsample_padding=downsample_padding 
)
 self.layer4 = self._make_layer(
 block,
planes=512,
blocks=layers[3],
stride=2,
groups=groups,
reduction=reduction,
downsample_kernel_size=downsample_kernel_size,
downsample_padding=downsample_padding 
)
 self.avg_pool = nn.AvgPool2d(7, stride=1)
 self.dropout = nn.Dropout(dropout_p)if dropout_p is not None else None
self.last_linear = nn.Linear(512 * block.expansion, num_classes)
 def _make_layer(self, block, planes, blocks, groups, reduction, stride=1,
downsample_kernel_size=1, downsample_padding=0):
downsample = None
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
 nn.Conv2d(self.inplanes, planes * block.expansion,
kernel_size=downsample_kernel_size, stride=stride,
padding=downsample_padding, bias=False),
nn.BatchNorm2d(planes * block.expansion), 
)
 layers = []
layers.append(block(self.inplanes, planes, groups, reduction, stride,
downsample))
self.inplanes = planes * block.expansion
for i in range(1, blocks):
layers.append(block(self.inplanes, planes, groups, reduction))
return nn.Sequential(*layers)
 def features(self, x):
x = self.layer0(x)
 x = self.layer1(x)
 x = self.layer2(x)
 x = self.layer3(x)
 x = self.layer4(x)
 return x
def logits(self, x):
x = self.avg_pool(x)
 if self.dropout is not None:
x = self.dropout(x)
 x = x.view(x.size(0), -1)
 x = self.last_linear(x)
 return x
def forward(self, x):
x = self.features(x)
 x = self.logits(x)
 return x
def se_resnext50_32x4d(num_classes=1000, pretrained='imagenet'):
model = SENet(SEResNeXtBottleneck, [3, 4, 6, 3], groups=32, reduction=16,
dropout_p=None, inplanes=64, input_3x3=False,
downsample_kernel_size=1, downsample_padding=0,
num_classes=num_classes)
 return model<load_pretrained>
one_hot_encoding = df_all.copy()
one_hot_encoding = pd.get_dummies(one_hot_encoding)
 one_hot_encoding.iloc[:,36:50].head()
model = se_resnext50_32x4d(pretrained=None)
 model.avg_pool = nn.AdaptiveAvgPool2d(1)
 model.last_linear = nn.Linear(model.last_linear.in_features, 186)
 modelvalue = torch.load(modelpath, map_location='cuda:0')
 newmodelvalue = {}
for kv in modelvalue:
newmodelvalue[kv[4:]]=modelvalue[kv]
model.load_state_dict(newmodelvalue)
 model = model.to(device )<load_from_csv>
del one_hot_encoding;
allpathes=[]
allpreds_root = []
allpreds_vowel = []
allpreds_consonant = []
tAllBegin = time.time()
for i in range(4):
test_csv = pd.read_parquet(os.path.join(root_path, f'test_image_data_{i}.parquet'))
tBegin = time.time()
dataloaders = make_loader(data_folder = test_csv,
batch_size=8,
num_workers = 2,
is_shuffle = False)
 pathes, logit1, logit2, logit3 = getmodeleval(model, dataloaders)
 preds_root = np.argmax(logit1, axis=1)
 preds_vowel = np.argmax(logit2, axis=1)
 preds_consonant = np.argmax(logit3, axis=1)
 allpathes.extend(pathes)
 allpreds_root.extend(preds_root.tolist())
 allpreds_vowel.extend(preds_vowel.tolist())
 allpreds_consonant.extend(preds_consonant.tolist())
 tEnd = time.time()
print(i, int(round(tEnd * 1000)) - int(round(tBegin * 1000)) , "ms")
 tAllEnd = time.time()
print(len(allpathes), len(allpreds_root), len(allpreds_vowel), len(allpreds_consonant), int(round(tAllEnd * 1000)) - int(round(tAllBegin * 1000)) , "ms" )<load_from_csv>
label_encoding = df_all.copy()
for i in categorical_features:
label_encoding[i], indexer = pd.factorize(label_encoding[i])
 label_encoding.iloc[:,20:30].head()
row_id=[]
target=[]
for idx, image_id in enumerate(allpathes):
target.extend([allpreds_consonant[idx]])
 target.extend([allpreds_root[idx]])
 target.extend([allpreds_vowel[idx]])
 row_id.extend([str(image_id)+ '_consonant_diacritic'])
 row_id.extend([str(image_id)+ '_grapheme_root'])
 row_id.extend([str(image_id)+ '_vowel_diacritic'])
 submission_df = pd.read_csv(root_path + '/sample_submission.csv')
 submission_df.target = np.hstack(np.array(target ).astype(np.int))
print(submission_df.head(10))
submission_df.to_csv('submission.csv', index=False)
 print("================end ======================" )<train_model>
del label_encoding;
print("A" )<set_options>
frequency_encoding_all = df_all.copy()
def frequency_encoding(frame, col):
freq_encoding = frame.groupby([col] ).size() /frame.shape[0]
freq_encoding = freq_encoding.reset_index().rename(columns={0:'{}_Frequency'.format(col)})
 return frame.merge(freq_encoding, on=col, how='left')
 for col in categorical_features:
frequency_encoding_all = frequency_encoding(frequency_encoding_all, col)
 frequency_encoding_all = frequency_encoding_all.drop(categorical_features,axis=1, inplace=False)
 frequency_encoding_all.iloc[:,20:30].head()
!nvidia-smi<import_modules>
del frequency_encoding_all
import pickle
import gc
import os
import cv2
from cv2 import resize
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pathlib import Path
import torch
from torch import nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
from typing import Union
from typing import List<load_from_csv>
n_folds = 5
def rmsle_cv(model,df):
kf = KFold(n_folds, shuffle=True, random_state=42 ).get_n_splits(df.values)
 rmse= np.sqrt(-cross_val_score(model, df.values, y_reg, scoring="neg_mean_squared_error", cv = kf))
return(rmse )
DEFAULT_H, DEFAULT_W = 137, 236
SIZE = 128
LABEL_PATH = Path('train.csv')
 DATADIR = Path('/kaggle/input/bengaliai-cv19')
 TEST_FORM = 'test_image_data_ID.parquet'
WEIGHTS_FILE = '/kaggle/input/densenet121-80-epochs-ohem-07/model_2020-03-07T12_40_50.436927.pt'
test = pd.read_csv(DATADIR/'test.csv')
 train = pd.read_csv(DATADIR/'train.csv')
 train_labels = train[['grapheme_root', 'vowel_diacritic', 'consonant_diacritic']].values
submission_df = pd.read_csv(DATADIR/'sample_submission.csv' )<load_pretrained>
one_hot_encoding = df_all.copy()
del one_hot_encoding['SalePrice']
one_hot_encoding = pd.get_dummies(one_hot_encoding)
 one_hot_encoding_train = one_hot_encoding[:len_train]
one_hot_encoding_test = one_hot_encoding[len_train:]
del one_hot_encoding
model = lgb.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)
 score = rmsle_cv(model,one_hot_encoding_train)
 print("One-hot encoding(5-folds)LGBM score: {:.4f}({:.4f})
 ".format(score.mean() , score.std()))
def rmsle(y, y_pred):
return np.sqrt(mean_squared_error(y, y_pred))
kfold_lgb_model = model.fit(one_hot_encoding_train, y_reg)
 train_prediction = model.predict(one_hot_encoding_train)
 prediction = np.expm1(kfold_lgb_model.predict(one_hot_encoding_test.values))
submission = pd.DataFrame({'Id': Id, 'SalePrice': prediction})
 submission.to_csv('OH_5FOLD.csv', index=False )
def load_images(train_test, indices=['0', '1', '2', '3']):

 path_form = {
'test': TEST_FORM
}[train_test]
imgs_list = []
for id in indices:
path = DATADIR / path_form.replace('ID', id)
 print('Loading', path)
 df = pd.read_parquet(path)
 imgs = df.iloc[:, 1:].to_numpy()
imgs_list.append(imgs)
 del imgs
gc.collect()
imgs_list = np.concatenate(imgs_list)
 imgs_list = imgs_list.reshape(-1, DEFAULT_H, DEFAULT_W)
 return imgs_list<load_pretrained>
n_folds = one_hot_encoding_train.shape[0]
def rmsle_cv(model,df):
kf = KFold(n_folds, shuffle=True, random_state=42 ).get_n_splits(df.values)
 rmse= np.sqrt(-cross_val_score(model, df.values, y_reg, scoring="neg_mean_squared_error", cv = kf))
return(rmse )
def get_data(train_test, indices=['0', '1', '2', '3']):

 imgs = load_images(train_test, indices=indices)
 if train_test == 'train':
labels = load_labels()
all_data = list(zip(imgs, labels))
else:
all_data = imgs
return all_data<set_options>
model = lgb.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)
 score = rmsle_cv(model,one_hot_encoding_train)
 print("One-hot encoding(LOOCV)LGBM score: {:.4f}({:.4f})
 ".format(score.mean() , score.std()))
def rmsle(y, y_pred):
return np.sqrt(mean_squared_error(y, y_pred))
loovc_lgb_model = model.fit(one_hot_encoding_train, y_reg)
 train_prediction = model.predict(one_hot_encoding_train)
 prediction = np.expm1(loovc_lgb_model.predict(one_hot_encoding_test.values))
submission = pd.DataFrame({'Id': Id, 'SalePrice': prediction})
 submission.to_csv('OH_LOOCV.csv', index=False )
dataset_cfg = {'aug_cfg': {
'resize_shape':(128, 128),
'crop': True,
'to_rgb': True,
'normalize_mean': [0.485, 0.456, 0.406],
'normalize_std': [0.229, 0.224, 0.225]
}
}<prepare_x_and_y>
n_folds = 5
def rmsle_cv(model,df):
kf = KFold(n_folds, shuffle=True, random_state=42 ).get_n_splits(df.values)
 rmse= np.sqrt(-cross_val_score(model, df.values, y_reg, scoring="neg_mean_squared_error", cv = kf))
return(rmse)
 label_encoding = df_all.copy()
for i in categorical_features:
label_encoding[i], indexer = pd.factorize(label_encoding[i])
 del label_encoding['SalePrice']
label_encoding_train = label_encoding[:len_train]
label_encoding_test = label_encoding[len_train:]
del label_encoding
model = lgb.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)
 score = rmsle_cv(model,label_encoding_train)
 print("Label encoding(5-folds)LGBM score: {:.4f}({:.4f})
 ".format(score.mean() , score.std()))
def rmsle(y, y_pred):
return np.sqrt(mean_squared_error(y, y_pred))
kfold_lgb_model = model.fit(label_encoding_train, y_reg)
 train_prediction = model.predict(label_encoding_train)
 prediction = np.expm1(model.predict(label_encoding_test.values))
submission = pd.DataFrame({'Id': Id, 'SalePrice': prediction})
 submission.to_csv('Label_5FOLD.csv', index=False )
def content_crop(img, pad_to_square: bool, white_background: bool):

 img = img[5:-5, 5:-5]
if white_background:
y_list, x_list = np.where(img < 235)
 else:
y_list, x_list = np.where(img > 80)
 xmin, xmax = np.min(x_list), np.max(x_list)
 ymin, ymax = np.min(y_list), np.max(y_list)
 xmin = xmin - 13 if(xmin > 13)else 0
ymin = ymin - 10 if(ymin > 10)else 0
xmax = xmax + 13 if(xmax < 223)else 236
ymax = ymax + 10 if(ymax < 127)else 137
img = img[ymin:ymax, xmin:xmax]
if white_background:
img[img > 235] = 255
else:
img[img < 28] = 0
if pad_to_square:
lx, ly = xmax - xmin, ymax - ymin
l = max(lx, ly)+ 16
if white_background:
constant_pad = 255
else:
constant_pad = 0
img = np.pad(img, [(( l - ly)// 2,),(( l - lx)// 2,)], mode='constant', constant_values=constant_pad)
 return img
class Preprocessor(object):
def __init__(self, dataset_cfg):
aug_cfg = dataset_cfg['aug_cfg']
self.resize_shape = aug_cfg['resize_shape']
self.crop = aug_cfg['crop']
self.to_rgb = aug_cfg['to_rgb']
self.normalize_mean = aug_cfg['normalize_mean']
self.normalize_std = aug_cfg['normalize_std']
def __call__(self, img, normalize=True):
if self.crop:
img = content_crop(img, pad_to_square=True, white_background=True)
 img = resize(img, self.resize_shape)
 if self.to_rgb:
img = np.repeat(np.expand_dims(img, axis=-1), 3, axis=-1)
 if not normalize:
return img
img = img / 255.
 if self.normalize_mean is not None:
img =(img - self.normalize_mean)/ self.normalize_std
img = torch.tensor(img)
 img = img.permute([2, 0, 1])
 return img<categorify>
n_folds = label_encoding_train.shape[0]
def rmsle_cv(model,df):
kf = KFold(n_folds, shuffle=True, random_state=42 ).get_n_splits(df.values)
 rmse= np.sqrt(-cross_val_score(model, df.values, y_reg, scoring="neg_mean_squared_error", cv = kf))
return(rmse)
 model = lgb.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)
 score = rmsle_cv(model,label_encoding_train)
 print("Label encoding(LOOCV)LGBM score: {:.4f}({:.4f})
 ".format(score.mean() , score.std()))
def rmsle(y, y_pred):
return np.sqrt(mean_squared_error(y, y_pred))
loovc_lgb_model = model.fit(label_encoding_train, y_reg)
 train_prediction = model.predict(label_encoding_train)
 prediction = np.expm1(loovc_lgb_model.predict(label_encoding_test.values))
submission = pd.DataFrame({'Id': Id, 'SalePrice': prediction})
 submission.to_csv('Label_LOOCV.csv', index=False )
class BengaliDataset(Dataset):

 def __init__(self, data_list, data_cfg, fname, indices=None):

 self.data_list = data_list
self.data_size = len(data_list)
 if indices is None:
indices = np.arange(self.data_size)
 self.indices = indices
self.preprocessor = Preprocessor(data_cfg)
 if fname:
self.df = pd.read_parquet(DATADIR / fname)
 self.fname = fname
def __len__(self)-> int:
return len(self.indices)
 def __getitem__(self, idx: int)->(np.ndarray, np.ndarray):
idx = self.indices[idx]
img = self.data_list[idx]
img = self.preprocessor(img)
 name = self.df.iloc[idx, 0]
return img, name<categorify>
n_folds = 5
def rmsle_cv(model,df):
kf = KFold(n_folds, shuffle=True, random_state=42 ).get_n_splits(df.values)
 rmse= np.sqrt(-cross_val_score(model, df.values, y_reg, scoring="neg_mean_squared_error", cv = kf))
return(rmse)
 frequency_encoding_all = df_all.copy()
def frequency_encoding(frame, col):
freq_encoding = frame.groupby([col] ).size() /frame.shape[0]
freq_encoding = freq_encoding.reset_index().rename(columns={0:'{}_Frequency'.format(col)})
 return frame.merge(freq_encoding, on=col, how='left')
 for col in categorical_features:
frequency_encoding_all = frequency_encoding(frequency_encoding_all, col)
 frequency_encoding_all = frequency_encoding_all.drop(categorical_features,axis=1, inplace=False)
 del frequency_encoding_all['SalePrice']
frequency_encoding_train = frequency_encoding_all[:len_train]
frequency_encoding_test = frequency_encoding_all[len_train:]
del frequency_encoding_all
model = lgb.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)
 score = rmsle_cv(model,frequency_encoding_train)
 print("Frequency encoding(5-folds)LGBM score: {:.4f}({:.4f})
 ".format(score.mean() , score.std()))
def rmsle(y, y_pred):
return np.sqrt(mean_squared_error(y, y_pred))
kfold_lgb_model = model.fit(frequency_encoding_train, y_reg)
 train_prediction = model.predict(frequency_encoding_train)
 prediction = np.expm1(model.predict(frequency_encoding_test.values))
submission = pd.DataFrame({'Id': Id, 'SalePrice': prediction})
 submission.to_csv('Frequency_5FOLD.csv', index=False )
<import_modules>
n_folds = frequency_encoding_train.shape[0]
def rmsle_cv(model,df):
kf = KFold(n_folds, shuffle=True, random_state=42 ).get_n_splits(df.values)
 rmse= np.sqrt(-cross_val_score(model, df.values, y_reg, scoring="neg_mean_squared_error", cv = kf))
return(rmse)
 model = lgb.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)
 score = rmsle_cv(model,frequency_encoding_train)
 print("Label encoding(LOOCV)LGBM score: {:.4f}({:.4f})
 ".format(score.mean() , score.std()))
def rmsle(y, y_pred):
return np.sqrt(mean_squared_error(y, y_pred))
loovc_lgb_model = model.fit(frequency_encoding_train, y_reg)
 train_prediction = model.predict(frequency_encoding_train)
 prediction = np.expm1(loovc_lgb_model.predict(frequency_encoding_test.values))
submission = pd.DataFrame({'Id': Id, 'SalePrice': prediction})
 submission.to_csv('Frequency_LOOCV.csv', index=False )
__all__ = ['DenseNet', 'densenet121']
model_urls = {
'densenet121': 'https://download.pytorch.org/models/densenet121-a639ec97.pth',
}
class _DenseLayer(nn.Module):
def __init__(self, num_input_features, growth_rate, bn_size, drop_rate, memory_efficient=False):
super(_DenseLayer, self ).__init__()
self.add_module('norm1', nn.BatchNorm2d(num_input_features)) ,
self.add_module('relu1', nn.ReLU(inplace=True)) ,
self.add_module('conv1', nn.Conv2d(num_input_features, bn_size *
growth_rate, kernel_size=1, stride=1,
bias=False)) ,
self.add_module('norm2', nn.BatchNorm2d(bn_size * growth_rate)) ,
self.add_module('relu2', nn.ReLU(inplace=True)) ,
self.add_module('conv2', nn.Conv2d(bn_size * growth_rate, growth_rate,
kernel_size=3, stride=1, padding=1,
bias=False)) ,
self.drop_rate = float(drop_rate)
 self.memory_efficient = memory_efficient
def bn_function(self, inputs):
concated_features = torch.cat(inputs, 1)
 bottleneck_output = self.conv1(self.relu1(self.norm1(concated_features)))
 return bottleneck_output
def any_requires_grad(self, input):
for tensor in input:
if tensor.requires_grad:
return True
return False
@torch.jit.unused
def call_checkpoint_bottleneck(self, input):
def closure(*inputs):
return self.bn_function(*inputs)
 return cp.checkpoint(closure, input)
 @torch.jit._overload_method
def forward(self, input):
pass
@torch.jit._overload_method
def forward(self, input):
pass
def forward(self, input):
if isinstance(input, Tensor):
prev_features = [input]
else:
prev_features = input
if self.memory_efficient and self.any_requires_grad(prev_features):
if torch.jit.is_scripting() :
raise Exception("Memory Efficient not supported in JIT")
 bottleneck_output = self.call_checkpoint_bottleneck(prev_features)
 else:
bottleneck_output = self.bn_function(prev_features)
 new_features = self.conv2(self.relu2(self.norm2(bottleneck_output)))
 if self.drop_rate > 0:
new_features = F.dropout(new_features, p=self.drop_rate,
training=self.training)
 return new_features
class _DenseBlock(nn.ModuleDict):
_version = 2
def __init__(self, num_layers, num_input_features, bn_size, growth_rate, drop_rate, memory_efficient=False):
super(_DenseBlock, self ).__init__()
for i in range(num_layers):
layer = _DenseLayer(
 num_input_features + i * growth_rate,
growth_rate=growth_rate,
bn_size=bn_size,
drop_rate=drop_rate,
memory_efficient=memory_efficient, 
)
 self.add_module('denselayer%d' %(i + 1), layer)
 def forward(self, init_features):
features = [init_features]
for name, layer in self.items() :
new_features = layer(features)
 features.append(new_features)
 return torch.cat(features, 1)
 class _Transition(nn.Sequential):
def __init__(self, num_input_features, num_output_features):
super(_Transition, self ).__init__()
self.add_module('norm', nn.BatchNorm2d(num_input_features))
self.add_module('relu', nn.ReLU(inplace=True))
self.add_module('conv', nn.Conv2d(num_input_features, num_output_features,
kernel_size=1, stride=1, bias=False))
self.add_module('pool', nn.AvgPool2d(kernel_size=2, stride=2))
class DenseNet(nn.Module):
r
__constants__ = ['features']
def __init__(self, growth_rate=32, block_config=(6, 12, 24, 16),
num_init_features=64, bn_size=4, drop_rate=0, num_classes=1000, memory_efficient=False):
super(DenseNet, self ).__init__()
self.features = nn.Sequential(OrderedDict([ 
('conv0', nn.Conv2d(3, num_init_features, kernel_size=7, stride=2,
padding=3, bias=False)) , 
('norm0', nn.BatchNorm2d(num_init_features)) , 
('relu0', nn.ReLU(inplace=True)) , 
('pool0', nn.MaxPool2d(kernel_size=3, stride=2, padding=1)) ,
]))
num_features = num_init_features
for i, num_layers in enumerate(block_config):
block = _DenseBlock(
 num_layers=num_layers,
num_input_features=num_features,
bn_size=bn_size,
growth_rate=growth_rate,
drop_rate=drop_rate,
memory_efficient=memory_efficient 
)
 self.features.add_module('denseblock%d' %(i + 1), block)
 num_features = num_features + num_layers * growth_rate
if i != len(block_config)- 1:
trans = _Transition(num_input_features=num_features,
num_output_features=num_features // 2)
 self.features.add_module('transition%d' %(i + 1), trans)
 num_features = num_features // 2
self.features.add_module('norm5', nn.BatchNorm2d(num_features))
self.classifier = nn.Linear(num_features, num_classes)
 for m in self.modules() :
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight)
 elif isinstance(m, nn.BatchNorm2d):
nn.init.constant_(m.weight, 1)
 nn.init.constant_(m.bias, 0)
 elif isinstance(m, nn.Linear):
nn.init.constant_(m.bias, 0)
 def forward(self, x):
features = self.features(x)
 out = F.relu(features, inplace=True)
 out = F.adaptive_avg_pool2d(out,(1, 1))
out = torch.flatten(out, 1)
 out = self.classifier(out)
 return out
def _load_state_dict(model, model_url, progress):
pattern = re.compile(
 r'^ (.*denselayer\d+\.( ?:norm|relu|conv)) \.((?:[12])\.( ?:weight|bias|running_mean|running_var)) $')
 state_dict = load_state_dict_from_url(model_url, progress=progress)
 for key in list(state_dict.keys()):
res = pattern.match(key)
 if res:
new_key = res.group(1)+ res.group(2)
 state_dict[new_key] = state_dict[key]
del state_dict[key]
model.load_state_dict(state_dict)
 def _densenet(arch, growth_rate, block_config, num_init_features, pretrained, progress,
**kwargs):
model = DenseNet(growth_rate, block_config, num_init_features, **kwargs)
 if pretrained:
_load_state_dict(model, model_urls[arch], progress)
 return model
def densenet121(pretrained=False, progress=True, **kwargs):
r
return _densenet('densenet121', 32,(6, 12, 24, 16), 64, pretrained, progress,
**kwargs )<load_pretrained>
one_hot_encoding = pd.concat([one_hot_encoding_train,one_hot_encoding_test])
 one_hot_encoding['Total_sqr_footage'] = one_hot_encoding['BsmtFinSF1'] + one_hot_encoding['BsmtFinSF2'] + one_hot_encoding['1stFlrSF'] + one_hot_encoding['2ndFlrSF']
one_hot_encoding['Total_Bathrooms'] = one_hot_encoding['FullBath'] + one_hot_encoding['HalfBath'] + one_hot_encoding['BsmtFullBath'] + one_hot_encoding['BsmtHalfBath']
one_hot_encoding['Total_porch_sf'] = one_hot_encoding['OpenPorchSF'] + one_hot_encoding['3SsnPorch'] + one_hot_encoding['EnclosedPorch'] + one_hot_encoding['ScreenPorch'] + one_hot_encoding['WoodDeckSF']
one_hot_encoding['TotalHouse'] = one_hot_encoding['TotalBsmtSF'] + one_hot_encoding['1stFlrSF'] + one_hot_encoding['2ndFlrSF']
one_hot_encoding['TotalArea'] = one_hot_encoding['TotalBsmtSF'] + one_hot_encoding['1stFlrSF'] + one_hot_encoding['2ndFlrSF'] + one_hot_encoding["GarageArea"]
one_hot_encoding['GrLivArea_OverallQual'] = one_hot_encoding['GrLivArea'] * one_hot_encoding['OverallQual']
one_hot_encoding['LotArea_OverallQual'] = one_hot_encoding['LotArea'] * one_hot_encoding['OverallQual']
def build_densenet_backbone(backbone_cfg, **kwargs):

 model = densenet121(pretrained=False)
 if backbone_cfg.get('pretrained_path'):
pretrained_path = backbone_cfg['pretrained_path']
state_dict = torch.load(pretrained_path, map_location='cpu')
 model.load_state_dict(state_dict, strict=False)
 return model<init_hyperparams>
model_cfg = {
'head_cfg': {
'head_name': 'simple_head',
'activation': 'leaky_relu',
'output_dims': [168, 11, 7],
'input_dims': 1000,
'hidden_dims': [512, 256],
'bn': True,
'dropout': -1
},
'backbone_cfg': {
}
}<choose_model_class>
one_hot_encoding['haspool'] = one_hot_encoding['PoolArea'].apply(lambda x: 1 if x > 0 else 0)
 one_hot_encoding['hasgarage'] = one_hot_encoding['GarageArea'].apply(lambda x: 1 if x > 0 else 0)
 one_hot_encoding['hasbsmt'] = one_hot_encoding['TotalBsmtSF'].apply(lambda x: 1 if x > 0 else 0)
 one_hot_encoding['hasfireplace'] = one_hot_encoding['Fireplaces'].apply(lambda x: 1 if x > 0 else 0 )
ACTIVATION_FN = {
'relu': F.relu,
'relu6': F.relu6,
'elu': F.elu,
'leaky_relu': F.leaky_relu,
None: None
}
class LinearLayer(nn.Module):
def __init__(self, input_dim, output_dim, activation, bn, dropout_rate = -1):
super(LinearLayer, self ).__init__()
self.input_dim = input_dim
self.output_dim = output_dim
self.linear = nn.Linear(input_dim, output_dim)
 self.activation_fn = ACTIVATION_FN[activation]
if bn:
self.bn = nn.BatchNorm1d(self.output_dim)
 else:
self.bn = None
if dropout_rate > 0:
self.dropout = nn.Dropout(p=dropout_rate)
 else:
self.dropout = None
def forward(self, x):
x = self.linear(x)
 if self.bn is not None:
x = self.bn(x)
 if self.activation_fn is not None:
x = self.activation_fn(x, inplace=True)
 if self.dropout is not None:
x = self.dropout(x)
 return x 
<choose_model_class>
numeric_dtypes = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']
numerics2 = []
for i in one_hot_encoding.columns:
if one_hot_encoding[i].dtype in numeric_dtypes:
numerics2.append(i)
 skew_features = one_hot_encoding[numerics2].apply(lambda x: skew(x)).sort_values(ascending=False)
 skews = pd.DataFrame({'skew':skew_features})
 skews.head()
def build_head(head_cfg):
return SimplePredictionHead(head_cfg)
 class SimplePredictionHead(nn.Module):
def __init__(self, head_cfg):
super(SimplePredictionHead, self ).__init__()
self.fc_layers = []
input_dim = head_cfg['input_dims']
for hidden_dim in head_cfg['hidden_dims']:
self.fc_layers.append(
 LinearLayer(input_dim, hidden_dim, bn=head_cfg['bn'], activation=head_cfg['activation'],
dropout_rate=head_cfg['dropout'])
)
 input_dim = hidden_dim
output_dims = head_cfg['output_dims']
self.fc_layers.append(
 LinearLayer(input_dim, sum(output_dims), bn=False, activation=None, dropout_rate=-1)
)
 self.fc_layers = nn.Sequential(*self.fc_layers)
 for m in self.modules() :
if isinstance(m, nn.BatchNorm1d):
nn.init.ones_(m.weight)
 nn.init.zeros_(m.bias)
 elif isinstance(m, nn.Linear):
nn.init.normal_(m.weight, 0, 0.01)
 nn.init.zeros_(m.bias)
 def forward(self, x):
return self.fc_layers(x )<categorify>
one_hot_encoding_train = one_hot_encoding[:len_train]
one_hot_encoding_test = one_hot_encoding[len_train:]
del one_hot_encoding
kfolds = KFold(n_splits=5, shuffle=True, random_state=42)
 def cv_rmse(model):
rmse = np.sqrt(-cross_val_score(model, one_hot_encoding_train, y_reg,
scoring="neg_mean_squared_error",
cv = kfolds))
return(rmse)
 def ridge_selector(k):
ridge_model = make_pipeline(RobustScaler() ,
RidgeCV(alphas = [k],
cv=kfolds)).fit(one_hot_encoding_train, y_reg)
 ridge_rmse = cv_rmse(ridge_model ).mean()
return(ridge_rmse)
 r_alphas = [.0001,.0003,.0005,.0007,.0009, 
.01, 0.05, 0.1, 0.3, 1, 3, 5, 10, 15, 20, 30, 50, 60, 70, 80]
ridge_scores = []
for alpha in r_alphas:
score = ridge_selector(alpha)
 ridge_scores.append(score)
 plt.plot(r_alphas, ridge_scores, label='Ridge')
 plt.legend('center')
 plt.xlabel('alpha')
 plt.ylabel('score' )
class BaselineModel(nn.Module):
def __init__(self, model_cfg):
super(BaselineModel, self ).__init__()
self.backbone = build_densenet_backbone(model_cfg['backbone_cfg'])
 self.head = build_head(model_cfg['head_cfg'])
 self.heads_dims = model_cfg['head_cfg']['output_dims']
def forward(self, x):
x = self.backbone(x)
 x = self.head(x)
 grapheme_logits, vowel_logits, consonant_logits = torch.split(x, self.heads_dims, dim=1)
 return grapheme_logits, vowel_logits, consonant_logits<load_pretrained>
alphas_alt = [9,9.1,9.2,9.3,9.4,9.5,9.6,9.7,9.8,9.9,10,10.1,10.2]
ridge_model2 = make_pipeline(RobustScaler() ,
RidgeCV(alphas = alphas_alt,
cv=kfolds)).fit(one_hot_encoding_train, y_reg)
 print("Ridge rmse : ",cv_rmse(ridge_model2 ).mean() )
model = BaselineModel(model_cfg)
 state_dict = torch.load(WEIGHTS_FILE, map_location='cpu')
 model.load_state_dict(state_dict['model_state'])
 model.to(device )<split>
print("Best of alpha in ridge model :" ,ridge_model2.steps[1][1].alpha_ )
def test_eval() :
model.eval()
test_data = ['test_image_data_0.parquet','test_image_data_1.parquet','test_image_data_2.parquet','test_image_data_3.parquet']
row_id,target = [],[]
batch_size=1
for idx, fname in enumerate(test_data):
test_images = get_data('test', indices=[str(idx)])
 test_dataset = BengaliDataset(test_images, dataset_cfg, fname=fname)
 test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False,
num_workers=4)
 with torch.no_grad() :
for inputs, name in test_loader:
inputs = inputs.to(device)
 name = str(name ).strip("'() ,'")
 grapheme_logits, vowel_logits, consonant_logits = model(inputs.float())
 grapheme_logits = grapheme_logits.argmax(-1)
 vowel_logits = vowel_logits.argmax(-1)
 consonant_logits = consonant_logits.argmax(-1)
 row_id += [f'{name}_grapheme_root',f'{name}_vowel_diacritic',
f'{name}_consonant_diacritic']
target += [grapheme_logits.item() , vowel_logits.item() ,
consonant_logits.item() ]
del test_images, test_dataset, test_loader
gc.collect()
return pd.DataFrame({'row_id': row_id, 'target': target})
<prepare_output>
alphas2 = [0.00005, 0.0001, 0.0002, 0.0003, 0.0004, 0.0005,
0.0006, 0.0007, 0.0008]
lasso_model2 = make_pipeline(RobustScaler() ,
LassoCV(max_iter=1e7,
alphas = alphas2,
random_state = 42)).fit(one_hot_encoding_train, y_reg)
 scores = lasso_model2.steps[1][1].mse_path_
plt.plot(alphas2, scores, label='Lasso')
 plt.legend(loc='center')
 plt.xlabel('alpha')
 plt.ylabel('RMSE')
 plt.tight_layout()
plt.show()
submission_df = test_eval()<save_to_csv>
print("Best of alpha in lasso model :",lasso_model2.steps[1][1].alpha_)
 print("lasso rmse : ",cv_rmse(lasso_model2 ).mean() )
submission_df.to_csv('submission.csv', index=False )<import_modules>
e_alphas = [0.0001, 0.0002, 0.0003, 0.0004, 0.0005, 0.0006, 0.0007]
e_l1ratio = [0.8, 0.85, 0.9, 0.95, 0.99, 1]
elastic_cv = make_pipeline(RobustScaler() ,
ElasticNetCV(max_iter=1e7, alphas=e_alphas,
cv=kfolds, l1_ratio=e_l1ratio))
elastic_model3 = elastic_cv.fit(one_hot_encoding_train, y_reg)
 print("elastic model rmse : ",cv_rmse(elastic_model3 ).mean() )
import numpy as np
import pandas as pd
import os 
<load_from_csv>
xgb3 = XGBRegressor(learning_rate =0.01, n_estimators=5200, max_depth=3,
min_child_weight=0 ,gamma=0, subsample=0.7,
colsample_bytree=0.7,objective= 'reg:linear',
nthread=4,scale_pos_weight=1,seed=27, reg_alpha=0.00006)
 xgb_fit = xgb3.fit(one_hot_encoding_train, y_reg)
 print("Xgboost model rmse : ",cv_rmse(xgb_fit ).mean() )
submission = pd.read_csv('/kaggle/input/lish-moa/sample_submission.csv')
 public_ids = list(submission['sig_id'].values)
 submission.shape<load_from_csv>
model = lgb.LGBMRegressor(objective='regression',num_leaves=5,
learning_rate=0.01, n_estimators=5000,
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 = model.fit(one_hot_encoding_train, y_reg)
 print("lightgbm model rmse : ",cv_rmse(model ).mean() )
test = pd.read_csv('/kaggle/input/lish-moa/test_features.csv')
 test_ids = list(test['sig_id'].values)
 private_ids = list(set(test_ids)-set(public_ids))
len(private_ids )<load_from_csv>
feature_importance_df = pd.DataFrame()
feature_importance_df["feature"] = one_hot_encoding_test.columns
feature_importance_df["importance"] = model.feature_importances_
def make_filename(idx):
return glob.glob('.. /input/moa-1082020/' + str(idx)+ '.csv')[0]
def read_predictions(idx):
temp = pd.read_csv(make_filename(idx))
return temp
predictions = [read_predictions(idx)for idx in range(1,18)]
len(predictions )<prepare_x_and_y>
train_ridge_preds = ridge_model2.predict(one_hot_encoding_train)
 train_lasso_preds = lasso_model2.predict(one_hot_encoding_train)
 train_elastic_preds = elastic_model3.predict(one_hot_encoding_train)
 train_xgb_preds = xgb_fit.predict(one_hot_encoding_train)
 train_lgbm_preds = lgbm_fit.predict(one_hot_encoding_train)
 stackX = pd.DataFrame(np.transpose(np.array([train_ridge_preds,train_lasso_preds,train_elastic_preds,train_xgb_preds,train_lgbm_preds])))
 model = lgb.LGBMRegressor(objective='regression',num_leaves=5,
learning_rate=0.01, n_estimators=4500,
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)
 stack_fit = model.fit(stackX, y_reg )
y_pred = pd.DataFrame()
y_pred['sig_id'] = predictions[0]['sig_id']
for column in target_columns:
column_data = []
for i in range(len(predictions)) :
column_data.append(predictions[i][column])
 y_pred[column] = np.mean(column_data, axis=0)
 y_pred.shape<save_to_csv>
print("lightgbm model rmse : ",cv_rmse(model ).mean() )
submission = pd.DataFrame(index = public_ids + private_ids, columns=target_columns)
 submission.index.name = 'sig_id'
submission[:] = 0
submission.loc[y_pred.sig_id,:] = y_pred[target_columns].values
submission.loc[test[test.cp_type == 'ctl_vehicle'].sig_id] = 0
submission.to_csv('submission.csv', index=True)
 submission.head().T<set_options>
test_ridge_preds = ridge_model2.predict(one_hot_encoding_test)
 test_lasso_preds = lasso_model2.predict(one_hot_encoding_test)
 test_elastic_preds = elastic_model3.predict(one_hot_encoding_test)
 test_xgb_preds = xgb_fit.predict(one_hot_encoding_test)
 test_lgbm_preds = lgbm_fit.predict(one_hot_encoding_test )
if torch.cuda.is_available() :
device = torch.device("cuda")
 print('There are %d GPU(s)available.' % torch.cuda.device_count())
 print('We will use the GPU:', torch.cuda.get_device_name(0))
else:
print('No GPU available, using the CPU instead.')
 device = torch.device("cpu" )<load_from_csv>
submission = pd.DataFrame({'Id': Id, 'SalePrice': np.expm1(test_ridge_preds)})
 submission.to_csv('ridge.csv', index=False)
 submission = pd.DataFrame({'Id': Id, 'SalePrice': np.expm1(test_lasso_preds)})
 submission.to_csv('lasso.csv', index=False)
 submission = pd.DataFrame({'Id': Id, 'SalePrice': np.expm1(test_elastic_preds)})
 submission.to_csv('elastic.csv', index=False)
 submission = pd.DataFrame({'Id': Id, 'SalePrice': np.expm1(test_xgb_preds)})
 submission.to_csv('xgb.csv', index=False)
 submission = pd.DataFrame({'Id': Id, 'SalePrice': np.expm1(test_lgbm_preds)})
 submission.to_csv('lgbm.csv', index=False )
train_df = pd.read_csv('/kaggle/input/nlp-getting-started/train.csv',encoding='UTF-8')
 print('Number of training sentences: {:,}
'.format(train_df.shape[0]))
train_df.sample(10 )<load_pretrained>
test_stackX = pd.DataFrame(np.transpose(np.array([test_ridge_preds,test_lasso_preds,test_elastic_preds,test_xgb_preds,test_lgbm_preds])))
 stack_pred = np.expm1(stack_fit.predict(test_stackX))
submission = pd.DataFrame({'Id': Id, 'SalePrice': stack_pred})
 submission.to_csv('LGB_stacking.csv', index=False )
with open('.. /input/bert-prediction/predictions.pkl','rb')as f:
predictions = pickle.load(f)
<prepare_output>
average = 0.2*test_ridge_preds + 0.2*test_lasso_preds + 0.2*test_elastic_preds + 0.2*test_xgb_preds + 0.2*test_lgbm_preds
average = np.expm1(average)
 submission = pd.DataFrame({'Id': Id, 'SalePrice': average})
 submission.to_csv('SimpleAvg.csv', index=False )
train_df['infold_pred'] = predictions['infold_pred']
train_df['outfold_pred'] = predictions['outfold_pred']<define_variables>
weight_average1 = 0.3980767*test_ridge_preds + -0.03065248*test_lasso_preds + 0.12292276*test_elastic_preds + -0.20778906*test_xgb_preds + 0.71743772*test_lgbm_preds
weight_average1 = np.expm1(weight_average1)
 submission = pd.DataFrame({'Id': Id, 'SalePrice': weight_average1})
 submission.to_csv('WeightAvg1.csv', index=False )
remove_rows_based_on_cv = True
model_name = 'albert'
model_shortcut_name = 'albert-base-v1'
do_lower_case = True
learning_rate = 5e-6
epochs = 6
batch_size = 16
run_test_to_get_best_epoch = False
epochs_final = 2
score_to_take_best = 'val_f1_score'
score_to_take_best_order = False<filter>
weight_average2 = 0.28018685*test_ridge_preds + 0.10355858*test_lasso_preds + 0.1161906*test_elastic_preds + 0.006204816*test_xgb_preds + 0.49386202*test_lgbm_preds
weight_average2 = np.expm1(weight_average2)
 submission = pd.DataFrame({'Id': Id, 'SalePrice': weight_average2})
 submission.to_csv('WeightAvg2.csv', index=False )