Kaggle competition: Costa Rican Household Poverty Level Prediction
if FINETUNE:
Pseudo_Labeling = True
VERBOSE = 0
save_path = '.. /input/multilabel-pbestpre-mlp/'
sample_sub_path = '.. /input/lish-moa/sample_submission.csv'
overall_oof_scores = []
oof_mlp2 = []
submission_mlp2 = []
for m in range(len(model_params)) :
print(model_names[m], model_params[m])
 model_name = model_names[m]
oof_score, res, ss = train_model(train, train_targets, train_targets_nonscored, top_feats, model_name, save_path,
N_STARTS, N_SPLITS, model_params[m], test, sample_sub_path, Pseudo_Labeling, VERBOSE)
 submission_mlp2.append(ss)
 if CALCULATE_OOF_PL:
tr_targets = pd.read_csv('.. /input/lish-moa/train_targets_scored.csv' ).drop('sig_id', axis = 1)
 res_all = np.zeros(tr_targets[cols].shape)
 res_all[train_features['cp_type'] == 0] = res[cols].values
overall_oof_score = log_loss_metric(tr_targets[cols].values, res_all)
 overall_oof_scores.append(overall_oof_score)
 print(f'{model_name} Overall OOF CV Score:', overall_oof_score)
 oof_mlp2.append(res_all )<compute_test_metric>
warnings.filterwarnings('ignore')
if FINETUNE:
if CALCULATE_OOF_PL:
for n, name in enumerate(model_names):
print(f'{name} OOF:\t', overall_oof_scores[n] )<load_from_csv>
train_data = pd.read_csv('.. /input/train.csv')
 print(train_data.shape)
 train_data.head()
if FINETUNE:
ss = pd.read_csv('.. /input/lish-moa/sample_submission.csv')
 ss[cols] = 0.1296464333222514 * submission_mlp2[0][cols].values + \
0.2250012012344317 * submission_mlp2[1][cols].values + \
0.06289126408177141 * submission_mlp2[2][cols].values + \
0.06845298029278386 * submission_mlp2[3][cols].values + \
0.39624897237262097 * submission_tabnet2[cols].values + \
0.1177591486961407 * submission_grownet[cols].values<save_to_csv>
test_data = pd.read_csv('.. /input/test.csv')
 print(test_data.shape)
 test_data.head()
ss.to_csv('submission.csv', index = False)
 ss.head(10 )<install_modules>
trainId = train_data['Id']
testId = test_data['Id']
! pip install.. /input/moa-pytorch16/torch-1.6.0cu101-cp37-cp37m-linux_x86_64.whl<install_modules>
train_data_1 = train_data.drop(['Id', 'idhogar'], axis=1)
 test_data_1 = test_data.drop(['Id', 'idhogar'], axis=1 )
!pip install.. /input/moaiterative/iterative_stratification-0.1.6-py3-none-any.whl<feature_engineering>
train_data_1 = pd.get_dummies(train_data_1)
 test_data_1 = pd.get_dummies(test_data_1 )
os.environ["CUDA_LAUNCH_BLOCKING"] = "1" 
<set_options>
train_data_1['Id'] = trainId
test_data_1['Id'] = testId
def seed_everything(seed_value):
random.seed(seed_value)
 np.random.seed(seed_value)
 torch.manual_seed(seed_value)
 os.environ['PYTHONHASHSEED'] = str(seed_value)
 if torch.cuda.is_available() :
torch.cuda.manual_seed(seed_value)
 torch.cuda.manual_seed_all(seed_value)
 torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
seed_everything(1984 )<load_from_csv>
train_label = train_data_1['Target']
train_data_1, test_data_1 = train_data_1.align(test_data_1, join='inner', axis=1 )
train = pd.read_csv('.. /input/lish-moa/train_features.csv')
 train_targets_scored = pd.read_csv('.. /input/lish-moa/train_targets_scored.csv')
 train_targets_nonscored = pd.read_csv('.. /input/lish-moa/train_targets_nonscored.csv')
 test_features = pd.read_csv('.. /input/lish-moa/test_features.csv')
 submission = pd.read_csv('.. /input/lish-moa/sample_submission.csv')
 remove_vehicle = True
if remove_vehicle:
train_features = train.loc[train['cp_type']=='trt_cp'].reset_index(drop=True)
 train_targets_scored = train_targets_scored.loc[train['cp_type']=='trt_cp'].reset_index(drop=True)
 train_targets_nonscored = train_targets_nonscored.loc[train['cp_type']=='trt_cp'].reset_index(drop=True)
 else:
train_features = train 
<data_type_conversions>
poly_features = train_data_1[['escolari', 'cielorazo', 'meaneduc', 'hogar_nin', 'r4t1', 'SQBhogar_nin', 'Target']]
poly_features_test = test_data_1[['escolari', 'cielorazo', 'meaneduc', 'hogar_nin', 'r4t1', 'SQBhogar_nin']]
def get_ratio_labels(df):
columns = list(df.columns)
 columns.pop(0)
 ratios = []
toremove = []
for c in columns:
counts = df[c].value_counts()
if len(counts)!= 1:
ratios.append(counts[0]/counts[1])
 else:
toremove.append(c)
 print(f"remove {len(toremove)} columns")
 for t in toremove:
columns.remove(t)
 return columns, np.array(ratios ).astype(np.int32)
 columns, ratios = get_ratio_labels(train_targets_scored)
 columns_nonscored, ratios_nonscored = get_ratio_labels(train_targets_nonscored )<define_variables>
imputer = Imputer(strategy='median')
 poly_target = poly_features['Target']
