-
Notifications
You must be signed in to change notification settings - Fork 0
/
random_forest_test.py
144 lines (116 loc) · 4.21 KB
/
random_forest_test.py
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
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import StratifiedKFold
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import accuracy_score, precision_recall_fscore_support
import json
import pandas as pd
import numpy as np
from tqdm import tqdm
def get_data():
with open("data/sets.json") as f:
data = json.load(f)
set_collection = {}
for item in data:
tune = {
"position": item["settingorder"],
"type": item["type"],
"meter": item["meter"],
"mode": item["mode"][1:],
"tonic": item["mode"][:1],
}
if item["tuneset"] not in set_collection:
set_collection[item["tuneset"]] = [tune]
else:
set_collection[item["tuneset"]].append(tune)
return set_collection
def split_data(set_collection, features, set_size):
tune_set = []
for k, v in set_collection.items():
if len(v) == set_size:
tune_set.extend(v)
df = pd.DataFrame(tune_set).copy() # Create an explicit copy
if features == ["all"]:
X = df.drop("position", axis=1)
else:
X = df[features].copy() # Create a copy of the selected features
y = df["position"]
# Encode categorical variables
le = LabelEncoder()
for col in X.columns:
if X[col].dtype == 'object':
X.loc[:, col] = le.fit_transform(X[col])
return X, y
def random_forest_tune_position(X, y):
skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
clf = RandomForestClassifier(n_estimators=100, random_state=42)
fold_results = []
for fold, (train_index, test_index) in enumerate(skf.split(X, y), 1):
X_train, X_test = X.iloc[train_index], X.iloc[test_index]
y_train, y_test = y.iloc[train_index], y.iloc[test_index]
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
precision, recall, f1, _ = precision_recall_fscore_support(y_test, y_pred, average='weighted', zero_division=0)
accuracy = accuracy_score(y_test, y_pred)
fold_results.append({
'fold': fold,
'precision': float(precision),
'recall': float(recall),
'f1': float(f1),
'accuracy': float(accuracy),
'support': int(len(y_test))
})
# Calculate feature importance
clf.fit(X, y) # Fit on entire dataset for overall feature importance
feature_importance = pd.DataFrame({
'feature': X.columns,
'importance': clf.feature_importances_
}).sort_values('importance', ascending=False)
return {
'fold_results': fold_results,
'feature_importance': feature_importance.to_dict(orient='records')
}
def analyze_folds(fold_results):
metrics = ['precision', 'recall', 'f1', 'accuracy', 'support']
analysis = {}
for metric in metrics:
values = [fold[metric] for fold in fold_results]
analysis[metric] = {
'mean': float(np.mean(values)),
'std': float(np.std(values)),
'min': float(np.min(values)),
'max': float(np.max(values)),
'median': float(np.median(values))
}
return analysis
def main():
data = get_data()
set_sizes = [2, 3]
feature_combinations = [
["all"],
["type"],
["meter"],
["mode"],
["tonic"],
["type", "meter"],
["type", "mode"],
["type", "tonic"],
["meter", "mode"],
["meter", "tonic"],
["mode", "tonic"]
]
results = {}
for set_size in set_sizes:
results[f"set_size_{set_size}"] = {}
for features in tqdm(feature_combinations):
X, y = split_data(data, features, set_size)
feature_key = "_".join(features)
rf_results = random_forest_tune_position(X, y)
results[f"set_size_{set_size}"][feature_key] = {
'metrics': analyze_folds(rf_results['fold_results']),
'feature_importance': rf_results['feature_importance']
}
# Save results to a JSON file
with open("results/random_forest_results.json", "w") as f:
json.dump(results, f, indent=2)
if __name__ == "__main__":
main()