Kaggle competition: Severstal: Steel Defect Detection
<SOS> metric: Dice Kaggle data source: severstal:-steel-defect-detection<feature_engineering>
import mxnet as mx
from mxnet.gluon import data, HybridBlock, nn
import pandas as pd
import cv2
import os
import numpy as np
from mxnet.gluon.data.vision import transforms
from mxnet.gluon.model_zoo import vision
import glob
from mxnet import nd as F, gluon
from gluoncv import model_zoo as gm
model.eval()
prev_test_df = None
for(test_df, sample_prediction_df)in tqdm(iter_test):
if(prev_test_df is not None)&(psutil.virtual_memory().percent < 90):
prev_test_df['answered_correctly'] = eval(test_df['prior_group_answers_correct'].iloc[0])
 prev_test_df = prev_test_df[prev_test_df.content_type_id == False]
prev_group = prev_test_df[['user_id', 'content_id', 'answered_correctly']].groupby('user_id' ).apply(lambda r:(
 r['content_id'].values,
r['answered_correctly'].values))
for prev_user_id in prev_group.index:
if prev_user_id in group.index:
group[prev_user_id] =(
 np.append(group[prev_user_id][0], prev_group[prev_user_id][0])[-MAX_SEQ:],
np.append(group[prev_user_id][1], prev_group[prev_user_id][1])[-MAX_SEQ:] 
)
 else:
group[prev_user_id] =(
 prev_group[prev_user_id][0],
prev_group[prev_user_id][1] 
)
 prev_test_df = test_df.copy()
test_df = test_df[test_df.content_type_id == False]
test_dataset = TestDataset(group, test_df, skills)
 test_dataloader = DataLoader(test_dataset, batch_size=51200, shuffle=False)
 outs = []
for item in tqdm(test_dataloader):
x = item[0].to(device ).long()
target_id = item[1].to(device ).long()
with torch.no_grad() :
output, att_weight = model(x, target_id)
 outs.extend(torch.sigmoid(output)[:, -1].view(-1 ).data.cpu().numpy())
 test_df['answered_correctly'] = outs
env.predict(test_df.loc[test_df['content_type_id'] == 0, ['row_id', 'answered_correctly']] )<predict_on_test>
%pylab inline
att_weight = att_weight.detach().cpu().numpy()<set_options>
ls.. /input/mxnet-gluon-baseline/model/
sns.set()
%matplotlib inline<set_options>
class ResNetBackbone(mx.gluon.HybridBlock):
def __init__(self, backbone='resnet50', pretrained_base=True,dilated=True, **kwargs):
super(ResNetBackbone, self ).__init__()
with self.name_scope() :
if backbone == 'resnet50':
pretrained = resnet50_v1s(pretrained=pretrained_base, dilated=dilated, **kwargs)
 elif backbone == 'resnet101':
pretrained = resnet101_v1s(pretrained=pretrained_base, dilated=dilated, **kwargs)
 elif backbone == 'resnet152':
pretrained = resnet152_v1s(pretrained=pretrained_base, dilated=dilated, **kwargs)
 else:
raise RuntimeError(f'unknown backbone: {backbone}')
 self.conv1 = pretrained.conv1
self.bn1 = pretrained.bn1
self.relu = pretrained.relu
self.maxpool = pretrained.maxpool
self.layer1 = pretrained.layer1
self.layer2 = pretrained.layer2
self.layer3 = pretrained.layer3
self.layer4 = pretrained.layer4
def hybrid_forward(self, F, x):
x = self.conv1(x)
 x = self.bn1(x)
 x = self.relu(x)
 x = self.maxpool(x)
 c1 = self.layer1(x)
 c2 = self.layer2(c1)
 c3 = self.layer3(c2)
 c4 = self.layer4(c3)
 return c1, c2, c3, c4
%matplotlib inline
sns.set()
warnings.filterwarnings("ignore" )<feature_engineering>
class ResNetFPN(mx.gluon.HybridBlock):
def __init__(self, backbone= 'resnet50', backbone_lr_mult=0.1, **kwargs):
super(ResNetFPN, self ).__init__()
self.backbone_name = backbone
self.backbone_lr_mult = backbone_lr_mult
self._kwargs = kwargs
with self.name_scope() :
self.backbone = ResNetBackbone(backbone=self.backbone_name, pretrained_base=False, dilated=False, **kwargs)
 self.head = _FPNHead(output_channels=256, **kwargs)
 def load_pretrained_weights(self):