poly_features = poly_features.drop(columns=['Target'] )
GENES = [col for col in train_features.columns if col.startswith('g-')]
CELLS = [col for col in train_features.columns if col.startswith('c-')]<load_from_csv>
poly_features = imputer.fit_transform(poly_features)
 poly_features_test = imputer.transform(poly_features_test )
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
 def load_data(train_path, cols):
if isinstance(train_path, list):
df_base = pd.read_csv(train_path[0])
 for i in range(1, len(train_path)) :
df_base.append(pd.read_csv(train_path[i]))
df_base = df_base[cols]
else:
df = pd.read_csv(train_path)
 df_base = df[cols]
x = df_base.values.reshape(-1, df_base.shape[1] ).astype('float32')
 standardizer = preprocessing.StandardScaler()
x = standardizer.fit_transform(x)
 return x, standardizer
def numpyToTensor(x):
x_train = torch.from_numpy(x ).to(device)
 return x_train
class DataBuilder(Dataset):
def __init__(self, path, cols):
self.x, self.standardizer = load_data(path, cols)
 self.x = numpyToTensor(self.x)
 self.len=self.x.shape[0]
def __getitem__(self,index):
return self.x[index]
def __len__(self):
return self.len<categorify>
poly_transformer = PolynomialFeatures(degree=3 )
class Autoencoder(nn.Module):
def __init__(self,D_in, H, H2, latent_dim):
super(Autoencoder,self ).__init__()
self.linear1=nn.Linear(D_in,H)
 self.lin_bn1 = nn.BatchNorm1d(num_features=H)
 self.linear2=nn.Linear(H,H2)
 self.lin_bn2 = nn.BatchNorm1d(num_features=H2)
 self.linear3=nn.Linear(H2,H2)
 self.lin_bn3 = nn.BatchNorm1d(num_features=H2)
 self.fc1 = nn.Linear(H2, latent_dim)
 self.bn1 = nn.BatchNorm1d(num_features=latent_dim)
 self.fc21 = nn.Linear(latent_dim, latent_dim)
 self.fc22 = nn.Linear(latent_dim, latent_dim)
 self.fc3 = nn.Linear(latent_dim, latent_dim)
 self.fc_bn3 = nn.BatchNorm1d(latent_dim)
 self.fc4 = nn.Linear(latent_dim, H2)
 self.fc_bn4 = nn.BatchNorm1d(H2)
 self.linear4=nn.Linear(H2,H2)
 self.lin_bn4 = nn.BatchNorm1d(num_features=H2)
 self.linear5=nn.Linear(H2,H)
 self.lin_bn5 = nn.BatchNorm1d(num_features=H)
 self.linear6=nn.Linear(H,D_in)
 self.lin_bn6 = nn.BatchNorm1d(num_features=D_in)
 self.leaky_relu = nn.LeakyReLU()
def encode(self, x):
lin1 = self.leaky_relu(self.lin_bn1(self.linear1(x)))
 lin2 = self.leaky_relu(self.lin_bn2(self.linear2(lin1)))
 lin3 = self.leaky_relu(self.lin_bn3(self.linear3(lin2)))
 fc1 = F.leaky_relu(self.bn1(self.fc1(lin3)))
 r1 = self.fc21(fc1)
 r2 = self.fc22(fc1)
 return r1, r2
def reparameterize(self, mu, logvar):
if self.training:
std = logvar.mul(0.5 ).exp_()
eps = Variable(std.data.new(std.size() ).normal_())
 return eps.mul(std ).add_(mu)
 else:
return mu
def decode(self, z):
fc3 = self.leaky_relu(self.fc_bn3(self.fc3(z)))
 fc4 = self.leaky_relu(self.fc_bn4(self.fc4(fc3)))
 lin4 = self.leaky_relu(self.lin_bn4(self.linear4(fc4)))
 lin5 = self.leaky_relu(self.lin_bn5(self.linear5(lin4)))
 return self.lin_bn6(self.linear6(lin5))
def forward(self, x):
mu, logvar = self.encode(x)
 z = self.reparameterize(mu, logvar)
 return self.decode(z), mu, logvar
class customLoss(nn.Module):
def __init__(self):
super(customLoss, self ).__init__()
self.mse_loss = nn.MSELoss(reduction="sum")
 def forward(self, x_recon, x, mu, logvar):
loss_MSE = self.mse_loss(x_recon, x)
 loss_KLD = -0.5 * torch.sum(1 + logvar - mu.pow(2)- logvar.exp())
 return loss_MSE + loss_KLD
def weights_init_uniform_rule(m):
classname = m.__class__.__name__
if classname.find('Linear')!= -1:
n = m.in_features
y = 1.0/np.sqrt(n)
 m.weight.data.uniform_(-y, y)
 m.bias.data.fill_(0)
 def train(epoch, dataloader, model, optimizer):
loss_mse = customLoss()
model.train()
train_loss = 0
for batch_idx, data in enumerate(dataloader):
data = data.to(device)
 optimizer.zero_grad()
recon_batch, mu, logvar = model(data)
 loss = loss_mse(recon_batch, data, mu, logvar)
 loss.backward()
train_loss += loss.item()
optimizer.step()
if epoch % 100 == 0:
print('====> Epoch: {} Average loss: {:.4f}'.format(epoch, train_loss / len(dataloader.dataset)))
 def encode_features(data_loader, model, optimizer):
mu_output = []
logvar_output = []
with torch.no_grad() :
for i,(data)in enumerate(data_loader):
data = data.to(device)
 optimizer.zero_grad()
recon_batch, mu, logvar = model(data)
 mu_tensor = mu
