Kaggle competition: Global Wheat Detection
i_cols = ['M1','M2','M3','M5','M6','M7','M8','M9']
train['M_type'] = train[i_cols].astype(str ).apply(lambda x: '_'.join(x), axis=1)
 test['M_type'] = test[i_cols].astype(str ).apply(lambda x: '_'.join(x), axis=1 )<feature_engineering>
sys.path.insert(0, ".. /input/weightedboxesfusion/")
 NMS_IOU_THR = 0.6
NMS_CONF_THR = 0.5
best_iou_thr = 0.42
best_skip_box_thr = 0.41
best_final_score = 0
best_score_threshold = 0
cfgfile = '.. /input/yolov4weights/submit.cfg'
weightfile = '.. /input/yolov4weights/submit.weights'
WEIGHTS = Darknet(cfgfile)
 WEIGHTS.load_weights(weightfile)
 WEIGHTS.cuda()
is_TEST = len(os.listdir('.. /input/global-wheat-detection/test/')) >11
is_AUG = True
is_ROT = True
VALIDATE = True
PSEUDO = True
marking = pd.read_csv('.. /input/global-wheat-detection/train.csv')
 bboxs = np.stack(marking['bbox'].apply(lambda x: np.fromstring(x[1:-1], sep=',')))
 for i, column in enumerate(['x', 'y', 'w', 'h']):
marking[column] = bboxs[:,i]
marking.drop(columns=['bbox'], inplace=True )
def id_split(df):
df['device_name'] = df['DeviceInfo'].str.split('/', expand=True)[0]
df['device_version'] = df['DeviceInfo'].str.split('/', expand=True)[1]
df['OS_id_30'] = df['id_30'].str.split(' ', expand=True)[0]
df['version_id_30'] = df['id_30'].str.split(' ', expand=True)[1]
df['browser_id_31'] = df['id_31'].str.split(' ', expand=True)[0]
df['version_id_31'] = df['id_31'].str.split(' ', expand=True)[1]
df['screen_width'] = df['id_33'].str.split('x', expand=True)[0]
df['screen_height'] = df['id_33'].str.split('x', expand=True)[1]
df['id_34'] = df['id_34'].str.split(':', expand=True)[1]
df['id_23'] = df['id_23'].str.split(':', expand=True)[1]
df.loc[df['device_name'].str.contains('SM', na=False), 'device_name'] = 'Samsung'
df.loc[df['device_name'].str.contains('SAMSUNG', na=False), 'device_name'] = 'Samsung'
df.loc[df['device_name'].str.contains('GT-', na=False), 'device_name'] = 'Samsung'
df.loc[df['device_name'].str.contains('Moto G', na=False), 'device_name'] = 'Motorola'
df.loc[df['device_name'].str.contains('Moto', na=False), 'device_name'] = 'Motorola'
df.loc[df['device_name'].str.contains('moto', na=False), 'device_name'] = 'Motorola'
df.loc[df['device_name'].str.contains('LG-', na=False), 'device_name'] = 'LG'
df.loc[df['device_name'].str.contains('rv:', na=False), 'device_name'] = 'RV'
df.loc[df['device_name'].str.contains('HUAWEI', na=False), 'device_name'] = 'Huawei'
df.loc[df['device_name'].str.contains('ALE-', na=False), 'device_name'] = 'Huawei'
df.loc[df['device_name'].str.contains('-L', na=False), 'device_name'] = 'Huawei'
df.loc[df['device_name'].str.contains('Blade', na=False), 'device_name'] = 'ZTE'
df.loc[df['device_name'].str.contains('BLADE', na=False), 'device_name'] = 'ZTE'
df.loc[df['device_name'].str.contains('Linux', na=False), 'device_name'] = 'Linux'
df.loc[df['device_name'].str.contains('XT', na=False), 'device_name'] = 'Sony'
df.loc[df['device_name'].str.contains('HTC', na=False), 'device_name'] = 'HTC'
df.loc[df['device_name'].str.contains('ASUS', na=False), 'device_name'] = 'Asus'
df.loc[df.device_name.isin(df.device_name.value_counts() [df.device_name.value_counts() < 200].index), 'device_name'] = "Others"
df['had_id'] = 1
gc.collect()
return df
train = id_split(train)
 test = id_split(test )<data_type_conversions>