pretrained = ResNetBackbone(backbone=self.backbone_name, pretrained_base=True, dilated=False, **self._kwargs)
 backbone_params = self.backbone.collect_params()
pretrained_weights = pretrained.collect_params()
for k, v in pretrained_weights.items() :
param_name = backbone_params.prefix + k[len(pretrained_weights.prefix):]
backbone_params[param_name].set_data(v.data())
 self.backbone.collect_params().setattr('lr_mult', self.backbone_lr_mult)
 def hybrid_forward(self,F, x):
c1, c2, c3, c4 = self.backbone(x)
 p1, p2, p3, p4 = self.head(c1, c2, c3, c4)
 return p1, p2, p3, p4
class ResNetUnet(mx.gluon.HybridBlock):
def __init__(self, backbone= 'resnet101', backbone_lr_mult=0.1, cls_branch=False, **kwargs):
super(ResNetUnet, self ).__init__()
self.backbone_name = backbone
self.backbone_lr_mult = backbone_lr_mult
self.cls_branch = cls_branch
self._kwargs = kwargs
with self.name_scope() :
self.backbone = ResNetBackbone(backbone=self.backbone_name, pretrained_base=False, dilated=False, **kwargs)
 self.head = _UnetHead(**kwargs)
 def load_pretrained_weights(self):
pretrained = ResNetBackbone(backbone=self.backbone_name, pretrained_base=True, dilated=False, **self._kwargs)
 backbone_params = self.backbone.collect_params()
pretrained_weights = pretrained.collect_params()
for k, v in pretrained_weights.items() :
param_name = backbone_params.prefix + k[len(pretrained_weights.prefix):]
backbone_params[param_name].set_data(v.data())
 self.backbone.collect_params().setattr('lr_mult', self.backbone_lr_mult)
 def hybrid_forward(self,F, x):
c1, c2, c3, c4 = self.backbone(x)
 out = self.head(c1, c2, c3, c4)
 if self.cls_branch:
logits = F.max(F.mean(out, axis=1), axis=(1, 2))
return out, logits
return out
class _DecoderBlock(HybridBlock):
def __init__(self, output_channels, norm_layer=nn.BatchNorm):
super(_DecoderBlock, self ).__init__()
with self.name_scope() :
self.block = nn.HybridSequential()
self.block.add(ConvBlock(output_channels, kernel_size=3, padding=1, norm_layer=norm_layer))
self.block.add(ConvBlock(output_channels, kernel_size=3, padding=1, norm_layer=norm_layer))
def hybrid_forward(self, F, x, y=None):
if y is not None:
x = F.contrib.BilinearResize2D(x, scale_height=2, scale_width=2)
 x = F.concat(x, y, dim=1)
 out = self.block(x)
 return out
class _UnetHead(HybridBlock):
def __init__(self, num_classes, output_channels=[256, 128, 64, 32], scale=4, norm_layer=nn.BatchNorm):
super(_UnetHead, self ).__init__()
self.scale = scale
with self.name_scope() :
self.block4 = _DecoderBlock(output_channels[0], norm_layer=norm_layer)
 self.block3 = _DecoderBlock(output_channels[1], norm_layer=norm_layer)
 self.block2 = _DecoderBlock(output_channels[2], norm_layer=norm_layer)
 self.block1 = _DecoderBlock(output_channels[3], norm_layer=norm_layer)
 self.postprocess_block = nn.Conv2D(num_classes, kernel_size=1)
 def hybrid_forward(self, F, c1, c2, c3, c4):
p4 = self.block4(c4)
 p3 = self.block3(p4, c3)
 p2 = self.block2(p3, c2)
 p1 = self.block1(p2, c1)
 if self.scale > 1:
p1 = F.contrib.BilinearResize2D(p1, scale_height=self.scale, scale_width=self.scale)
 out = self.postprocess_block(p1)
 return out
