5
5
from sklearn .ensemble import RandomForestClassifier
6
6
from sklearn .preprocessing import StandardScaler
7
7
8
- warnings .filterwarnings (' ignore' )
8
+ warnings .filterwarnings (" ignore" )
9
9
10
10
11
- def find_best_random_state (data : pd .DataFrame , target_column : str , iterations : int = 200 ) -> int :
11
+ def find_best_random_state (
12
+ data : pd .DataFrame , target_column : str , iterations : int = 200
13
+ ) -> int :
12
14
"""
13
15
Find the best random state for the Random Forest Classifier that maximizes accuracy.
14
16
@@ -25,7 +27,9 @@ def find_best_random_state(data: pd.DataFrame, target_column: str, iterations: i
25
27
target = data [target_column ]
26
28
27
29
# Split dataset into train and test sets
28
- X_train , X_test , y_train , y_test = train_test_split (predictors , target , test_size = 0.20 , random_state = 0 )
30
+ X_train , X_test , y_train , y_test = train_test_split (
31
+ predictors , target , test_size = 0.20 , random_state = 0
32
+ )
29
33
30
34
# Scale features
31
35
scaler = StandardScaler ()
@@ -40,19 +44,21 @@ def find_best_random_state(data: pd.DataFrame, target_column: str, iterations: i
40
44
rf = RandomForestClassifier (random_state = random_state )
41
45
rf .fit (X_train_scaled , y_train )
42
46
y_pred_rf = rf .predict (X_test_scaled )
43
-
47
+
44
48
current_accuracy = round (accuracy_score (y_test , y_pred_rf ) * 100 , 2 )
45
49
if current_accuracy > max_accuracy_rf :
46
50
max_accuracy_rf = current_accuracy
47
51
best_random_state = random_state
48
52
49
- print (f"The best random state is: { best_random_state } with an accuracy score of: { max_accuracy_rf } %" )
53
+ print (
54
+ f"The best random state is: { best_random_state } with an accuracy score of: { max_accuracy_rf } %"
55
+ )
50
56
return best_random_state
51
57
52
58
53
59
if __name__ == "__main__" :
54
60
# Load dataset
55
61
dataset = pd .read_csv ("heart.csv" )
56
-
62
+
57
63
# Find the best random state
58
64
best_state = find_best_random_state (dataset , target_column = "target" )
0 commit comments