def convert(size, box):
dw = 1./ size[0]
dh = 1./ size[1]
x =(box[0] + box[1])/ 2.0
y =(box[2] + box[3])/ 2.0
w = box[1] - box[0]
h = box[3] - box[2]
x = x * dw
w = w * dw
y = y * dh
h = h * dh
return [x, y, w, h]
def convert_to_yolo_label(coco_format_box, w = 1024, h = 1024):
bbox = ast.literal_eval(coco_format_box)
 xmin = bbox[0]
xmax = bbox[0] + bbox[2]
ymin = bbox[1]
ymax = bbox[1] + bbox[3]
b =(float(xmin), float(xmax), float(ymin), float(ymax))
yolo_box = convert(( w, h), b)
 if np.max(yolo_box)> 1 or np.min(yolo_box)< 0:
print("BOX HAS AN ISSUE")
 return yolo_box
def convertTrainLabel() :
df = pd.read_csv('.. /input/global-wheat-detection/train.csv')
 index = list(set(df.image_id))
df['yolo_box'] = df.bbox.apply(convert_to_yolo_label)
 unique_img_ids = df.image_id.unique()
for fold in [0]:
val_index = index[len(index)*fold//5:len(index)*(fold+1)//5]
source = 'train'
for img_id in unique_img_ids:
filt_df = df.query("image_id == @img_id")
 path2save = 'val2017/' if img_id in val_index else 'train2017/'
os.makedirs('convertor/fold{}/{}'.format(fold,path2save), exist_ok=True)
 folder_location = 'convertor/fold0/'+path2save
all_boxes = filt_df.yolo_box.values
file_name = "{}/{}.txt".format(folder_location,img_id)
 s = "0 %s %s %s %s
"
with open(file_name, 'a')as file:
for i in all_boxes:
new_line =(s % tuple(i))
file.write(new_line)
 sh.copy(".. /input/global-wheat-detection/{}/{}.jpg".format(source,img_id),'convertor/fold{}/{}/{}.jpg'.format(fold,path2save,img_id))
print("finished positive images")
 all_imgs = glob.glob(".. /input/global-wheat-detection/train/*.jpg")
 all_imgs = [i.split("/")[-1].replace(".jpg", "")for i in all_imgs]
positive_imgs = df.image_id.unique()
negative_images = set(all_imgs)- set(positive_imgs)
 folder_location = 'convertor/fold0/train2017/'
for i in list(negative_images):
file_name = folder_location+"{}.txt".format(i)
 sh.copy(".. /input/global-wheat-detection/train/{}.jpg".format(i),'convertor/fold0/train2017/{}.jpg'.format(i))
with open(file_name, 'w')as fp:
pass
print('finished negative images')
 def run_wbf(boxes, scores, image_size=1024, iou_thr=0.5, skip_box_thr=0.7, weights=None):
labels = [np.zeros(score.shape[0])for score in scores]
boxes = [box/(image_size)for box in boxes]
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)
 return boxes, scores, labels
def TTAImage(image, index):
image1 = image.copy()
if index==0:
rotated_image = cv2.rotate(image1, cv2.ROTATE_90_CLOCKWISE)
 return rotated_image
elif index==1:
rotated_image2 = cv2.rotate(image1, cv2.ROTATE_90_CLOCKWISE)
 rotated_image2 = cv2.rotate(rotated_image2, cv2.ROTATE_90_CLOCKWISE)
 return rotated_image2
elif index==2:
rotated_image3 = cv2.rotate(image1, cv2.ROTATE_90_CLOCKWISE)
 rotated_image3 = cv2.rotate(rotated_image3, cv2.ROTATE_90_CLOCKWISE)
 rotated_image3 = cv2.rotate(rotated_image3, cv2.ROTATE_90_CLOCKWISE)
 return rotated_image3