class _FPNHead(HybridBlock):
def __init__(self, output_channels=256, norm_layer=nn.BatchNorm):
super(_FPNHead, self ).__init__()
self._hdsize = {}
with self.name_scope() :
self.block4 = ConvBlock(output_channels, kernel_size=1, norm_layer=norm_layer)
 self.block3 = ConvBlock(output_channels, kernel_size=1, norm_layer=norm_layer)
 self.block2 = ConvBlock(output_channels, kernel_size=1, norm_layer=norm_layer)
 self.block1 = ConvBlock(output_channels, kernel_size=1, norm_layer=norm_layer)
 def hybrid_forward(self, F, c1, c2, c3, c4):
p4 = self.block4(c4)
 p3 = self._resize_as(F, 'id_1', p4, c3)+ self.block3(c3)
 p2 = self._resize_as(F, 'id_2', p3, c2)+ self.block2(c2)
 p1 = self._resize_as(F, 'id_3', p2, c1)+ self.block1(c1)
 return p1, p2, p3, p4
def _resize_as(self, F, name, x, y):
h_key = name + '_h'
w_key = name + '_w'
if hasattr(y, 'shape'):
_, _, h, w = y.shape
_, _, h2, w2 = x.shape
if h == h2 and w == w2:
h = 0
w = 0
self._hdsize[h_key] = h
self._hdsize[w_key] = w
else:
h, w = self._hdsize[h_key], self._hdsize[w_key]
if h == 0 and w == 0:
return x
else:
return F.contrib.BilinearResize2D(x, height=h, width=w)
 class SemanticFPNHead(HybridBlock):
def __init__(self, num_classes, output_channels=128, norm_layer=nn.BatchNorm):
super(SemanticFPNHead, self ).__init__()
self._hdsize = {}
with self.name_scope() :
self.block4_1 = ConvBlock(output_channels, kernel_size=3, padding=1, norm_layer=norm_layer)
 self.block4_2 = ConvBlock(output_channels, kernel_size=3, padding=1, norm_layer=norm_layer)
 self.block4_3 = ConvBlock(output_channels, kernel_size=3, padding=1, norm_layer=norm_layer)
 self.block3_1 = ConvBlock(output_channels, kernel_size=3, padding=1, norm_layer=norm_layer)
 self.block3_2 = ConvBlock(output_channels, kernel_size=3, padding=1, norm_layer=norm_layer)
 self.block2 = ConvBlock(output_channels, kernel_size=3, padding=1, norm_layer=norm_layer)
 self.block1 = ConvBlock(output_channels, kernel_size=1, norm_layer=norm_layer)
 self.postprocess_block = nn.Conv2D(num_classes, kernel_size=1)
 def hybrid_forward(self, F, c1, c2, c3, c4):
out4 = self._resize_as(F, 'id_1', self.block4_1(c4), c3)
 out4 = self._resize_as(F, 'id_2', self.block4_2(out4), c2)
 out4 = self._resize_as(F, 'id_3', self.block4_3(out4), c1)
 out3 = self._resize_as(F, 'id_4', self.block3_1(c3), c2)
 out3 = self._resize_as(F, 'id_5', self.block3_2(out3), c1)
 out2 = self._resize_as(F, 'id_6', self.block2(c2), c1)
 out1 = self.block1(c1)
 out = out1 + out2 + out3 + out4
out = self.postprocess_block(out)
 out = F.contrib.BilinearResize2D(out,scale_height=4,scale_width=4)
 return out
def _resize_as(self, F,name, x, y):
h_key = name + '_h'
w_key = name + '_w'
if hasattr(y, 'shape'):
_, _, h, w = y.shape
_, _, h2, w2 = x.shape
if h == h2 and w == w2:
h = 0
w = 0
self._hdsize[h_key]=h
self._hdsize[w_key]=w
else:
h, w = self._hdsize[h_key], self._hdsize[w_key]
if h == 0 and w == 0:
return x
else:
return F.contrib.BilinearResize2D(x,height=h,width=w)
 class ConvBlock(HybridBlock):
def __init__(self, output_channels, kernel_size, padding=0, activation='relu', norm_layer=nn.BatchNorm):
super().__init__()
self.body = nn.HybridSequential()
self.body.add(
 nn.Conv2D(output_channels, kernel_size=kernel_size, padding=padding, activation=activation),
norm_layer(in_channels=output_channels)
)
 def hybrid_forward(self, F, x):
