超参数调整专题
知识点回顾
1. 网格搜索
2. 随机搜索(简单介绍,非重点 实战中很少用到,可以不了解)
3. 贝叶斯优化(2种实现逻辑,以及如何避开必须用交叉验证的问题)
4. time库的计时模块,方便后人查看代码运行时长
题目:对于信贷数据的其他模型,如LightGBM和KNN 尝试用下贝叶斯优化和网格搜索
import pandas as pd #用于数据处理和分析,可处理表格数据。
import numpy as np #用于数值计算,提供了高效的数组操作。
import matplotlib.pyplot as plt #用于绘制各种类型的图表
import seaborn as sns #基于matplotlib的高级绘图库,能绘制更美观的统计图形。
# 设置中文字体(解决中文显示问题)
plt.rcParams['font.sans-serif'] = ['SimHei'] # Windows系统常用黑体字体
plt.rcParams['axes.unicode_minus'] = False # 正常显示负号
data = pd.read_csv('heart.csv')
# 提取连续值特征
continuous_features = ['age', 'trestbps', 'chol', 'thalach', 'oldpeak']
# 提取离散值特征
discrete_features = ['sex', 'cp', 'fbs', 'restecg', 'exang', 'slope', 'ca', 'thal', 'target']
# 定义映射字典
mapping = {
'cp': {0: 0, 1: 1, 2: 2, 3: 3},
'restecg': {0: 0, 1: 1, 2: 2},
'slope': {0: 0, 1: 1, 2: 2},
'ca': {0: 0, 1: 1, 2: 2, 3: 3, 4: 4},
'thal': {0: 0, 1: 1, 2: 2, 3: 3}
}
# 使用映射字典进行转换
for feature, mapping in mapping.items():
data[feature] = data[feature].map(mapping)
columns_to_encode = ['sex','fbs','exang']
# Purpose 独热编码
data = pd.get_dummies(data, columns=columns_to_encode)
data2 = pd.read_csv("heart.csv") # 重新读取数据,用来做列名对比
list_final = [] # 新建一个空列表,用于存放独热编码后新增的特征名
for i in data.columns:
if i not in data2.columns:
list_final.append(i) # 这里打印出来的就是独热编码后的特征名
for i in list_final:
data[i] = data[i].astype(int) # 这里的i就是独热编码后的特征名
# 划分训练集和测试机
from sklearn.model_selection import train_test_split
X = data.drop(['target'], axis=1) # 特征,axis=1表示按列删除
y = data['target'] # 标签
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # 80%训练集,20%测试集
import lightgbm as lgb #LightGBM分类器
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score # 用于评估分类器性能的指标
from sklearn.metrics import classification_report, confusion_matrix #用于生成分类报告和混淆矩阵
import warnings #用于忽略警告信息
import time
warnings.filterwarnings("ignore") # 忽略所有警告信息
print("--- 1. 默认参数LightGBM (训练集 -> 测试集) ---")
start_time = time.time() # 记录开始时间
lgb_model = lgb.LGBMClassifier(random_state=42)
lgb_model.fit(X_train, y_train) # 在训练集上训练
lgb_pred = lgb_model.predict(X_test) # 在测试集上预测
end_time = time.time() # 记录结束时间
print(f"训练与预测耗时: {end_time - start_time:.4f} 秒")
print("\n默认随机森林 在测试集上的分类报告:")
print(classification_report(y_test, rf_pred))
print("默认随机森林 在测试集上的混淆矩阵:")
print(confusion_matrix(y_test, rf_pred))
print("\n--- 2. 网格搜索优化LightGBM (训练集 -> 测试集) ---")
from sklearn.model_selection import GridSearchCV
# 定义要搜索的参数网格
param_grid = {
'n_estimators': [50, 100, 200], # 树的数量
'max_depth': [-1, 10, 20, 30], # 树的最大深度,-1表示不限制
'num_leaves': [20, 31, 40], # 树的最大叶子节点数
'learning_rate': [0.01, 0.1, 0.2], # 学习率
}
# 创建网格搜索对象
grid_search = GridSearchCV(estimator=lgb.LGBMClassifier(random_state=42), # LightGBM分类器
param_grid=param_grid, # 参数网格
cv=5, # 5折交叉验证
n_jobs=-1, # 使用所有可用的CPU核心进行并行计算
scoring='accuracy') # 使用准确率作为评分标准
start_time = time.time()
# 在训练集上进行网格搜索
grid_search.fit(X_train, y_train) # 在训练集上训练,模型实例化和训练的方法都被封装在这个网格搜索对象里了
end_time = time.time()
print(f"网格搜索耗时: {end_time - start_time:.4f} 秒")
print("最佳参数: ", grid_search.best_params_) #best_params_属性返回最佳参数组合
# 使用最佳参数的模型进行预测
best_model = grid_search.best_estimator_ # 获取最佳模型
best_pred = best_model.predict(X_test) # 在测试集上进行预测
print("\n网格搜索优化后的LightGBM分类器 在测试集上的分类报告:")
print(classification_report(y_test, best_pred))
print("网格搜索优化后的LightGBM分类器 在测试集上的混淆矩阵:")
print(confusion_matrix(y_test, best_pred))
# --- 2. 贝叶斯优化LightGBM分类器 ---
print("\n--- 2. 贝叶斯优化随机森林 (训练集 -> 测试集) ---")
from skopt import BayesSearchCV
from skopt.space import Integer, Real
# 定义要搜索的参数空间
search_space = {
'n_estimators': Integer(50, 200), # 树的数量
'max_depth': Integer(-1, 30), # 树的最大深度,-1表示不限制
'num_leaves': Integer(20, 50), # 树的最大叶子节点数
'learning_rate': Real(0.01, 0.2, prior='log-uniform'), # 学习率,对数均匀分布
}
# 创建贝叶斯优化搜索对象
bayes_search = BayesSearchCV(
estimator=lgb.LGBMClassifier(random_state=42),
search_spaces=search_space,
n_iter=32, # 迭代次数,可根据需要调整
cv=5, # 5折交叉验证,这个参数是必须的,不能设置为1,否则就是在训练集上做预测了
n_jobs=-1,
scoring='accuracy'
)
start_time = time.time()
# 在训练集上进行贝叶斯优化搜索
bayes_search.fit(X_train, y_train)
end_time = time.time()
print(f"贝叶斯优化耗时: {end_time - start_time:.4f} 秒")
print("最佳参数: ", bayes_search.best_params_)
# 使用最佳参数的模型进行预测
best_model = bayes_search.best_estimator_
best_pred = best_model.predict(X_test)
print("\n贝叶斯优化后的LightGBM分类器 在测试集上的分类报告:")
print(classification_report(y_test, best_pred))
print("贝叶斯优化后的LightGBM分类器 在测试集上的混淆矩阵:")
print(confusion_matrix(y_test, best_pred))