elif index == 3:
return image1
def rotBoxes90(boxes, im_w, im_h):
ret_boxes =[]
for box in boxes:
x1, y1, x2, y2 = box
x1, y1, x2, y2 = x1-im_w//2, im_h//2 - y1, x2-im_w//2, im_h//2 - y2
x1, y1, x2, y2 = y1, -x1, y2, -x2
x1, y1, x2, y2 = int(x1+im_w//2), int(im_h//2 - y1), int(x2+im_w//2), int(im_h//2 - y2)
 x1a, y1a, x2a, y2a = min(x1, x2), min(y1, y2), max(x1, x2), max(y1, y2)
 ret_boxes.append([x1a, y1a, x2a, y2a])
 return np.array(ret_boxes)
 def process_det(index, det, imgsize=1024, score_threshold=0.35):
try :
scores = det[index][:, 5].copy()
det = det[index][:, :4].copy()
bboxes = np.zeros(( det.shape))
bboxes[:, 0] =(det[:, 0] * imgsize ).astype(int)
 bboxes[:, 1] =(det[:, 1] * imgsize ).astype(int)
 bboxes[:, 2] =(det[:, 2] * imgsize ).astype(int)
 bboxes[:, 3] =(det[:, 3] * imgsize ).astype(int)
 bboxes =(bboxes ).clip(min = 0, max = imgsize ).astype(int)
 indexes = np.where(scores>score_threshold)
 bboxes = bboxes[indexes]
scores = scores[indexes]
return bboxes, scores
except IndexError:
print(det)
 def detect1Image(img, img0, model, device, aug):
pred = do_detect(model, img, NMS_CONF_THR, NMS_IOU_THR, use_cuda=1)
 prednp = np.array(pred)
 if prednp is None or prednp.size==0:
return np.array([]), np.array([])
 else:
boxes, scores = process_det(0, prednp)
 return np.array(boxes), np.array(scores )
for df in [train, test]:
df['DeviceInfo'] = df['DeviceInfo'].fillna('unknown_device' ).str.lower()
df['DeviceInfo_device'] = df['DeviceInfo'].apply(lambda x: ''.join([i for i in x if i.isalpha() ]))
df['DeviceInfo_version'] = df['DeviceInfo'].apply(lambda x: ''.join([i for i in x if i.isnumeric() ]))
df['id_30'] = df['id_30'].fillna('unknown_device' ).str.lower()
df['id_30_device'] = df['id_30'].apply(lambda x: ''.join([i for i in x if i.isalpha() ]))
df['id_30_version'] = df['id_30'].apply(lambda x: ''.join([i for i in x if i.isnumeric() ]))
df['id_31'] = df['id_31'].fillna('unknown_device' ).str.lower()
df['id_31_device'] = df['id_31'].apply(lambda x: ''.join([i for i in x if i.isalpha() ]))<feature_engineering>
@jit(nopython=True)
 def calculate_iou(gt, pr, form='pascal_voc')-> float:

 if form == 'coco':
gt = gt.copy()
pr = pr.copy()
gt[2] = gt[0] + gt[2]
gt[3] = gt[1] + gt[3]
pr[2] = pr[0] + pr[2]
pr[3] = pr[1] + pr[3]
dx = min(gt[2], pr[2])- max(gt[0], pr[0])+ 1
if dx < 0:
return 0.0
dy = min(gt[3], pr[3])- max(gt[1], pr[1])+ 1
if dy < 0:
return 0.0
overlap_area = dx * dy
union_area =(
(gt[2] - gt[0] + 1)*(gt[3] - gt[1] + 1)+ 
(pr[2] - pr[0] + 1)*(pr[3] - pr[1] + 1)-
overlap_area 
)
 return overlap_area / union_area
@jit(nopython=True)
 def find_best_match(gts, pred, pred_idx, threshold = 0.5, form = 'pascal_voc', ious=None)-> int:

 best_match_iou = -np.inf
best_match_idx = -1
for gt_idx in range(len(gts)) :
if gts[gt_idx][0] < 0:
continue
iou = -1 if ious is None else ious[gt_idx][pred_idx]
if iou < 0:
iou = calculate_iou(gts[gt_idx], pred, form=form)
 if ious is not None:
ious[gt_idx][pred_idx] = iou
if iou < threshold:
continue
if iou > best_match_iou:
best_match_iou = iou
best_match_idx = gt_idx
return best_match_idx
@jit(nopython=True)
 def calculate_precision(gts, preds, threshold = 0.5, form = 'coco', ious=None)-> float:

 n = len(preds)
 tp = 0
fp = 0
for pred_idx in range(n):
best_match_gt_idx = find_best_match(gts, preds[pred_idx], pred_idx,
threshold=threshold, form=form, ious=ious)
 if best_match_gt_idx >= 0:
tp += 1
gts[best_match_gt_idx] = -1
else:
fp += 1
fn =(gts.sum(axis=1)> 0 ).sum()
return tp /(tp + fp + fn)
 @jit(nopython=True)
 def calculate_image_precision(gts, preds, thresholds =(0.5,), form = 'coco')-> float:

 n_threshold = len(thresholds)
 image_precision = 0.0
ious = np.ones(( len(gts), len(preds)))* -1
for threshold in thresholds:
precision_at_threshold = calculate_precision(gts.copy() , preds, threshold=threshold,
form=form, ious=ious)
 image_precision += precision_at_threshold / n_threshold
return image_precision
iou_thresholds = numba.typed.List()
for x in [0.5, 0.55, 0.6, 0.65, 0.7, 0.75]:
iou_thresholds.append(x)
 def validate() :
source = 'convertor/fold0/val2017'
device = torch.device('cuda')if torch.cuda.is_available() else torch.device('cpu')
 model = WEIGHTS
model.to(device ).eval()
dataset = LoadImages(source, img_size=1024)
 results = []
for path, img, img0, vid_cap in dataset:
image_id = os.path.basename(path ).split('.')[0]
img = img.transpose(1,2,0)
 enboxes = []
enscores = []
if is_ROT:
for i in range(4):
img1 = TTAImage(img, i)
 boxes, scores = detect1Image(img1, img0, model, device, aug=False)
 for _ in range(3-i):
boxes = rotBoxes90(boxes, *img.shape[:2])
 enboxes.append(boxes)
 enscores.append(scores)
 boxes, scores = detect1Image(img, img0, model, device, aug=is_AUG)
 enboxes.append(boxes)
 enscores.append(scores)
 boxes, scores, labels = run_wbf(enboxes, enscores, image_size=1024, iou_thr=best_iou_thr, skip_box_thr=best_skip_box_thr)
 boxes = boxes.astype(np.int32 ).clip(min=0, max=1024)
 boxes[:, 2] = boxes[:, 2] - boxes[:, 0]
boxes[:, 3] = boxes[:, 3] - boxes[:, 1]
boxes = boxes[scores >= 0.05].astype(np.int32)
 scores = scores[scores >= float(0.05)]
records = marking[marking['image_id'] == image_id]
gtboxes = records[['x', 'y', 'w', 'h']].values
gtboxes = gtboxes.astype(np.int32 ).clip(min=0, max=1024)
 gtboxes[:, 2] = gtboxes[:, 0] + gtboxes[:, 2]
gtboxes[:, 3] = gtboxes[:, 1] + gtboxes[:, 3]
result = {
'image_id': image_id,
'pred_enboxes': enboxes,
'pred_enscores': enscores,
'gt_boxes': gtboxes,
}
results.append(result)
 return results
def calculate_final_score(all_predictions, iou_thr, skip_box_thr, score_threshold):
final_scores = []
for i in range(len(all_predictions)) :
gt_boxes = all_predictions[i]['gt_boxes'].copy()
enboxes = all_predictions[i]['pred_enboxes'].copy()
enscores = all_predictions[i]['pred_enscores'].copy()
image_id = all_predictions[i]['image_id']
pred_boxes, scores, labels = run_wbf(enboxes, enscores, image_size=1024, iou_thr=iou_thr, skip_box_thr=skip_box_thr)
 pred_boxes = pred_boxes.astype(np.int32 ).clip(min=0, max=1024)
 indexes = np.where(scores>score_threshold)
 pred_boxes = pred_boxes[indexes]
scores = scores[indexes]
image_precision = calculate_image_precision(gt_boxes, pred_boxes,thresholds=iou_thresholds,form='pascal_voc')
 final_scores.append(image_precision)
 return np.mean(final_scores )
train['TransactionAmt_log'] = np.log(train['TransactionAmt'])
 test['TransactionAmt_log'] = np.log(test['TransactionAmt'] )<data_type_conversions>
!pip install scikit-optimize
def log(text):
print(text)
 def optimize(space, all_predictions, n_calls=10):
@use_named_args(space)
 def score(**params):
log('-'*10)
 log(params)
 final_score = calculate_final_score(all_predictions, **params)
 log(f'final_score = {final_score}')
 log('-'*10)
 return -final_score
return gp_minimize(func=score, dimensions=space, n_calls=n_calls)
 def letterbox(img, new_shape=(416, 416), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True):
shape = img.shape[:2]
if isinstance(new_shape, int):
new_shape =(new_shape, new_shape)
 r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
 if not scaleup:
r = min(r, 1.0)
 ratio = r, r
new_unpad = int(round(shape[1] * r)) , int(round(shape[0] * r))
dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1]
if auto:
dw, dh = np.mod(dw, 64), np.mod(dh, 64)
 elif scaleFill:
