Kaggle competition: SIIM-ACR Pneumothorax Segmentation
<SOS> metric: SIIMDice Kaggle data source: siim-acr-pneumothorax-segmentation<save_to_csv>
!git clone https://github.com/qubvel/efficientnet.git
plt.style.use('seaborn-white')
 sns.set_style("white")
 seed = 10
np.random.seed(seed)
 random.seed(seed)
 os.environ['PYTHONHASHSEED'] = str(seed)
 np.random.seed(seed)
 tf.set_random_seed(seed)
 %matplotlib inline
submission = pd.concat([pd.Series(range(1,28001),name = "ImageId"),results],axis = 1)
 submission.to_csv("cnn_mnist_datagen.csv",index=False )<load_from_csv>
!mkdir masks
!unzip -q.. /input/data-repack-and-image-statistics/masks.zip -d masks
!mkdir train
!unzip -q.. /input/data-repack-and-image-statistics/train.zip -d train
!mkdir test
!unzip -q.. /input/data-repack-and-image-statistics/test.zip -d test
train_df = pd.read_csv('/kaggle/input/digit-recognizer/train.csv')
 test_df = pd.read_csv('/kaggle/input/digit-recognizer/test.csv' )<import_modules>
all_mask_fn = glob.glob('./masks/*')
 mask_df = pd.DataFrame()
mask_df['file_names'] = all_mask_fn
mask_df['mask_percentage'] = 0
mask_df.set_index('file_names',inplace=True)
 for fn in all_mask_fn:
mask_df.loc[fn,'mask_percentage'] = np.array(Image.open(fn)).sum() /(256*256*255)
 mask_df.reset_index(inplace=True)
 sns.distplot(mask_df.mask_percentage)
 mask_df['labels'] = 0
mask_df.loc[mask_df.mask_percentage>0,'labels'] = 1
from matplotlib import pyplot as plt<prepare_x_and_y>
all_train_fn = glob.glob('./train/*')
 total_samples = len(all_train_fn)
 idx = np.arange(total_samples)
 train_fn,val_fn = train_test_split(all_train_fn,stratify=mask_df.labels,test_size=0.1,random_state=10)
 print('No.of train files:', len(train_fn))
print('No.of val files:', len(val_fn))
masks_train_fn = [fn.replace('./train','./masks')for fn in train_fn]
masks_val_fn = [fn.replace('./train','./masks')for fn in val_fn]
y_train = train_df.iloc[:,0]
X_train = train_df.iloc[:,1:]
X_test = test_df.copy()<define_search_space>
train_im_path,train_mask_path = './keras_im_train','./keras_mask_train'
h,w,batch_size = 256,256,16
val_im_path,val_mask_path = './keras_im_val','./keras_mask_val'
class DataGenerator(keras.utils.Sequence):
'Generates data for Keras'
def __init__(self, train_im_path=train_im_path,train_mask_path=train_mask_path,
augmentations=None, batch_size=batch_size,img_size=256, n_channels=3, shuffle=True):
'Initialization'
self.batch_size = batch_size
self.train_im_paths = glob.glob(train_im_path+'/*')
 self.train_im_path = train_im_path
self.train_mask_path = train_mask_path
self.img_size = img_size
self.n_channels = n_channels
self.shuffle = shuffle
self.augment = augmentations
self.on_epoch_end()
def __len__(self):
'Denotes the number of batches per epoch'
return int(np.ceil(len(self.train_im_paths)/ self.batch_size))
def __getitem__(self, index):
'Generate one batch of data'
indexes = self.indexes[index*self.batch_size:min(( index+1)*self.batch_size,len(self.train_im_paths)) ]
list_IDs_im = [self.train_im_paths[k] for k in indexes]
X, y = self.data_generation(list_IDs_im)
 if self.augment is None:
return X,np.array(y)/255
else:
im,mask = [],[]
for x,y in zip(X,y):
augmented = self.augment(image=x, mask=y)
 im.append(augmented['image'])
 mask.append(augmented['mask'])
 return np.array(im),np.array(mask)/255
def on_epoch_end(self):
'Updates indexes after each epoch'
self.indexes = np.arange(len(self.train_im_paths))
if self.shuffle == True:
np.random.shuffle(self.indexes)
 def data_generation(self, list_IDs_im):
