Kaggle competition: Understanding Clouds from Satellite Images
<SOS> metric: Dice Kaggle data source: understanding-clouds-from-satellite-images<import_modules>
seed(10)
 set_random_seed(10)
 %matplotlib inline
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import GridSearchCV<load_from_csv>
test_imgs_folder = '.. /input/understanding_cloud_organization/test_images/'
train_imgs_folder = '.. /input/understanding_cloud_organization/train_images/'
num_cores = multiprocessing.cpu_count()
train = pd.read_csv(".. /input/titanic/train.csv")
 test = pd.read_csv(".. /input/titanic/test.csv" )<count_missing_values>
train_df = pd.read_csv('.. /input/understanding_cloud_organization/train.csv')
 train_df.head()
train.isnull().sum()<count_missing_values>
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.isnull().sum()<feature_engineering>
img_2_ohe_vector = {img:vec for img, vec in zip(train_df['Image'], train_df.iloc[:, 2:].values)}
train.loc[:, "Age"] = train.groupby(["Pclass", "Sex"] ).Age.apply(lambda x: x.fillna(x.median()))
test.loc[:, "Age"] = test.groupby(["Pclass", "Sex"] ).Age.apply(lambda x : x.fillna(x.median()))<drop_column>
train_imgs, val_imgs = train_test_split(train_df['Image'].values,
test_size=0.2,
stratify=train_df['Class'].map(lambda x: str(sorted(list(x)))) ,
random_state=10 )
train.drop(["Cabin", "Name", "Ticket", "Fare"], axis = "columns", inplace = True)
 test.drop(["Cabin", "Name", "Ticket", "Fare"], axis = "columns", inplace = True )<prepare_x_and_y>
class DataGenenerator(Sequence):
def __init__(self, images_list=None, folder_imgs=train_imgs_folder,
batch_size=32, shuffle=True, augmentation=None,
resized_height=224, resized_width=224, 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 )
X = train.drop(["PassengerId", "Survived"], axis = "columns")
 y = train.Survived<split>
albumentations_train = Compose([
VerticalFlip() , HorizontalFlip() , Rotate(limit=30), GridDistortion()
], p=1 )
X_train, X_valid, y_train, y_valid = train_test_split(X, y, random_state = 1 )<define_variables>
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 )
numerical_cols = ["Age", "Parch", "SibSp"]
categorical_cols = ["Pclass", "Sex", "Embarked"]<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
numerical_transform = StandardScaler()
categorical_tranform = Pipeline(steps = [ 
("imputer", SimpleImputer(strategy = "most_frequent")) , 
("onehot", OneHotEncoder(handle_unknown = "ignore"))
])
 preprocessor = ColumnTransformer(transformers=[ 
("num", numerical_transform, numerical_cols), 
("cat", categorical_tranform, categorical_cols)
 ] )<train_on_grid>
train_metric_callback = PrAucCallback(data_generator_train_eval)
 val_callback = PrAucCallback(data_generator_val, stage='val' )
classifier = Pipeline(steps= [ 
("preprocessor", preprocessor), 
("model", LogisticRegression(max_iter = 10000))
])
 param_grid = {
'model__C': [0.001, 0.01, 0.1,1, 10, 100, 1000]
}
clf_LR = GridSearchCV(classifier, param_grid, cv = 5, scoring= "accuracy")
 clf_LR.fit(X_train, y_train )<find_best_score>
def get_model() :
K.clear_session()
base_model = DenseNet169(weights='imagenet', include_top=False, pooling='avg', input_shape=(224, 224, 3))
x = base_model.output
y_pred = Dense(4, activation='sigmoid' )(x)
 return Model(inputs=base_model.input, outputs=y_pred)
 model = get_model()
print(clf_LR.best_params_)
 print(clf_LR.best_score_ )<train_on_grid>
for base_layer in model.layers[:-1]:
base_layer.trainable = False
model.compile(optimizer=Adam(lr=1e-4), loss='binary_crossentropy')
 history_0 = model.fit_generator(generator=data_generator_train,
validation_data=data_generator_val,
epochs=1,
callbacks=[train_metric_callback, val_callback],
workers=num_cores,
verbose=1
)
classifier = Pipeline(steps= [ 
("preprocessor", preprocessor), 
("model", SVC())
 ])
 param_grid = {
'model__C': [0.01, 0.1,1, 10, 100],
"model__gamma": [0.001, 0.01, 0.1, 1]
}
clf_SVC = GridSearchCV(classifier, param_grid, cv = 5, scoring= "accuracy")
 clf_SVC.fit(X_train, y_train )<find_best_params>
for base_layer in model.layers[:-1]:
base_layer.trainable = True
model.compile(optimizer=Adam(lr=1e-5), loss='binary_crossentropy')
 history_1 = model.fit_generator(generator=data_generator_train,
validation_data=data_generator_val,
epochs=2,
callbacks=[train_metric_callback, val_callback],
workers=num_cores,
verbose=1,
initial_epoch=1
)
print(clf_SVC.best_params_)
 print(clf_SVC.best_score_ )<compute_train_metric>
model = load_model('.. /input/clouds-classifier-files/classifier_densenet169_epoch_21_val_pr_auc_0.8365921057512743.h5' )
models = [LogisticRegression(max_iter= 10000, C = 0.1), SVC(C = 10, gamma= 0.1), RandomForestClassifier(n_estimators= 50)]
scores = []
for model in models:
classifier = Pipeline(steps= [ 
("preprocessor", preprocessor), 
("model", model)
 ])
 cross = cross_val_score(classifier, X_train, y_train)
 scores.append(np.average(cross))
scores<choose_model_class>
Image(".. /input/clouds-classifier-files/loss_hist_densenet169.png" )
classifier_final = Pipeline(steps= [ 
("preprocessor", preprocessor), 
("model", SVC(C = 10, gamma = 0.1))
] )<train_model>
Image(".. /input/clouds-classifier-files/pr_auc_hist_densenet169.png" )
classifier_final.fit(X_train, y_train )<predict_on_test>
class_names = ['Fish', 'Flower', 'Sugar', 'Gravel']
def get_threshold_for_recall(y_true, y_pred, class_i, recall_threshold=0.95, 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 )
pred = classifier_final.predict(X_valid)
 accuracy_score(y_valid, pred )<define_variables>
data_generator_test = DataGenenerator(folder_imgs=test_imgs_folder, shuffle=False)
 y_pred_test = model.predict_generator(data_generator_test, workers=num_cores )
PassengerId = test.PassengerId<drop_column>
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}' )
test.drop("PassengerId", axis = "columns", inplace = True )<predict_on_test>
submission = pd.read_csv('.. /input/efficient-net-b4-unet-clouds/submission.csv')
 submission.head()
predictions = classifier_final.predict(test )<save_to_csv>
predictions_nonempty = set(submission.loc[~submission['EncodedPixels'].isnull() , 'Image_Label'].values )
output = pd.DataFrame({"PassengerId": PassengerId,
"Survived": predictions})
 output.to_csv("submission.csv", index = False )<set_options>
print(f'{len(image_labels_empty.intersection(predictions_nonempty)) } masks would be removed' )
%matplotlib inline
sns.set(palette=sns.color_palette('Set2',9)) 
<install_modules>
submission.loc[submission['Image_Label'].isin(image_labels_empty), 'EncodedPixels'] = np.nan
submission.to_csv('submission_segmentation_and_classifier.csv', index=None )