dw, dh = 0.0, 0.0
new_unpad = new_shape
ratio = new_shape[0] / shape[1], new_shape[1] / shape[0]
dw /= 2
dh /= 2
if shape[::-1] != new_unpad:
img = cv2.resize(img, new_unpad, interpolation=cv2.INTER_LINEAR)
 top, bottom = int(round(dh - 0.1)) , int(round(dh + 0.1))
left, right = int(round(dw - 0.1)) , int(round(dw + 0.1))
img = cv2.copyMakeBorder(img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color)
 return img, ratio,(dw, dh)
 class LoadImages:
def __init__(self, path, img_size=416):
path = str(Path(path))
files = []
if os.path.isdir(path):
files = sorted(glob.glob(os.path.join(path, '*.*')))
 elif os.path.isfile(path):
files = [path]
img_formats = ['.bmp', '.jpg', '.jpeg', '.png', '.tif', '.tiff', '.dng']
images = [x for x in files if os.path.splitext(x)[-1].lower() in img_formats]
videos = []
nI, nV = len(images), len(videos)
 self.img_size = img_size
self.files = images + videos
self.nF = nI + nV
self.video_flag = [False] * nI + [True] * nV
self.mode = 'images'
if any(videos):
self.new_video(videos[0])
 else:
self.cap = None
assert self.nF > 0, 'No images or found in %s.Supported formats are:
images: %s
videos: %s' % \ 
(path)
 def __iter__(self):
