机器学习构建预测模型,R2卡在0.6-0.69不动,网格搜索和贝叶斯优化以及前后两者结合调整超参数都不能将R2提升,该怎么办
数据100组,三个特征变量,一个目标变量。进行过异常值剔除
剔除代码
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# 从CSV文件读取数据
file_path = 'C:/Users/GMQ/Desktop/data.csv' # 替换成你的文件路径
df = pd.read_csv(file_path, header=None) # 假设没有列名,使用默认的列索引
# 分离特征和目标变量
features = df.iloc[:-1] # 前三行是特征
target = df.iloc[-1] # 最后一行是目标变量
# 绘制箱线图
plt.figure(figsize=(10, 6))
sns.boxplot(data=features.T) # 转置以便每一列是一个特征
plt.title('Boxplot of Features')
plt.xticks(rotation=45)
plt.show()
# 处理异常值
for column in features.columns:
Q1 = features[column].quantile(0.25)
Q3 = features[column].quantile(0.75)
IQR = Q3 - Q1
# 根据箱线图定义删除或替换异常值
features[column] = features[column].clip(lower=Q1 - 1.5 * IQR, upper=Q3 + 1.5 * IQR)
# 或者替换为中位数
# median = features[column].median()
# features[column] = features[column].where((features[column] >= Q1 - 1.5 * IQR) & (features[column] <= Q3 + 1.5 * IQR), median)
# 处理后的数据集
processed_df = pd.concat([features, target], axis=0)
# 保存处理后的数据集到CSV文件
processed_file_path = 'processed_data.csv' # 替换成你想要保存的文件路径
processed_df.to_csv(processed_file_path, index=False, header=False) # 不保存索引和列名
模型代码
import pandas as pd
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.metrics import r2_score, mean_absolute_error
from skopt import BayesSearchCV
# 1. 加载数据
file_path = 'C:/Users/GMQ/Desktop/processed_data.csv' # 修改为你的数据文件路径
df = pd.read_csv(file_path)
# 假设数据包含四列,前三列为特征变量,最后一列为目标变量
X = df.iloc[:, :-1]
y = df.iloc[:, -1]
# 2. 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 3. 定义梯度提升回归模型
model = GradientBoostingRegressor(random_state=42)
# 4. 第一阶段:网格搜索
param_grid = {
'n_estimators': [200, 300, 400],
'learning_rate': [0.01, 0.05, 0.1],
'max_depth': [5, 7, 9]
}
grid_search = GridSearchCV(
estimator=model,
param_grid=param_grid,
scoring='r2',
cv=5,
verbose=1,
n_jobs=-1
)
grid_search.fit(X_train, y_train)
# 获取网格搜索的最佳参数
best_params_grid = grid_search.best_params_
# 5. 第二阶段:贝叶斯优化
param_space = {
'n_estimators': (best_params_grid['n_estimators'] - 50, best_params_grid['n_estimators'] + 50),
'learning_rate': (best_params_grid['learning_rate'] * 0.5, best_params_grid['learning_rate'] * 1.5, 'log-uniform'),
'max_depth': (best_params_grid['max_depth'] - 2, best_params_grid['max_depth'] + 2)
}
bayes_search = BayesSearchCV(
estimator=model,
search_spaces=param_space,
scoring='r2',
cv=5,
n_iter=50, # 迭代次数,可以根据计算资源和时间进行调整
random_state=42,
verbose=1,
n_jobs=-1 # 并行处理的作业数,-1表示使用所有可用的CPU核心
)
bayes_search.fit(X_train, y_train)
# 获取最佳参数和最佳分数
best_params_bayes = bayes_search.best_params_
best_score_bayes = bayes_search.best_score_
# 训练最终模型(使用最佳参数)
best_params_grid.update(best_params_bayes) # 更新参数为网格搜索和贝叶斯优化得到的最佳参数
model.set_params(**best_params_grid)
model.fit(X_train, y_train)
# 在测试集上评估模型
y_pred = model.predict(X_test)
r2 = r2_score(y_test, y_pred)
mae = mean_absolute_error(y_test, y_pred)
# 打印模型优化结果
print("\n梯度提升回归模型优化结果:")
print(f"最佳参数: {best_params_grid}")
print(f"最佳R^2分数: {best_score_bayes:.4f}")
print(f"测试集上的R^2分数: {r2:.4f}")
print(f"测试集上的平均绝对误差: {mae:.4f}")
print("------------------------------------------------------------")