Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

classification_utils.py 17 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
  1. import time
  2. import pathlib
  3. from collections import defaultdict
  4. import pandas as pd
  5. import numpy as np
  6. import matplotlib.pyplot as plt
  7. from sklearn.metrics import (
  8. accuracy_score,
  9. recall_score,
  10. precision_score,
  11. roc_auc_score,
  12. roc_curve,
  13. classification_report,
  14. confusion_matrix,
  15. ConfusionMatrixDisplay,
  16. # RocCurveDisplay,
  17. f1_score,
  18. average_precision_score,
  19. precision_recall_curve,
  20. )
  21. from sklearn.experimental import enable_halving_search_cv
  22. from sklearn.model_selection import RandomizedSearchCV # --> GridSearchCV trop lent
  23. # from sklearn.model_selection import HalvingGridSearchCV, HalvingRandomSearchCV # --> ne supporte pas le multi-scoring
  24. def print_classification_report(y_true, y_pred):
  25. """Display a classification report based on the provided lists
  26. Parameters
  27. ----------
  28. y_true: list
  29. the expected values
  30. y_pred: list
  31. the predicted values
  32. """
  33. report = classification_report(
  34. y_true,
  35. y_pred,
  36. labels=[0, 1],
  37. target_names=["Prediction = 0", "Prediction = 1"],
  38. zero_division=0,
  39. )
  40. print("--- Classification Report ---".ljust(100, "-"), "\n\n", report)
  41. def print_confusion_matrix(y_true, y_pred):
  42. """Display a confusion matrix based on the provided lists
  43. Parameters
  44. ----------
  45. y_true: list
  46. the expected values
  47. y_pred: list
  48. the predicted values
  49. """
  50. cm = confusion_matrix(y_true, y_pred, labels=[0, 1])
  51. disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=[0, 1])
  52. fig, ax = plt.subplots(figsize=(6, 6))
  53. disp.plot(ax=ax)
  54. print("--- Confusion Matrix ---".ljust(100, "-"), "\n")
  55. plt.show()
  56. def print_rocauc(y_true_dict, y_pred_dict, figsize=[5, 5], ax=None, top_others=3):
  57. """Display the 'top_others' best ROC Curves + the last provided ROC Curve
  58. Parameters
  59. ----------
  60. y_true_dict: list
  61. the expected values for several models
  62. y_pred_dict: list
  63. the predicted values for several models
  64. """
  65. print("--- ROC AUC ---".ljust(100, "-"), "\n")
  66. auc_scores = {}
  67. # last_index = len(y_pred_dict)
  68. if ax is None:
  69. plt.figure(figsize=figsize)
  70. ax = plt
  71. # find top scores:
  72. last_score_name = list(y_pred_dict)[-1]
  73. sorted_scores = defaultdict(list)
  74. for i, (model_name, y_pred) in enumerate(y_pred_dict.items()):
  75. if model_name != last_score_name:
  76. y_true = y_true_dict[model_name]
  77. roc_score = roc_auc_score(y_true, y_pred)
  78. sorted_scores[model_name] = roc_score
  79. sorted_scores = sorted(sorted_scores, key=lambda x: sorted_scores[x], reverse=True)[
  80. :top_others
  81. ]
  82. sorted_scores.append(last_score_name)
  83. # display
  84. # for i, (model_name, y_pred) in enumerate(y_pred_dict.items()):
  85. for i, model_name in enumerate(sorted_scores):
  86. alpha_v = 1 if i == min(top_others, len(sorted_scores) - 1) else 0.2
  87. y_true = y_true_dict[model_name]
  88. y_pred = y_pred_dict[model_name]
  89. roc_score = roc_auc_score(y_true, y_pred)
  90. fpr, tpr, thresholds = roc_curve(y_true, y_pred)
  91. ax.plot(fpr, tpr, label=f"{model_name} ({roc_score:.2f})", alpha=alpha_v)
  92. auc_scores[model_name] = roc_score
  93. ax.plot(
  94. [0, 1], [0, 1], label="Random (0.5)", linestyle="--", color="red", alpha=0.5
  95. )
  96. plt.xlabel("FPR (Positive label: 1)")
  97. plt.ylabel("TPR (Positive label: 1)")
  98. # plt.legend()
  99. ax.legend(loc="center left", bbox_to_anchor=(1, 0.5))
  100. plt.show()
  101. return auc_scores
  102. def print_prauc(y_true_dict, y_pred_dict, figsize=[5, 5], ax=None, top_others=3):
  103. """Display the 'top_others' best Precision Recall Curves + the last provided Precision Recall Curve
  104. Parameters
  105. ----------
  106. y_true_dict: list
  107. the expected values for several models
  108. y_pred_dict: list
  109. the predicted values for several models
  110. """
  111. print("--- PRECISION RECALL AUC ---".ljust(100, "-"), "\n")
  112. auc_scores = {}
  113. # last_index = len(y_pred_dict)
  114. if ax is None:
  115. plt.figure(figsize=figsize)
  116. ax = plt
  117. # find top scores:
  118. last_score_name = list(y_pred_dict)[-1]
  119. sorted_scores = defaultdict(list)
  120. for i, (model_name, y_pred) in enumerate(y_pred_dict.items()):
  121. if model_name != last_score_name:
  122. y_true = y_true_dict[model_name]
  123. pr_score = average_precision_score(y_true, y_pred)
  124. sorted_scores[model_name] = pr_score
  125. sorted_scores = sorted(sorted_scores, key=lambda x: sorted_scores[x], reverse=True)[
  126. :top_others
  127. ]
  128. sorted_scores.append(last_score_name)
  129. # display
  130. # for i, (model_name, y_pred) in enumerate(y_pred_dict.items()):
  131. for i, model_name in enumerate(sorted_scores):
  132. alpha_v = 1 if i == min(top_others, len(sorted_scores) - 1) else 0.2
  133. y_true = y_true_dict[model_name]
  134. y_pred = y_pred_dict[model_name]
  135. pr_score = average_precision_score(y_true, y_pred)
  136. precision, recall, thresholds = precision_recall_curve(y_true, y_pred)
  137. ax.plot(
  138. recall, precision, label=f"{model_name} ({pr_score:.2f})", alpha=alpha_v
  139. )
  140. auc_scores[model_name] = pr_score
  141. y_true = np.array(y_true)
  142. no_skill = len(y_true[y_true == 1]) / len(y_true)
  143. ax.plot(
  144. [0, 1],
  145. [no_skill, no_skill],
  146. label="No skill",
  147. linestyle="--",
  148. color="red",
  149. alpha=0.3,
  150. )
  151. ax.plot([1, 0], [0, 1], label="Balanced", linestyle="--", color="green", alpha=0.5)
  152. plt.xlabel("Recall")
  153. plt.ylabel("Precision")
  154. # plt.legend()
  155. ax.legend(loc="center left", bbox_to_anchor=(1, 0.5))
  156. plt.show()
  157. return auc_scores
  158. def save_score(
  159. method_name, threshold, param_grid, training_time, inference_time, **scores
  160. ):
  161. """Save the scores into the 'scores_df' DataFrame and to the 'scores_path' CSV file.
  162. Each call to this function appends exactly one row to the DataFrame and hence to the CSV.
  163. Parameters
  164. ----------
  165. method_name: str
  166. the name used to identify the record in the list
  167. threshold: float
  168. the threshold used to get the provided scores
  169. param_grid: dict
  170. the parameter grid used to get the provided scores
  171. training_time: float
  172. the time needed for the fitting process
  173. inference_time: float
  174. the time needed for the prediction process
  175. scores: list of parameters
  176. the scores to register
  177. """
  178. idx = np.where(scores_df.Method == method_name)[0]
  179. idx = idx[0] if idx.size > 0 else len(scores_df.index)
  180. rocauc_value = scores.get("roc_auc", None)
  181. f1_value = scores.get("f1", None)
  182. accuracy_value = scores.get("accuracy", None)
  183. precision_value = scores.get("precision", None)
  184. recall_value = scores.get("recall", None)
  185. prauc_value = scores.get("average_precision", None)
  186. TP = scores.get("TP", None)
  187. FP = scores.get("FP", None)
  188. TN = scores.get("TN", None)
  189. FN = scores.get("FN", None)
  190. scores_df.loc[idx] = [
  191. method_name,
  192. threshold,
  193. param_grid,
  194. rocauc_value,
  195. prauc_value,
  196. f1_value,
  197. accuracy_value,
  198. precision_value,
  199. recall_value,
  200. TP,
  201. TN,
  202. FP,
  203. FN,
  204. training_time,
  205. inference_time,
  206. ]
  207. scores_df.to_csv(scores_path, index=False)
  208. def init_scores(file_path="data/scores.csv", append=False):
  209. global scores_df, scores_path, y_preds, y_trues
  210. scores_df = pd.DataFrame(
  211. columns=[
  212. "Method",
  213. "threshold",
  214. "params",
  215. "ROC AUC",
  216. "PR AUC",
  217. "F1 score",
  218. "Accuracy",
  219. "Precision",
  220. "Recall",
  221. "TP",
  222. "TN",
  223. "FP",
  224. "FN",
  225. "Training time",
  226. "Inference time",
  227. ]
  228. )
  229. y_preds = {}
  230. y_trues = {}
  231. scores_path = pathlib.Path(file_path)
  232. if append is True and scores_path.is_file():
  233. scores_df = pd.read_csv(scores_path)
  234. else:
  235. scores_df.to_csv(scores_path, index=False)
  236. def get_scores(
  237. method_name,
  238. y_ref,
  239. X_ref=None,
  240. model=None,
  241. y_pred=None,
  242. y_pred_proba=None,
  243. param_grid=None,
  244. threshold=None,
  245. training_time=None,
  246. inference_time=None,
  247. register=False,
  248. simple=False,
  249. show_classification=True,
  250. show_confusion=True,
  251. show_roccurves=True,
  252. **scores,
  253. ):
  254. """Compute / Display / Save scores for the provided model
  255. More precisely, it compute the scores then call various function to display and save them.
  256. Parameters
  257. ----------
  258. method_name: str
  259. the name used to identify the record in the list
  260. model:
  261. the model that needs to be evaluated
  262. y_pred:
  263. the predicted values (only if the model is not provided)
  264. y_pred_proba:
  265. the predicted proba values (only if the model is not provided)
  266. X_ref: list of lists
  267. the X values used to get the predictions
  268. y_ref: list
  269. the expected values
  270. param_grid: dict
  271. the parameter grid used to get the provided scores
  272. training_time: float
  273. the time needed for the fitting process
  274. inference_time: float
  275. the time needed for the prediction process
  276. scores: list of parameters
  277. the scores to register
  278. Return
  279. ------
  280. dict:
  281. the dictionary of the computed scores
  282. """
  283. if model is not None:
  284. y_pred, y_pred_proba, inference_time = predict(model, X_ref, threshold)
  285. if y_pred is None or y_pred_proba is None:
  286. raise Exception("We either need the model with a X_ref to compute y_pred & y_pred_proba or directly the y_pred & y_pred_proba")
  287. try:
  288. cm = confusion_matrix(y_ref, y_pred, labels=[0, 1])
  289. scores = {
  290. "roc_auc": roc_auc_score(y_ref, y_pred_proba),
  291. "f1": f1_score(y_ref, y_pred),
  292. "accuracy": accuracy_score(y_ref, y_pred),
  293. "precision": precision_score(y_ref, y_pred, zero_division=0),
  294. "recall": recall_score(y_ref, y_pred),
  295. "average_precision": average_precision_score(y_ref, y_pred_proba),
  296. "TN": cm[0][0],
  297. "FP": cm[0][1],
  298. "FN": cm[1][0],
  299. "TP": cm[1][1],
  300. }
  301. except NameError:
  302. print("We either need a model or the y_pred & y_pred_proba variables")
  303. # Register score and replace if it already exists
  304. if register:
  305. save_score(
  306. method_name, threshold, param_grid, training_time, inference_time, **scores
  307. )
  308. # Basic report
  309. scores_str = ""
  310. for key in scores.keys():
  311. if type(scores[key]) == np.float64 and key not in ["TP", "TN", "FP", "FN"]:
  312. scores_str += f"{key.upper().rjust(20)} : {scores[key]:.4f}\n"
  313. scores_str += f"\n{'TRAINING-TIME'.rjust(20)} : {training_time:.4f}\n{'INFERENCE-TIME'.rjust(20)} : {inference_time:.4f}\n"
  314. print(
  315. "-" * 100,
  316. "These information are based on the best estimator of the above cross-validation".center(
  317. 100,
  318. ),
  319. "-" * 100,
  320. sep="\n",
  321. end="\n\n",
  322. )
  323. print(f"--- {method_name} ---".ljust(100, "-"), "\n\n", scores_str, sep="")
  324. if simple:
  325. return
  326. # Classification report
  327. if show_classification:
  328. print_classification_report(y_ref, y_pred)
  329. # Confusion Matrix
  330. if show_confusion:
  331. print_confusion_matrix(y_ref, y_pred)
  332. # ROC AUC curves
  333. if show_roccurves:
  334. y_preds[method_name] = y_pred_proba
  335. y_trues[method_name] = y_ref
  336. print_rocauc(y_trues, y_preds)
  337. print_prauc(y_trues, y_preds)
  338. return scores
  339. def predict(model, X_ref, threshold=None):
  340. """Convenience function that generalize the prediction process
  341. Parameters
  342. ----------
  343. model:
  344. the model that needs to make predictions
  345. X_ref: list of lists
  346. the X values used to get the predictions
  347. threshold: float (None)
  348. the threshold used to get the provided scores
  349. Returns
  350. -------
  351. list
  352. the binary predictions
  353. list
  354. the probabilities
  355. float
  356. the time needed for the prediction process
  357. """
  358. t0 = time.perf_counter()
  359. try:
  360. y_pred_proba = model.predict_proba(X_ref)[:, 1]
  361. except Exception:
  362. y_pred_proba = model.predict(X_ref)
  363. if threshold:
  364. y_pred = get_labels_from_threshold(y_pred_proba, threshold)
  365. else:
  366. y_pred = model.predict(X_ref)
  367. tt = time.perf_counter() - t0
  368. return y_pred, y_pred_proba, tt
  369. def get_labels_from_threshold(y_proba, threshold):
  370. """Convenience function that quickly convert proabilities to binary results
  371. Parameters
  372. ----------
  373. y_proba: list
  374. the list of probabilities
  375. threshold: float (None)
  376. the threshold used to make the choices
  377. Returns
  378. -------
  379. list
  380. the binary predictions
  381. """
  382. return (y_proba >= threshold).astype("int")
  383. def find_best_threshold(model, X_valid, y_valid, eval_function):
  384. """Find the threshold that maximize the provided scoring function
  385. Parameters
  386. ----------
  387. model:
  388. the model that needs to make predictions
  389. X_valid: list of lists
  390. the X values used to get the predictions
  391. y_valid: list
  392. the expected values
  393. eval_function: function
  394. the scoring method used to find the best threshold
  395. Returns
  396. -------
  397. float
  398. the best score found for the provided metric
  399. float
  400. the threshold matching the best metric's score
  401. """
  402. best_threshold = 0.0
  403. best_score = 0.0
  404. try:
  405. y_pred_proba = model.predict_proba(X_valid)[:, 1]
  406. except Exception:
  407. y_pred_proba = model.predict(X_valid)
  408. for threshold in np.arange(0, 1, 0.001):
  409. y_pred_threshold = get_labels_from_threshold(y_pred_proba, threshold)
  410. score = eval_function(y_valid, y_pred_threshold)
  411. if score >= best_score:
  412. best_threshold = threshold
  413. best_score = score
  414. return best_score, best_threshold
  415. def fit_model(
  416. model,
  417. X_ref,
  418. y_ref,
  419. param_grid={},
  420. scoring="roc_auc",
  421. cv=5,
  422. verbose=2,
  423. register=True,
  424. ):
  425. """Search the best hyper-parameters for the provided model
  426. Parameters
  427. ----------
  428. model:
  429. the model that needs to make predictions
  430. X_ref: list of lists
  431. the X values used to get the predictions
  432. y_ref: list
  433. the expected values
  434. param_grid: dict
  435. the parameter grid used to get the provided scores
  436. scoring: str
  437. the scoring method to use when evaluating the model in the Grid Search CV process
  438. cv: int / CrossValidation
  439. the number of cross validations to apply OR the instance of a CrossValidation instance
  440. verbose: int
  441. defines how much details are printed while training the model
  442. 0 : nothing
  443. 1 : K-fold scores + results for test set
  444. 2 : K-fold scores + results for test & train sets
  445. Returns
  446. -------
  447. dict
  448. a dictionnary containing:
  449. - grid: the grid search instance
  450. - model: the grid search best estimator
  451. - training_time: the fitting time
  452. - inference_time: the prediction time
  453. - param_grid: the parameters used for the grid search
  454. """
  455. fit_time = time.perf_counter()
  456. grid_model = RandomizedSearchCV(
  457. model,
  458. param_grid,
  459. scoring=scoring,
  460. n_jobs=-1,
  461. verbose=0,
  462. cv=cv,
  463. random_state=0,
  464. refit=scoring,
  465. )
  466. # grid_model = HalvingRandomSearchCV(model, param_grid, scoring=scoring, n_jobs=-1, verbose=0, cv=cv, min_resources=500, random_state=0)
  467. # grid_model = HalvingGridSearchCV(model, param_grid, scoring=scoring, n_jobs=-1, verbose=0, cv=cv, min_resources=500, random_state=0)
  468. # grid_model = GridSearchCV(model, param_grid, scoring=scoring, n_jobs=-1, verbose=0, cv=cv, refit="roc_auc", return_train_score=True)
  469. grid_model.fit(X_ref, y_ref)
  470. fit_time = time.perf_counter() - fit_time
  471. results = grid_model.cv_results_
  472. n_splits = cv.n_splits if hasattr(cv, "n_splits") else cv
  473. sets_list = ["test"] if verbose < 3 else ["train", "test"]
  474. # Print K-fold scores
  475. if verbose > 1:
  476. for i in range(n_splits):
  477. print("".center(100, "-"))
  478. for sample in sets_list:
  479. scores_str = f"{scoring.upper()}: {results[f'split{i}_{sample}_score'].mean():.4f}"
  480. print(f"FOLD-{i+1} {sample.upper().rjust(6)} scores | {scores_str}")
  481. # Print overall scores
  482. if verbose > 0:
  483. for sample in sets_list:
  484. print(
  485. "\n",
  486. f" {sample.upper()}-CV-SPLIT MEAN SCORES ".center(100, "-"),
  487. sep="",
  488. )
  489. mean_str = f"{scoring.upper()}: {results[f'mean_{sample}_score'].mean():.4f} (std:{results[f'std_{sample}_score'].mean():.4f})"
  490. print(f"\n- {mean_str}")
  491. print("\n", "".center(100, "-"), sep="")
  492. inf_time = pd.Series(grid_model.cv_results_["mean_score_time"]).mean()
  493. return {
  494. "grid": grid_model,
  495. "model": grid_model.best_estimator_,
  496. "training_time": fit_time,
  497. "inference_time": inf_time,
  498. "param_grid": param_grid,
  499. } # , **scores_args}
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...