'Generates data containing batch_size samples'
X = np.empty(( len(list_IDs_im),self.img_size,self.img_size, self.n_channels))
y = np.empty(( len(list_IDs_im),self.img_size,self.img_size, 1))
for i, im_path in enumerate(list_IDs_im):
im = np.array(Image.open(im_path))
mask_path = im_path.replace(self.train_im_path,self.train_mask_path)
 mask = np.array(Image.open(mask_path))
if len(im.shape)==2:
im = np.repeat(im[...,None],3,2)
 X[i,] = cv2.resize(im,(self.img_size,self.img_size))
y[i,] = cv2.resize(mask,(self.img_size,self.img_size)) [..., np.newaxis]
y[y>0] = 255
return np.uint8(X),np.uint8(y )
X_train = X_train / 255.0
X_test = X_test/ 255.0
X_train_im = X_train.values.reshape(-1,28,28,1)
 X_test_im = X_test.values.reshape(-1,28,28,1 )<import_modules>
Compose, HorizontalFlip, CLAHE, HueSaturationValue,
RandomBrightness, RandomContrast, RandomGamma,OneOf,
ToFloat, ShiftScaleRotate,GridDistortion, ElasticTransform, JpegCompression, HueSaturationValue,
RGBShift, RandomBrightness, RandomContrast, Blur, MotionBlur, MedianBlur, GaussNoise,CenterCrop,
IAAAdditiveGaussianNoise,GaussNoise,OpticalDistortion,RandomSizedCrop 
)
 AUGMENTATIONS_TRAIN = Compose([
HorizontalFlip(p=0.5),
OneOf([
RandomContrast() ,
RandomGamma() ,
RandomBrightness() ,
], p=0.3),
OneOf([
ElasticTransform(alpha=120, sigma=120 * 0.05, alpha_affine=120 * 0.03),
GridDistortion() ,
OpticalDistortion(distort_limit=2, shift_limit=0.5),
], p=0.3),
RandomSizedCrop(min_max_height=(160, 256), height=h, width=w,p=0.25),
ToFloat(max_value=1)
 ],p=1)
 AUGMENTATIONS_TEST = Compose([
ToFloat(max_value=1)
 ],p=1 )
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.callbacks import EarlyStopping
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D,MaxPooling2D,Flatten,Dense,Dropout<choose_model_class>
def get_iou_vector(A, B):
batch_size = A.shape[0]
metric = 0.0
for batch in range(batch_size):
t, p = A[batch], B[batch]
true = np.sum(t)
 pred = np.sum(p)
 if true == 0:
metric +=(pred == 0)
 continue
intersection = np.sum(t * p)
 union = true + pred - intersection
iou = intersection / union
iou = np.floor(max(0,(iou - 0.45)*20)) / 10
metric += iou
metric /= batch_size
return metric
def my_iou_metric(label, pred):
return tf.py_func(get_iou_vector, [label, pred > 0.5], tf.float64 )
model = Sequential()
model.add(Conv2D(64 , 7 ,activation='relu', padding = "same" ,input_shape=[28,28,1]))
model.add(MaxPooling2D(2))
model.add(Conv2D(128 , 3,activation='relu', padding = "same"))
model.add(Conv2D(128 , 3,activation='relu', padding = "same"))
model.add(MaxPooling2D(2))
model.add(Conv2D(256 , 3,activation='relu', padding = "same"))
model.add(Conv2D(256 , 3,activation='relu', padding = "same"))
model.add(MaxPooling2D(2))
model.add(Flatten())
 model.add(Dense(128,activation='elu',kernel_initializer="he_normal"))
model.add(Dropout(0.5))
model.add(Dense(64,activation='elu',kernel_initializer="he_normal",kernel_regularizer=keras.regularizers.l2(0.01)))
 model.add(Dropout(0.5))
model.add(Dense(64,activation='softmax')) 
<choose_model_class>
def dice_coef(y_true, y_pred):
y_true_f = K.flatten(y_true)
 y_pred = K.cast(y_pred, 'float32')
 y_pred_f = K.cast(K.greater(K.flatten(y_pred), 0.5), 'float32')
 intersection = y_true_f * y_pred_f
score = 2.* K.sum(intersection)/(K.sum(y_true_f)+ K.sum(y_pred_f))
return score
def dice_loss(y_true, y_pred):
smooth = 1.
 y_true_f = K.flatten(y_true)
 y_pred_f = K.flatten(y_pred)
 intersection = y_true_f * y_pred_f
