Kaggle competition: Understanding Clouds from Satellite Images
<SOS> metric: Dice Kaggle data source: understanding-clouds-from-satellite-images<train_on_grid>
seed(10)
 set_random_seed(10)
 %matplotlib inline
param_grid = [
{'n_estimators': randint(80,150),'max_depth':[5], 'criterion':['gini']}
]
ext_best, ext_grid, ext =random_grid_search(ExtraTreesClassifier(random_state=42),param_grid,X=train,y=target,n=20 )<train_on_grid>
!pip install keras-rectified-adam
models=[ 
('svc', svc_best), 
('log', log_best), 
('xgb',xgb_best), 
('gbc', gbc_best), 
('xgbc', xgbc_best), 
('ada', xgbc_best), 
('rdf',rdf_best), 
('ext',ext_best)
 ]
vot_hard = VotingClassifier(estimators=models, voting='hard', n_jobs=-1)
 vot_hard.fit(train,target)
 vot_soft = VotingClassifier(estimators=models, voting='soft', n_jobs=-1)
 vot_soft.fit(train,target)
 stack=StackingClassifier(estimators=models,cv=kfolds,n_jobs=-1,stack_method='predict_proba')
 stack.fit(train,target)
 prediction_hard=vot_hard.predict(test)
 prediction_soft=vot_soft.predict(test)
 prediction_stack=stack.predict(test)
<compute_train_metric>
test_imgs_folder = '.. /input/understanding_cloud_organization/test_images/'
train_imgs_folder = '.. /input/understanding_cloud_organization/train_images/'
num_cores = multiprocessing.cpu_count()
kfolds=StratifiedKFold(n_splits=3)
 scores=[]
models=[vot_hard,vot_soft,stack]
for model in models:
scores.append(cross_val_score(model,train,target,cv=kfolds))
scores_mean=np.mean(scores,axis=1 )<save_to_csv>
train_df = pd.read_csv('.. /input/understanding_cloud_organization/train.csv')
 train_df.head()
Survived_hard = pd.Series(prediction_hard, name="Survived")
 result_hard = pd.concat([Id,Survived_hard],axis=1)
 result_hard.to_csv("submission_hard.csv",index=False)
 Survived_soft = pd.Series(prediction_soft, name="Survived")
 result_soft = pd.concat([Id,Survived_soft],axis=1)
 result_soft.to_csv("submission_soft.csv",index=False)
 Survived_stack = pd.Series(prediction_stack, name="Survived")
 result_stack = pd.concat([Id,Survived_stack],axis=1)
 result_stack.to_csv("submission_stack.csv",index=False )<load_from_csv>
train_df = train_df[~train_df['EncodedPixels'].isnull() ]
train_df['Image'] = train_df['Image_Label'].map(lambda x: x.split('_')[0])
 train_df['Class'] = train_df['Image_Label'].map(lambda x: x.split('_')[1])
 classes = train_df['Class'].unique()
train_df = train_df.groupby('Image')['Class'].agg(set ).reset_index()
for class_name in classes:
train_df[class_name] = train_df['Class'].map(lambda x: 1 if class_name in x else 0)
 train_df.head()
train = pd.read_csv('.. /input/titanic/train.csv')
 test = pd.read_csv('.. /input/titanic/test.csv' )<prepare_x_and_y>
img_2_ohe_vector = {img:vec for img, vec in zip(train_df['Image'], train_df.iloc[:, 2:].values)}
train_x = train.drop(['Survived'], axis=1)
 train_y = train['Survived']<create_dataframe>
train_imgs, val_imgs = train_test_split(train_df['Image'].values,
test_size=0.17,
stratify=train_df['Class'].map(lambda x: str(sorted(list(x)))) ,
random_state=2019 )
test_x = test.copy()<import_modules>
class DataGenenerator(Sequence):
def __init__(self, images_list=None, folder_imgs=train_imgs_folder,
batch_size=16, shuffle=True, augmentation=None,
resized_height=256, resized_width=256, num_channels=3):
self.batch_size = batch_size
self.shuffle = shuffle
self.augmentation = augmentation
if images_list is None:
self.images_list = os.listdir(folder_imgs)
 else:
