Kaggle competition: HuBMAP - Hacking the Kidney
<SOS> metric: Dice Kaggle data source: hubmap-hacking-the-kidney<predict_on_test>
!pip install.. /input/kerasapplications/keras-team-keras-applications-3b180cb -f./ --no-index -q
!pip install.. /input/efficientnet/efficientnet-1.1.0/ -f./ --no-index -q
y_predicted = model.predict(x_val)
 y_grand_truth = y_val
y_predicted = np.argmax(y_predicted,axis=1)
 y_grand_truth = np.argmax(y_grand_truth,axis=1)
 cm = confusion_matrix(y_grand_truth, y_predicted )<prepare_output>
os.environ['SM_FRAMEWORK'] = 'tf.keras'
scores = np.zeros(( 10,3))
def calc_F1(num):
TP = cm[num,num]
FN = np.sum(cm[num,:])-cm[num,num]
FP = np.sum(cm[:,num])-cm[num,num]
precision = TP/(TP+FP)
 recall = TP/(TP+FN)
 F1_score = 2*(recall * precision)/(recall + precision)
 return precision, recall, F1_score
for i in range(10):
precision, recall, F1_score = calc_F1(i)
 scores[i,:] = precision, recall, F1_score
scores_frame = pd.DataFrame(scores,columns=["Precision", "Recall", "F1 Score"], index=[list(range(0, 10)) ] )<load_from_csv>
MODEL_PATH = '.. /input/train-fpn-segmentation-model-no-43/'
with open(MODEL_PATH+'hparams.json')as json_file:
hparams = json.load(json_file)
 hparams
raw_dig = pd.read_csv(".. /input/Kannada-MNIST/Dig-MNIST.csv")
 raw_dig.head()
x_dig = raw_dig.iloc[:, 1:].values.astype('float32')/ 255
y_dig = raw_dig.iloc[:, 0].values
x_dig = x_dig.reshape(-1,28,28,1)
 y_dig = to_categorical(y_dig)
 model.evaluate(x_dig, y_dig, verbose=2 )<load_from_csv>
IMG_SIZE = hparams['IMG_SIZE']
SCALE_FACTOR = hparams['SCALE_FACTOR']
K_SPLITS = hparams['K_SPLITS']
def read_tif_file(fname):
img = io.imread(fname)
 img = np.squeeze(img)
 if img.shape[0] == 3:
img = img.swapaxes(0,1)
 img = img.swapaxes(1,2)
 return img
def map_img2file(fname):
img = read_tif_file(fname)
 dims = np.array(img.shape)
 ch = 1 if len(dims)== 2 else dims[2]
for i in range(ch):
f = np.memmap('img{}.dat'.format(i), dtype=np.uint8, mode='w+', shape=(dims[0], dims[1]))
f[:] = img[:,:,i] if ch > 1 else img[:,:]
del f
return dims
def get_patch_from_file(dims, pos, psize):
ch = 1 if len(dims)== 2 else dims[2]
patch = np.zeros([psize[0], psize[1]], dtype=np.uint8)if ch == 1 else np.zeros([psize[0], psize[1], ch], dtype=np.uint8)
 for i in range(ch):
f = np.memmap('img{}.dat'.format(i), dtype=np.uint8, mode='r', shape=(dims[0], dims[1]))
p = f[pos[0]:pos[0]+psize[0], pos[1]:pos[1]+psize[1]]
crop = p.shape
if ch == 1:
patch[0:p.shape[0], 0:p.shape[1]] = p
else:
patch[0:p.shape[0], 0:p.shape[1],i] = p
del f
return patch, crop
sample_sub=pd.read_csv('.. /input/Kannada-MNIST/sample_submission.csv')
 raw_test_id=raw_test.id
raw_test=raw_test.drop("id",axis="columns")
 raw_test=raw_test / 255
test=raw_test.values.reshape(-1,28,28,1)
 test.shape<save_to_csv>
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 )
sub=model.predict(test)
 sub=np.argmax(sub,axis=1)
 sample_sub['label']=sub
sample_sub.to_csv('submission.csv',index=False )<set_options>
def create_TTA_batch(img):
if len(img.shape)< 4:
img = np.expand_dims(img, 0)
 batch=np.zeros(( img.shape[0]*8,img.shape[1],img.shape[2],img.shape[3]), dtype=np.float32)
 for i in range(img.shape[0]):
orig = tf.keras.preprocessing.image.img_to_array(img[i,:,:,:])/255.
 batch[i*8,:,:,:] = orig
