使用RF估算浓度,价格,等,下面两个代码,第一个代码是寻找最优参数,第二个是预测。
话不多说直接上代码
RF_reserach.py
'''
@Project :moxing
@File :RF_reserach.py
@IDE :PyCharm
@Author :11
@Date :2023/6/29 11:31
'''
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import GridSearchCV, train_test_split
import logging
# 配置日志输出
logging.basicConfig(filename='01month_rf_model_04csv.log', level=logging.INFO)
# 读取数据
data = pd.read_csv(r'G:\RF\normalized_month_12\01\04.csv')
# 定义特征和目标列
X = data.drop(columns=['CO2']) #目标列名
y = data['CO2']
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 定义随机森林回归器
rf = RandomForestRegressor()
#定义参数网格
param_grid = {
'n_estimators': [200, 300, 500,700,1000], # 决策树数量
'max_depth': [10, 20,], # 最大树深度
'min_samples_split': [2, 5,10,20], # 节点分裂所需的最小样本数
'min_samples_leaf': [1,2,4,8], # 叶节点所需的最小样本数
'max_feature

该代码示例展示了如何利用Python的scikit-learn库进行随机森林回归(RandomForestRegressor)的参数调优。首先,通过GridSearchCV进行参数网格搜索,找到最优参数组合,然后用这些参数训练模型并在测试集上进行预测,最后评估模型的性能,包括MAE、MSE、RMSE和R²分数。整个过程的日志被记录下来以便后续分析。
388

被折叠的 条评论
为什么被折叠?



