Kaggle competition: Histopathologic Cancer Detection
gp = GP()<statistical_test>
training_data_generator = ImageDataGenerator(rescale=1./255,horizontal_flip=True,vertical_flip=True,rotation_range=180,zoom_range=[1, 1.5],
fill_mode='reflect',
width_shift_range=0.3,
height_shift_range=0.3,
shear_range=0.3,
channel_shift_range=0.3 )
def maddest(d, axis=None):
return np.mean(np.absolute(d - np.mean(d, axis)) , axis)
 def high_pass_filter(x, low_cutoff=1000, sample_rate=10000):
nyquist = 0.5 * sample_rate
norm_low_cutoff = low_cutoff / nyquist
print(norm_low_cutoff)
 sos = butter(10, Wn=[norm_low_cutoff], btype='highpass', output='sos')
 filtered_sig = signal.sosfilt(sos, x)
 return filtered_sig
def denoise_signal(x, wavelet='db4', level=1):
coeff = pywt.wavedec(x, wavelet, mode="per")
 sigma =(1/0.6745)* maddest(coeff[-level])
 uthresh = sigma * np.sqrt(2*np.log(len(x)))
 coeff[1:] =(pywt.threshold(i, value=uthresh, mode='hard')for i in coeff[1:])
 return pywt.waverec(coeff, wavelet, mode='per' )<load_from_csv>
training_generator = training_data_generator.flow_from_directory(training_path,
target_size=(IMAGE_SIZE,IMAGE_SIZE),
batch_size=BATCH_SIZE,
class_mode='binary')
 validation_generator = ImageDataGenerator(rescale=1./255 ).flow_from_directory(validation_path,
target_size=(IMAGE_SIZE,IMAGE_SIZE),
batch_size=BATCH_SIZE,
class_mode='binary' )
base = '.. /input/clean-kalman/'
train = pd.read_csv(os.path.join(base + 'train_clean_kalman.csv'))
test = pd.read_csv(os.path.join(base + 'test_clean_kalman.csv'))<feature_engineering>
input_shape =(96, 96, 3)
 inputs = Input(input_shape)
 vgg = VGG19(weights='imagenet',include_top=False, input_shape=input_shape)
 outputs = GlobalAveragePooling2D()(vgg(inputs))
outputs = Dropout(0.5 )(outputs)
 outputs = Dense(1, activation='sigmoid' )(outputs)
 model = Model(inputs, outputs)
 model.compile(optimizer=Adam(lr=0.0001, decay=0.00001),
loss='binary_crossentropy',
metrics=['accuracy'])
 model.summary()
def features(df):
df = df.sort_values(by=['time'] ).reset_index(drop=True)
 df.index =(( df.time * 10_000)- 1 ).values
df['batch'] = df.index // 25_000
df['batch_index'] = df.index -(df.batch * 25_000)
 df['batch_slices'] = df['batch_index'] // 2500
df['batch_slices2'] = df.apply(lambda r: '_'.join([str(r['batch'] ).zfill(3), str(r['batch_slices'] ).zfill(3)]), axis=1)
 for c in ['batch','batch_slices2']:
d = {}
d['mean'+c] = df.groupby([c])['signal'].mean()
d['median'+c] = df.groupby([c])['signal'].median()
d['max'+c] = df.groupby([c])['signal'].max()
d['min'+c] = df.groupby([c])['signal'].min()
d['std'+c] = df.groupby([c])['signal'].std()
d['mean_abs_chg'+c] = df.groupby([c])['signal'].apply(lambda x: np.mean(np.abs(np.diff(x))))
d['abs_max'+c] = df.groupby([c])['signal'].apply(lambda x: np.max(np.abs(x)))
 d['abs_min'+c] = df.groupby([c])['signal'].apply(lambda x: np.min(np.abs(x)))
 d['range'+c] = d['max'+c] - d['min'+c]
d['maxtomin'+c] = d['max'+c] / d['min'+c]
d['abs_avg'+c] =(d['abs_min'+c] + d['abs_max'+c])/ 2
for v in d:
df[v] = df[c].map(d[v].to_dict())
 df['signal_shift_+1'] = [0,] + list(df['signal'].values[:-1])
 df['signal_shift_-1'] = list(df['signal'].values[1:])+ [0]
for i in df[df['batch_index']==0].index:
df['signal_shift_+1'][i] = np.nan
for i in df[df['batch_index']==49999].index:
df['signal_shift_-1'][i] = np.nan
for c in [c1 for c1 in df.columns if c1 not in ['time', 'signal', 'open_channels', 'batch',
'batch_index', 'batch_slices', 'batch_slices2'
]]:
df[c+'_msignal'] = df[c] - df['signal']
return df
train = features(train)
 test = features(test)
 col = [c for c in train.columns if c not in ['time', 'open_channels', 'batch', 'batch_index', 'batch_slices',
'batch_slices2',
'mean_abs_chgbatch', 'meanbatch', 'rangebatch', 'stdbatch',
'maxbatch', 'medianbatch', 'abs_minbatch', 'abs_avgbatch']]
target = train['open_channels']
train = train[col]<categorify>
history = model.fit_generator(training_generator,
steps_per_epoch=len(training_generator),
validation_data=validation_generator,
validation_steps=len(validation_generator),
epochs=EPOCHS,
verbose=VERBOSITY,shuffle=True,
callbacks=[PlotLossesKeras() ,
ModelCheckpoint(MODEL_FILE,
monitor='val_acc',
verbose=VERBOSITY,
save_best_only=True,
mode='max'),
CSVLogger(TRAINING_LOGS_FILE,
append=False,
separator=';')])
 model.load_weights(MODEL_FILE )
<predict_on_test><EOS> 
tta_steps = 5
test_datagen = ImageDataGenerator(
 shear_range=0.1,
zoom_range=[1,1.5],
horizontal_flip=True,
rotation_range=10.,
fill_mode='reflect',
width_shift_range = 0.1,
height_shift_range = 0.1)
 testing_files = glob(os.path.join(INPUT_DIR+'test/','*.tif'))
submission = pd.DataFrame()
for index in range(0, len(testing_files), TESTING_BATCH_SIZE):
predicted_labels=[]
data_frame = pd.DataFrame({'path': testing_files[index:index+TESTING_BATCH_SIZE]})
 data_frame['id'] = data_frame.path.map(lambda x: x.split('/')[3].split(".")[0])
 data_frame['image'] = data_frame['path'].map(imread)
 if(index==57000):
TESTING_BATCH_SIZE=548;
images = np.stack(data_frame.image, axis=0)
 for i in tqdm(range(tta_steps)) :
preds = model.predict_generator(test_datagen.flow(images/255, batch_size=TESTING_BATCH_SIZE, shuffle=False), steps = len(images)/TESTING_BATCH_SIZE)
 predicted_labels.append(preds)
 predictions = np.max(predicted_labels,axis=0)
 data_frame['label'] = predictions
submission = pd.concat([submission, data_frame[["id", "label"]]])
 submission.to_csv(KAGGLE_SUBMISSION_FILE, index=False, header=True )