score =(2.* K.sum(intersection)+ smooth)/(K.sum(y_true_f)+ K.sum(y_pred_f)+ smooth)
 return 1.- score
def bce_dice_loss(y_true, y_pred):
return binary_crossentropy(y_true, y_pred)+ dice_loss(y_true, y_pred)
 def bce_logdice_loss(y_true, y_pred):
return binary_crossentropy(y_true, y_pred)- K.log(1.- dice_loss(y_true, y_pred))
def exponential_decay(lr0, s):
def exponential_decay_fn(epoch):
return lr0 * 0.1**(epoch / s)
 return exponential_decay_fn
exponential_decay_fn = exponential_decay(lr0=0.01, s=20)
 lr_scheduler = keras.callbacks.LearningRateScheduler(exponential_decay_fn)
 optimizer=keras.optimizers.SGD(lr=0.01,momentum=0.9, nesterov=True)
 model.compile(loss="sparse_categorical_crossentropy",optimizer=optimizer,metrics=['accuracy'] )<train_model>
class SnapshotCallbackBuilder:
def __init__(self, nb_epochs, nb_snapshots, init_lr=0.1):
self.T = nb_epochs
self.M = nb_snapshots
self.alpha_zero = init_lr
def get_callbacks(self, model_prefix='Model'):
callback_list = [
callbacks.ModelCheckpoint("./keras.model",monitor='val_my_iou_metric',
mode = 'max', save_best_only=True, verbose=1),
swa,
callbacks.LearningRateScheduler(schedule=self._cosine_anneal_schedule)
 ]
