Kaggle competition: HuBMAP - Hacking the Kidney
<SOS> metric: Dice Kaggle data source: hubmap-hacking-the-kidney<define_variables>
warnings.filterwarnings("ignore" )
seed = 18
np.random.seed(seed )<set_options>
bs = 8
sz = 2*512
overlap = 2*2*64
reduce = 2
TH = 0.43
DATA = '.. /input/hubmap-kidney-segmentation/test/'
MODELS = [f'.. /input/hubmap-models/model0_r2_{i}.pth' for i in range(4)]
df_sample = pd.read_csv('.. /input/hubmap-kidney-segmentation/sample_submission.csv')
 NUM_WORKERS = 2
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu' )
warnings.filterwarnings('ignore' )<load_from_csv>
def enc2mask(encs, shape):
img = np.zeros(shape[0]*shape[1], dtype=np.uint8)
 for m,enc in enumerate(encs):
if isinstance(enc,np.float)and np.isnan(enc): continue
s = enc.split()
for i in range(len(s)//2):
start = int(s[2*i])- 1
length = int(s[2*i+1])
 img[start:start+length] = 1 + m
return img.reshape(shape ).T
def mask2enc(mask, n=1):
pixels = mask.T.flatten()
encs = []
for i in range(1,n+1):
p =(pixels == i ).astype(np.int8)
 if p.sum() == 0: encs.append(np.nan)
 else:
p = np.concatenate([[0], p, [0]])
 runs = np.where(p[1:] != p[:-1])[0] + 1
runs[1::2] -= runs[::2]
encs.append(' '.join(str(x)for x in runs))
return encs
def rle_encode_less_memory(img):

 pixels = img.T.flatten()
pixels[0] = 0
pixels[-1] = 0
runs = np.where(pixels[1:] != pixels[:-1])[0] + 2
runs[1::2] -= runs[::2]
return ' '.join(str(x)for x in runs )
dig_mnist = pd.read_csv(".. /input/Kannada-MNIST/Dig-MNIST.csv")
 sample_submission = pd.read_csv(".. /input/Kannada-MNIST/sample_submission.csv")
 test = pd.read_csv(".. /input/Kannada-MNIST/test.csv")
 train = pd.read_csv(".. /input/Kannada-MNIST/train.csv" )<prepare_x_and_y>
mean = np.array([0.65459856,0.48386562,0.69428385])
 std = np.array([0.15167958,0.23584107,0.13146145])
 def img2tensor(img,dtype:np.dtype=np.float32):
if img.ndim==2 : img = np.expand_dims(img,2)
 img = np.transpose(img,(2,0,1))
return torch.from_numpy(img.astype(dtype, copy=False))
s_th = 10
p_th = 1000*(sz//256)**2
names,preds = [],[]
identity = rasterio.Affine(1, 0, 0, 0, 1, 0)
 class HuBMAPDataset(Dataset):
def __init__(self, idx, sz=sz, reduce=reduce):
self.data = rasterio.open(os.path.join(DATA,idx+'.tiff'), transform = identity,
num_threads='all_cpus')
 if self.data.count != 3:
subdatasets = self.data.subdatasets
self.layers = []
if len(subdatasets)> 0:
for i, subdataset in enumerate(subdatasets, 0):
self.layers.append(rasterio.open(subdataset))
self.shape = self.data.shape
self.reduce = reduce
self.sz = reduce*(sz - overlap)
 self.sz0 = reduce*sz
self.pad0 =(self.sz -(self.shape[0] - reduce*overlap)%self.sz)%self.sz
self.pad1 =(self.sz -(self.shape[1] - reduce*overlap)%self.sz)%self.sz
if self.pad0 < reduce*overlap: self.pad0 += self.sz
if self.pad1 < reduce*overlap: self.pad1 += self.sz
self.n0 =(self.shape[0] - reduce*overlap + self.pad0)//self.sz
self.n1 =(self.shape[1] - reduce*overlap + self.pad1)//self.sz
def __len__(self):
return self.n0*self.n1
def __getitem__(self, idx):
n0,n1 = idx//self.n1, idx%self.n1
x0,y0 = -self.pad0//2 + n0*self.sz, -self.pad1//2 + n1*self.sz
p00,p01 = max(0,x0), min(x0+self.sz0,self.shape[0])
 p10,p11 = max(0,y0), min(y0+self.sz0,self.shape[1])
 img = np.zeros(( self.sz0,self.sz0,3),np.uint8)
 if self.data.count == 3:
img[(p00-x0):(p01-x0),(p10-y0):(p11-y0)] = np.moveaxis(self.data.read([1,2,3],
window=Window.from_slices(( p00,p01),(p10,p11))), 0, -1)
 else:
for i,layer in enumerate(self.layers):
img[(p00-x0):(p01-x0),(p10-y0):(p11-y0),i] =\
layer.read(1,window=Window.from_slices(( p00,p01),(p10,p11)))
 if self.reduce != 1:
img = cv2.resize(img,(self.sz0//reduce,self.sz0//reduce),interpolation = cv2.INTER_AREA)
 hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
 h,s,v = cv2.split(hsv)
 if(s>s_th ).sum() <= p_th or img.sum() <= p_th:
return img2tensor(( img/255.0 - mean)/std), -1
else: return img2tensor(( img/255.0 - mean)/std), idx
x = train.iloc[:,1:].values
y = train.label.values<drop_column>
class Model_pred:
def __init__(self, models, dl, tta:bool=True, half:bool=False):
self.models = models
self.dl = dl
self.tta = tta
self.half = half
def __iter__(self):
count=0
with torch.no_grad() :
for x,y in iter(self.dl):
if(( y>=0 ).sum() > 0):
x = x[y>=0].to(device)
 y = y[y>=0]
if self.half: x = x.half()
py = None
for model in self.models:
p = model(x)
 p = torch.sigmoid(p ).detach()
if py is None: py = p
else: py += p
if self.tta:
flips = [[-1],[-2],[-2,-1]]
for f in flips:
xf = torch.flip(x,f)
 for model in self.models:
p = model(xf)
 p = torch.flip(p,f)
 py += torch.sigmoid(p ).detach()
py /=(1+len(flips))
py /= len(self.models)
 py = F.upsample(py, scale_factor=reduce, mode="bilinear")
 py = py.permute(0,2,3,1 ).float().cpu()
batch_size = len(py)
 for i in range(batch_size):
yield py[i],y[i]
count += 1
def __len__(self):
return len(self.dl.dataset )
x_test = test.drop("id", axis=1 ).iloc[:,:].values<prepare_x_and_y>
class FPN(nn.Module):
def __init__(self, input_channels:list, output_channels:list):
super().__init__()
self.convs = nn.ModuleList(
 [nn.Sequential(nn.Conv2d(in_ch, out_ch*2, kernel_size=3, padding=1),
nn.ReLU(inplace=True), nn.BatchNorm2d(out_ch*2),
nn.Conv2d(out_ch*2, out_ch, kernel_size=3, padding=1))
for in_ch, out_ch in zip(input_channels, output_channels)])
 def forward(self, xs:list, last_layer):
hcs = [F.interpolate(c(x),scale_factor=2**(len(self.convs)-i),mode='bilinear')
 for i,(c,x)in enumerate(zip(self.convs, xs)) ]
hcs.append(last_layer)
 return torch.cat(hcs, dim=1)
 class UnetBlock(Module):
def __init__(self, up_in_c:int, x_in_c:int, nf:int=None, blur:bool=False,
self_attention:bool=False, **kwargs):
super().__init__()
self.shuf = PixelShuffle_ICNR(up_in_c, up_in_c//2, blur=blur, **kwargs)
 self.bn = nn.BatchNorm2d(x_in_c)
 ni = up_in_c//2 + x_in_c
nf = nf if nf is not None else max(up_in_c//2,32)
 self.conv1 = ConvLayer(ni, nf, norm_type=None, **kwargs)
 self.conv2 = ConvLayer(nf, nf, norm_type=None,
xtra=SelfAttention(nf)if self_attention else None, **kwargs)
 self.relu = nn.ReLU(inplace=True)
 def forward(self, up_in:Tensor, left_in:Tensor)-> Tensor:
s = left_in
up_out = self.shuf(up_in)
 cat_x = self.relu(torch.cat([up_out, self.bn(s)], dim=1))
return self.conv2(self.conv1(cat_x))
class _ASPPModule(nn.Module):
def __init__(self, inplanes, planes, kernel_size, padding, dilation, groups=1):
super().__init__()
self.atrous_conv = nn.Conv2d(inplanes, planes, kernel_size=kernel_size,
stride=1, padding=padding, dilation=dilation, bias=False, groups=groups)
 self.bn = nn.BatchNorm2d(planes)
 self.relu = nn.ReLU()
self._init_weight()
def forward(self, x):
x = self.atrous_conv(x)
 x = self.bn(x)
 return self.relu(x)
 def _init_weight(self):
for m in self.modules() :
if isinstance(m, nn.Conv2d):
torch.nn.init.kaiming_normal_(m.weight)
 elif isinstance(m, nn.BatchNorm2d):
m.weight.data.fill_(1)
 m.bias.data.zero_()
class ASPP(nn.Module):
def __init__(self, inplanes=512, mid_c=256, dilations=[6, 12, 18, 24], out_c=None):
super().__init__()
self.aspps = [_ASPPModule(inplanes, mid_c, 1, padding=0, dilation=1)] + \
[_ASPPModule(inplanes, mid_c, 3, padding=d, dilation=d,groups=4)for d in dilations]
self.aspps = nn.ModuleList(self.aspps)
 self.global_pool = nn.Sequential(nn.AdaptiveMaxPool2d(( 1, 1)) ,
nn.Conv2d(inplanes, mid_c, 1, stride=1, bias=False),
nn.BatchNorm2d(mid_c), nn.ReLU())
 out_c = out_c if out_c is not None else mid_c
self.out_conv = nn.Sequential(nn.Conv2d(mid_c*(2+len(dilations)) , out_c, 1, bias=False),
nn.BatchNorm2d(out_c), nn.ReLU(inplace=True))
self.conv1 = nn.Conv2d(mid_c*(2+len(dilations)) , out_c, 1, bias=False)
 self._init_weight()
def forward(self, x):
x0 = self.global_pool(x)
 xs = [aspp(x)for aspp in self.aspps]
x0 = F.interpolate(x0, size=xs[0].size() [2:], mode='bilinear', align_corners=True)
 x = torch.cat([x0] + xs, dim=1)
 return self.out_conv(x)
 def _init_weight(self):
for m in self.modules() :
if isinstance(m, nn.Conv2d):
torch.nn.init.kaiming_normal_(m.weight)
 elif isinstance(m, nn.BatchNorm2d):
m.weight.data.fill_(1)
 m.bias.data.zero_()
x_dig = dig_mnist.drop('label', axis=1 ).iloc[:,:].values
y_dig = keras.utils.to_categorical(dig_mnist.label )<categorify>
class UneXt50(nn.Module):
def __init__(self, stride=1, **kwargs):
super().__init__()
m = ResNet(Bottleneck, [3, 4, 6, 3], groups=32, width_per_group=4)
 self.enc0 = nn.Sequential(m.conv1, m.bn1, nn.ReLU(inplace=True))
self.enc1 = nn.Sequential(nn.MaxPool2d(kernel_size=3, stride=2, padding=1, dilation=1),
m.layer1)
 self.enc2 = m.layer2
self.enc3 = m.layer3
self.enc4 = m.layer4
self.aspp = ASPP(2048,256,out_c=512,dilations=[stride*1,stride*2,stride*3,stride*4])
 self.drop_aspp = nn.Dropout2d(0.5)
 self.dec4 = UnetBlock(512,1024,256)
 self.dec3 = UnetBlock(256,512,128)
 self.dec2 = UnetBlock(128,256,64)
 self.dec1 = UnetBlock(64,64,32)
 self.fpn = FPN([512,256,128,64],[16]*4)
 self.drop = nn.Dropout2d(0.1)
 self.final_conv = ConvLayer(32+16*4, 1, ks=1, norm_type=None, act_cls=None)
 def forward(self, x):
enc0 = self.enc0(x)
 enc1 = self.enc1(enc0)
 enc2 = self.enc2(enc1)
 enc3 = self.enc3(enc2)
 enc4 = self.enc4(enc3)
 enc5 = self.aspp(enc4)
 dec3 = self.dec4(self.drop_aspp(enc5),enc3)
 dec2 = self.dec3(dec3,enc2)
 dec1 = self.dec2(dec2,enc1)
 dec0 = self.dec1(dec1,enc0)
 x = self.fpn([enc5, dec3, dec2, dec1], dec0)
 x = self.final_conv(self.drop(x))
x = F.interpolate(x,scale_factor=2,mode='bilinear')
 return x
x = x.reshape(x.shape[0], 28, 28, 1)
 y = keras.utils.to_categorical(y, 10 )<split>
models = []
for path in MODELS:
state_dict = torch.load(path,map_location=torch.device('cpu'))
model = UneXt50(2)
 model.load_state_dict(state_dict)
 model.float()
model.eval()
model.to(device)
 models.append(model)
 del state_dict
x_train, x_val, y_train, y_val = train_test_split(x, y, test_size = 0.1, random_state = seed )<load_pretrained>
names,preds = [],[]
for idx,row in tqdm(df_sample.iterrows() ,total=len(df_sample)) :
idx = row['id']
ds = HuBMAPDataset(idx)
 dl = DataLoader(ds,bs,num_workers=0,shuffle=False,pin_memory=True)
 mp = Model_pred(models,dl)
 mask = torch.zeros(ds.shape[0]+ds.pad0,ds.shape[1]+ds.pad1,dtype=torch.int8)
 for p,id in iter(mp):
j,i = id%ds.n1,id//ds.n1
ix,iy = ds.sz*i, ds.sz*j
px0, px1 = reduce*overlap//2, -reduce*overlap//2
py0, py1 = reduce*overlap//2, -reduce*overlap//2
mask[(ix+px0):(ix+ds.sz0+px1),(iy+py0):(iy+ds.sz0+py1)] = \ 
(p.squeeze(-1)> TH)[px0:(ds.sz0 + px1),py0:(ds.sz0 + py1)]
mask = mask[ds.pad0//2:-(ds.pad0-ds.pad0//2)if ds.pad0 > 0 else ds.shape[0],
ds.pad1//2:-(ds.pad1-ds.pad1//2)if ds.pad1 > 0 else ds.shape[1]]
rle = rle_encode_less_memory(mask.numpy())
 names.append(idx)
 preds.append(rle)
 gc.collect()
train_datagen = ImageDataGenerator(rescale = 1./255.,
rotation_range = 10,
width_shift_range = 0.25,
height_shift_range = 0.25,
shear_range = 10,
zoom_range = 0.1,
horizontal_flip = False )<create_dataframe>
df = pd.DataFrame({'id':names,'predicted':preds})
 df.to_csv('submission.csv',index=False )
<choose_model_class><EOS> 
df = pd.DataFrame({'id':names,'predicted':preds})
 df.to_csv('submission0.csv',index=False)
 df = df.set_index('id')
 dfr = pd.read_csv('.. /input/hubmap-models/submission_0938.csv')
 dfr = dfr.loc[dfr.id == 'd488c759a']
df.update(dfr.set_index('id'))
df = df.reset_index()
df.to_csv('submission.csv',index=False )