batch[i*8+1,:,:,:] = np.rot90(orig, axes=(0, 1), k=1)
 batch[i*8+2,:,:,:] = np.rot90(orig, axes=(0, 1), k=2)
 batch[i*8+3,:,:,:] = np.rot90(orig, axes=(0, 1), k=3)
 orig = orig[:, ::-1]
batch[i*8+4,:,:,:] = orig
batch[i*8+5,:,:,:] = np.rot90(orig, axes=(0, 1), k=1)
 batch[i*8+6,:,:,:] = np.rot90(orig, axes=(0, 1), k=2)
 batch[i*8+7,:,:,:] = np.rot90(orig, axes=(0, 1), k=3)
 return batch
def mask_TTA(masks):
batch=np.zeros(( masks.shape[0],masks.shape[1],masks.shape[2],masks.shape[3]), dtype=np.float32)
 for i in range(masks.shape[0]//8):
batch[i*8,:,:,:] = masks[i*8]
batch[i*8+1,:,:,:] = np.rot90(masks[i*8+1], axes=(0, 1), k=3)
 batch[i*8+2,:,:,:] = np.rot90(masks[i*8+2], axes=(0, 1), k=2)
 batch[i*8+3,:,:,:] = np.rot90(masks[i*8+3], axes=(0, 1), k=1)
 batch[i*8+4,:,:,:] = masks[i*8+4][:, ::-1]
batch[i*8+5,:,:,:] = np.rot90(masks[i*8+5], axes=(0, 1), k=3)[:, ::-1]
batch[i*8+6,:,:,:] = np.rot90(masks[i*8+6], axes=(0, 1), k=2)[:, ::-1]
batch[i*8+7,:,:,:] = np.rot90(masks[i*8+7], axes=(0, 1), k=1)[:, ::-1]
return(batch )
matplotlib.use('Agg')
 %matplotlib inline 
<define_variables>
MEANING_OF_LIFE = 42
MEANING_OF_LIFE_REV = int(str(MEANING_OF_LIFE)[::-1])
 PATH = '.. /input/hubmap-kidney-segmentation/test/'
filelist = glob.glob(PATH+'*.tiff')
 if len(filelist)== 5:
filelist = filelist[:1]
SUB_FILE = './submission.csv'
with open(SUB_FILE, 'w')as f:
f.write("id,predicted
")
 MODELS = [MODEL_PATH+'FPN-model-2']
s_th = MEANING_OF_LIFE+K_SPLITS
p_th = IMG_SIZE*IMG_SIZE//32
size = int(IMG_SIZE * SCALE_FACTOR)
 OVERLAP = size//2
STEP = size-OVERLAP
for file in filelist:
fid = file.replace('\','.' ).replace('/','.' ).split('.')[-2]
print(fid)
 dims = map_img2file(file)
 pmask = np.zeros(dims[:2], dtype=np.uint8)
 x_shft, y_shft = 0,0
if fid == 'afa5e8098':
x_shft, y_shft = MEANING_OF_LIFE, MEANING_OF_LIFE_REV
for modl in range(len(MODELS)) :
print(MODELS[modl])
 mname = MODELS[modl]
with open(mname+'.json', 'r')as m:
lm = m.read()
model = model_from_json(lm)
 model.load_weights(mname+'.h5')
 for x in range(( dims[0]-OVERLAP-x_shft)//STEP + min(1,(dims[0]-OVERLAP-x_shft)% STEP)) :
for y in range(( dims[1]-OVERLAP-y_shft)//STEP + min(1,(dims[1]-OVERLAP-y_shft)% STEP)) :
tile, crop = get_patch_from_file(dims, [x*STEP+x_shft, y*STEP+y_shft], [size,size])
 patch = cv2.resize(tile,
dsize=(IMG_SIZE, IMG_SIZE),
interpolation = cv2.INTER_AREA)
 _, s, _ = cv2.split(cv2.cvtColor(patch, cv2.COLOR_BGR2HSV))
if(s>s_th ).sum() > p_th:
batch = create_TTA_batch(patch)
 preds = model.predict(batch)
 pred = mask_TTA(preds)
 mask = np.rint(np.sum(pred, axis=0))
pint =cv2.resize(mask.astype(int), dsize=(size, size), interpolation = cv2.INTER_NEAREST)
 pmask[x*STEP:x*STEP+crop[0], y*STEP:y*STEP+crop[1]] += pint[0:crop[0], 0:crop[1]].astype(np.uint8)
 pmask = pmask >= MEANING_OF_LIFE_REV - K_SPLITS
with open(SUB_FILE, 'a')as f:
f.write("{},".format(fid))
f.write(rle_encode_less_memory(pmask))
f.write("
" )
<define_variables><EOS> 
%rm -f *.dat