generated from BrenoFariasdaSilva/Template-Project
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrfe.py
More file actions
2121 lines (1758 loc) · 99.6 KB
/
rfe.py
File metadata and controls
2121 lines (1758 loc) · 99.6 KB
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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
================================================================================
Recursive Feature Elimination (RFE) Automation and Feature Analysis Tool (rfe.py)
================================================================================
Author : Breno Farias da Silva
Created : 2025-10-07
Description :
Utility to automate Recursive Feature Elimination (RFE) workflows for
structured classification datasets. The module bundles safe dataset
loading, preprocessing, scaling, RFE selection (Random Forest base),
evaluation and export of structured run results for reproducible analysis.
Core features:
- Safe CSV loading with column sanitization and basic validation
- Z-score standardization of numeric features prior to RFE
- RFE using RandomForestClassifier (configurable number of selected features)
- Performance evaluation (accuracy, precision, recall, F1, FPR, FNR)
- Export of run results to `Feature_Analysis/RFE_Run_Results.csv` with hardware metadata
- Portable: skips platform-specific features on unsupported OS (e.g., sound on Windows)
Usage:
- Set `csv_file` in `main()` or call `run_rfe(csv_path)` programmatically.
- Run: `python3 rfe.py` or via the project Makefile target.
Outputs:
- `Feature_Analysis/RFE_Run_Results.csv` summarizing each run
- Per-run JSON fields for `top_features` and `rfe_ranking` inside the CSV
Notes & conventions:
- The last column of the input CSV is treated as the target variable.
- Only numeric columns (or coercible-to-numeric) are used for feature ranking.
- Defaults: 80/20 train-test split, RandomForest with 100 trees, fixed seed
- Toggle `VERBOSE = True` for detailed runtime logs useful during debugging
TODOs:
- Add CLI argument parsing for dataset path, `n_select`, and parallel runs.
- Support additional estimators (SVM, Gradient Boosting) and compare results.
- Integrate automatic handling for categorical and missing data.
- Add unit tests for preprocessing and metric computations.
Dependencies:
- Python >= 3.9
- pandas, numpy, scikit-learn, matplotlib, colorama
"""
import argparse # For command-line argument parsing
import atexit # For playing a sound when the program finishes
import csv # For CSV quoting options
import dataframe_image as dfi # For exporting DataFrame images (zebra-striped PNG)
import datetime # For timestamping
import glob # For finding exported model files
import json # For saving lists and dicts as JSON strings
import math # For mathematical operations
import numpy as np # For numerical operations
import os # For file and directory operations
import pandas as pd # For data manipulation
import platform # For getting the operating system name
import psutil # For hardware information
import re # For regular expressions
import subprocess # For executing system commands
import sys # For system-specific parameters and functions
import telegram_bot as telegram_module # For setting Telegram prefix and device info
import time # For measuring elapsed time
import traceback # For formatting and printing exception tracebacks
import yaml # For loading configuration from YAML files
from colorama import Style # For coloring the terminal
from joblib import dump, load # For exporting and loading trained models and scalers
from Logger import Logger # For logging output to both terminal and file
from pathlib import Path # For handling file paths
from sklearn.ensemble import RandomForestClassifier # For the Random Forest model
from sklearn.feature_selection import RFE # For Recursive Feature Elimination
from sklearn.metrics import ( # For performance metrics
accuracy_score,
confusion_matrix,
f1_score,
precision_score,
recall_score,
)
from sklearn.model_selection import StratifiedKFold, train_test_split # For train/test split and stratified K-Fold CV
from sklearn.preprocessing import StandardScaler # For scaling the data (standardization)
from telegram_bot import TelegramBot, send_exception_via_telegram, send_telegram_message, setup_global_exception_hook # For sending progress messages to Telegram
from typing import Any, Dict, Optional, Union, Tuple, cast # For type hinting
# Macros:
class BackgroundColors: # Colors for the terminal
CYAN = "\033[96m" # Cyan
GREEN = "\033[92m" # Green
YELLOW = "\033[93m" # Yellow
RED = "\033[91m" # Red
BOLD = "\033[1m" # Bold
UNDERLINE = "\033[4m" # Underline
CLEAR_TERMINAL = "\033[H\033[J" # Clear the terminal
# Global state (initialized in main)
CONFIG: Dict[str, Any] = {}
CLI_ARGS: Dict[str, Any] = {}
TELEGRAM_BOT = None
logger = None
SOUND_COMMANDS = {
"Darwin": "afplay",
"Linux": "aplay",
"Windows": "start",
}
SOUND_FILE = "./.assets/Sounds/NotificationSound.wav"
RUN_FUNCTIONS = {"Play Sound": True}
# Functions Definitions:
# setup_global_exception_hook() will be called from main() after configuration
def verbose_output(true_string="", false_string=""):
"""
Outputs a message if the VERBOSE constant is set to True.
:param true_string: The string to be outputted if the VERBOSE constant is set to True.
:param false_string: The string to be outputted if the VERBOSE constant is set to False.
:return: None
"""
try:
if is_verbose():
if true_string:
print(true_string)
else:
if false_string:
print(false_string)
except Exception as e:
print(str(e))
send_exception_via_telegram(type(e), e, e.__traceback__)
raise
def get_default_config() -> Dict[str, Any]:
"""
Return the default configuration for the RFE tool.
Must match config.yaml.example exactly.
:param: None
:return: Dict with default configuration values
"""
return {
"rfe": {
"execution": {
"verbose": False,
"skip_train_if_model_exists": False,
"dataset_path": None,
},
"model": {"estimator": "random_forest", "random_state": 42},
"selection": {"n_features_to_select": 10, "step": 1},
"cross_validation": {"n_folds": 10},
"multiprocessing": {"n_jobs": -1, "cpu_processes": 1},
"caching": {"enabled": True, "pickle_protocol": 4},
"export": {
"results_dir": "Feature_Analysis/RFE",
"results_filename": "RFE_Results.csv",
"results_csv_columns": [
"timestamp",
"tool",
"model",
"dataset",
"hyperparameters",
"cv_method",
"train_test_split",
"scaling",
"cv_accuracy",
"cv_precision",
"cv_recall",
"cv_f1_score",
"test_accuracy",
"test_precision",
"test_recall",
"test_f1_score",
"test_fpr",
"test_fnr",
"feature_extraction_time_s",
"training_time_s",
"testing_time_s",
"hardware",
"top_features",
"rfe_ranking",
]
},
}
}
def load_config_file(path: Optional[str]) -> Dict[str, Any]:
"""
Load YAML config file. Returns empty dict if none found.
:param path: Optional path to the config file. If None, will look for config.yaml or config.yaml.example in the script directory.
:return: Dict with the loaded configuration, or empty dict if no file found
"""
candidate = None
if path:
candidate = Path(path)
else:
p = Path(__file__).parent
c = p / "config.yaml"
e = p / "config.yaml.example"
if c.exists():
candidate = c
elif e.exists():
candidate = e
if candidate is None or not candidate.exists():
return {}
with open(candidate, "r", encoding="utf-8") as fh:
return yaml.safe_load(fh) or {}
def parse_cli_args() -> Dict[str, Any]:
"""
Parse command-line arguments and return them as a dictionary.
:param: None
:return: Dict with the parsed command-line arguments
"""
parser = argparse.ArgumentParser(description="Run RFE pipeline")
parser.add_argument("--config", type=str, default=None)
parser.add_argument("--dataset_path", type=str, default=None)
parser.add_argument("--n_features_to_select", type=int, default=None)
parser.add_argument("--step", type=int, default=None)
parser.add_argument("--estimator", type=str, default=None)
parser.add_argument("--random_state", type=int, default=None)
parser.add_argument("--n_folds", type=int, default=None)
parser.add_argument("--n_jobs", type=int, default=None)
parser.add_argument("--cpu_processes", type=int, default=None)
parser.add_argument("--caching_enabled", type=lambda s: str(s).lower() in ("1", "true", "yes", "y"), default=None)
parser.add_argument("--pickle_protocol", type=int, default=None)
parser.add_argument("--verbose", action="store_true")
parser.add_argument("--skip_train_if_model_exists", action="store_true")
parser.add_argument("--results_dir", type=str, default=None, help="Override results directory for RFE exports (overrides config.rfe.export.results_dir)")
parser.add_argument("--results_filename", type=str, default=None, help="Override results filename for RFE exports (overrides config.rfe.export.results_filename)")
args = parser.parse_args()
return vars(args)
def deep_merge_dicts(base: Dict[str, Any], override: Dict[str, Any]) -> Dict[str, Any]:
"""
Recursively merge two dictionaries, with values from the override taking precedence.
:param base: The base dictionary to merge into
:param override: The dictionary with values to override in the base
:return: A new dictionary resulting from the deep merge of base and override
"""
result = dict(base)
for k, v in (override or {}).items():
if k in result and isinstance(result[k], dict) and isinstance(v, dict):
result[k] = deep_merge_dicts(result[k], v)
else:
result[k] = v
return result
def validate_config_structure(config: Dict[str, Any]) -> None:
"""
Validates the structure and types of the configuration dictionary. Raises ValueError if any required section or key is missing or has an invalid type.
:param config: The configuration dictionary to validate
:return: None
"""
if not isinstance(config, dict):
raise ValueError("config must be a dict")
if "rfe" not in config or not isinstance(config["rfe"], dict):
raise ValueError("Missing required top-level 'rfe' section in config")
r = config["rfe"]
required = ["execution", "model", "selection", "cross_validation", "multiprocessing", "caching", "export"]
for key in required:
if key not in r or not isinstance(r[key], dict):
raise ValueError(f"Missing required 'rfe.{key}' section in config or wrong type")
cols = r["export"].get("results_csv_columns")
if not isinstance(cols, list) or not cols:
raise ValueError("rfe.export.results_csv_columns must be a non-empty list in config")
sel = r["selection"]
if sel.get("n_features_to_select") is not None:
if not isinstance(sel["n_features_to_select"], int) or sel["n_features_to_select"] <= 0:
raise ValueError("rfe.selection.n_features_to_select must be an int > 0 or null")
if not isinstance(sel.get("step", 1), int) or sel.get("step", 1) <= 0:
raise ValueError("rfe.selection.step must be an int > 0")
cv = r["cross_validation"].get("n_folds")
if not isinstance(cv, int) or cv <= 1:
raise ValueError("rfe.cross_validation.n_folds must be an int > 1")
mp = r["multiprocessing"]
if not isinstance(mp.get("n_jobs"), int):
raise ValueError("rfe.multiprocessing.n_jobs must be an integer")
if not isinstance(mp.get("cpu_processes"), int) or mp.get("cpu_processes") < 1:
raise ValueError("rfe.multiprocessing.cpu_processes must be an int >= 1")
cache = r["caching"]
if not isinstance(cache.get("enabled"), bool):
raise ValueError("rfe.caching.enabled must be a boolean")
pp = cache.get("pickle_protocol")
if not isinstance(pp, int) or not (0 <= pp <= 5):
raise ValueError("rfe.caching.pickle_protocol must be int between 0 and 5")
def get_config(cli_args: Optional[Dict[str, Any]] = None) -> Tuple[Dict[str, Any], Dict[str, str]]:
"""
Returns the merged configuration dictionary and a dictionary of sources for each key in the merged config.
:param cli_args: Optional dictionary of command-line arguments to override config values
:return: Tuple of (merged_config, sources_dict) where merged_config is the final configuration dictionary and sources_dict maps config sections to their source ('default', 'file', 'cli')
"""
defaults = get_default_config()
file_cfg = load_config_file((cli_args or {}).get("config"))
file_rfe = file_cfg.get("rfe") if isinstance(file_cfg, dict) and "rfe" in file_cfg else file_cfg
merged = deep_merge_dicts(defaults["rfe"], file_rfe or {})
cli = cli_args or {}
exec_cfg = merged.get("execution", {})
if cli.get("dataset_path") is not None:
exec_cfg["dataset_path"] = cli.get("dataset_path")
if cli.get("verbose"):
exec_cfg["verbose"] = True
if cli.get("skip_train_if_model_exists"):
exec_cfg["skip_train_if_model_exists"] = True
model_cfg = merged.get("model", {})
if cli.get("estimator") is not None:
model_cfg["estimator"] = cli.get("estimator")
if cli.get("random_state") is not None:
model_cfg["random_state"] = cli.get("random_state")
sel = merged.get("selection", {})
if cli.get("n_features_to_select") is not None:
sel["n_features_to_select"] = cli.get("n_features_to_select")
if cli.get("step") is not None:
sel["step"] = cli.get("step")
cv = merged.get("cross_validation", {})
if cli.get("n_folds") is not None:
cv["n_folds"] = cli.get("n_folds")
mp = merged.get("multiprocessing", {})
if cli.get("n_jobs") is not None:
mp["n_jobs"] = cli.get("n_jobs")
if cli.get("cpu_processes") is not None:
mp["cpu_processes"] = cli.get("cpu_processes")
cache = merged.get("caching", {})
if cli.get("caching_enabled") is not None:
cache["enabled"] = bool(cli.get("caching_enabled"))
if cli.get("pickle_protocol") is not None:
raw_pickle_protocol = cli.get("pickle_protocol") # Retrieve raw CLI value for 'pickle_protocol' (Any | None)
if raw_pickle_protocol is None: # Ensure the retrieved CLI value is not None before conversion
raise ValueError("pickle_protocol CLI argument is required") # Raise to preserve strict semantics when missing
if isinstance(raw_pickle_protocol, int): # If the raw value is already an int
cache["pickle_protocol"] = raw_pickle_protocol # Assign the int value directly into cache
elif isinstance(raw_pickle_protocol, str) and raw_pickle_protocol.strip() != "": # If it's a non-empty string
cache["pickle_protocol"] = int(raw_pickle_protocol) # Safely convert numeric string to int and assign into cache
else: # Any other type is invalid for conversion
raise ValueError("Invalid pickle_protocol CLI value; expected int or numeric string") # Raise to avoid unsafe int() call
if cli.get("results_dir") is not None:
merged.setdefault("export", {})["results_dir"] = cli.get("results_dir")
if cli.get("results_filename") is not None:
merged.setdefault("export", {})["results_filename"] = cli.get("results_filename")
merged["execution"] = exec_cfg
merged["model"] = model_cfg
merged["selection"] = sel
merged["cross_validation"] = cv
merged["multiprocessing"] = mp
merged["caching"] = cache
final = {"rfe": merged}
validate_config_structure(final)
sources = {"rfe": "merged"}
return final, sources
def get_results_csv_columns(config: Optional[Dict[str, Any]] = None) -> list:
"""
Get the list of columns to be used in the results CSV export from the configuration.
:param config: Optional configuration dictionary to read the columns from. If None, will use the global CONFIG variable.
:return: List of column names to be used in the results CSV export
"""
cfg = config or CONFIG
try:
cols = cfg["rfe"]["export"]["results_csv_columns"]
except Exception:
raise ValueError("rfe.export.results_csv_columns missing from configuration")
if not isinstance(cols, list) or not cols:
raise ValueError("rfe.export.results_csv_columns must be a non-empty list")
return cols
def is_verbose() -> bool:
"""
Verify if verbose output is enabled based on the CLI arguments or configuration.
:param: None
:return: True if verbose output is enabled, False otherwise
"""
return bool((CLI_ARGS.get("verbose") if isinstance(CLI_ARGS, dict) else False) or (CONFIG.get("rfe", {}).get("execution", {}).get("verbose") if isinstance(CONFIG, dict) else False))
def verify_dot_env_file():
"""
Verifies if the .env file exists in the current directory.
:return: True if the .env file exists, False otherwise
"""
try:
env_path = Path(__file__).parent / ".env" # Path to the .env file
if not env_path.exists(): # If the .env file does not exist
print(f"{BackgroundColors.CYAN}.env{BackgroundColors.YELLOW} file not found at {BackgroundColors.CYAN}{env_path}{BackgroundColors.YELLOW}. Telegram messages may not be sent.{Style.RESET_ALL}")
return False # Return False
return True # Return True if the .env file exists
except Exception as e:
print(str(e))
send_exception_via_telegram(type(e), e, e.__traceback__)
raise
def setup_telegram_bot():
"""
Sets up the Telegram bot for progress messages.
:return: None
"""
try:
verbose_output(
f"{BackgroundColors.GREEN}Setting up Telegram bot for messages...{Style.RESET_ALL}"
) # Output the verbose message
verify_dot_env_file() # Verify if the .env file exists
global TELEGRAM_BOT # Declare the module-global TELEGRAM_BOT variable
try: # Try to initialize the Telegram bot
TELEGRAM_BOT = TelegramBot() # Initialize Telegram bot for progress messages
telegram_module.TELEGRAM_DEVICE_INFO = f"{telegram_module.get_local_ip()} - {platform.system()}"
telegram_module.RUNNING_CODE = os.path.basename(__file__)
except Exception as e:
print(f"{BackgroundColors.RED}Failed to initialize Telegram bot: {e}{Style.RESET_ALL}")
TELEGRAM_BOT = None # Set to None if initialization fails
except Exception as e:
print(str(e))
send_exception_via_telegram(type(e), e, e.__traceback__)
raise
def safe_filename(name):
"""
Converts a string to a safe filename by replacing invalid characters with underscores.
:param name: The original string
:return: A safe filename string
"""
try:
return re.sub(r'[\\/*?:"<>|]', "_", name) # Replace invalid characters with underscores
except Exception as e:
print(str(e))
send_exception_via_telegram(type(e), e, e.__traceback__)
raise
def verify_filepath_exists(filepath):
"""
Verify if a file or folder exists at the specified path.
:param filepath: Path to the file or folder
:return: True if the file or folder exists, False otherwise
"""
try:
verbose_output(
f"{BackgroundColors.GREEN}Verifying if the file or folder exists at the path: {BackgroundColors.CYAN}{filepath}{Style.RESET_ALL}"
) # Output the verbose message
return os.path.exists(filepath) # Return True if the file or folder exists, False otherwise
except Exception as e:
print(str(e))
send_exception_via_telegram(type(e), e, e.__traceback__)
raise
def load_dataset(csv_path):
"""
Load CSV and return DataFrame.
:param csv_path: Path to CSV dataset.
:return: DataFrame
"""
try:
verbose_output(
f"\n{BackgroundColors.GREEN}Loading dataset from: {BackgroundColors.CYAN}{csv_path}{Style.RESET_ALL}"
) # Output the loading dataset message
if not verify_filepath_exists(csv_path): # If the CSV file does not exist
print(f"{BackgroundColors.RED}CSV file not found: {csv_path}{Style.RESET_ALL}")
return None # Return None
df = pd.read_csv(csv_path, low_memory=False) # Load the dataset
df.columns = df.columns.str.strip() # Clean column names by stripping leading/trailing whitespace
if df.shape[1] < 2: # If there are less than 2 columns
print(f"{BackgroundColors.RED}CSV must have at least 1 feature and 1 target.{Style.RESET_ALL}")
return None # Return None
send_telegram_message(TELEGRAM_BOT, [f"Dataset loaded from: {csv_path}"]) # Send message about dataset loading
return df # Return the loaded DataFrame
except Exception as e:
print(str(e))
send_exception_via_telegram(type(e), e, e.__traceback__)
raise
def sanitize_feature_names(columns):
r"""
Sanitize column names by removing special JSON characters that LightGBM doesn't support.
Replaces: { } [ ] : , " \ with underscores.
:param columns: pandas Index or list of column names
:return: list of sanitized column names
"""
try:
sanitized = [] # List to store sanitized column names
for col in columns: # Iterate over each column name
clean_col = re.sub(r"[{}\[\]:,\"\\]", "_", str(col)) # Replace special characters with underscores
clean_col = re.sub(r"_+", "_", clean_col) # Replace multiple underscores with a single underscore
clean_col = clean_col.strip("_") # Remove leading/trailing underscores
sanitized.append(clean_col) # Add sanitized column name to the list
return sanitized # Return the list of sanitized column names
except Exception as e:
print(str(e))
send_exception_via_telegram(type(e), e, e.__traceback__)
raise
def preprocess_dataframe(df, remove_zero_variance=True):
"""
Preprocess a DataFrame by removing rows with NaN or infinite values and
dropping zero-variance numeric features.
:param df: pandas DataFrame to preprocess
:param remove_zero_variance: whether to drop numeric columns with zero variance
:return: cleaned DataFrame
"""
try:
if remove_zero_variance: # If remove_zero_variance is set to True
verbose_output(
f"{BackgroundColors.GREEN}Preprocessing DataFrame: "
f"{BackgroundColors.CYAN}normalizing and sanitizing column names, removing NaN/infinite rows, and dropping zero-variance numeric features"
f"{BackgroundColors.GREEN}.{Style.RESET_ALL}"
)
else: # If remove_zero_variance is set to False
verbose_output(
f"{BackgroundColors.GREEN}Preprocessing DataFrame: "
f"{BackgroundColors.CYAN}normalizing and sanitizing column names and removing NaN/infinite rows"
f"{BackgroundColors.GREEN}.{Style.RESET_ALL}"
)
if df is None: # If the DataFrame is None
return df # Return None
df.columns = df.columns.str.strip() # Remove leading/trailing whitespace from column names
df.columns = sanitize_feature_names(df.columns) # Sanitize column names to remove special characters
df_clean = df.replace([np.inf, -np.inf], np.nan).dropna() # Remove rows with NaN or infinite values
if remove_zero_variance: # If remove_zero_variance is set to True
numeric_cols = df_clean.select_dtypes(include=["number"]).columns # Select only numeric columns
if len(numeric_cols) > 0: # If there are numeric columns
variances = df_clean[numeric_cols].var(axis=0, ddof=0) # Calculate variances
zero_var_cols = variances[variances == 0].index.tolist() # Get columns with zero variance
if zero_var_cols: # If there are zero-variance columns
df_clean = df_clean.drop(columns=zero_var_cols) # Drop zero-variance columns
return df_clean # Return the cleaned DataFrame
except Exception as e:
print(str(e))
send_exception_via_telegram(type(e), e, e.__traceback__)
raise
def scale_and_split(X, y, test_size=0.2, random_state=42):
"""
Scales numeric features and splits into train/test sets.
:param X: Features DataFrame
:param y: Target Series
:param test_size: Proportion of the dataset to include in the test split
:param random_state: Random seed for reproducibility
:return: X_train, X_test, y_train, y_test, feature_columns
"""
try:
scaler = StandardScaler() # Initialize the scaler
X_numeric = X.select_dtypes(include=["number"]).copy() # Pick numeric columns first
if X_numeric.shape[1] == 0: # No numeric columns detected
coerced_cols = {} # Dictionary to hold coerced numeric columns
for col in X.columns: # Try coercing each column to numeric
coerced = pd.to_numeric(X[col], errors="coerce") # Coerce invalid -> NaN
if coerced.notna().sum() > 0: # Keep columns that produced numeric values
coerced_cols[col] = coerced
if coerced_cols: # Build DataFrame from coerced columns
X_numeric = pd.DataFrame(coerced_cols, index=X.index) # Use original index
else: # Nothing numeric available -> cannot proceed
raise ValueError(
"No numeric features found after preprocessing. Ensure the dataset contains numeric columns for RFE."
)
X_scaled = scaler.fit_transform(X_numeric.values) # Scale the numeric array
stratify_param = y if len(np.unique(y)) > 1 else None # Avoid stratify for constant labels
X_train, X_test, y_train, y_test = train_test_split(
X_scaled, y, test_size=test_size, random_state=random_state, stratify=stratify_param
) # Split into train/test sets
return X_train, X_test, y_train, y_test, X_numeric.columns # Return the split data and feature columns
except Exception as e:
print(str(e))
send_exception_via_telegram(type(e), e, e.__traceback__)
raise
def run_rfe_selector(X_train, y_train, n_select=10, step=1, estimator_name="random_forest", random_state=42):
"""
Runs RFE with RandomForestClassifier and returns the selector object.
:param X_train: Training features
:param y_train: Training target
:param n_select: Number of features to select
:param random_state: Random seed for reproducibility
:return: selector (fitted RFE object), model, feature_extraction_time_s
"""
try:
estimator_name_l = (estimator_name or "random_forest").lower()
if "random" in estimator_name_l:
n_jobs_val = CONFIG.get("rfe", {}).get("multiprocessing", {}).get("n_jobs") if isinstance(CONFIG, dict) else -1
model = RandomForestClassifier(n_estimators=100, random_state=random_state, n_jobs=int(n_jobs_val) if n_jobs_val is not None else -1)
else:
raise ValueError(f"Unsupported estimator '{estimator_name}'. Supported: 'random_forest'")
n_features = X_train.shape[1] # Get the number of features
if n_select is None:
n_select = n_features # default to all (caller may reduce later)
n_select = int(n_select)
if n_select <= 0:
raise ValueError(f"n_features_to_select must be > 0, got {n_select}")
n_select = n_select if n_features >= n_select else n_features # Adjust n_select if more than available features
selector = RFE(model, n_features_to_select=n_select, step=int(step)) # Initialize RFE
sel_start = time.perf_counter() # Start perf_counter for selector fitting
selector = selector.fit(X_train, y_train) # Fit RFE (feature selection) as part of feature extraction
sel_end = time.perf_counter() # End perf_counter for selector fitting
feature_extraction_time_s = round(sel_end - sel_start, 6) # Compute selector fit duration rounded to 6 decimals
return selector, model, feature_extraction_time_s # Return the fitted selector, model and feature extraction time
except Exception as e:
print(str(e))
send_exception_via_telegram(type(e), e, e.__traceback__)
raise
def compute_rfe_metrics(selector, X_train, X_test, y_train, y_test, random_state=42, estimator_name="random_forest"):
"""
Computes performance metrics using the RFE-selected features.
:param selector: Fitted RFE object
:param X_train: Training features
:param X_test: Testing features
:param y_train: Training target
:param y_test: Testing target
:param random_state: Random seed for reproducibility
:return: metrics tuple (acc, prec, rec, f1, fpr, fnr, training_time_s, testing_time_s)
"""
try:
verbose_output(
f"{BackgroundColors.GREEN}Computing performance metrics using RFE-selected features...{Style.RESET_ALL}"
) # Output the verbose message
support = selector.support_ # Get the mask of selected features
X_train_selected = X_train[:, support] # Select training features
X_test_selected = X_test[:, support] # Select testing features
estimator_name_l = (estimator_name or "random_forest").lower()
if "random" in estimator_name_l:
n_jobs_val = CONFIG.get("rfe", {}).get("multiprocessing", {}).get("n_jobs") if isinstance(CONFIG, dict) else -1
model = RandomForestClassifier(n_estimators=100, random_state=random_state, n_jobs=int(n_jobs_val) if n_jobs_val is not None else -1) # Initialize the model
else:
raise ValueError(f"Unsupported estimator '{estimator_name}' for compute_rfe_metrics. Supported: 'random_forest'")
train_start = time.perf_counter() # Start perf_counter immediately before model.fit (training window)
model.fit(X_train_selected, y_train) # Fit the model on selected features (training)
train_end = time.perf_counter() # End perf_counter immediately after model.fit
training_time_s = round(train_end - train_start, 6) # Compute training time rounded to 6 decimals
test_start = time.perf_counter() # Start perf_counter immediately before prediction (testing window)
y_pred = model.predict(X_test_selected) # Predict on selected test features (testing)
acc = accuracy_score(y_test, y_pred) # Calculate accuracy
prec = precision_score(y_test, y_pred, average="weighted", zero_division=0) # Calculate precision
rec = recall_score(y_test, y_pred, average="weighted", zero_division=0) # Calculate recall
f1 = f1_score(y_test, y_pred, average="weighted", zero_division=0) # Calculate F1-score
if len(np.unique(y_test)) == 2: # If binary classification
cm = confusion_matrix(y_test, y_pred) # Confusion matrix for observed labels
if cm.shape == (2, 2): # Expect 2x2 matrix for binary
tn, fp, fn, tp = cm.ravel() # Unpack
fpr = fp / (fp + tn) if (fp + tn) > 0 else 0 # Calculate false positive rate
fnr = fn / (fn + tp) if (fn + tp) > 0 else 0 # Calculate false negative rate
else: # Fallback: compute rates from sums if unexpected shape
total = cm.sum() if cm.size > 0 else 1
fpr = float(cm.sum() - np.trace(cm)) / float(total) if total > 0 else 0
fnr = fpr # Fallback estimate when binary layout is unexpected
else: # For multi-class classification
cm = confusion_matrix(y_test, y_pred) # Confusion matrix for observed labels
supports = cm.sum(axis=1) # Support for each class
fprs = [] # List to hold per-class FPR
fnrs = [] # List to hold per-class FNR
for i in range(cm.shape[0]): # For each class
tp = cm[i, i] # True positives for class i
fn = cm[i, :].sum() - tp # False negatives: actual i but predicted not-i
fp = cm[:, i].sum() - tp # False positives: predicted i but actual not-i
tn = cm.sum() - (tp + fp + fn) # True negatives: everything else
denom_fnr = (tp + fn) if (tp + fn) > 0 else 1 # Denominator for FNR (avoid div0)
denom_fpr = (fp + tn) if (fp + tn) > 0 else 1 # Denominator for FPR (avoid div0)
fnr_i = fn / denom_fnr # Per-class false negative rate
fpr_i = fp / denom_fpr # Per-class false positive rate
fprs.append((fpr_i, supports[i])) # Store FPR with class support for weighting
fnrs.append((fnr_i, supports[i])) # Store FNR with class support for weighting
total_support = float(supports.sum()) if supports.sum() > 0 else 1.0 # Total support across classes
fpr = float(sum(v * s for v, s in fprs) / total_support) # Weighted average FPR across classes
fnr = float(sum(v * s for v, s in fnrs) / total_support) # Weighted average FNR across classes
test_end = time.perf_counter() # End perf_counter immediately after metrics computed
testing_time_s = round(test_end - test_start, 6) # Compute testing time rounded to 6 decimals
return (
float(acc), # Accuracy
float(prec), # Precision
float(rec), # Recall
float(f1), # F1-score
float(fpr), # False positive rate
float(fnr), # False negative rate
float(training_time_s), # Training time in seconds (rounded 6 decimals)
float(testing_time_s), # Testing time in seconds (rounded 6 decimals)
) # Return the metrics as Python floats
except Exception as e:
print(str(e))
send_exception_via_telegram(type(e), e, e.__traceback__)
raise
def extract_top_features(selector, X_columns):
"""
Returns top selected features and their RFE rankings.
:param selector: Fitted RFE object
:param X_columns: Original feature column names
:return: top_features list, rfe_ranking dict
"""
try:
rfe_ranking = {
f: r for f, r in zip(X_columns, selector.ranking_)
} # Map normalized feature names to their RFE rankings
rfe_ranking = {k: int(v) for k, v in rfe_ranking.items()} # Convert numpy types to Python int
top_features = [f for f, s in zip(X_columns, selector.support_) if s] # List of top selected features
return top_features, rfe_ranking # Return the top features and their rankings
except Exception as e:
print(str(e))
send_exception_via_telegram(type(e), e, e.__traceback__)
raise
def print_top_features(top_features, rfe_ranking):
"""
Prints top features and their RFE rankings to the terminal.
:param top_features: List of top features
:param rfe_ranking: Dict mapping normalized feature names to RFE rankings
"""
try:
print(f"\n{BackgroundColors.BOLD}Top {len(top_features)} features selected by RFE:{Style.RESET_ALL}")
for i, feat in enumerate(top_features, start=1): # Print each top feature with its ranking
rank_info = (
f" {BackgroundColors.GREEN}(RFE ranking {BackgroundColors.CYAN}{rfe_ranking[feat]}{Style.RESET_ALL})"
if feat in rfe_ranking
else " (RFE ranking N/A)"
) # Get ranking info
print(f"{i}. {feat}{rank_info}") # Print the feature and its ranking
except Exception as e:
print(str(e))
send_exception_via_telegram(type(e), e, e.__traceback__)
raise
def print_metrics(metrics_tuple):
"""
Prints metrics for the current run to the terminal.
:param metrics_tuple: Tuple of average metrics
"""
try:
print(f"\n{BackgroundColors.BOLD}Average Metrics:{Style.RESET_ALL}")
print(f" {BackgroundColors.GREEN}Accuracy: {BackgroundColors.CYAN}{truncate_value(metrics_tuple[0])}{Style.RESET_ALL}")
print(f" {BackgroundColors.GREEN}Precision: {BackgroundColors.CYAN}{truncate_value(metrics_tuple[1])}{Style.RESET_ALL}")
print(f" {BackgroundColors.GREEN}Recall: {BackgroundColors.CYAN}{truncate_value(metrics_tuple[2])}{Style.RESET_ALL}")
print(f" {BackgroundColors.GREEN}F1-Score: {BackgroundColors.CYAN}{truncate_value(metrics_tuple[3])}{Style.RESET_ALL}")
print(
f" {BackgroundColors.GREEN}False Positive Rate (FPR): {BackgroundColors.CYAN}{truncate_value(metrics_tuple[4])}{Style.RESET_ALL}"
)
print(
f" {BackgroundColors.GREEN}False Negative Rate (FNR): {BackgroundColors.CYAN}{truncate_value(metrics_tuple[5])}{Style.RESET_ALL}"
)
try:
if len(metrics_tuple) >= 8: # If tuple has training and testing times
displayed_elapsed = int(round(float(metrics_tuple[6]) + float(metrics_tuple[7]))) # Sum training+testing
else:
displayed_elapsed = int(round(float(metrics_tuple[6]))) # Fallback to the single elapsed value
except Exception:
displayed_elapsed = 0 # On error, show zero
print(f" {BackgroundColors.GREEN}Elapsed Time: {BackgroundColors.CYAN}{displayed_elapsed}s{Style.RESET_ALL}")
send_telegram_message(
TELEGRAM_BOT,
[
f"Average Metrics:\n"
f" Accuracy: {truncate_value(metrics_tuple[0])}\n"
f" Precision: {truncate_value(metrics_tuple[1])}\n"
f" Recall: {truncate_value(metrics_tuple[2])}\n"
f" F1-Score: {truncate_value(metrics_tuple[3])}\n"
f" False Positive Rate (FPR): {truncate_value(metrics_tuple[4])}\n"
f" False Negative Rate (FNR): {truncate_value(metrics_tuple[5])}\n"
f" Elapsed Time: {displayed_elapsed}s"
],
) # Send metrics to Telegram
except Exception as e:
print(str(e))
send_exception_via_telegram(type(e), e, e.__traceback__)
raise
def get_hardware_specifications():
"""
Returns system specs: real CPU model (Windows/Linux/macOS), physical cores,
RAM in GB, and OS name/version.
:return: Dictionary with keys: cpu_model, cores, ram_gb, os
"""
try:
verbose_output(
f"{BackgroundColors.GREEN}Fetching system specifications...{Style.RESET_ALL}"
) # Output the verbose message
system = platform.system() # Identify OS type
try: # Try to fetch real CPU model using OS-specific methods
if system == "Windows": # Windows: use WMIC
out = subprocess.check_output("wmic cpu get Name", shell=True).decode(errors="ignore") # Run WMIC
cpu_model = out.strip().split("\n")[1].strip() # Extract model line
elif system == "Linux": # Linux: read from /proc/cpuinfo
cpu_model = "Unknown" # Default
with open("/proc/cpuinfo") as f: # Open cpuinfo
for line in f: # Iterate lines
if "model name" in line: # Model name entry
cpu_model = line.split(":", 1)[1].strip() # Extract name
break # Stop after first match
elif system == "Darwin": # MacOS: use sysctl
out = subprocess.check_output(["sysctl", "-n", "machdep.cpu.brand_string"]) # Run sysctl
cpu_model = out.decode().strip() # Extract model string
else: # Unsupported OS
cpu_model = "Unknown" # Fallback
except Exception: # If any method fails
cpu_model = "Unknown" # Fallback on failure
cores = psutil.cpu_count(logical=False) # Physical core count
ram_gb = round(psutil.virtual_memory().total / (1024**3), 1) # Total RAM in GB
os_name = f"{platform.system()} {platform.release()}" # OS name + version
return { # Build final dictionary
"cpu_model": cpu_model, # CPU model string
"cores": cores, # Physical cores
"ram_gb": ram_gb, # RAM in gigabytes
"os": os_name, # Operating system
}
except Exception as e:
print(str(e))
send_exception_via_telegram(type(e), e, e.__traceback__)
raise
def populate_hardware_column_and_order(df, config: Optional[Dict[str, Any]] = None, column_name="hardware"):
"""
Add a hardware-specs column to `df` and reorder columns so the hardware
column appears immediately after `elapsed_time_s`.
:param df: pandas DataFrame with RFE results
:param column_name: name for the hardware column
:return: reordered DataFrame with hardware column added
"""
try:
df_results = df.copy() # Copy DataFrame to modify
hardware_specs = get_hardware_specifications() # Get system specs
df_results[column_name] = (
hardware_specs["cpu_model"]
+ " | Cores: "
+ str(hardware_specs["cores"])
+ " | RAM: "
+ str(hardware_specs["ram_gb"])
+ " GB | OS: "
+ hardware_specs["os"]
) # Add hardware specs column
cols = get_results_csv_columns(config)
columns_order = [(column_name if str(c).lower() == "hardware" else c) for c in cols]
return df_results.reindex(columns=columns_order)
except Exception as e:
print(str(e))
send_exception_via_telegram(type(e), e, e.__traceback__)
raise
def export_final_model(X_numeric, feature_columns, top_features, y_array, csv_path):
"""
Train a final RandomForest on the full numeric dataset restricted to
`top_features`, save model, scaler, and feature list to disk and
return their paths.
All newly added lines include inline comments explaining their purpose.
:param X_numeric: DataFrame of numeric features
:param feature_columns: Original feature column names
:param top_features: List of top selected features
:param y_array: Numpy array of target labels
:param csv_path: Original CSV file path
:return: model_path, scaler_path, features_path
"""
try:
scaler_full = StandardScaler() # Create a scaler for full-data training
X_full_scaled = scaler_full.fit_transform(X_numeric.values) # Scale all numeric features
sel_indices = [i for i, f in enumerate(feature_columns) if f in top_features] # Get indices for top features
X_final = X_full_scaled[:, sel_indices] if sel_indices else X_full_scaled # Select columns or keep all if none
model_rs = CONFIG.get("rfe", {}).get("model", {}).get("random_state") if isinstance(CONFIG, dict) else 42
n_jobs_val = CONFIG.get("rfe", {}).get("multiprocessing", {}).get("n_jobs") if isinstance(CONFIG, dict) else -1
final_model = RandomForestClassifier(n_estimators=100, random_state=int(model_rs) if model_rs is not None else 42, n_jobs=int(n_jobs_val) if n_jobs_val is not None else -1) # Instantiate final RF
final_model.fit(X_final, y_array) # Fit final model on entire dataset using selected features
cfg_source = CONFIG if isinstance(CONFIG, dict) and CONFIG else get_default_config()
rfe_cfg_local = cfg_source.get("rfe") if isinstance(cfg_source.get("rfe"), dict) else cfg_source
export_cfg_local = (rfe_cfg_local or {}).get("export", {})
results_dir_raw_local = export_cfg_local.get("results_dir") or os.path.join("Feature_Analysis", "RFE")
if os.path.isabs(results_dir_raw_local):
resolved_dir_local = os.path.abspath(os.path.expanduser(results_dir_raw_local))
else:
dataset_dir_local = os.path.dirname(csv_path) or "."
resolved_dir_local = os.path.abspath(os.path.expanduser(os.path.join(dataset_dir_local, results_dir_raw_local)))
models_dir = os.path.join(resolved_dir_local, "Models")
os.makedirs(models_dir, exist_ok=True) # Ensure directory exists
timestamp = datetime.datetime.now().strftime("%Y_%m_%d-%H_%M_%S") # Timestamp for filenames (YYYY_MM_DD-HH_MM_SS)
base_name = safe_filename(Path(csv_path).stem) # Safe base name from dataset path