Kaggle competition: University of Liverpool - Ion Switching
<SOS> metric: MacroFScore Kaggle data source: university-of-liverpool-ion-switching<train_model>
import numpy as np
import pandas as pd
import os
train_x, test_x, train_y, test_y = train_test_split(X, y, test_size=0.15,random_state=42)
 model_xgb = xgb.XGBRegressor(**Best_params_xgb)
 model_xgb.fit(train_x,train_y,eval_set=[(test_x,test_y)],
early_stopping_rounds=100,verbose=False )<compute_train_metric>
warnings.simplefilter('ignore')
 warnings.filterwarnings('ignore')
 pd.set_option('display.max_columns', 1000)
 pd.set_option('display.max_rows', 500)
preds = model_xgb.predict(test_x)
 rmse = mean_squared_error(test_y, preds,squared=False)
 rmse<prepare_x_and_y>
EPOCHS = 150
NNBATCHSIZE = 32
GROUP_BATCH_SIZE = 4000
SEED = 123
LR = 0.001
SPLITS = 5
outdir = 'wavenet_models'
flip = False
noise = False
if not os.path.exists(outdir):
os.makedirs(outdir)
 def seed_everything(seed):
random.seed(seed)
 np.random.seed(seed)
 os.environ['PYTHONHASHSEED'] = str(seed)
 tf.random.set_seed(seed )
test_X = test[features]<predict_on_test>
def read_data() :
train = pd.read_csv('.. /input/data-without-drift/train_clean.csv', dtype={'time': np.float32, 'signal': np.float32, 'open_channels':np.int32})
 test = pd.read_csv('/kaggle/input/data-without-drift/test_clean.csv', dtype={'time': np.float32, 'signal': np.float32})
 Y_train_proba = np.load("/kaggle/input/ion-shifted-rfc-proba/Y_train_proba.npy")
 Y_test_proba = np.load("/kaggle/input/ion-shifted-rfc-proba/Y_test_proba.npy")
 print(train.shape,Y_train_proba.shape)
 for i in range(11):
train[f"proba_{i}"] = Y_train_proba[:, i]
test[f"proba_{i}"] = Y_test_proba[:, i]
sub = pd.read_csv('/kaggle/input/liverpool-ion-switching/sample_submission.csv', dtype={'time': np.float32})
 return train, test, sub