self.images_list = deepcopy(images_list)
 self.folder_imgs = folder_imgs
self.len = len(self.images_list)// self.batch_size
self.resized_height = resized_height
self.resized_width = resized_width
self.num_channels = num_channels
self.num_classes = 4
self.is_test = not 'train' in folder_imgs
if not shuffle and not self.is_test:
self.labels = [img_2_ohe_vector[img] for img in self.images_list[:self.len*self.batch_size]]
def __len__(self):
return self.len
def on_epoch_start(self):
if self.shuffle:
random.shuffle(self.images_list)
 def __getitem__(self, idx):
current_batch = self.images_list[idx * self.batch_size:(idx + 1)* self.batch_size]
X = np.empty(( self.batch_size, self.resized_height, self.resized_width, self.num_channels))
y = np.empty(( self.batch_size, self.num_classes))
for i, image_name in enumerate(current_batch):
path = os.path.join(self.folder_imgs, image_name)
 img = cv2.resize(cv2.imread(path),(self.resized_height, self.resized_width)).astype(np.float32)
 if not self.augmentation is None:
augmented = self.augmentation(image=img)
 img = augmented['image']
X[i, :, :, :] = img/255.0
if not self.is_test:
y[i, :] = img_2_ohe_vector[image_name]
return X, y
def get_labels(self):
if self.shuffle:
images_current = self.images_list[:self.len*self.batch_size]
labels = [img_2_ohe_vector[img] for img in images_current]
else:
labels = self.labels
return np.array(labels )
from sklearn.preprocessing import LabelEncoder<drop_column>
albumentations_train = Compose([
VerticalFlip() , HorizontalFlip() , Rotate(limit=10), GridDistortion()
], p=1 )
train_x = train_x.drop(['PassengerId'], axis=1)
 test_x = test_x.drop(['PassengerId'], axis=1 )<drop_column>
data_generator_train = DataGenenerator(train_imgs, augmentation=albumentations_train)
 data_generator_train_eval = DataGenenerator(train_imgs, shuffle=False)
 data_generator_val = DataGenenerator(val_imgs, shuffle=False )
train_x = train_x.drop(['Name', 'Ticket', 'Cabin'], axis=1)
 test_x = test_x.drop(['Name', 'Ticket', 'Cabin'], axis=1 )<categorify>
class PrAucCallback(Callback):
def __init__(self, data_generator, num_workers=num_cores,
early_stopping_patience=5,
plateau_patience=3, reduction_rate=0.5,
stage='train', checkpoints_path='checkpoints/'):
super(Callback, self ).__init__()
self.data_generator = data_generator
self.num_workers = num_workers
self.class_names = ['Fish', 'Flower', 'Sugar', 'Gravel']
self.history = [[] for _ in range(len(self.class_names)+ 1)]
self.early_stopping_patience = early_stopping_patience
self.plateau_patience = plateau_patience
self.reduction_rate = reduction_rate
self.stage = stage
self.best_pr_auc = -float('inf')
 if not os.path.exists(checkpoints_path):
os.makedirs(checkpoints_path)
 self.checkpoints_path = checkpoints_path