mu_output.append(mu_tensor)
 mu_result = torch.cat(mu_output, dim=0)
 logvar_tensor = logvar
logvar_output.append(logvar_tensor)
 logvar_result = torch.cat(logvar_output, dim=0)
 return mu_result
def get_encoder_features(TRAIN_DATA_PATH, TEST_DATA_PATH, cols, latent_dim, name, train_flag=True):
print('Reading train data...')
 data_set_train=DataBuilder(TRAIN_DATA_PATH, cols)
 trainloader=DataLoader(dataset=data_set_train,batch_size=512)
 print('Reading test data...')
 data_set_test=DataBuilder(TEST_DATA_PATH, cols)
 testloader=DataLoader(dataset=data_set_test,batch_size=512)
 print('Reading data...')
 data_set = DataBuilder([TRAIN_DATA_PATH, TEST_DATA_PATH], cols)
 loader=DataLoader(dataset=data_set,batch_size=512)
 print('Prepare params...')
 D_in = data_set_train.x.shape[1]
H = D_in -(D_in - latent_dim)// 4
H2 = D_in -(D_in - latent_dim)// 2
model = Autoencoder(D_in, H, H2, latent_dim ).to(device)
 model.apply(weights_init_uniform_rule)
 optimizer = optim.Adam(model.parameters() , lr=1e-3)
 loss_mse = customLoss()
epochs = 500
log_interval = 50
val_losses = []
train_losses = []
print("train or load model...")
 if train_flag:
print("train model...")
 for epoch in range(1, epochs + 1):
train(epoch, loader, model, optimizer)
 torch.save(model.state_dict() , name)
 else:
print("load model...")
 model.load_state_dict(torch.load(name))
model.eval()
print("extract features...")
 train_encoder = encode_features(trainloader, model, optimizer)
 test_encoder = encode_features(testloader, model, optimizer)
 return train_encoder, test_encoder<categorify>
poly_transformer.fit(poly_features )
TRAIN_DATA_PATH = '.. /input/lish-moa/train_features.csv'
TEST_DATA_PATH = '.. /input/lish-moa/test_features.csv'
gene_encode_dim = 50
cell_encode_dim = 30
genes_model_name = '.. /input/moa-tabnet-1830/autoencode_genes_50_30_default'
cells_model_name = '.. /input/moa-tabnet-1830/autoencode_cells_50_30_default'
train_gene_encoder, test_gene_encoder = get_encoder_features(TRAIN_DATA_PATH, TEST_DATA_PATH, GENES, gene_encode_dim, genes_model_name,
train_flag=False)
 train_cell_encoder, test_cell_encoder = get_encoder_features(TRAIN_DATA_PATH, TEST_DATA_PATH, CELLS, cell_encode_dim, cells_model_name,
train_flag=False)
 train_gene_encoder_pd = pd.DataFrame(train_gene_encoder.cpu().numpy() , columns=[f'VAE_G_{i}' for i in range(gene_encode_dim)])
 test_gene_encoder_pd = pd.DataFrame(test_gene_encoder.cpu().numpy() , columns=[f'VAE_G_{i}' for i in range(gene_encode_dim)])
 train_cell_encoder_pd = pd.DataFrame(train_cell_encoder.cpu().numpy() , columns=[f'VAE_C_{i}' for i in range(cell_encode_dim)])
 test_cell_encoder_pd = pd.DataFrame(test_cell_encoder.cpu().numpy() , columns=[f'VAE_C_{i}' for i in range(cell_encode_dim)] )<merge>
poly_features = poly_transformer.transform(poly_features)
 poly_features_test = poly_transformer.transform(poly_features_test)
 print(poly_features.shape )
train_gene_encoder_pd['sig_id'] = train_features['sig_id']
train_cell_encoder_pd['sig_id'] = train_features['sig_id']
test_gene_encoder_pd['sig_id'] = test_features['sig_id']
test_cell_encoder_pd['sig_id'] = test_features['sig_id']
train_features = train_features.merge(train_gene_encoder_pd, on='sig_id')
 train_features = train_features.merge(train_cell_encoder_pd, on='sig_id')
 test_features = test_features.merge(test_gene_encoder_pd, on='sig_id')
 test_features = test_features.merge(test_cell_encoder_pd, on='sig_id' )<create_dataframe>
poly_transformer.get_feature_names(['escolari', 'cielorazo', 'meaneduc', 'hogar_nin', 'r4t1', 'SQBhogar_nin'])[:15]
n_comp = 80
pca_g = load('.. /input/moa-tabnet-1830/pca_g.joblib')
 data = pd.concat([pd.DataFrame(train_features[GENES]), pd.DataFrame(test_features[GENES])])
 data2 = pca_g.transform(data[GENES])
 train2 = data2[:train_features.shape[0]];
test2 = data2[-test_features.shape[0]:]
train2 = pd.DataFrame(train2, columns=[f'pca_G-{i}' for i in range(n_comp)])
 test2 = pd.DataFrame(test2, columns=[f'pca_G-{i}' for i in range(n_comp)])
 train_features = pd.concat(( train_features, train2), axis=1)
 test_features = pd.concat(( test_features, test2), axis=1)
 n_comp = 40
pca_c = load('.. /input/moa-tabnet-1830/pca_c.joblib')
 data = pd.concat([pd.DataFrame(train_features[CELLS]), pd.DataFrame(test_features[CELLS])])
 data2 = pca_c.transform(data[CELLS])
 train2 = data2[:train_features.shape[0]];