return callback_list
def _cosine_anneal_schedule(self, t):
cos_inner = np.pi *(t %(self.T // self.M))
cos_inner /= self.T // self.M
cos_out = np.cos(cos_inner)+ 1
return float(self.alpha_zero / 2 * cos_out )
checkpoint_cb = keras.callbacks.ModelCheckpoint("my_keras_model.h5",save_best_only=True)
 history = model.fit(X_train_im, y_train, epochs=100,batch_size=32,validation_split=0.1,callbacks=[EarlyStopping(patience=5),lr_scheduler,checkpoint_cb] )<load_pretrained>
def convolution_block(x, filters, size, strides=(1,1), padding='same', activation=True):
x = Conv2D(filters, size, strides=strides, padding=padding )(x)
 x = BatchNormalization()(x)
 if activation == True:
x = LeakyReLU(alpha=0.1 )(x)
 return x
def residual_block(blockInput, num_filters=16):
x = LeakyReLU(alpha=0.1 )(blockInput)
 x = BatchNormalization()(x)
 blockInput = BatchNormalization()(blockInput)
 x = convolution_block(x, num_filters,(3,3))
x = convolution_block(x, num_filters,(3,3), activation=False)
 x = Add()([x, blockInput])
 return x
model = keras.models.load_model("my_keras_model.h5")
<predict_on_test>
def UXception(input_shape=(None, None, 3),dropout_rate=0.5):
backbone = Xception(input_shape=input_shape,weights='imagenet',include_top=False)
 input = backbone.input
start_neurons = 16
conv4 = backbone.layers[121].output
conv4 = LeakyReLU(alpha=0.1 )(conv4)
 pool4 = MaxPooling2D(( 2, 2))(conv4)
 pool4 = Dropout(dropout_rate )(pool4)
 convm = Conv2D(start_neurons * 32,(3, 3), activation=None, padding="same" )(pool4)
 convm = residual_block(convm,start_neurons * 32)
 convm = residual_block(convm,start_neurons * 32)
 convm = LeakyReLU(alpha=0.1 )(convm)
 deconv4 = Conv2DTranspose(start_neurons * 16,(3, 3), strides=(2, 2), padding="same" )(convm)
 uconv4 = concatenate([deconv4, conv4])
 uconv4 = Dropout(dropout_rate )(uconv4)
 uconv4 = Conv2D(start_neurons * 16,(3, 3), activation=None, padding="same" )(uconv4)
 uconv4 = residual_block(uconv4,start_neurons * 16)
 uconv4 = residual_block(uconv4,start_neurons * 16)
 uconv4 = LeakyReLU(alpha=0.1 )(uconv4)
 deconv3 = Conv2DTranspose(start_neurons * 8,(3, 3), strides=(2, 2), padding="same" )(uconv4)
 conv3 = backbone.layers[31].output
uconv3 = concatenate([deconv3, conv3])
 uconv3 = Dropout(dropout_rate )(uconv3)
 uconv3 = Conv2D(start_neurons * 8,(3, 3), activation=None, padding="same" )(uconv3)
 uconv3 = residual_block(uconv3,start_neurons * 8)
 uconv3 = residual_block(uconv3,start_neurons * 8)
 uconv3 = LeakyReLU(alpha=0.1 )(uconv3)
 deconv2 = Conv2DTranspose(start_neurons * 4,(3, 3), strides=(2, 2), padding="same" )(uconv3)
 conv2 = backbone.layers[21].output
conv2 = ZeroPadding2D(((1,0),(1,0)) )(conv2)
 uconv2 = concatenate([deconv2, conv2])
 uconv2 = Dropout(0.1 )(uconv2)
 uconv2 = Conv2D(start_neurons * 4,(3, 3), activation=None, padding="same" )(uconv2)
 uconv2 = residual_block(uconv2,start_neurons * 4)
 uconv2 = residual_block(uconv2,start_neurons * 4)
 uconv2 = LeakyReLU(alpha=0.1 )(uconv2)
 deconv1 = Conv2DTranspose(start_neurons * 2,(3, 3), strides=(2, 2), padding="same" )(uconv2)
 conv1 = backbone.layers[11].output
conv1 = ZeroPadding2D(((3,0),(3,0)) )(conv1)
 uconv1 = concatenate([deconv1, conv1])
 uconv1 = Dropout(0.1 )(uconv1)
 uconv1 = Conv2D(start_neurons * 2,(3, 3), activation=None, padding="same" )(uconv1)
 uconv1 = residual_block(uconv1,start_neurons * 2)
 uconv1 = residual_block(uconv1,start_neurons * 2)
 uconv1 = LeakyReLU(alpha=0.1 )(uconv1)
 uconv0 = Conv2DTranspose(start_neurons * 1,(3, 3), strides=(2, 2), padding="same" )(uconv1)
 uconv0 = Dropout(dropout_rate )(uconv0)
 uconv0 = Conv2D(start_neurons * 1,(3, 3), activation=None, padding="same" )(uconv0)
 uconv0 = residual_block(uconv0,start_neurons * 1)
 uconv0 = residual_block(uconv0,start_neurons * 1)
 uconv0 = LeakyReLU(alpha=0.1 )(uconv0)
 uconv0 = Dropout(dropout_rate/2 )(uconv0)
 output_layer = Conv2D(1,(1,1), padding="same", activation="sigmoid" )(uconv0)
 model = Model(input, output_layer)
 model.name = 'u-xception'
return model
y_test = model.predict(X_test_im )<load_from_csv>
K.clear_session()
img_size = 256
model = UXception(input_shape=(img_size,img_size,3))
submission = pd.read_csv('/kaggle/input/digit-recognizer/sample_submission.csv' )<save_to_csv>
class SWA(keras.callbacks.Callback):
def __init__(self, filepath, swa_epoch):
super(SWA, self ).__init__()
self.filepath = filepath
self.swa_epoch = swa_epoch
def on_train_begin(self, logs=None):
self.nb_epoch = self.params['epochs']
print('Stochastic weight averaging selected for last {} epochs.' 
.format(self.nb_epoch - self.swa_epoch))
def on_epoch_end(self, epoch, logs=None):
if epoch == self.swa_epoch:
self.swa_weights = self.model.get_weights()
elif epoch > self.swa_epoch:
for i in range(len(self.swa_weights)) :
self.swa_weights[i] =(self.swa_weights[i] * 
(epoch - self.swa_epoch)+ self.model.get_weights() [i])/(( epoch - self.swa_epoch)+ 1)
 else:
pass
def on_train_end(self, logs=None):
self.model.set_weights(self.swa_weights)
 print('Final model parameters set to stochastic weight average.')
 self.model.save_weights(self.filepath)
 print('Final stochastic averaged weights saved to file.' )
submission.to_csv("cnn_mnist_datagen.csv",index=False)
<import_modules>
model.compile(loss=bce_dice_loss, optimizer='adam', metrics=[my_iou_metric] )
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow.keras import layers,models,initializers<define_variables>
epochs = 80
snapshot = SnapshotCallbackBuilder(nb_epochs=epochs,nb_snapshots=1,init_lr=1e-3)
 batch_size = 16
swa = SWA('./keras_swa.model',77)
 valid_im_path,valid_mask_path = './keras_im_val','./keras_mask_val'
training_generator = DataGenerator(augmentations=AUGMENTATIONS_TRAIN,img_size=img_size)
 validation_generator = DataGenerator(train_im_path = valid_im_path ,
train_mask_path=valid_mask_path,augmentations=AUGMENTATIONS_TEST,
img_size=img_size)
 history = model.fit_generator(generator=training_generator,
validation_data=validation_generator,
use_multiprocessing=False,
epochs=epochs,verbose=2,
callbacks=snapshot.get_callbacks() )
np.random.seed(20200422)
 tf.random.set_seed(20200422 )<load_from_csv>
try:
print('using swa weight model')
 model.load_weights('./keras_swa.model')
 except Exception as e:
print(e)
 model.load_weights('./keras.model' )
sample_submission = pd.read_csv('.. /input/digit-recognizer/sample_submission.csv')
 train = pd.read_csv('.. /input/digit-recognizer/train.csv')
 test = pd.read_csv('.. /input/digit-recognizer/test.csv' )<categorify>
def predict_result(model,validation_generator,img_size):
preds_test1 = model.predict_generator(validation_generator ).reshape(-1, img_size, img_size)
 return preds_test1
train_labels = tf.keras.utils.to_categorical(train['label'],10)
 train.drop('label',axis=1,inplace=True)
 train_images = train/255
test_images = test/255<choose_model_class>
validation_generator = DataGenerator(train_im_path = valid_im_path ,
train_mask_path=valid_mask_path,augmentations=AUGMENTATIONS_TEST,
img_size=img_size,shuffle=False)
 AUGMENTATIONS_TEST_FLIPPED = Compose([
HorizontalFlip() ,
ToFloat(max_value=1)
 ],p=1)
 validation_generator_flipped = DataGenerator(train_im_path = valid_im_path ,
train_mask_path=valid_mask_path,augmentations=AUGMENTATIONS_TEST_FLIPPED,
img_size=img_size,shuffle=False)
 preds_valid_orig = predict_result(model,validation_generator,img_size)
 preds_valid_flipped = predict_result(model,validation_generator_flipped,img_size)
 preds_valid_flipped = np.array([np.fliplr(x)for x in preds_valid_flipped])
 preds_valid = 0.5*preds_valid_orig + 0.5*preds_valid_flipped
model = models.Sequential()
model.add(layers.Reshape(( 28,28,1),input_shape=(28*28,),name='reshape'))
model.add(layers.Conv2D(32,(5,5),padding='same',
kernel_initializer=initializers.TruncatedNormal() ,
use_bias=True,activation='relu',name='conv_filter1'))
model.add(layers.MaxPooling2D(( 2,2),name='max_pooling1'))
model.add(layers.Conv2D(64,(5,5),padding='same',
kernel_initializer=initializers.TruncatedNormal() ,
use_bias=True,activation='relu',name='conv_filter2'))
model.add(layers.MaxPooling2D(( 2,2),name='max_pooling2'))
model.add(layers.Flatten(name='flatten'))
model.add(layers.Dense(1024,activation='relu',
kernel_initializer=initializers.TruncatedNormal() ,
name='hidden'))
model.add(layers.Dropout(rate=0.5,name='dropout'))
model.add(layers.Dense(10,activation='softmax',name='softmax'))
model.summary()<train_model>
valid_fn = glob.glob('./keras_mask_val/*')
 y_valid_ori = np.array([cv2.resize(np.array(Image.open(fn)) ,(img_size,img_size)) for fn in valid_fn])
 assert y_valid_ori.shape == preds_valid.shape
model.compile(optimizer='adam',loss='categorical_crossentropy',metrics=['acc'])
 histroy = model.fit(train_images,train_labels,batch_size=128,epochs=10 )<create_dataframe>
threshold_best = 0.5
max_images = 64
grid_width = 16
grid_height = int(max_images / grid_width)
 fig, axs = plt.subplots(grid_height, grid_width, figsize=(grid_width, grid_height))
validation_generator = DataGenerator(train_im_path = valid_im_path ,
train_mask_path=valid_mask_path,augmentations=AUGMENTATIONS_TEST,
img_size=img_size,batch_size=64,shuffle=False)
 images,masks = validation_generator.__getitem__(0)
 for i,(im, mask)in enumerate(zip(images,masks)) :
pred = preds_valid[i]
ax = axs[int(i / grid_width), i % grid_width]
ax.imshow(im[...,0], cmap="bone")
 ax.imshow(mask.squeeze() , alpha=0.5, cmap="Reds")
 ax.imshow(np.array(np.round(pred > threshold_best), dtype=np.float32), alpha=0.5, cmap="Greens")
 ax.axis('off')
 plt.suptitle("Green:Prediction , Red: Pneumothorax." )
pd.DataFrame({'acc':histroy.history['acc'],'loss':histroy.history['loss']} ).plot()<save_to_csv>
thresholds = np.linspace(0.2, 0.9, 31)
 ious = np.array([iou_metric_batch(y_valid_ori, np.int32(preds_valid > threshold)) for threshold in tqdm_notebook(thresholds)] )
predict_value = model.predict(test_images)
 predict_index = np.argmax(predict_value,axis=1)
 sample_submission['Label'] = predict_index
sample_submission.to_csv('submission.csv',index=False )<set_options>
max_images = 64
grid_width = 16
grid_height = int(max_images / grid_width)
 fig, axs = plt.subplots(grid_height, grid_width, figsize=(grid_width, grid_height))
validation_generator = DataGenerator(train_im_path = valid_im_path ,
train_mask_path=valid_mask_path,augmentations=AUGMENTATIONS_TEST,
img_size=img_size,batch_size=64,shuffle=False)
 images,masks = validation_generator.__getitem__(0)
 for i,(im, mask)in enumerate(zip(images,masks)) :
pred = preds_valid[i]
ax = axs[int(i / grid_width), i % grid_width]
ax.imshow(im[...,0], cmap="bone")
 ax.imshow(mask.squeeze() , alpha=0.5, cmap="Reds")
 ax.imshow(np.array(np.round(pred > threshold_best), dtype=np.float32), alpha=0.5, cmap="Greens")
 ax.axis('off')
 plt.suptitle("Green:Prediction , Red: Pneumothorax." )
%matplotlib inline
np.random.seed(2)
 sns.set(style='white', context='notebook', palette='deep' )<load_from_csv>
test_fn = glob.glob('./test/*')
 x_test = [cv2.resize(np.array(Image.open(fn)) ,(img_size,img_size)) for fn in test_fn]
x_test = np.array(x_test)
 x_test = np.array([np.repeat(im[...,None],3,2)for im in x_test])
 print(x_test.shape)
 preds_test_orig = model.predict(x_test,batch_size=batch_size)
 x_test = np.array([np.fliplr(x)for x in x_test])
 preds_test_flipped = model.predict(x_test,batch_size=batch_size)
 preds_test_flipped = np.array([np.fliplr(x)for x in preds_test_flipped])
 preds_test = 0.5*preds_test_orig + 0.5*preds_test_flipped
train = pd.read_csv(".. /input/train.csv")
 test = pd.read_csv(".. /input/test.csv" )<feature_engineering>
sys.path.insert(0, '.. /input/siim-acr-pneumothorax-segmentation')
 rles = []
i,max_img = 1,10
plt.figure(figsize=(16,4))
for p in tqdm_notebook(preds_test):
p = p.squeeze()
im = cv2.resize(p,(1024,1024))
im = im > threshold_best
im =(im.T*255 ).astype(np.uint8)
 rles.append(mask2rle(im, 1024, 1024))
i += 1
if i<max_img:
plt.subplot(1,max_img,i)
 plt.imshow(im)
 plt.axis('off' )
X_train = X_train / 255.0
test = test / 255.0<categorify>
ids = [o.split('/')[-1][:-4] for o in test_fn]
sub_df = pd.DataFrame({'ImageId': ids, 'EncodedPixels': rles})
 sub_df.loc[sub_df.EncodedPixels=='', 'EncodedPixels'] = '-1'
sub_df.head()
<define_variables><EOS> 
sub_df.to_csv('submission.csv', index=False )