def batching(df, batch_size):
df['group'] = df.groupby(df.index//batch_size, sort=False)['signal'].agg(['ngroup'] ).values
df['group'] = df['group'].astype(np.uint16)
 return df
def normalize(train, test):
train_input_mean = train.signal.mean()
train_input_sigma = train.signal.std()
train['signal'] =(train.signal - train_input_mean)/ train_input_sigma
test['signal'] =(test.signal - train_input_mean)/ train_input_sigma
return train, test
def lag_with_pct_change(df, windows):
for window in windows:
df['signal_shift_pos_' + str(window)] = df.groupby('group')['signal'].shift(window ).fillna(0)
 df['signal_shift_neg_' + str(window)] = df.groupby('group')['signal'].shift(-1 * window ).fillna(0)
 return df
def run_feat_engineering(df, batch_size):
df = batching(df, batch_size = batch_size)
 df = lag_with_pct_change(df, [1, 2, 3])
 df['signal_2'] = df['signal'] ** 2
return df
def feature_selection(train, test):
features = [col for col in train.columns if col not in ['index', 'group', 'open_channels', 'time']]
train = train.replace([np.inf, -np.inf], np.nan)
 test = test.replace([np.inf, -np.inf], np.nan)
 for feature in features:
feature_mean = pd.concat([train[feature], test[feature]], axis = 0 ).mean()
train[feature] = train[feature].fillna(feature_mean)
 test[feature] = test[feature].fillna(feature_mean)
 return train, test, features
def split(GROUP_BATCH_SIZE=4000, SPLITS=5):
print('Reading Data Started...')
 train, test, sample_submission = read_data()
train, test = normalize(train, test)
 print('Reading and Normalizing Data Completed')
 print('Creating Features')
 print('Feature Engineering Started...')
 train = run_feat_engineering(train, batch_size=GROUP_BATCH_SIZE)
 test = run_feat_engineering(test, batch_size=GROUP_BATCH_SIZE)
 train, test, features = feature_selection(train, test)
 print(train.head())
 print('Feature Engineering Completed...')
 target = ['open_channels']
group = train['group']
kf = GroupKFold(n_splits=SPLITS)
 splits = [x for x in kf.split(train, train[target], group)]
new_splits = []
for sp in splits:
new_split = []
new_split.append(np.unique(group[sp[0]]))
new_split.append(np.unique(group[sp[1]]))
new_split.append(sp[1])
 new_splits.append(new_split)
 target_cols = ['open_channels']
print(train.head() , train.shape)
 train_tr = np.array(list(train.groupby('group' ).apply(lambda x: x[target_cols].values)) ).astype(np.float32)
 train = np.array(list(train.groupby('group' ).apply(lambda x: x[features].values)))
 test = np.array(list(test.groupby('group' ).apply(lambda x: x[features].values)))
 print(train.shape, test.shape, train_tr.shape)
 return train, test, train_tr, new_splits
preds = model_xgb.predict(test_X )<save_to_csv>
import torch.nn.functional as F
sub['target']=preds
sub.to_csv('submission_xgb.csv', index=False )<prepare_x_and_y>
mish = Mish()
mish
X = train_01[features]
y = train_01['target']<init_hyperparams>
class Wave_Block(nn.Module):
def __init__(self,in_channels,out_channels,dilation_rates):
super(Wave_Block,self ).__init__()
self.num_rates = dilation_rates
self.convs = nn.ModuleList()
self.filter_convs = nn.ModuleList()
self.gate_convs = nn.ModuleList()
self.mish = Mish()
self.convs.append(nn.Conv1d(in_channels,out_channels,kernel_size=1))
dilation_rates = [2**i for i in range(dilation_rates)]
for dilation_rate in dilation_rates:
self.filter_convs.append(nn.Conv1d(out_channels,out_channels,kernel_size=3,padding=dilation_rate,dilation=dilation_rate))
self.gate_convs.append(nn.Conv1d(out_channels,out_channels,kernel_size=3,padding=dilation_rate,dilation=dilation_rate))
self.convs.append(nn.Conv1d(out_channels,out_channels,kernel_size=1))
def forward(self,x):
x = self.convs[0](x)
 res = x
for i in range(self.num_rates):
x = self.mish(self.filter_convs[i](x)) *F.sigmoid(self.gate_convs[i](x))
x = self.convs[i+1](x)
 res = torch.add(res, x)
 return res
class Classifier(nn.Module):
def __init__(self):
super().__init__()
input_size = 128
self.LSTM1 = nn.GRU(input_size=19,hidden_size=64,num_layers=2,batch_first=True,bidirectional=True)
 self.LSTM = nn.GRU(input_size=input_size,hidden_size=64,num_layers=2,batch_first=True,bidirectional=True)
 self.trfrmr = nn.TransformerEncoderLayer(128, 4, dim_feedforward=512, dropout=0.1, activation='gelu')
 self.wave_block1 = Wave_Block(128,16,12)
 self.wave_block2 = Wave_Block(16,32,8)
 self.wave_block3 = Wave_Block(32,64,4)
 self.wave_block4 = Wave_Block(64, 128, 1)
 self.fc = nn.Linear(128, 11)
 def forward(self,x):
x,_ = self.LSTM1(x)
 x = x.permute(0, 2, 1)
 x = self.wave_block1(x)
 x = self.wave_block2(x)
 x = self.wave_block3(x)
 x = self.wave_block4(x)
 x = x.permute(0, 2, 1)
 x,_ = self.LSTM(x)
 x = self.trfrmr(x)
 x = self.fc(x)
 return x
class EarlyStopping:
def __init__(self, patience=7, delta=0, checkpoint_path='checkpoint.pt', is_maximize=True):
self.patience, self.delta, self.checkpoint_path = patience, delta, checkpoint_path
self.counter, self.best_score = 0, None
self.is_maximize = is_maximize
def load_best_weights(self, model):
model.load_state_dict(torch.load(self.checkpoint_path))
def __call__(self, score, model):
if self.best_score is None or \ 
(score > self.best_score + self.delta if self.is_maximize else score < self.best_score - self.delta):
torch.save(model.state_dict() , self.checkpoint_path)
 self.best_score, self.counter = score, 0
return 1
else:
self.counter += 1
if self.counter >= self.patience:
return 2
return 0
params_lgb = {'num_leaves': 31,
'min_data_in_leaf': 20,
'min_child_weight': 0.001,
'max_depth': -1,
'learning_rate': 0.005,
'bagging_fraction': 1,
'feature_fraction': 1,
'lambda_l1': 0,
'lambda_l2': 0,
'random_state': 48}<choose_model_class>
model = Classifier()
model
model_lgb = lgb.LGBMRegressor(**params_lgb )<define_search_space>
class IronDataset(Dataset):
def __init__(self, data, labels, training=True, transform=None, seq_len=5000, flip=0.5, noise_level=0, class_split=0.0):
self.data = data
self.labels = labels
self.transform = transform
self.training = training
self.flip = flip
self.noise_level = noise_level
self.class_split = class_split
self.seq_len = seq_len
def __len__(self):
return len(self.data)
 def __getitem__(self, idx):
if torch.is_tensor(idx):
idx = idx.tolist()
data = self.data[idx]
labels = self.labels[idx]
return [data.astype(np.float32), labels.astype(int)]
param_range = np.linspace(0, 1, 10)
 param_range<define_variables>
train, test, train_tr, new_splits = split()
param_name = 'lambda_l1'<define_variables>
pip install torchcontrib
param_name = 'lambda_l2'<define_variables>
!pip install pytorch_toolbelt
param_name = 'feature_fraction'<define_search_space>
from pytorch_toolbelt import losses as L
param_name = 'bagging_fraction'<define_search_space>
from torchcontrib.optim import SWA
import torchcontrib
param_name = 'n_estimators'<define_search_space>
%%time
test_y = np.zeros([int(2000000/GROUP_BATCH_SIZE), GROUP_BATCH_SIZE, 1])
 test_dataset = IronDataset(test, test_y, flip=False)
 test_dataloader = DataLoader(test_dataset, NNBATCHSIZE, shuffle=False)
 test_preds_all = np.zeros(( 2000000, 11))
oof_score = []
for index,(train_index, val_index, _)in enumerate(new_splits[0:], start=0):
print("Fold : {}".format(index))
train_dataset = IronDataset(train[train_index], train_tr[train_index], seq_len=GROUP_BATCH_SIZE, flip=flip, noise_level=noise)
 train_dataloader = DataLoader(train_dataset, NNBATCHSIZE, shuffle=True,num_workers = 16)
 valid_dataset = IronDataset(train[val_index], train_tr[val_index], seq_len=GROUP_BATCH_SIZE, flip=False)
 valid_dataloader = DataLoader(valid_dataset, NNBATCHSIZE, shuffle=False)
 it = 0
model = Classifier()
model = model.cuda()
early_stopping = EarlyStopping(patience=40, is_maximize=True,
checkpoint_path=os.path.join(outdir, "gru_clean_checkpoint_fold_{}_iter_{}.pt".format(index,
it)))
 weight = None
criterion = L.FocalLoss()
avg_train_losses, avg_valid_losses = [], []
for epoch in range(EPOCHS):
if epoch < 1:
optimizer = torch.optim.Adam(model.parameters() , lr=LR)
 elif epoch < 7:
optimizer = torch.optim.Adam(model.parameters() , lr=LR/3)
 elif epoch < 50:
optimizer = torch.optim.Adam(model.parameters() , lr=LR/5)
 elif epoch < 60:
optimizer = torch.optim.Adam(model.parameters() , lr=LR/7)
 elif epoch < 70:
optimizer = torch.optim.Adam(model.parameters() , lr=LR/9)
 elif epoch < 80:
optimizer = torch.optim.Adam(model.parameters() , lr=LR/11)
 elif epoch < 90:
optimizer = torch.optim.Adam(model.parameters() , lr=LR/13)
 else:
optimizer = torch.optim.Adam(model.parameters() , lr=LR/100)
 optimizer = torchcontrib.optim.SWA(optimizer, swa_start=2, swa_freq=2, swa_lr=0.00011)
 train_losses, valid_losses = [], []
tr_loss_cls_item, val_loss_cls_item = [], []
model.train()
train_preds, train_true = torch.Tensor([] ).cuda() , torch.LongTensor([] ).cuda()
print('**********************************')
 print("Folder : {} Epoch : {}".format(index, epoch))
print("Curr learning_rate: {:0.9f}".format(optimizer.param_groups[0]['lr']))
for x, y in tqdm(train_dataloader):
x = x.cuda()
y = y.cuda()
optimizer.zero_grad()
predictions = model(x)
 predictions_ = predictions.view(-1, predictions.shape[-1])
 y_ = y.view(-1)
 loss = criterion(predictions_, y_)
 loss.backward()
optimizer.step()
train_losses.append(loss.item())
 train_true = torch.cat([train_true, y_], 0)
 train_preds = torch.cat([train_preds, predictions_], 0)
 if epoch >= 90:
optimizer.update_swa()
optimizer.swap_swa_sgd()
val_preds, val_true = torch.Tensor([] ).cuda() , torch.LongTensor([] ).cuda()
print('EVALUATION')
 with torch.no_grad() :
for x, y in tqdm(valid_dataloader):
x = x.cuda()
y = y.cuda()
predictions = model(x)
 predictions_ = predictions.view(-1, predictions.shape[-1])
 y_ = y.view(-1)
 loss = criterion(predictions_, y_)
 valid_losses.append(loss.item())
 val_true = torch.cat([val_true, y_], 0)
 val_preds = torch.cat([val_preds, predictions_], 0)
 train_loss = np.average(train_losses)
 valid_loss = np.average(valid_losses)
 avg_train_losses.append(train_loss)
 avg_valid_losses.append(valid_loss)
 print("train_loss: {:0.6f}, valid_loss: {:0.6f}".format(train_loss, valid_loss))
train_score = f1_score(train_true.cpu().detach().numpy() , train_preds.cpu().detach().numpy().argmax(1),
labels=list(range(11)) , average='macro')
 val_score = f1_score(val_true.cpu().detach().numpy() , val_preds.cpu().detach().numpy().argmax(1),
labels=list(range(11)) , average='macro')
 print("train_f1: {:0.6f}, valid_f1: {:0.6f}".format(train_score, val_score))
res = early_stopping(val_score, model)
 if res == 2:
print("Early Stopping")
 print('folder %d global best val max f1 model score %f' %(index, early_stopping.best_score))
break
elif res == 1:
print('save folder %d global val max f1 model score %f' %(index, val_score))
print('Folder {} finally best global max f1 score is {}'.format(index, early_stopping.best_score))
oof_score.append(round(early_stopping.best_score, 6))
model.eval()
pred_list = []
with torch.no_grad() :
for x, y in tqdm(test_dataloader):
x = x.cuda()
y = y.cuda()
predictions = model(x)
 predictions_ = predictions.view(-1, predictions.shape[-1])
 pred_list.append(F.softmax(predictions_, dim=1 ).cpu().numpy())
 test_preds = np.vstack(pred_list)
 test_preds_all += test_preds
<prepare_x_and_y><EOS> 
print('all folder score is:%s'%str(oof_score))
print('OOF mean score is: %f'%(sum(oof_score)/len(oof_score)))
 print('Generate submission.............')
 submission_csv_path = '/kaggle/input/liverpool-ion-switching/sample_submission.csv'
ss = pd.read_csv(submission_csv_path, dtype={'time': str})
 test_preds_all = test_preds_all / np.sum(test_preds_all, axis=1)[:, None]
test_pred_frame = pd.DataFrame({'time': ss['time'].astype(str),
'open_channels': np.argmax(test_preds_all, axis=1)})
 test_pred_frame.to_csv("./gru_preds.csv", index=False)
 print('over' )