test2 = data2[-test_features.shape[0]:]
train2 = pd.DataFrame(train2, columns=[f'pca_1_C-{i}' for i in range(n_comp)])
 test2 = pd.DataFrame(test2, columns=[f'pca_1_C-{i}' for i in range(n_comp)])
 train_features = pd.concat(( train_features, train2), axis=1)
 test_features = pd.concat(( test_features, test2), axis=1)
 n_comp = 80
print("FastICA on genes")
 transformer = load('.. /input/moa-tabnet-1830/FastICA_g.joblib')
 data = pd.concat([pd.DataFrame(train_features[GENES]), pd.DataFrame(test_features[GENES])])
 data2 = transformer.transform(data[GENES])
 train2 = data2[:train_features.shape[0]];
test2 = data2[-test_features.shape[0]:]
train2 = pd.DataFrame(train2, columns=[f'FastICA_G-{i}' for i in range(n_comp)])
 test2 = pd.DataFrame(test2, columns=[f'FastICA_G-{i}' for i in range(n_comp)])
 train_features = pd.concat(( train_features, train2), axis=1)
 test_features = pd.concat(( test_features, test2), axis=1)
 n_comp = 40
print("FastICA on cells")
 transformer = load('.. /input/moa-tabnet-1830/FastICA_c.joblib')
 data = pd.concat([pd.DataFrame(train_features[CELLS]), pd.DataFrame(test_features[CELLS])])
 data2 = transformer.transform(data[CELLS])
 train2 = data2[:train_features.shape[0]];
test2 = data2[-test_features.shape[0]:]
train2 = pd.DataFrame(train2, columns=[f'FastICA_C-{i}' for i in range(n_comp)])
 test2 = pd.DataFrame(test2, columns=[f'FastICA_C-{i}' for i in range(n_comp)])
 train_features = pd.concat(( train_features, train2), axis=1)
 test_features = pd.concat(( test_features, test2), axis=1)
 n_comp = 80
print("FactorAnalysis on genes")
 transformer = load('.. /input/moa-tabnet-1830/FactorAnalysis_g.joblib')
 data = pd.concat([pd.DataFrame(train_features[GENES]), pd.DataFrame(test_features[GENES])])
 data2 = transformer.transform(data[GENES])
 train2 = data2[:train_features.shape[0]];
test2 = data2[-test_features.shape[0]:]
train2 = pd.DataFrame(train2, columns=[f'FactorAnalysis_G-{i}' for i in range(n_comp)])
 test2 = pd.DataFrame(test2, columns=[f'FactorAnalysis_G-{i}' for i in range(n_comp)])
 train_features = pd.concat(( train_features, train2), axis=1)
 test_features = pd.concat(( test_features, test2), axis=1)
 n_comp = 40
print("FactorAnalysis on cells")
 transformer = load('.. /input/moa-tabnet-1830/FactorAnalysis_c.joblib')
 data = pd.concat([pd.DataFrame(train_features[CELLS]), pd.DataFrame(test_features[CELLS])])
 data2 = transformer.transform(data[CELLS])
 train2 = data2[:train_features.shape[0]];
test2 = data2[-test_features.shape[0]:]
train2 = pd.DataFrame(train2, columns=[f'FactorAnalysis_C-{i}' for i in range(n_comp)])
 test2 = pd.DataFrame(test2, columns=[f'FactorAnalysis_C-{i}' for i in range(n_comp)])
 train_features = pd.concat(( train_features, train2), axis=1)
 test_features = pd.concat(( test_features, test2), axis=1)
 n_comp = 80
print("FeatureAgglomeration on genes")
 transformer = load('.. /input/moa-tabnet-1830/FeatureAgglomeration_g.joblib')
 data = pd.concat([pd.DataFrame(train_features[GENES]), pd.DataFrame(test_features[GENES])])
 data2 = transformer.transform(data[GENES])
 train2 = data2[:train_features.shape[0]];
test2 = data2[-test_features.shape[0]:]
train2 = pd.DataFrame(train2, columns=[f'FeatureAgglomeration_G-{i}' for i in range(n_comp)])
 test2 = pd.DataFrame(test2, columns=[f'FeatureAgglomeration_G-{i}' for i in range(n_comp)])
 train_features = pd.concat(( train_features, train2), axis=1)
 test_features = pd.concat(( test_features, test2), axis=1)
 n_comp = 40
print("FeatureAgglomeration on cells")
 transformer = load('.. /input/moa-tabnet-1830/FeatureAgglomeration_c.joblib')
 data = pd.concat([pd.DataFrame(train_features[CELLS]), pd.DataFrame(test_features[CELLS])])
 data2 = transformer.transform(data[CELLS])
 train2 = data2[:train_features.shape[0]];
test2 = data2[-test_features.shape[0]:]
train2 = pd.DataFrame(train2, columns=[f'FeatureAgglomeration_C-{i}' for i in range(n_comp)])
 test2 = pd.DataFrame(test2, columns=[f'FeatureAgglomeration_C-{i}' for i in range(n_comp)])
 train_features = pd.concat(( train_features, train2), axis=1)
 test_features = pd.concat(( test_features, test2), axis=1)
