Kaggle competition: Google Analytics Customer Revenue Prediction
if PSEUDO or VALIDATE:
convertTrainLabel()<load_pretrained>
file_train = ".. /input/train_v2.csv"
file_test = ".. /input/test_v2.csv"
chunk_size = 10000
def load_data(file,chunk_size,nrows_load=None,test_data=False):
df_res = pd.DataFrame()
df_reader = pd.read_csv(file,
dtype={ 'date': str, 'fullVisitorId': str},
chunksize=10000)
 for cidx, df in enumerate(df_reader):
df.reset_index(drop=True, inplace=True)
 process_df(df,test_data)
 df_res = pd.concat([df_res,df ], axis=0 ).reset_index(drop=True)
 del df
gc.collect()
if cidx % 20 == 0:
print('{}: rows loaded: {}'.format(cidx, df_res.shape[0]))
if nrows_load:
if res.shape[0] >= nrows_load:
break
return df_res
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<find_best_params>
def parse_json(x,s):
res = json.loads(x)
 try:
return res[s]
except:
return float('NaN')
 def process_df(df,test_data):
df['days'] = df['date'].str[-2:]
df['days'] = df['days'].astype(int)
 df['month'] = df['date'].str[-4:-2]
df['month'] = df['month'].astype(int)
 df['year'] = df['date'].str[:4]
df['year'] = df['year'].astype(int)
 process_dict = {
'totals':['transactionRevenue','newVisits','pageviews','hits'] ,
'trafficSource':['campaign','source','medium'] ,
'device':['browser'],
'geoNetwork': ['country','city','continent','region','subContinent']
}
for c,l in process_dict.items() :
for it in l:
df[it] = df[c].apply(lambda x : parse_json(x,it))
cols = ['country','campaign','source','medium','continent','city','region','socialEngagementType','browser'
,'channelGrouping','subContinent','date']
labelencoder_X=LabelEncoder()
for c in cols:
df.loc[:,c] = labelencoder_X.fit_transform(df.loc[:,c])
 df['transactionRevenue'].fillna(0,inplace=True)
 df['newVisits'].fillna(0,inplace=True)
 df['pageviews'].fillna(0,inplace=True)
 df['transactionRevenue'] = df['transactionRevenue'].astype('float32')
 df['newVisits']= df['newVisits'].astype('uint16')
 df['pageviews'] = df['pageviews'].astype('uint16')
 df['hits'] = df['hits'].astype('uint32')
 rm_col = ['subContinent',
'channelGrouping','date','continent','customDimensions','fullVisitorId']
if test_data:
rm_col = rm_col[:-1]
df.drop(list(process_dict.keys())+ rm_col, axis=1,inplace=True)
 df = load_data(file_train,chunk_size)
 df_test =load_data(file_test,chunk_size,test_data=True )
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 )<load_pretrained>
per = sum(df['transactionRevenue'] > 0)/ len(df['transactionRevenue'])
 print('Percentage of transactions greater than 0 : {} %'.format(per*100))
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<save_to_csv>
X = df[df.columns[df.columns != 'transactionRevenue']]
Y = np.log1p(df['transactionRevenue'])
 X_train, X_val, y_train, y_val = train_test_split(X, Y, test_size=0.4, random_state=42)
 X_test = df_test[df_test.columns[df_test.columns != 'transactionRevenue']]
Y_test = np.log1p(df_test['transactionRevenue'])
 indices_nonzero = np.where(y_train > 0)
 indices_zero = np.where(y_train == 0)
 num_nonzero = len(indices_nonzero[0])
 num_zero = len(indices_zero[0])
 print('Number of non-zero transactions revenues = ', num_nonzero)
 print('Number of zero transactions revenues = ', num_zero)
 all_indx = list(indices_zero[0][0:num_nonzero])+ list(indices_nonzero[0])
 X_sample = X_train.iloc[all_indx,:]
y_sample = y_train.iloc[all_indx]
X_train_sample, X_val_sample, y_train_sample, y_val_sample = train_test_split(X_sample, y_sample, test_size=0.45, random_state=42)
 print('Sample X_Train shape ', X_train_sample.shape )