self.count = 0
return self
def __next__(self):
if self.count == self.nF:
raise StopIteration
path = self.files[self.count]
self.count += 1
img0 = cv2.imread(path)
 assert img0 is not None, 'Image Not Found ' + path
print('image %g/%g %s: ' %(self.count, self.nF, path), end='')
 img = letterbox(img0, new_shape=self.img_size)[0]
img = img[:, :, ::-1].transpose(2, 0, 1)
 img = np.ascontiguousarray(img)
 return path, img, img0, self.cap
def __len__(self):
return self.nF
train['TransactionAmt_decimal'] =(( train['TransactionAmt'] - train['TransactionAmt'].astype(int)) * 1000 ).astype(int)
 test['TransactionAmt_decimal'] =(( test['TransactionAmt'] - test['TransactionAmt'].astype(int)) * 1000 ).astype(int )<feature_engineering>
def makePseudolabel() :
source = '.. /input/global-wheat-detection/test/'
imagenames = os.listdir(source)
 device = torch.device('cuda')if torch.cuda.is_available() else torch.device('cpu')
 model = WEIGHTS
model.to(device ).eval()
dataset = LoadImages(source, img_size=1024)
 path2save = 'train2017/'
if not os.path.exists('convertor/fold0/labels/'+path2save):
os.makedirs('convertor/fold0/labels/'+path2save)
 if not os.path.exists('convertor/fold0/images/{}'.format(path2save)) :
os.makedirs('convertor/fold0/images/{}'.format(path2save))
for path, img, img0, vid_cap in dataset:
image_id = os.path.basename(path ).split('.')[0]
img = img.transpose(1,2,0)
 enboxes = []
enscores = []
if is_ROT:
for i in range(4):
img1 = TTAImage(img, i)
 boxes, scores = detect1Image(img1, img0, model, device, aug=False)
 for _ in range(3-i):
boxes = rotBoxes90(boxes, *img.shape[:2])
 enboxes.append(boxes)
 enscores.append(scores)
 boxes, scores = detect1Image(img, img0, model, device, aug=is_AUG)
 enboxes.append(boxes)
 enscores.append(scores)
 boxes, scores, labels = run_wbf(enboxes, enscores, image_size=1024, iou_thr=best_iou_thr, skip_box_thr=best_skip_box_thr)
 boxes = boxes.astype(np.int32 ).clip(min=0, max=1024)
 indices = scores >= best_score_threshold