<feature_engineering>
poly_features = pd.DataFrame(poly_features, columns=poly_transformer.get_feature_names(['escolari', 'cielorazo', 'meaneduc', 'hogar_nin', 'r4t1', 'SQBhogar_nin']))
poly_features['Target'] = poly_target
def stat_feat(df, features_g, features_c):
df['g_sum'] = df[features_g].sum(axis = 1)
 df['g_mean'] = df[features_g].mean(axis = 1)
 df['g_std'] = df[features_g].std(axis = 1)
 df['g_kurt'] = df[features_g].kurtosis(axis = 1)
 df['g_skew'] = df[features_g].skew(axis = 1)
 df['c_sum'] = df[features_c].sum(axis = 1)
 df['c_mean'] = df[features_c].mean(axis = 1)
 df['c_std'] = df[features_c].std(axis = 1)
 df['c_kurt'] = df[features_c].kurtosis(axis = 1)
 df['c_skew'] = df[features_c].skew(axis = 1)
 df['gc_sum'] = df[features_g + features_c].sum(axis = 1)
 df['gc_mean'] = df[features_g + features_c].mean(axis = 1)
 df['gc_std'] = df[features_g + features_c].std(axis = 1)
 df['gc_kurt'] = df[features_g + features_c].kurtosis(axis = 1)
 df['gc_skew'] = df[features_g + features_c].skew(axis = 1)
 return df
train_features = stat_feat(train_features, GENES, CELLS)
 test_features = stat_feat(test_features, GENES, CELLS )<categorify>
poly_features_test = pd.DataFrame(poly_features_test, columns=poly_transformer.get_feature_names(['escolari', 'cielorazo', 'meaneduc', 'hogar_nin', 'r4t1', 'SQBhogar_nin']))
class VarianceThreshold:
def __init__(self, threshold):
self.threshold = threshold
def fit(self, df, cont_cols):
self.cont_cols = cont_cols
self.var = df[cont_cols].var()
good_cols = self.var[self.var > self.threshold]
self.index = good_cols.index.to_list()
self.dropcols = [x for x in cont_cols if x not in self.var[self.var > self.threshold].index.to_list() ]
self.validcols = [x for x in cont_cols if x in self.var[self.var > self.threshold].index.to_list() ]
def transform(self, df):
return df.drop(self.dropcols, axis=1)
 def fit_transform(self, df, cont_cols):
self.fit(df, cont_cols)
 return self.transform(df), self.validcols<define_variables>
poly_features['Id'] = train_data_1['Id']
cont_cols = [col for col in train_features.columns.to_list() if col not in ['sig_id','cp_type','cp_time','cp_dose']]<normalization>
train_data_poly = train_data_1.merge(poly_features, on='Id', how='left' )
threshold = 0.2
print('Variance Threshold:', threshold)
 VarThres = VarianceThreshold(threshold)
 train_features, cont_cols = VarThres.fit_transform(train_features, cont_cols)
 test_features = VarThres.transform(test_features )<categorify>
poly_features_test['Id'] = test_data_1['Id']
qt = load('.. /input/moa-tabnet-1830/qt.joblib')
 train_features[cont_cols] = qt.fit_transform(train_features[cont_cols])
 test_features[cont_cols] = qt.transform(test_features[cont_cols] )<categorify>
test_data_poly = test_data_1.merge(poly_features_test, on='Id', how='left' )
def transform_data(train, test, col, normalize=True, removed_vehicle=False):

 mapping = {"cp_type":{"trt_cp": 0, "ctl_vehicle":1},
"cp_time":{48:0, 72:1, 24:2},
"cp_dose":{"D1":0, "D2":1}}
if removed_vehicle:
categories_tr = np.stack([ train[c].apply(lambda x: mapping[c][x] ).values for c in col[1:3]], axis=1)
 categories_test = np.stack([ test[c].apply(lambda x: mapping[c][x] ).values for c in col[1:3]], axis=1)
 else:
categories_tr = np.stack([ train[c].apply(lambda x: mapping[c][x] ).values for c in col[:3]], axis=1)
 categories_test = np.stack([ test[c].apply(lambda x: mapping[c][x] ).values for c in col[:3]], axis=1)
 max_ = 10.
 min_ = -10.
 if removed_vehicle:
numerical_tr = train[col[3:]].values
numerical_test = test[col[3:]].values
else:
numerical_tr = train[col[3:]].values
numerical_test = test[col[3:]].values
if normalize:
numerical_tr =(numerical_tr-min_)/(max_ - min_)
 numerical_test =(numerical_test-min_)/(max_ - min_)
 return categories_tr, categories_test, numerical_tr, numerical_test
col_features = list(train_features.columns)[1:]
cat_tr, cat_test, numerical_tr, numerical_test = transform_data(train_features, test_features, col_features, normalize=False, removed_vehicle=remove_vehicle)
 targets_tr = train_targets_scored[columns].values.astype(np.float32)
 targets2_tr = train_targets_nonscored[columns_nonscored].values.astype(np.float32)
<compute_train_metric>
train_data_poly, test_data_poly = train_data_poly.align(test_data_poly, join='inner', axis=1 )
def evals(model, X, y, verbose=True):
with torch.no_grad() :
y_preds = model.predict(X)
 y_preds = torch.clamp(y_preds, 0.0,1.0 ).detach().numpy()
score = log_loss_multi(y, y_preds)
 return y_preds, score
def inference_fn(model, X ,verbose=True):
with torch.no_grad() :
y_preds = model.predict(X)
 y_preds = torch.sigmoid(torch.as_tensor(y_preds)).numpy()
return y_preds<compute_test_metric>
train_data_1.drop(['Id'], axis=1, inplace=True)
 test_data_1.drop(['Id'], axis=1, inplace=True)
 train_data_poly.drop(['Id'], axis=1, inplace=True)
 test_data_poly.drop(['Id'], axis=1, inplace=True )
def log_loss_score(actual, predicted, eps=1e-15):

 p1 = actual * np.log(predicted+eps)
 p0 =(1-actual)* np.log(1-predicted+eps)
 loss = p0 + p1
return -loss.mean()<compute_test_metric>
imputer = Imputer(strategy='median')
 poly_features = imputer.fit_transform(train_data_poly)
 poly_features_test = imputer.transform(test_data_poly )