return self.body(x)
def add_user_feats_without_update(df, answered_correctly_sum_u_dict, count_u_dict):
acsu = np.zeros(len(df), dtype=np.int32)
 cu = np.zeros(len(df), dtype=np.int32)
 for cnt, row in enumerate(df[['user_id']].values):
acsu[cnt] = answered_correctly_sum_u_dict[row[0]]
cu[cnt] = count_u_dict[row[0]]
user_feats_df = pd.DataFrame({'answered_correctly_sum_u':acsu, 'count_u':cu})
 user_feats_df['answered_correctly_avg_u'] = user_feats_df['answered_correctly_sum_u'] / user_feats_df['count_u']
df = pd.concat([df, user_feats_df], axis=1)
 return df
def update_user_feats(df, answered_correctly_sum_u_dict, count_u_dict):
for row in df[['user_id','answered_correctly','content_type_id']].values:
if row[2] == 0:
answered_correctly_sum_u_dict[row[0]] += row[1]
count_u_dict[row[0]] += 1<split>
class SteelUnet(HybridBlock):
def __init__(self, n_classes=5, ctx=mx.cpu()):
super().__init__()
with self.name_scope() :
self.feature_extractor = ResNetFPN()
self.segment_head = SemanticFPNHead(num_classes=n_classes)
 def hybrid_forward(self, F, x):
fpn_feature = self.feature_extractor(x)
 segment_out = self.segment_head(*fpn_feature)
 return segment_out
env = riiideducation.make_env()
iter_test = env.iter_test()<choose_model_class>
ctx = mx.gpu()
unet = ResNetUnet(output_channels=[256, 128, 64, 32], num_classes=5)
 unet.load_parameters('.. /input/mxnet-gluon-baseline/unet_14_-1.params')
 unet.collect_params().reset_ctx(ctx )
MAX_SEQ = 100
class FFN(nn.Module):
def __init__(self, state_size=200):
super(FFN, self ).__init__()
self.state_size = state_size
self.lr1 = nn.Linear(state_size, state_size)
 self.relu = nn.ReLU()
self.lr2 = nn.Linear(state_size, state_size)
 self.dropout = nn.Dropout(0.2)
 def forward(self, x):
x = self.lr1(x)
 x = self.relu(x)
 x = self.lr2(x)
 return self.dropout(x)
 def future_mask(seq_length):
future_mask = np.triu(np.ones(( seq_length, seq_length)) , k=1 ).astype('bool')
 return torch.from_numpy(future_mask)
 class SAKTModel(nn.Module):
def __init__(self, n_skill, max_seq=MAX_SEQ, embed_dim=128):
super(SAKTModel, self ).__init__()
self.n_skill = n_skill
self.embed_dim = embed_dim
self.embedding = nn.Embedding(2*n_skill+1, embed_dim)
 self.pos_embedding = nn.Embedding(max_seq-1, embed_dim)
 self.e_embedding = nn.Embedding(n_skill+1, embed_dim)
 self.multi_att = nn.MultiheadAttention(embed_dim=embed_dim, num_heads=8, dropout=0.2)
 self.dropout = nn.Dropout(0.2)
 self.layer_normal = nn.LayerNorm(embed_dim)
 self.ffn = FFN(embed_dim)
 self.pred = nn.Linear(embed_dim, 1)
 def forward(self, x, question_ids):
device = x.device
x = self.embedding(x)
 pos_id = torch.arange(x.size(1)).unsqueeze(0 ).to(device)
 pos_x = self.pos_embedding(pos_id)
 x = x + pos_x
e = self.e_embedding(question_ids)
 x = x.permute(1, 0, 2)
 e = e.permute(1, 0, 2)
 att_mask = future_mask(x.size(0)).to(device)
 att_output, att_weight = self.multi_att(e, x, x, attn_mask=att_mask)
 att_output = self.layer_normal(att_output + e)
 att_output = att_output.permute(1, 0, 2)
 x = self.ffn(att_output)
 x = self.layer_normal(x + att_output)
 x = self.pred(x)
 return x.squeeze(-1), att_weight
class TestDataset(Dataset):
def __init__(self, samples, test_df, skills, max_seq=MAX_SEQ):
super(TestDataset, self ).__init__()
self.samples = samples
self.user_ids = [x for x in test_df["user_id"].unique() ]
self.test_df = test_df
self.skills = skills
self.n_skill = len(skills)
 self.max_seq = max_seq