boxes = boxes[indices]
scores = scores[indices]
boxes[:, 2] = boxes[:, 2] - boxes[:, 0]
boxes[:, 3] = boxes[:, 3] - boxes[:, 1]
yolo_box = []
for bbox in boxes:
xmin = bbox[0]
xmax = bbox[0] + bbox[2]
ymin = bbox[1]
ymax = bbox[1] + bbox[3]
b =(float(xmin), float(xmax), float(ymin), float(ymax))
yolo_box.append(convert(( 1024, 1024), b))
folder_location = 'convertor/fold0/'+path2save
file_name = "{}/{}.txt".format(folder_location,image_id)
 s = "0 %s %s %s %s
"
with open(file_name, 'w+')as file:
for i in yolo_box:
new_line =(s % tuple(i))
file.write(new_line)
 sh.copy(".. /input/global-wheat-detection/test/{}.jpg".format(image_id),'convertor/fold0/{}/{}.jpg'.format(path2save,image_id))
def generate_train() :
image_files = []
os.chdir(os.path.join("convertor", "fold0", "train2017"))
for filename in os.listdir(os.getcwd()):
if filename.endswith(".jpg"):
image_files.append("/kaggle/working/convertor/fold0/train2017/" + filename)
 os.chdir(".. ")
 with open("train.txt", "w+")as outfile:
for image in image_files:
outfile.write(image)
 outfile.write("
")
 outfile.close()
os.chdir(".. ")
 os.chdir(".. " )
train['TransactionAmt_check'] = np.where(train['TransactionAmt'].isin(test['TransactionAmt']), 1, 0)
 test['TransactionAmt_check'] = np.where(test['TransactionAmt'].isin(train['TransactionAmt']), 1, 0 )<categorify>
if PSEUDO or VALIDATE:
convertTrainLabel()
i_cols = [
'id_02__id_20',
'id_02__D8',
'D11__DeviceInfo',
'DeviceInfo__P_emaildomain',
'P_emaildomain__C2',
'card2__dist1',
'card1__card5',
'card2__id_20',
'card5__P_emaildomain',
'addr1__card1'
]
for feature in i_cols:
f1, f2 = feature.split('__')
 train[feature] = train[f1].astype(str)+ '_' + train[f2].astype(str)
 test[feature] = test[f1].astype(str)+ '_' + test[f2].astype(str)
 le = preprocessing.LabelEncoder()
le.fit(list(train[feature].astype(str ).values)+ list(test[feature].astype(str ).values))
train[feature] = le.transform(list(train[feature].astype(str ).values))
test[feature] = le.transform(list(test[feature].astype(str ).values))<define_variables>
if PSEUDO:
makePseudolabel()
if is_TEST:
torch.cuda.empty_cache()
generate_train()
!mkdir backup
!rm obj.names
!touch obj.names
!echo "wheat" >> obj.names
print('training')
 !./darknet detector train.. /input/yolov4weights/trainsubmit.data.. /input/yolov4weights/trainsubmit.cfg.. /input/yolov4weights/submit.weights -dont_show -clear 1
WEIGHTS = Darknet(cfgfile)
 WEIGHTS.load_weights('backup/trainsubmit_final.weights')
 WEIGHTS.cuda()
else:
pass
i_cols = [
'card1','card2','card3','card5','card4',
'C1','C2','C3','C4','C5','C6','C7','C8','C9','C10','C11','C12','C13','C14',
'D1','D2','D3','D4','D5','D6','D7','D8','D9',
'addr1','addr2',
'dist1','dist2',
'P_emaildomain', 'R_emaildomain',
'DeviceInfo', 'DeviceInfo_device', 'DeviceInfo_version',
'id_30', 'id_30_device', 'id_30_version',
'id_31_device',
'id_33',
'uid', 'uid2', 'uid3','uid4', 'uid5'
]
for feature in i_cols:
train[feature + '_count_full'] = train[feature].map(pd.concat([train[feature], test[feature]], ignore_index=True ).value_counts(dropna=False))
test[feature + '_count_full'] = test[feature].map(pd.concat([train[feature], test[feature]], ignore_index=True ).value_counts(dropna=False))<count_values>
if VALIDATE and is_TEST:
all_predictions = validate()

 best_final_score = -opt_result.fun
best_iou_thr = opt_result.x[0]
best_skip_box_thr = opt_result.x[1]
best_score_threshold = opt_result.x[2]
print('-'*13 + 'WBF' + '-'*14)
 print("[Baseline score]", calculate_final_score(all_predictions, 0.6, 0.43, 0))
print(f'[Best Iou Thr]: {best_iou_thr:.3f}')
 print(f'[Best Skip Box Thr]: {best_skip_box_thr:.3f}')
 print(f'[Best Score Thr]: {best_score_threshold:.3f}')
 print(f'[Best Score]: {best_final_score:.4f}')
 print('-'*30)
 for score_threshold in tqdm(np.arange(0, 1, 0.01), total=np.arange(0, 1, 0.01 ).shape[0]):
final_score = calculate_final_score(all_predictions, best_iou_thr, best_skip_box_thr, score_threshold)
 if final_score > best_final_score:
best_final_score = final_score
best_score_threshold = score_threshold
print('-'*30)
 print(f'[Best Score Threshold]: {best_score_threshold}')
 print(f'[OOF Score]: {best_final_score:.4f}')
 print('-'*30 )
<categorify>
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)
 def detect() :