def log_loss_multi(y_true, y_pred):
M = y_true.shape[1]
results = np.zeros(M)
 for i in range(M):
results[i] = log_loss_score(y_true[:,i], y_pred[:,i])
 return results.mean() 
<compute_test_metric>
scaler = MinMaxScaler(feature_range=(0,1))
poly_features = scaler.fit_transform(train_pca)
 poly_features_test = scaler.transform(test_pcs )
def auc_multi(y_true, y_pred):
M = y_true.shape[1]
results = np.zeros(M)
 for i in range(M):
try:
results[i] = roc_auc_score(y_true[:,i], y_pred[:,i])
 except:
pass
return results.mean()<import_modules>
model = lgb.LGBMClassifier(n_estimators=100, objective='multiclass',
class_weight = 'balanced', learning_rate = 0.05,
reg_alpha = 0.1, reg_lambda = 0.1,
subsample = 0.8, n_jobs = -1, random_state = 50 )
create_dataloaders,
create_explain_matrix)
 class TabModel(BaseEstimator):
def __init__(self, n_d=8, n_a=8, n_steps=3, gamma=1.3, cat_idxs=[], cat_dims=[], cat_emb_dim=1,
n_independent=2, n_shared=2, epsilon=1e-15, momentum=0.02,
lambda_sparse=1e-3, seed=0,
clip_value=1, verbose=1,
optimizer_fn=torch.optim.Adam,
optimizer_params=dict(lr=2e-2),
scheduler_params=None, scheduler_fn=None,
mask_type="sparsemax",
input_dim=None, output_dim=None,
device_name='auto'):

 self.n_d = n_d
self.n_a = n_a
self.n_steps = n_steps
self.gamma = gamma
self.cat_idxs = cat_idxs
self.cat_dims = cat_dims
self.cat_emb_dim = cat_emb_dim
self.n_independent = n_independent
self.n_shared = n_shared
self.epsilon = epsilon
self.momentum = momentum
self.lambda_sparse = lambda_sparse
self.clip_value = clip_value
self.verbose = verbose
self.optimizer_fn = optimizer_fn
self.optimizer_params = optimizer_params
self.device_name = device_name
self.scheduler_params = scheduler_params
self.scheduler_fn = scheduler_fn
self.mask_type = mask_type
self.input_dim = input_dim
self.output_dim = output_dim
self.batch_size = 1024
self.seed = seed
torch.manual_seed(self.seed)
 if device_name == 'auto':
if torch.cuda.is_available() :
device_name = 'cuda'
else:
device_name = 'cpu'
self.device = torch.device(device_name)
 print(f"Device used : {self.device}")
 @abstractmethod
def construct_loaders(self, X_train, y_train, X_valid, y_valid,
weights, batch_size, num_workers, drop_last):

 raise NotImplementedError('users must define construct_loaders to use this base class')
 def init_network(
 self,
input_dim,
output_dim,
n_d,
n_a,
n_steps,
gamma,
cat_idxs,
cat_dims,
cat_emb_dim,
n_independent,
n_shared,
epsilon,
virtual_batch_size,
momentum,
device_name,
mask_type, 
):
self.network = tab_network.TabNet(
 input_dim,
output_dim,
n_d=n_d,
n_a=n_a,
n_steps=n_steps,
gamma=gamma,
cat_idxs=cat_idxs,
cat_dims=cat_dims,
cat_emb_dim=cat_emb_dim,
n_independent=n_independent,
n_shared=n_shared,
epsilon=epsilon,
virtual_batch_size=virtual_batch_size,
momentum=momentum,
device_name=device_name,
mask_type=mask_type ).to(self.device)
 self.reducing_matrix = create_explain_matrix(
 self.network.input_dim,
self.network.cat_emb_dim,
self.network.cat_idxs,
self.network.post_embed_dim)
 def fit(self, X_train, y_train, X_valid=None, y_valid=None, loss_fn=None,
weights=0, max_epochs=100, patience=10, batch_size=1024,
virtual_batch_size=128, num_workers=0, drop_last=False):

 self.update_fit_params(X_train, y_train, X_valid, y_valid, loss_fn,
weights, max_epochs, patience, batch_size,
virtual_batch_size, num_workers, drop_last)
 train_dataloader, valid_dataloader = self.construct_loaders(X_train,
y_train,
X_valid,
y_valid,
self.updated_weights,
self.batch_size,
self.num_workers,
self.drop_last)
 self.init_network(
 input_dim=self.input_dim,
output_dim=self.output_dim,
n_d=self.n_d,
n_a=self.n_a,
n_steps=self.n_steps,
gamma=self.gamma,
cat_idxs=self.cat_idxs,
cat_dims=self.cat_dims,
cat_emb_dim=self.cat_emb_dim,
n_independent=self.n_independent,
n_shared=self.n_shared,
epsilon=self.epsilon,
virtual_batch_size=self.virtual_batch_size,
momentum=self.momentum,
device_name=self.device_name,
mask_type=self.mask_type 
)
 self.optimizer = self.optimizer_fn(self.network.parameters() ,
**self.optimizer_params)
 if self.scheduler_fn:
self.scheduler = self.scheduler_fn(self.optimizer, **self.scheduler_params)
 else:
self.scheduler = None
self.losses_train = []
self.losses_valid = []
self.learning_rates = []
self.metrics_train = []
self.metrics_valid = []
if self.verbose > 0:
print("Will train until validation stopping metric",
f"hasn't improved in {self.patience} rounds.")
 msg_epoch = f'| EPOCH | train | valid | total time(s)'
