基于sklearn采用optuna实现对随机森林回归预测自动调整参数,预期r2达到0.95左右
时间: 2024-04-10 17:31:20 浏览: 14
你可以使用Optuna来自动调整随机森林回归模型的参数以达到预期的R2值。下面是一个基于sklearn和Optuna的示例代码:
```python
import optuna
from sklearn.datasets import make_regression
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import r2_score
from sklearn.model_selection import train_test_split
# 生成随机数据
X, y = make_regression(n_samples=1000, n_features=10, random_state=42)
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
def objective(trial):
# 定义参数搜索空间
n_estimators = trial.suggest_int('n_estimators', 100, 1000, step=100)
max_depth = trial.suggest_int('max_depth', 3, 10)
min_samples_split = trial.suggest_int('min_samples_split', 2, 10)
min_samples_leaf = trial.suggest_int('min_samples_leaf', 1, 10)
# 初始化随机森林回归器
model = RandomForestRegressor(n_estimators=n_estimators,
max_depth=max_depth,
min_samples_split=min_samples_split,
min_samples_leaf=min_samples_leaf,
random_state=42)
# 训练模型
model.fit(X_train, y_train)
# 在测试集上进行预测
y_pred = model.predict(X_test)
# 计算R2得分作为目标函数的返回值
r2 = r2_score(y_test, y_pred)
return r2
# 创建Optuna的study对象
study = optuna.create_study(direction='maximize')
# 进行参数搜索
study.optimize(objective, n_trials=100)
# 打印最佳参数和R2得分
print('Best R2 Score:', study.best_value)
print('Best Parameters:', study.best_params)
```
你可以根据自己的数据和需求修改参数搜索空间的范围。运行代码后,会输出最佳的R2得分和对应的最佳参数。请注意,由于随机性的存在,每次运行的结果可能会有所不同。