source = '.. /input/global-wheat-detection/test/'
weights = WEIGHTS
imagenames = os.listdir(source)
 device = torch.device('cuda')if torch.cuda.is_available() else torch.device('cpu')
 model = WEIGHTS
model.to(device ).eval()
dataset = LoadImages(source, img_size=1024)
 results = []
fig, ax = plt.subplots(5, 2, figsize=(30, 70))
count = 0
for path, img, img0, vid_cap in dataset:
image_id = os.path.basename(path ).split('.')[0]
img = img.transpose(1,2,0)
 enboxes = []
enscores = []
if is_ROT:
for i in range(4):
img1 = TTAImage(img, i)
 boxes, scores = detect1Image(img1, img0, model, device, aug=False)
 for _ in range(3-i):
boxes = rotBoxes90(boxes, *img.shape[:2])
 enboxes.append(boxes)
 enscores.append(scores)
 boxes, scores = detect1Image(img, img0, model, device, aug=is_AUG)
 enboxes.append(boxes)
 enscores.append(scores)
 boxes, scores, labels = run_wbf(enboxes, enscores, image_size=1024, iou_thr=best_iou_thr, skip_box_thr=best_skip_box_thr)
 boxes = boxes.astype(np.int32 ).clip(min=0, max=1023)
 boxes[:, 2] = boxes[:, 2] - boxes[:, 0]
boxes[:, 3] = boxes[:, 3] - boxes[:, 1]
indices = scores >= best_score_threshold
boxes = boxes[indices]
scores = scores[indices]
if count<10:
img_ = cv2.imread(path)
 img_ = cv2.cvtColor(img_, cv2.COLOR_BGR2RGB)
 for box, score in zip(boxes,scores):
cv2.rectangle(img_,(box[0], box[1]),(box[2]+box[0], box[3]+box[1]),(220, 0, 0), 2)
 cv2.putText(img_, '%.2f'%(score),(box[0], box[1]), cv2.FONT_HERSHEY_SIMPLEX, 0.5,(255,255,255), 2, cv2.LINE_AA)
 ax[count%5][count//5].imshow(img_)
 count+=1
result = {
'image_id': image_id,
'PredictionString': format_prediction_string(boxes, scores)
 }
results.append(result)
 return results
i_cols = [
'ProductCD',
'M4',
'id_12', 'id_15', 'id_16', 'id_28', 'id_29', 'id_35', 'id_36', 'id_37', 'id_38',
'DeviceType'
]
for col in i_cols:
temp_dict = train.groupby([col])['isFraud'].agg(['mean'] ).reset_index().rename(columns={'mean': col+'_target_mean'})
 temp_dict.index = temp_dict[col].values
temp_dict = temp_dict[col+'_target_mean'].to_dict()
train[col+'_target_mean'] = train[col].map(temp_dict)
 test[col+'_target_mean'] = test[col].map(temp_dict )<feature_engineering>
results = detect()
test_df = pd.DataFrame(results, columns=['image_id', 'PredictionString'])
 !rm -rf./*
test_df.to_csv('submission.csv', index=False)
 test_df.head()