print('---------------------------------------')
 print(msg_epoch)
 total_time = 0
while(self.epoch < self.max_epochs and
self.patience_counter < self.patience):
starting_time = time.time()
self.learning_rates.append(self.optimizer.param_groups[-1]["lr"])
 fit_metrics = self.fit_epoch(train_dataloader, valid_dataloader)
 self.losses_train.append(fit_metrics['train']['loss_avg'])
 self.losses_valid.append(fit_metrics['valid']['total_loss'])
 self.metrics_train.append(fit_metrics['train']['stopping_loss'])
 self.metrics_valid.append(fit_metrics['valid']['stopping_loss'])
 stopping_loss = fit_metrics['valid']['stopping_loss']
if stopping_loss < self.best_cost:
self.best_cost = stopping_loss
self.patience_counter = 0
self.best_network = deepcopy(self.network)
 has_improved = True
else:
self.patience_counter += 1
has_improved=False
self.epoch += 1
total_time += time.time() - starting_time
if self.verbose > 0:
if self.epoch % self.verbose == 0:
separator = "|"
msg_epoch = f"| {self.epoch:<5} | "
msg_epoch += f" {fit_metrics['train']['stopping_loss']:.5f}"
msg_epoch += f' {separator:<2} '
msg_epoch += f" {fit_metrics['valid']['stopping_loss']:.5f}"
msg_epoch += f' {separator:<2} '
msg_epoch += f" {np.round(total_time, 1):<10}"
msg_epoch += f" {has_improved}"
print(msg_epoch)
 if self.verbose > 0:
if self.patience_counter == self.patience:
print(f"Early stopping occured at epoch {self.epoch}")
 print(f"Training done in {total_time:.3f} seconds.")
 print('---------------------------------------')
 self.history = {"train": {"loss": self.losses_train,
"metric": self.metrics_train,
"lr": self.learning_rates},
"valid": {"loss": self.losses_valid,
"metric": self.metrics_valid}}
self.load_best_model()
self._compute_feature_importances(train_dataloader)
 def save_model(self, path):

 saved_params = {}
for key, val in self.get_params().items() :
if isinstance(val, type):
continue
else:
saved_params[key] = val
Path(path ).mkdir(parents=True, exist_ok=True)
 with open(Path(path ).joinpath("model_params.json"), "w", encoding="utf8")as f:
json.dump(saved_params, f)
 torch.save(self.network.state_dict() , Path(path ).joinpath("network.pt"))
shutil.make_archive(path, 'zip', path)
 shutil.rmtree(path)
 print(f"Successfully saved model at {path}.zip")
 return f"{path}.zip"
def load_model(self, filepath):
try:
try:
with zipfile.ZipFile(filepath)as z:
with z.open("model_params.json")as f:
loaded_params = json.load(f)
 with z.open("network.pt")as f:
try:
saved_state_dict = torch.load(f)
 except io.UnsupportedOperation:
saved_state_dict = torch.load(io.BytesIO(f.read()))
except:
with open(os.path.join(filepath, "model_params.json")) as f:
loaded_params = json.load(f)
 saved_state_dict = torch.load(os.path.join(filepath, "network.pt"), map_location="cpu")
 except KeyError:
raise KeyError("Your zip file is missing at least one component")
 if torch.cuda.is_available() :
device_name = 'cuda'
else:
device_name = 'cpu'
loaded_params["device_name"] = device_name
self.__init__(**loaded_params)
 self.init_network(
 input_dim=self.input_dim,
output_dim=self.output_dim,
n_d=self.n_d,
n_a=self.n_a,
n_steps=self.n_steps,
gamma=self.gamma,
cat_idxs=self.cat_idxs,
cat_dims=self.cat_dims,
cat_emb_dim=self.cat_emb_dim,
n_independent=self.n_independent,
n_shared=self.n_shared,
epsilon=self.epsilon,
virtual_batch_size=1024,
momentum=self.momentum,
device_name=self.device_name,
mask_type=self.mask_type 
)
 self.network.load_state_dict(saved_state_dict)
 self.network.eval()
return
def fit_epoch(self, train_dataloader, valid_dataloader):

 train_metrics = self.train_epoch(train_dataloader)
 valid_metrics = self.predict_epoch(valid_dataloader)
 fit_metrics = {'train': train_metrics,
'valid': valid_metrics}
return fit_metrics
@abstractmethod
def train_epoch(self, train_loader):

 raise NotImplementedError('users must define train_epoch to use this base class')
 @abstractmethod
def train_batch(self, data, targets):

 raise NotImplementedError('users must define train_batch to use this base class')
 @abstractmethod
def predict_epoch(self, loader):

 raise NotImplementedError('users must define predict_epoch to use this base class')
 @abstractmethod
def predict_batch(self, data, targets):

 raise NotImplementedError('users must define predict_batch to use this base class')
 def load_best_model(self):
if self.best_network is not None:
self.network = self.best_network
@abstractmethod
def predict(self, X):

 raise NotImplementedError('users must define predict to use this base class')
 def explain(self, X):

 self.network.eval()
dataloader = DataLoader(PredictDataset(X),
batch_size=self.batch_size, shuffle=False)
 for batch_nb, data in enumerate(dataloader):
data = data.to(self.device ).float()
M_explain, masks = self.network.forward_masks(data)
 for key, value in masks.items() :
masks[key] = csc_matrix.dot(value.cpu().detach().numpy() ,
self.reducing_matrix)
 if batch_nb == 0:
res_explain = csc_matrix.dot(M_explain.cpu().detach().numpy() ,
self.reducing_matrix)
 res_masks = masks
