In [1]기본 학습 (r1)
from sklearn.ensemble import RandomForestClassifier
model_rf = RandomForestClassifier(n_estimators=300, random_state=42, class_weight='balanced')
model_rf.fit(X_train, y_train)
rf_pred = model_rf.predict(X_val)
print(confusion_matrix(y_val, rf_pred))
print('F1 Score :', f1_score(y_val, rf_pred))
Out[1] 출력 보기
[[15776 297]
[ 1648 279]]
F1 Score : 0.22293248102277266
In [2]Optuna로 튜닝 (r3)
def objective_rf(trial):
n_estimators = trial.suggest_int('n_estimators', 50, 500)
max_depth = trial.suggest_int('max_depth', 2, 12)
min_samples_leaf = trial.suggest_int('min_samples_leaf', 1, 50)
model = RandomForestClassifier(
n_estimators=n_estimators,
max_depth=max_depth,
min_samples_leaf=min_samples_leaf,
class_weight='balanced',
random_state=42
)
model.fit(X_train, y_train)
pred = model.predict(X_val)
return f1_score(y_val, pred)
study_rf = optuna.create_study(direction='maximize')
study_rf.optimize(objective_rf, n_trials=100)
print('best f1 :', study_rf.best_value)
print('best params :', study_rf.best_params)
Out[2] 출력 보기
best f1 : 0.35168558360155855
best params : {'n_estimators': 438, 'max_depth': 12, 'min_samples_leaf': 4}