Kaggle competition: Digit Recognizer
warnings.filterwarnings("ignore" )<load_from_csv>
import tensorflow as tf
from keras.layers import *
from keras.models import Model
from keras.optimizers import Adam
from keras.callbacks import EarlyStopping, ReduceLROnPlateau
from keras.utils import plot_model, to_categorical
from keras.preprocessing import image
from keras.preprocessing.image import ImageDataGenerator
import matplotlib.pyplot as plt
sz = 256
reduce = 4
TH = 0.40
DATA = '.. /input/hubmap-kidney-segmentation/test/'
MODELS = [f'.. /input/hubmap-fast-ai-starter/model_{i}.pth' for i in range(4)]
df_sample = pd.read_csv('.. /input/hubmap-kidney-segmentation/sample_submission.csv')
 bs = 64
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu' )<categorify>
def load_dataset() :
train = pd.read_csv('.. /input/digit-recognizer/train.csv')
 label = train.pop('label')
 return train, label, label.nunique()
X_train_orig, Y_train_orig, classes = load_dataset()
m = X_train_orig.shape[0]
def load_quizset() :
quiz = pd.read_csv('.. /input/digit-recognizer/test.csv')
 return quiz
X_quiz_orig = load_quizset()
mq = X_quiz_orig.shape[0]
X_train = X_train_orig.to_numpy().reshape(( -1,28,28,1)) /255.0
X_quiz = X_quiz_orig.to_numpy().reshape(( -1,28,28,1)) /255.0
Y_train = to_categorical(Y_train_orig.to_numpy())
 print("Training examples = ", str(m))
print("X_train shape: " + str(X_train.shape))
print("Y_train shape: " + str(Y_train.shape))
print("Quiz examples = ", str(mq))
print("X_quiz shape: " + str(X_quiz.shape))
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 )<categorify>
X_train[np.isnan(X_train)]
mean = np.array([0.65459856,0.48386562,0.69428385])
 std = np.array([0.15167958,0.23584107,0.13146145])
 s_th = 40
p_th = 1000*(sz//256)**2
identity = rasterio.Affine(1, 0, 0, 0, 1, 0)
 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))
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
self.pad0 =(self.sz - self.shape[0]%self.sz)%self.sz
self.pad1 =(self.sz - self.shape[1]%self.sz)%self.sz
self.n0max =(self.shape[0] + self.pad0)//self.sz
self.n1max =(self.shape[1] + self.pad1)//self.sz
def __len__(self):
return self.n0max*self.n1max
def __getitem__(self, idx):
n0,n1 = idx//self.n1max, idx%self.n1max
x0,y0 = -self.pad0//2 + n0*self.sz, -self.pad1//2 + n1*self.sz
p00,p01 = max(0,x0), min(x0+self.sz,self.shape[0])
 p10,p11 = max(0,y0), min(y0+self.sz,self.shape[1])
 img = np.zeros(( self.sz,self.sz,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.sz//reduce,self.sz//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<categorify>
train_image_gen = ImageDataGenerator(
 rotation_range=10,
width_shift_range=0.1,
height_shift_range=0.1,
shear_range=5,
zoom_range=0.1,
validation_split=0.2 
)
 train_image_gen.fit(X_train)
 val_image_gen = ImageDataGenerator()
data_gen = train_image_gen.flow(X_train,seed=130)
 plt.figure(figsize=(10,10))
i=0
for data in data_gen[1]:
plt.subplot(5,5,i+1)
 plt.xticks([])
 plt.yticks([])
 plt.grid(False)
 plt.imshow(image.array_to_img(data_gen[0][i]))
i = i+1
if i > 24:
break
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 )<define_search_model>
def model(input_shape,classes):

 X_input = Input(input_shape)
 X = ZeroPadding2D(( 3,3))(X_input)
 X = Conv2D(32,(7,7), strides=(1,1), name='conv1a' )(X)
 X = Activation('relu' )(X)
 X = Conv2D(64,(7,7), strides=(1,1), name='conv1b' )(X)
 X = Activation('relu' )(X)
 X = MaxPooling2D(( 2,2))(X)
 X = Dropout(0.3 )(X)
 X = Conv2D(128,(5,5), strides=(1,1), name='conv2a' )(X)
 X = Activation('relu' )(X)
 X = Conv2D(256,(5,5), strides=(1,1), name='conv2b' )(X)
 X = Activation('relu' )(X)
 X = MaxPooling2D(( 2,2), strides=(2,2))(X)
 X = Dropout(0.3 )(X)
 X = Flatten()(X)
 X = Dense(classes, activation='softmax', name='fc'+str(classes))(X)
 model = Model(inputs = X_input, outputs = X, name='MyModel')
 return model
model(X_train.shape[1:],classes ).summary()
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_()<choose_model_class>
learning_rate_reduction = ReduceLROnPlateau(monitor='val_categorical_accuracy',
patience=5,
verbose=1,
factor=0.3,
min_lr=1e-05 )
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.2)
 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<train_model>
BATCH_SIZE=4096
EPOCHS=1000
mymodel = model(X_train.shape[1:],classes)
 mymodel.compile(optimizer=Adam() ,
loss='categorical_crossentropy',
metrics=['categorical_accuracy','categorical_crossentropy'])
 history = mymodel.fit(train_image_gen.flow(x=X_train,y=Y_train,batch_size=BATCH_SIZE),
epochs=EPOCHS, shuffle=True,
validation_data=val_image_gen.flow(x=X_train,y=Y_train,batch_size=BATCH_SIZE),
callbacks=[tf.keras.callbacks.EarlyStopping(monitor='val_categorical_crossentropy',patience=16,restore_best_weights=True),
learning_rate_reduction] )
models = []
for path in MODELS:
state_dict = torch.load(path,map_location=torch.device('cpu'))
model = UneXt50()
model.load_state_dict(state_dict)
 model.float()
model.eval()
model.to(device)
 models.append(model)
 del state_dict<categorify>
Y_pred = mymodel.predict(X_train)
 Y_pred_classes = np.argmax(Y_pred,axis=1)
 Y_train_classes = np.argmax(Y_train,axis=1)
 errors =(Y_pred_classes - Y_train_classes !=0)
 Y_pred_errors = Y_pred_classes[errors]
Y_train_errors = Y_train_classes[errors]
X_train_errors = X_train[errors]
<save_to_csv><EOS> 
Y_quiz = mymodel.predict(X_quiz)
 Y_sub = np.argmax(Y_quiz,axis=1)
 Y_sub = pd.Series(Y_sub,name="Label")
 submission = pd.concat([pd.Series(range(1,28001),name='ImageId'),Y_sub],axis=1)
 submission.to_csv("submission.csv",index=False )