results = detect()
test_df = pd.DataFrame(results, columns=['image_id', 'PredictionString'])
 !rm -rf./*
test_df.to_csv('submission.csv', index=False)
 test_df.head()<define_variables>
def create_model_xgboost(X_train,y_train,X_val=None,y_val=None):
params = {'objective': 'reg:linear',
'eval_metric': 'rmse',
'min_child_weight':1.5,
'eta': 0.01,
'max_depth': 4,
'subsample': 0.7,
'colsample_bytree': 0.6,
'reg_alpha':1,
'reg_lambda':0.45,
'random_state': 42,
'silent': True}
xgb_train_data = xgboost.DMatrix(X_train, y_train)
 if not X_val is None:
xgb_val_data = xgboost.DMatrix(X_val, y_val)
 evals=[(xgb_train_data, 'train'),(xgb_val_data, 'valid')]
else:
evals=[(xgb_train_data, 'train')]
model = xgboost.train(params, xgb_train_data,
num_boost_round=1200,
evals= evals,
early_stopping_rounds=50,
verbose_eval=300)
 return model
def create_model_nn(in_dim,layer_size=250):
model = Sequential()
model.add(Dense(layer_size,activation='relu',input_dim=in_dim))
model.add(BatchNormalization())
 model.add(Dense(layer_size,activation='relu'))
model.add(Dense(layer_size,activation='relu'))
model.add(Dense(1, activation='linear'))
adam = optimizers.Adam(lr=0.1, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False)
 model.compile(optimizer=adam,loss='mse')
 return model
def create_model_lgbm(X_train,y_train,X_val=None,y_val=None):
dtrain = lgb.Dataset(X_train,label=y_train)
 dval = lgb.Dataset(X_val,label=y_val)
 param_up = {"objective" : "regression", "metric" : "rmse",
"max_depth": 2, "min_child_samples": 20,
"reg_alpha": 1.5, "reg_lambda": 1.5,
"num_leaves" : 15, "learning_rate" : 0.1,
"subsample" : 1, "colsample_bytree" : 1,
"verbosity": -1,'data_random_seed':4}
if not X_val is None:
valid_sets =(dtrain,dval)
 valid_names = ['train','valid']
else:
valid_sets =(dtrain)
 valid_names = ['train']
model = lgb.train(param_up,dtrain,num_boost_round=5000,valid_sets=valid_sets,valid_names=['train','valid'],verbose_eval=300,
early_stopping_rounds=50)
 return model
NMS_IOU_THR = 0.6
NMS_CONF_THR = 0.5
best_iou_thr = 0.6
best_skip_box_thr = 0.43
best_final_score = 0
best_score_threshold = 0
EPO = 15
WEIGHTS = '.. /input/best-yolov5x-fold0-1pt/best_yolov5x_fold0.pt'
CONFIG = '.. /input/best-yolov5x-fold0pt/yolov5x.yaml'
DATA = '.. /input/best-yolov5x-fold0pt/wheat0.yaml'
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 )<feature_engineering>
def fit_train(x,y,X_val,y_val,layer_size=64,mod = 'nn'):
if mod =='nn':
model = create_model_nn(x.shape[1],layer_size)
 history = model.fit(x, y, epochs=3, batch_size=128,validation_data=(X_val,y_val),verbose=1)
 print('Mean RMSE : ',np.sqrt(history.history['val_loss'] ).mean())
 elif mod =='xgboost':
model = create_model_xgboost(x,y,X_val,y_val)
 elif mod =='lgbm':
model = create_model_lgbm(x,y,X_val,y_val)
 else:
raise Exception('invalid model')
 return model
def calc_rmse(pred,y):
diff = pred - y
RMSE =(( diff ** 2 ).mean())**.5
print('RMSE : ',RMSE)
 def eval_set(model,x,y,mod='nn'):
if mod == 'nn':
p = model.predict(x,batch_size=64,verbose=1)
 pred = p[:,0]
elif mod == 'xgboost':
dx = xgboost.DMatrix(x)
 pred = model.predict(dx,ntree_limit=model.best_ntree_limit)
 elif mod == 'lgbm':
pred = model.predict(x, num_iteration=model.best_iteration)
 else:
raise Exception('invalid model')
 calc_rmse(pred,y )
def convertTrainLabel() :
df = pd.read_csv('.. /input/global-wheat-detection/train.csv')
 bboxs = np.stack(df['bbox'].apply(lambda x: np.fromstring(x[1:-1], sep=',')))
 for i, column in enumerate(['x', 'y', 'w', 'h']):
df[column] = bboxs[:,i]
df.drop(columns=['bbox'], inplace=True)
 df['x_center'] = df['x'] + df['w']/2
df['y_center'] = df['y'] + df['h']/2
df['classes'] = 0
df = df[['image_id','x', 'y', 'w', 'h','x_center','y_center','classes']]
index = list(set(df.image_id))
source = 'train'
if True:
for fold in [0]:
val_index = index[len(index)*fold//5:len(index)*(fold+1)//5]
for name, mini in tqdm(df.groupby('image_id')) :
path2save = 'val2017/' if name in val_index else 'train2017/'
os.makedirs('convertor/fold{}/labels/'.format(fold)+path2save, exist_ok=True)
 with open('convertor/fold{}/labels/'.format(fold)+path2save+name+".txt", 'w+')as f:
row = mini[['classes','x_center','y_center','w','h']].astype(float ).values
row = row/1024
row = row.astype(str)
 for j in range(len(row)) :
text = ' '.join(row[j])
 f.write(text)
 f.write("
")
 os.makedirs('convertor/fold{}/images/{}'.format(fold,path2save), exist_ok=True)
 sh.copy(".. /input/global-wheat-detection/{}/{}.jpg".format(source,name),'convertor/fold{}/images/{}/{}.jpg'.format(fold,path2save,name)) 
<concatenate>
print('Training on training/val Dataset')
 model_training = fit_train(X_train,y_train,X_val,y_val)
 print('-'*40)
 print('Training on Sample Dataset')
 model_sample = fit_train(X_train_sample,y_train_sample,X_val_sample,y_val_sample,layer_size=500)
 print('-'*40)
 print('Training on Full training Dataset')
 model_full = create_model_nn(X.shape[1])
 model_full.fit(X, Y, epochs=3, batch_size=128,verbose=1)
 print('-'*40 )
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 detect1Image(img, img0, model, device, aug):
img = img.transpose(2,0,1)
 img = torch.from_numpy(img ).to(device)
 img = img.float()
img /= 255.0
if img.ndimension() == 3:
img = img.unsqueeze(0)
 pred = model(img, augment=aug)[0]
pred = non_max_suppression(pred, NMS_CONF_THR, NMS_IOU_THR, merge=True, classes=None, agnostic=False)
 boxes = []
scores = []
for i, det in enumerate(pred):
if det is not None and len(det):
det[:, :4] = scale_coords(img.shape[2:], det[:, :4], img0.shape ).round()
for *xyxy, conf, cls in det:
boxes.append([int(xyxy[0]), int(xyxy[1]), int(xyxy[2]), int(xyxy[3])])
 scores.append(conf)
 return np.array(boxes), np.array(scores )<normalization>
print('Training on training/val Dataset')
 model_training = fit_train(X_train,y_train,X_val,y_val,mod='xgboost')
 print('-'*40)
 print('Training on Sample Dataset')
 model_sample = fit_train(X_train_sample,y_train_sample,X_val_sample,y_val_sample,layer_size=500,mod='xgboost')
 print('-'*40)
 print('Training on Full training Dataset')
 model_full = create_model_xgboost(X, Y)
 print('Full Training set -- Using Sample training model')
 eval_set(model_sample,X_train,y_train,mod='xgboost' )
@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/images/val2017'
weights = 'weights/best.pt'
if not os.path.exists(weights):
weights = WEIGHTS
device = torch.device('cuda')if torch.cuda.is_available() else torch.device('cpu')
 model = torch.load(weights, map_location=device)['model'].float()
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)
 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)
 def show_result(sample_id, preds, gt_boxes):
sample = cv2.imread(f'.. /input/global-wheat-detection/train/{sample_id}.jpg', cv2.IMREAD_COLOR)
 sample = cv2.cvtColor(sample, cv2.COLOR_BGR2RGB)
 fig, ax = plt.subplots(1, 1, figsize=(16, 8))
for pred_box in preds:
cv2.rectangle(
 sample, 
(pred_box[0], pred_box[1]), 
(pred_box[2], pred_box[3]), 
(220, 0, 0), 2 
)
 for gt_box in gt_boxes:
cv2.rectangle(
 sample, 
(gt_box[0], gt_box[1]), 
(gt_box[2], gt_box[3]), 
(0, 0, 220), 2 
)
 ax.set_axis_off()
ax.imshow(sample)
 ax.set_title("RED: Predicted | BLUE - Ground-truth" )<train_model>
print('Training on training/val Dataset')
 model_training = fit_train(X_train,y_train,X_val,y_val,mod='lgbm')
 print('-'*40)
 print('Training on Sample Dataset')
 model_sample = fit_train(X_train_sample,y_train_sample,X_val_sample,y_val_sample,layer_size=500,mod='lgbm')
 print('-'*40)
 print('Training on Full training Dataset')
 model_full = create_model_lgbm(X, Y)
 print('Full Training set -- Using Sample training model')
 eval_set(model_sample,X_train,y_train,mod='lgbm')
 print('-'*40 )
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 )<load_pretrained>
df_test['predictions'] = model_full.predict(df_test.loc[:,df_test.columns[1:]],num_iteration=model_full.best_iteration)
 df_test.loc[df_test['predictions']< 0 ,'predictions']= 0
sub_df = pd.DataFrame({'fullVisitorId':df_test['fullVisitorId'] , 'PredictedLogRevenue': np.expm1(df_test['predictions'])})
 sub_df = sub_df.groupby("fullVisitorId")["PredictedLogRevenue"].sum().reset_index()
sub_df.columns = ["fullVisitorId", "PredictedLogRevenue"]
sub_df["PredictedLogRevenue"] = np.log1p(sub_df["PredictedLogRevenue"])
 sub_df.to_csv("baseline_lgb_submission.csv", index=False )