Kaggle competition: Global Wheat Detection
<SOS> metric: custom metric Kaggle data source: global-wheat-detection<prepare_x_and_y>
!pip install --no-deps '.. /input/timm-package/timm-0.1.26-py3-none-any.whl' > /dev/null
!pip install --no-deps '.. /input/pycocotools/pycocotools-2.0-cp37-cp37m-linux_x86_64.whl' > /dev/null
X_train = train[SELECTED_FEATURES]
y_train = train['open_channels'].values
print(f'Original sizes: train: {train.shape}, test: {test.shape}')
 print(f'Reduced train sizes: X_train: {X_train.shape}, y_train: {y_train.shape}' )<compute_test_metric>
def get_valid_transforms() :
return A.Compose([
A.Resize(height=512, width=512, p=1.0),
ToTensorV2(p=1.0),
], p=1.0 )
def MacroF1Metric(preds, dtrain):
labels = dtrain.get_label()
preds = np.round(np.clip(preds, 0, 10)).astype(int)
 score = f1_score(labels, preds, average = 'macro')
 return('MacroF1Metric', score, True )<split>
DATA_ROOT_PATH = '.. /input/global-wheat-detection/test'
class DatasetRetriever(Dataset):
def __init__(self, image_ids, transforms=None):
super().__init__()
self.image_ids = image_ids
self.transforms = transforms
def __getitem__(self, index: int):
image_id = self.image_ids[index]
image = cv2.imread(f'{DATA_ROOT_PATH}/{image_id}.jpg', cv2.IMREAD_COLOR)
 image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB ).astype(np.float32)
 image /= 255.0
if self.transforms:
sample = {'image': image}
sample = self.transforms(**sample)
 image = sample['image']
return image, image_id
def __len__(self)-> int:
return self.image_ids.shape[0]
NUM_BOOST_ROUND = 2000
EARLY_STOPPING_ROUNDS = 40
VERBOSE_EVAL = 100
RANDOM_SEED = 13
LEARNING_RATE = 0.02
MAX_DEPTH = -1
NUM_LEAVES = 200
X_train1, X_valid1, y_train1, y_valid1 = train_test_split(X_train, y_train, test_size=0.3, random_state=RANDOM_SEED)
 params = {
'learning_rate': LEARNING_RATE,
'max_depth': MAX_DEPTH,
'num_leaves': NUM_LEAVES,
'metric': 'logloss',
'random_state': RANDOM_SEED,
'n_jobs':-1,
'sample_fraction':0.33
}
evals_result = {}
model = lgb.train(
 params,
train_set=lgb.Dataset(X_train1, y_train1),
num_boost_round = NUM_BOOST_ROUND,
valid_sets = lgb.Dataset(X_valid1, y_valid1),
verbose_eval = VERBOSE_EVAL,
evals_result = evals_result,
early_stopping_rounds = EARLY_STOPPING_ROUNDS,
feval = MacroF1Metric)
 gc.collect()<predict_on_test>
dataset = DatasetRetriever(
 image_ids=np.array([path.split('/')[-1][:-4] for path in glob(f'{DATA_ROOT_PATH}/*.jpg')]),
transforms=get_valid_transforms() 
)
 def collate_fn(batch):
return tuple(zip(*batch))
data_loader = DataLoader(
 dataset,
batch_size=2,
shuffle=False,
num_workers=4,
drop_last=False,
collate_fn=collate_fn
)
y_pred_train_lgb = model.predict(X_train, num_iteration=model.best_iteration)
 print('LGB score {0:.4f}'.format(np.mean(f1_score(y_train, np.round(np.clip(y_pred_train_lgb,0,10)).astype(int), average="macro"))))
gc.collect()<predict_on_test>
def load_net(checkpoint_path):
config = get_efficientdet_config('tf_efficientdet_d5')
 net = EfficientDet(config, pretrained_backbone=False)
 config.num_classes = 1
config.image_size=512
net.class_net = HeadNet(config, num_outputs=config.num_classes, norm_kwargs=dict(eps=.001, momentum=.01))
checkpoint = torch.load(checkpoint_path)
 net.load_state_dict(checkpoint['model_state_dict'])
 del checkpoint
gc.collect()
net = DetBenchEval(net, config)
 net.eval() ;
return net.cuda()
net = load_net('.. /input/wheat-effdet5-fold0-best-checkpoint/fold0-best-all-states.bin' )
y_hat = model.predict(test[SELECTED_FEATURES], num_iteration=model.best_iteration)
 y_pred = np.round(np.clip(y_hat,0,10)).astype(int )<save_to_csv>
def make_predictions(images, score_threshold=0.22):
images = torch.stack(images ).cuda().float()
predictions = []
with torch.no_grad() :
det = net(images, torch.tensor([1]*images.shape[0] ).float().cuda())
 for i in range(images.shape[0]):
boxes = det[i].detach().cpu().numpy() [:,:4]
scores = det[i].detach().cpu().numpy() [:,4]
indexes = np.where(scores > score_threshold)[0]
boxes = boxes[indexes]
boxes[:, 2] = boxes[:, 2] + boxes[:, 0]
boxes[:, 3] = boxes[:, 3] + boxes[:, 1]
predictions.append({
'boxes': boxes[indexes],
'scores': scores[indexes],
})
 return [predictions]
def run_wbf(predictions, image_index, image_size=512, iou_thr=0.44, skip_box_thr=0.43, weights=None):
boxes = [(prediction[image_index]['boxes']/(image_size-1)).tolist() for prediction in predictions]
scores = [prediction[image_index]['scores'].tolist() for prediction in predictions]
labels = [np.ones(prediction[image_index]['scores'].shape[0] ).tolist() for prediction in predictions]
boxes, scores, labels = weighted_boxes_fusion(boxes, scores, labels, weights=None, iou_thr=iou_thr, skip_box_thr=skip_box_thr)
 boxes = boxes*(image_size-1)
 return boxes, scores, labels
sub = pd.read_csv('.. /input/liverpool-ion-switching/sample_submission.csv')
 sub['open_channels'] = y_pred
sub.to_csv('submission.csv', index=False, float_format='%.4f')
 sub.head(20 )<import_modules>
def format_prediction_string(boxes, scores):
pred_strings = []
for j in zip(scores, boxes):
pred_strings.append("{0:.4f} {1} {2} {3} {4}".format(j[0], j[1][0], j[1][1], j[1][2], j[1][3]))
return " ".join(pred_strings )
warnings.simplefilter('ignore')
 warnings.filterwarnings('ignore')
 pd.set_option('display.max_columns', 1000)
 pd.set_option('display.max_rows', 500)
 %matplotlib inline<define_search_space>
results = []
for images, image_ids in data_loader:
predictions = make_predictions(images)
 for i, image in enumerate(images):
boxes, scores, labels = run_wbf(predictions, image_index=i)
 boxes =(boxes*2 ).astype(np.int32 ).clip(min=0, max=1023)
 image_id = image_ids[i]
boxes[:, 2] = boxes[:, 2] - boxes[:, 0]
boxes[:, 3] = boxes[:, 3] - boxes[:, 1]
result = {
'image_id': image_id,
'PredictionString': format_prediction_string(boxes, scores)
 }
results.append(result )
<define_variables><EOS> 
test_df = pd.DataFrame(results, columns=['image_id', 'PredictionString'])
 test_df.to_csv('submission.csv', index=False)
 test_df.head()