Kaggle competition: Global Wheat Detection
<SOS> metric: custom metric Kaggle data source: global-wheat-detection<train_on_grid>
!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
lasso=Lasso()
alpha=1/np.array([0.1,1,2,3,4,10,30,100,200,300,400,800,900,1000])
 lasso_params={'max_iter':[3000],'alpha':alpha}
grid_lasso=GridSearchCV(lasso,lasso_params,scoring=rmsle_scorer,cv=5)
 y_train_log=np.log1p(y_train)
 grid_lasso.fit(train,y_train_log)
 pred=grid_lasso.predict(train)
 print(grid_lasso.best_params_)
 print("RMSLE Value For Lasso Regression: ", rmsle(y_train_log,pred,True))
fig,ax=plt.subplots()
df=pd.DataFrame(grid_lasso.cv_results_)
 df['alpha']=df['param_alpha']
df['rmsle']=-df['mean_test_score']
sn.pointplot(data=df,x='alpha',y='rmsle',ax=ax )<train_model>
def get_valid_transforms() :
return A.Compose([
A.Resize(height=1024, width=1024, p=1.0),
ToTensorV2(p=1.0),
], p=1.0 )
rf=RandomForestRegressor(n_estimators=100)
 y_train_log=np.log1p(y_train)
 rf.fit(train,y_train_log)
 pred=rf.predict(train)
 print("RMSLE Value For Random Forest: ", rmsle(y_train_log,pred,True))<train_model>
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]
gbr=GradientBoostingRegressor(n_estimators=4000,alpha=0.01)
 y_train_log=np.log1p(y_train)
 gbr.fit(train,y_train_log)
 pred=gbr.predict(train)
 print("RMSLE Value For Gradient Boost: ", rmsle(y_train_log,pred,True))<save_to_csv>
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=2,
drop_last=False,
collate_fn=collate_fn
)
submission=pd.DataFrame({
'datetime':datetimecol,
'count':[max(0,x)for x in np.exp(pred_test)]
})
 submission.to_csv('bike_predictions_gbm.csv',index=False )<set_options>
def load_net(checkpoint_path):
config = get_efficientdet_config('tf_efficientdet_d4')
 net = EfficientDet(config, pretrained_backbone=False)
 config.num_classes = 1
config.image_size=1024
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/effdet4/effdet5-cutmix-augmix/best-checkpoint-018epoch.bin' )
pd.options.mode.chained_assignment = None
warnings.filterwarnings("ignore", category = DeprecationWarning)
 %matplotlib inline<load_from_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=1024, 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
dataTrain = pd.read_csv(".. /input/bike-sharing-demand/train.csv")
 dataTest = pd.read_csv(".. /input/bike-sharing-demand/test.csv" )<concatenate>
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 )
data = dataTrain.append(dataTest)
 data.reset_index(inplace = True)
 data.drop('index', inplace = True, axis = 1 )<feature_engineering>
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 ).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 )
<feature_engineering><EOS> 
test_df = pd.DataFrame(results, columns=['image_id', 'PredictionString'])
 test_df.to_csv('submission.csv', index=False)
 test_df.head()