else:
res_explain = np.vstack([res_explain,
csc_matrix.dot(M_explain.cpu().detach().numpy() ,
self.reducing_matrix)])
 for key, value in masks.items() :
res_masks[key] = np.vstack([res_masks[key], value])
 return res_explain, res_masks
def _compute_feature_importances(self, loader):
self.network.eval()
feature_importances_ = np.zeros(( self.network.post_embed_dim))
for data, targets in loader:
data = data.to(self.device ).float()
M_explain, masks = self.network.forward_masks(data)
 feature_importances_ += M_explain.sum(dim=0 ).cpu().detach().numpy()
feature_importances_ = csc_matrix.dot(feature_importances_,
self.reducing_matrix)
 self.feature_importances_ = feature_importances_ / np.sum(feature_importances_)
 class TabNetRegressor(TabModel):
def construct_loaders(self, X_train, y_train, X_valid, y_valid, weights,
batch_size, num_workers, drop_last):

 if isinstance(weights, int):
if weights == 1:
raise ValueError("Please provide a list of weights for regression.")
 if isinstance(weights, dict):
raise ValueError("Please provide a list of weights for regression.")
 train_dataloader, valid_dataloader = create_dataloaders(X_train,
y_train,
X_valid,
y_valid,
weights,
batch_size,
num_workers,
drop_last)
 return train_dataloader, valid_dataloader
def update_fit_params(self, X_train, y_train, X_valid, y_valid, loss_fn,
weights, max_epochs, patience,
batch_size, virtual_batch_size, num_workers, drop_last):
if loss_fn is None:
self.loss_fn = torch.nn.functional.mse_loss
else:
self.loss_fn = loss_fn
assert X_train.shape[1] == X_valid.shape[1], "Dimension mismatch X_train X_valid"
self.input_dim = X_train.shape[1]
if len(y_train.shape)== 1:
raise ValueError()
assert y_train.shape[1] == y_valid.shape[1], "Dimension mismatch y_train y_valid"
self.output_dim = y_train.shape[1]
self.updated_weights = weights
self.max_epochs = max_epochs
self.patience = patience
self.batch_size = batch_size
self.virtual_batch_size = virtual_batch_size
self.patience_counter = 0
self.epoch = 0
self.best_cost = np.inf
self.num_workers = num_workers
self.drop_last = drop_last
def train_epoch(self, train_loader):

 self.network.train()
y_preds = []
ys = []
total_loss = 0
for data, targets in train_loader:
batch_outs = self.train_batch(data, targets)
 y_preds.append(batch_outs["y_preds"].cpu().detach().numpy())
 ys.append(batch_outs["y"].cpu().detach().numpy())
 total_loss += batch_outs["loss"]
y_preds = np.vstack(y_preds)
 ys = np.vstack(ys)
 stopping_loss =log_loss_multi(ys, torch.sigmoid(torch.as_tensor(y_preds)).numpy())
 total_loss = total_loss / len(train_loader)
 epoch_metrics = {'loss_avg': total_loss,
'stopping_loss': total_loss,
}
if self.scheduler is not None:
self.scheduler.step()
return epoch_metrics
def train_batch(self, data, targets):

 self.network.train()
data = data.to(self.device ).float()
targets = targets.to(self.device ).float()
self.optimizer.zero_grad()
output, M_loss = self.network(data)
 loss = self.loss_fn(output, targets)
 loss -= self.lambda_sparse*M_loss
loss.backward()
if self.clip_value:
clip_grad_norm_(self.network.parameters() , self.clip_value)
 self.optimizer.step()
loss_value = loss.item()
batch_outs = {'loss': loss_value,
'y_preds': output,
'y': targets}
return batch_outs
def predict_epoch(self, loader):

 y_preds = []
ys = []
self.network.eval()
total_loss = 0
for data, targets in loader:
batch_outs = self.predict_batch(data, targets)
 total_loss += batch_outs["loss"]
y_preds.append(batch_outs["y_preds"].cpu().detach().numpy())
 ys.append(batch_outs["y"].cpu().detach().numpy())
 y_preds = np.vstack(y_preds)
 ys = np.vstack(ys)
 stopping_loss =log_loss_multi(ys, torch.sigmoid(torch.as_tensor(y_preds)).numpy())
 total_loss = total_loss / len(loader)
 epoch_metrics = {'total_loss': total_loss,
'stopping_loss': stopping_loss}
return epoch_metrics
def predict_batch(self, data, targets):

 self.network.eval()
data = data.to(self.device ).float()
targets = targets.to(self.device ).float()
output, M_loss = self.network(data)
 loss = self.loss_fn(output, targets)
 loss -= self.lambda_sparse*M_loss
loss_value = loss.item()
batch_outs = {'loss': loss_value,
'y_preds': output,
'y': targets}
return batch_outs
def predict(self, X):

 self.network.eval()
dataloader = DataLoader(PredictDataset(X),
batch_size=self.batch_size, shuffle=False)
 results = []
for batch_nb, data in enumerate(dataloader):
data = data.to(self.device ).float()
output, M_loss = self.network(data)
 predictions = output.cpu().detach().numpy()
results.append(predictions)
 res = np.vstack(results)
 return res<import_modules>
model.fit(poly_features, train_label )
from iterstrat.ml_stratifiers import MultilabelStratifiedKFold, MultilabelStratifiedShuffleSplit
from sklearn.metrics import roc_auc_score<set_options>
predictions = model.predict(poly_features_test )
<concatenate><EOS> 
submit = pd.read_csv('.. /input/sample_submission.csv')
 submit['Target'] = predictions
submit.to_csv('rf_poly_pca.csv', index=False )