def compute_pr_auc(self, y_true, y_pred):
pr_auc_mean = 0
print(f"
{'
")
 for class_i in range(len(self.class_names)) :
precision, recall, _ = precision_recall_curve(y_true[:, class_i], y_pred[:, class_i])
 pr_auc = auc(recall, precision)
 pr_auc_mean += pr_auc/len(self.class_names)
 print(f"PR AUC {self.class_names[class_i]}, {self.stage}: {pr_auc:.3f}
")
 self.history[class_i].append(pr_auc)
 print(f"
{'
PR AUC mean, {self.stage}: {pr_auc_mean:.3f}
{'
")
 self.history[-1].append(pr_auc_mean)
 return pr_auc_mean
def is_patience_lost(self, patience):
if len(self.history[-1])> patience:
best_performance = max(self.history[-1][-(patience + 1):-1])
 return best_performance == self.history[-1][-(patience + 1)] and best_performance >= self.history[-1][-1]
def early_stopping_check(self, pr_auc_mean):
if self.is_patience_lost(self.early_stopping_patience):
self.model.stop_training = True
def model_checkpoint(self, pr_auc_mean, epoch):
if pr_auc_mean > self.best_pr_auc:
for checkpoint in glob.glob(os.path.join(self.checkpoints_path, 'classifier_densenet169_epoch_*')) :
os.remove(checkpoint)
 self.best_pr_auc = pr_auc_mean
self.model.save(os.path.join(self.checkpoints_path, f'classifier_densenet169_epoch_{epoch}_val_pr_auc_{pr_auc_mean}.h5'))
print(f"
{'
Saved new checkpoint
{'
")
 def reduce_lr_on_plateau(self):
if self.is_patience_lost(self.plateau_patience):
new_lr = float(keras.backend.get_value(self.model.optimizer.lr)) * self.reduction_rate
keras.backend.set_value(self.model.optimizer.lr, new_lr)
 print(f"
{'
Reduced learning rate to {new_lr}.
 {'
")
 def on_epoch_end(self, epoch, logs={}):
y_pred = self.model.predict_generator(self.data_generator, workers=self.num_workers)
 y_true = self.data_generator.get_labels()
pr_auc_mean = self.compute_pr_auc(y_true, y_pred)
 if self.stage == 'val':
self.early_stopping_check(pr_auc_mean)
 self.model_checkpoint(pr_auc_mean, epoch)
 self.reduce_lr_on_plateau()
def get_pr_auc_history(self):
return self.history
for c in ['Sex', 'Embarked']:
le = LabelEncoder()
le.fit(train_x[c].fillna('NA'))
train_x[c] = le.transform(train_x[c].fillna('NA'))
test_x[c] = le.transform(test_x[c].fillna('NA'))<import_modules>
train_metric_callback = PrAucCallback(data_generator_train_eval)
 val_callback = PrAucCallback(data_generator_val, stage='val' )
from xgboost import XGBClassifier<train_model>
def dice_coef(y_true, y_pred, smooth=1):
y_true_f = K.flatten(y_true)
 y_pred_f = K.flatten(y_pred)
 intersection = K.sum(y_true_f * y_pred_f)
 return(2.* intersection + smooth)/(K.sum(y_true_f)+ K.sum(y_pred_f)+ smooth)
 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 )
model = XGBClassifier(n_estimators=20, random_state=71)
 model.fit(train_x, train_y )<predict_on_test>
!pip install -U git+https://github.com/qubvel/efficientnet
pred = model.predict_proba(test_x)[:, 1]<define_variables>
def get_model() :
K.clear_session()
base_model = efn.EfficientNetB4(weights='imagenet', include_top=False, pooling='avg', input_shape=(256, 256, 3))
x = base_model.output
y_pred = Dense(4, activation='sigmoid' )(x)
 return Model(inputs=base_model.input, outputs=y_pred)
 model = get_model()
pred_label = np.where(pred > 0.5, 1, 0 )<save_to_csv>
from keras_radam import RAdam
submission = pd.DataFrame({'PassengerId': test['PassengerId'], 'Survived': pred_label})
 submission.to_csv('submission_first.csv', index=False )<import_modules>
for base_layer in model.layers[:-5]:
base_layer.trainable = False
model.compile(optimizer=RAdam(warmup_proportion=0.1, min_lr=1e-5), loss=bce_dice_loss)
 history_0 = model.fit_generator(generator=data_generator_train,
validation_data=data_generator_val,
epochs=30,
callbacks=[train_metric_callback, val_callback],
workers=num_cores,
verbose=1
)
from sklearn.metrics import log_loss, accuracy_score
from sklearn.model_selection import KFold<define_variables>
for base_layer in model.layers[:-1]:
base_layer.trainable = True
model.compile(optimizer=RAdam(warmup_proportion=0.1, min_lr=1e-5), loss=bce_dice_loss)
 history_1 = model.fit_generator(generator=data_generator_train,
validation_data=data_generator_val,
epochs=20,
callbacks=[train_metric_callback, val_callback],
workers=num_cores,
verbose=1,
initial_epoch=1
)
scores_accuracy = []
scores_logloss = []<train_model>
class_names = ['Fish', 'Flower', 'Sugar', 'Gravel']
def get_threshold_for_recall(y_true, y_pred, class_i, recall_threshold=0.94, precision_threshold=0.94, plot=False):
precision, recall, thresholds = precision_recall_curve(y_true[:, class_i], y_pred[:, class_i])
 i = len(thresholds)- 1
best_recall_threshold = None
while best_recall_threshold is None:
next_threshold = thresholds[i]
next_recall = recall[i]
if next_recall >= recall_threshold:
best_recall_threshold = next_threshold
i -= 1
best_precision_threshold = [thres for prec, thres in zip(precision, thresholds)if prec >= precision_threshold][0]
if plot:
plt.figure(figsize=(10, 7))
plt.step(recall, precision, color='r', alpha=0.3, where='post')
 plt.fill_between(recall, precision, alpha=0.3, color='r')
 plt.axhline(y=precision[i + 1])
 recall_for_prec_thres = [rec for rec, thres in zip(recall, thresholds)
 if thres == best_precision_threshold][0]
plt.axvline(x=recall_for_prec_thres, color='g')
 plt.xlabel('Recall')
 plt.ylabel('Precision')
 plt.ylim([0.0, 1.05])
 plt.xlim([0.0, 1.0])
 plt.legend(['PR curve',
f'Precision {precision[i + 1]:.2f} corresponding to selected recall threshold',
f'Recall {recall_for_prec_thres:.2f} corresponding to selected precision threshold'])
 plt.title(f'Precision-Recall curve for Class {class_names[class_i]}')
 return best_recall_threshold, best_precision_threshold
y_pred = model.predict_generator(data_generator_val, workers=num_cores)
 y_true = data_generator_val.get_labels()
recall_thresholds = dict()
precision_thresholds = dict()
for i, class_name in tqdm(enumerate(class_names)) :
recall_thresholds[class_name], precision_thresholds[class_name] = get_threshold_for_recall(y_true, y_pred, i, plot=True )
kf = KFold(n_splits=4, shuffle=True, random_state=71)
 for tr_idx, va_idx in kf.split(train_x):
tr_x, va_x = train_x.iloc[tr_idx], train_x.iloc[va_idx]
tr_y, va_y = train_y.iloc[tr_idx], train_y.iloc[va_idx]
model = XGBClassifier(n_estimators=20, random_state=71)
 model.fit(tr_x, tr_y)
 va_pred = model.predict_proba(va_x)[:, 1]
logloss = log_loss(va_y, va_pred)
 accuracy = accuracy_score(va_y, va_pred > 0.5)
 scores_logloss.append(logloss)
 scores_accuracy.append(accuracy )<compute_test_metric>
data_generator_test = DataGenenerator(folder_imgs=test_imgs_folder, shuffle=False)
 y_pred_test = model.predict_generator(data_generator_test, workers=num_cores )
logloss = np.mean(scores_logloss)
 accuracy = np.mean(scores_accuracy)
 print(f'logloss: {logloss:.4f}, accuracy: {accuracy:.4f}' )<import_modules>
image_labels_empty = set()
for i,(img, predictions)in enumerate(zip(os.listdir(test_imgs_folder), y_pred_test)) :
for class_i, class_name in enumerate(class_names):
if predictions[class_i] < recall_thresholds[class_name]:
image_labels_empty.add(f'{img}_{class_name}' )
import itertools<define_search_space>
submission = pd.read_csv('.. /input/efficient-net-b4-unet-clouds/submission.csv')
 submission.head()
param_space = {
'max_depth': [3, 5, 7],
'min_child_weight': [1.0, 2.0, 4.0]
}<concatenate>
predictions_nonempty = set(submission.loc[~submission['EncodedPixels'].isnull() , 'Image_Label'].values )
param_combinations = itertools.product(param_space['max_depth'], param_space['min_child_weight'] )<define_variables>
print(f'{len(image_labels_empty.intersection(predictions_nonempty)) } masks would be removed' )
params = []
scores = []<train_model>
submission.loc[submission['Image_Label'].isin(image_labels_empty), 'EncodedPixels'] = np.nan
submission.to_csv('submission_segmentation_and_classifier_efficientnetb4_16btch_size.csv', index=None )