def __len__(self):
return self.test_df.shape[0]
def __getitem__(self, index):
test_info = self.test_df.iloc[index]
user_id = test_info["user_id"]
target_id = test_info["content_id"]
q = np.zeros(self.max_seq, dtype=int)
 qa = np.zeros(self.max_seq, dtype=int)
 if user_id in self.samples.index:
q_, qa_ = self.samples[user_id]
seq_len = len(q_)
 if seq_len >= self.max_seq:
q = q_[-self.max_seq:]
qa = qa_[-self.max_seq:]
else:
q[-seq_len:] = q_
qa[-seq_len:] = qa_
x = np.zeros(self.max_seq-1, dtype=int)
 x = q[1:].copy()
x +=(qa[1:] == 1)* self.n_skill
questions = np.append(q[2:], [target_id])
 return x, questions<load_pretrained>
def mask2rle(mask):
if np.sum(mask)== 0: return ''
ar = mask.flatten(order='F')
 EncodedPixel = ''
l = 0
for i in range(len(ar)) :
if ar[i] == 0:
if l > 0:
if EncodedPixel != '': EncodedPixel += ' '
EncodedPixel += str(st+1)+' '+str(l)
 l = 0
else:
if l == 0: st = i
l += 1
return EncodedPixel
answered_correctly_sum_u_dict = joblib.load(".. /input/lgbm-with-loop-feature-engineering-dataset/answered_correctly_sum_u_dict.pkl.zip")
 count_u_dict = joblib.load(".. /input/lgbm-with-loop-feature-engineering-dataset/count_u_dict.pkl.zip")
 questions_df = pd.read_feather('.. /input/lgbm-with-loop-feature-engineering-dataset/questions_df.feather')
 content_df = pd.read_feather('.. /input/lgbm-with-loop-feature-engineering-dataset/content_df.feather')
 prior_question_elapsed_time_mean = joblib.load(".. /input/lgbm-with-loop-feature-engineering-dataset/prior_question_elapsed_time_mean.pkl.zip")
 TARGET = 'answered_correctly'
FEATS = ['answered_correctly_avg_u', 'answered_correctly_sum_u', 'count_u',
'answered_correctly_avg_c', 'part', 'prior_question_had_explanation',
'prior_question_elapsed_time'
]
lgbm_model = lgb.Booster(model_file=".. /input/lgbm-with-loop-feature-engineering-dataset/fold0_lgb_model.txt")
 lgbm_model.best_iteration = joblib.load(".. /input/lgbm-with-loop-feature-engineering-dataset/fold0_lgb_model_best_iteration.pkl.zip")
 optimized_weights = joblib.load(".. /input/lgbm-with-loop-feature-engineering-dataset/optimized_weights.pkl.zip" )<load_pretrained>
def remove_small_one(predict, min_size):
H,W = predict.shape
num_component, component = cv2.connectedComponents(predict.astype(np.uint8))
predict = np.zeros(( H,W), np.bool)
 for c in range(1,num_component):
p =(component==c)
 if p.sum() >min_size:
predict[p] = True
return predict
skills = joblib.load(".. /input/riiid-sakt-model-dataset-public/skills.pkl.zip")
 n_skill = len(skills)
 print("number skills", len(skills))
group = joblib.load(".. /input/riiid-sakt-model-dataset-public/group.pkl.zip")
 device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
 sakt_model = SAKTModel(n_skill, embed_dim=128)
 try:
sakt_model.load_state_dict(torch.load(".. /input/riiid-sakt-model-dataset-public/sakt_model.pt"))
except:
sakt_model.load_state_dict(torch.load(".. /input/riiid-sakt-model-dataset-public/sakt_model.pt", map_location='cpu'))
sakt_model.to(device)
 sakt_model.eval()<groupby>
submission = pd.read_csv(".. /input/severstal-steel-defect-detection/sample_submission.csv")
 print(len(ImageId),len(submission['ImageId_ClassId']))
for i, encoded in zip(ImageId_ClassIds,EncodedPixels):
submission.loc[submission['ImageId_ClassId']==i,["EncodedPixels"]] = encoded
submission.to_csv('submission.csv',index=False )