超参数调整专题
知识点回顾
- 网格搜索
- 随机搜索(简单介绍,非重点 实战中很少用到,可以不了解)
- 贝叶斯优化(2种实现逻辑,以及如何避开必须用交叉验证的问题)
- 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(r'data.csv') #读取数据
# 先筛选字符串变量
discrete_features = data.select_dtypes(include=['object']).columns.tolist()
# Home Ownership 标签编码
home_ownership_mapping = {
'Own Home': 1,
'Rent': 2,
'Have Mortgage': 3,
'Home Mortgage': 4
}
data['Home Ownership'] = data['Home Ownership'].map(home_ownership_mapping)
# Years in current job 标签编码
years_in_job_mapping = {
'< 1 year': 1,
'1 year': 2,
'2 years': 3,
'3 years': 4,
'4 years': 5,
'5 years': 6,
'6 years': 7,
'7 years': 8,
'8 years': 9,
'9 years': 10,
'10+ years': 11
}
data['Years in current job'] = data['Years in current job'].map(years_in_job_mapping)
# Purpose 独热编码,记得需要将bool类型转换为数值
data = pd.get_dummies(data, columns=['Purpose'])
data2 = pd.read_csv(r"data.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就是独热编码后的特征名
# Term 0 - 1 映射
term_mapping = {
'Short Term': 0,
'Long Term': 1
}
data['Term'] = data['Term'].map(term_mapping)
data.rename(columns={'Term': 'Long Term'}, inplace=True) # 重命名列
continuous_features = data.select_dtypes(include=['int64', 'float64']).columns.tolist() #把筛选出来的列名转换成列表
# 连续特征用中位数补全
for feature in continuous_features:
mode_value = data[feature].mode()[0] #获取该列的众数。
data[feature] = data[feature].fillna(mode_value) #用众数填充该列的缺失值,inplace=True表示直接在原数据上修改。
# new机器学习模型建模
# 划分训练集、验证集和测试集,因为需要考2次
from sklearn.model_selection import train_test_split
X = data.drop(['Credit Default'], axis=1) # 特征,axis=1表示按列删除
y = data['Credit Default'] # 标签
# 按照8:1:1划分训练集、验证集和测试集
X_train, X_temp, y_train, y_temp = train_test_split(X, y, test_size=0.2, random_state=42) # 划分训练集和临时集,20%作为临时集
X_val, X_test, y_val, y_test = train_test_split(X_temp, y_temp, test_size=0.5, random_state=42) # 从临时集中划分验证集和测试集,50%作为验证集,50%作为测试集
# X_train, y_train (80%)
# X_val, y_val (10%)
# X_test, y_test (10%)
print("Data shapes:")
print("X_train:", X_train.shape)
print("y_train:", y_train.shape)
print("X_val:", X_val.shape)
print("y_val:", y_val.shape)
print("X_test:", X_test.shape)
print("y_test:", y_test.shape)
# 最开始也说了 很多调参函数自带交叉验证,甚至是必选的参数,你如果想要不交叉反而实现起来会麻烦很多
# 所以这里我们还是只划分一次数据集
# 划分训练集和测试集,因为需要考2次
from sklearn.model_selection import train_test_split
X = data.drop(['Credit Default'], axis=1) # 特征,axis=1表示按列删除
y = data['Credit Default'] # 标签
# 按照8:2划分训练集、验证集和测试集
X_train, X_temp, y_train, y_temp = train_test_split(X, y, test_size=0.2, random_state=42) # 划分训练集和临时集,20%作为临时集
from sklearn.ensemble import RandomForestClassifier #随机森林分类器
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score # 用于评估分类器性能的指标
from sklearn.metrics import classification_report, confusion_matrix #用于生成分类报告和混淆矩阵
import warnings #用于忽略警告信息
warnings.filterwarnings("ignore") # 忽略所有警告信息
# --- 1. 默认参数的随机森林 ---
# 评估基准模型,这里确实不需要验证集,因为我们是用测试集来评估模型的
print("--- 1. 默认参数随机森林 (训练集 -> 测试集) ---")
import time # 这里介绍一个新的库,time库,主要用于时间相关的操作,因为调参需要很长时间,记录下会帮助后人知道大概的时长
start_time = time.time() # 记录开始时间
rf_model = RandomForestClassifier(random_state=42) # 创建随机森林分类器,random_state=42用于设置随机种子,保证每次运行结果一致
rf_model.fit(X_train, y_train) # 在训练集上训练
rf_pred = rf_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("默认随机森林 在测试集上的混淆矩阵:") # 打印混淆矩阵
# 贝叶斯优化所需要安装scikit-optimize这个库
# pip install scikit-optimize -i https://pypi.tuna.tsinghua.edu.cn/simple
# --- 2. 网格搜索优化随机森林 ---
print("--- 2. 网格搜索优化随机森林 ---")
from sklearn.model_selection import GridSearchCV # 用于进行网格搜索
# 定义参数网格,这里我们只调整n_estimators和max_depth,因为这两个参数对模型性能影响最大
param_grid = {
'n_estimators': [50, 100, 200], # 树的数量
'max_depth': [None, 10, 20, 30], # 树的最大深度
'min_samples_split': [2, 5, 10], # 分裂内部节点所需的最小样本数
'min_samples_leaf': [1, 2, 4] # 叶节点所需的最小样本数
}
# 创建网格搜索对象,使用5折交叉验证
grid_search = GridSearchCV(estimator=RandomForestClassifier(random_state=42), # 随机森林分类器
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网格搜索优化后的随机森林 在测试集上的分类报告:") # 打印分类报告
print(classification_report(y_test, best_pred)) # 打印分类报告
print("网格搜索优化后的随机森林 在测试集上的混淆矩阵:") # 打印混淆矩阵
print(confusion_matrix(y_test, best_pred)) # 打印混淆矩阵
# --- 2. 贝叶斯优化随机森林 ---
print("--- 2. 贝叶斯优化随机森林 ---")
from skopt import BayesSearchCV # 用于进行贝叶斯优化
from skopt.space import Integer # 用于定义整数类型的搜索空间
# 定义要搜索的参数空间,这里我们只调整n_estimators和max_depth,因为这两个参数对模型性能影响最大
search_space = {
'n_estimators': Integer(50, 200), # 树的数量
'max_depth': Integer(10, 30), # 树的最大深度
'min_samples_split': Integer(2, 10), # 分裂内部节点所需的最小样本数
'min_samples_leaf': Integer(1, 4) # 叶节点所需的最小样本数
}
# 创建贝叶斯优化搜索对象,使用5折交叉验证
bayes_search = BayesSearchCV(
estimator=RandomForestClassifier(random_state=42), # 随机森林分类器
search_spaces=search_space, # 参数空间
n_iter=50, # 搜索迭代次数
cv=5, # 5折交叉验证
n_jobs=-1, # 使用所有可用的CPU核心进行并行计算
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_params_属性返回最佳参数组合
# 使用最佳参数的模型进行预测
best_model = bayes_search.best_estimator_ # 获取最佳模型
best_pred = best_model.predict(X_test) # 在测试集上进行预测
print("\n贝叶斯优化后的随机森林 在测试集上的分类报告:") # 打印分类报告
print(classification_report(y_test, best_pred)) # 打印分类报告
print("贝叶斯优化后的随机森林 在测试集上的混淆矩阵:") # 打印混淆矩阵
print(confusion_matrix(y_test, best_pred)) # 打印混淆矩阵
#LightGBM和KNN 尝试用下贝叶斯优化和网格搜索
# --- 3. LightGBM ---
print("--- 3. LightGBM ---")
import lightgbm as lgb # 导入LightGBM库
# 定义LightGBM模型,设置 verbose=-1 以忽略警告信息
lgb_model = lgb.LGBMClassifier(random_state=42, verbose=-1) # 创建LightGBM分类器,random_state=42用于设置随机种子,保证每次运行结果一致
# 定义参数网格,这里我们只调整n_estimators和max_depth,因为这两个参数对模型性能影响最大
param_grid = {
'n_estimators': [50, 100, 200], # 树的数量
'max_depth': [None, 10, 20, 30], # 树的最大深度
'min_child_samples': [1, 2, 4] # 子样本数
}
# 创建网格搜索对象,使用5折交叉验证
grid_search = GridSearchCV(estimator=lgb_model, # 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)) # 打印混淆矩阵
#贝叶斯优化后的LightGBM
print("--- 3. 贝叶斯优化LightGBM ---")
from skopt import BayesSearchCV # 用于进行贝叶斯优化
from skopt.space import Integer # 用于定义整数类型的搜索空间
# 定义要搜索的参数空间,这里我们只调整n_estimators和max_depth,因为这两个参数对模型性能影响最大
search_space = {
'n_estimators': Integer(50, 200), # 树的数量
'max_depth': Integer(10, 30), # 树的最大深度
'min_child_samples': Integer(1, 4) # 子样本数
}
# 创建贝叶斯优化搜索对象,使用5折交叉验证
bayes_search = BayesSearchCV(
estimator=lgb_model, # LightGBM分类器
search_spaces=search_space, # 参数空间
n_iter=50, # 搜索迭代次数
cv=5, # 5折交叉验证
n_jobs=-1, # 使用所有可用的CPU核心进行并行计算
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_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)) # 打印混淆矩阵
#KNN
print("--- 4. KNN ---")
from sklearn.neighbors import KNeighborsClassifier # 导入KNN分类器
# 定义KNN模型
knn_model = KNeighborsClassifier() # 创建KNN分类器
# 定义参数网格,这里我们只调整n_neighbors和weights,因为这两个参数对模型性能影响最大
param_grid = {
'n_neighbors': [3, 5, 7, 9], # K值
'weights': ['uniform', 'distance'] # 权重
}
# 创建网格搜索对象,使用5折交叉验证
grid_search = GridSearchCV(estimator=knn_model, # KNN分类器
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} 秒") # 打印网格搜索0耗时
print("最佳参数: ", grid_search.best_params_) #best_params_属性返回最佳参数组合
# 使用最佳参数的模型进行预测
best_model = grid_search.best_estimator_ # 获取最佳模型
best_pred = best_model.predict(X_test) # 在测试集上进行预测
print("\n网格搜索优化后的KNN 在测试集上的分类报告:") # 打印分类报告
print(classification_report(y_test, best_pred)) # 打印分类报告
print("网格搜索优化后的KNN 在测试集上的混淆矩阵:") # 打印混淆矩阵
print(confusion_matrix(y_test, best_pred)) # 打印混淆矩阵
#贝叶斯优化后的KNN
print("--- 4. 贝叶斯优化KNN ---")
from skopt import BayesSearchCV # 用于进行贝叶斯优化
from skopt.space import Integer # 用于定义整数类型的搜索空间
# 定义要搜索的参数空间,这里我们只调整n_neighbors和weights,因为这两个参数对模型性能影响最大
search_space = {
'n_neighbors': Integer(3, 9), # K值
'weights': ['uniform', 'distance'] # 权重
}
# 创建贝叶斯优化搜索对象,使用5折交叉验证
bayes_search = BayesSearchCV(
estimator=knn_model, # KNN分类器
search_spaces=search_space, # 参数空间
n_iter=50, # 搜索迭代次数
cv=5, # 5折交叉验证
n_jobs=-1, # 使用所有可用的CPU核心进行并行计算
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_params_属性返回最佳参数组合
# 使用最佳参数的模型进行预测
best_model = bayes_search.best_estimator_ # 获取最佳模型
best_pred = best_model.predict(X_test) # 在测试集上进行预测
print("\n贝叶斯优化后的KNN 在测试集上的分类报告:") # 打印分类报告
print(classification_report(y_test, best_pred)) # 打印分类报告
print("贝叶斯优化后的KNN 在测试集上的混淆矩阵:") # 打印混淆矩阵
print(confusion_matrix(y_test, best_pred)) # 打印混淆矩阵
输出相关网格和贝叶斯优化
--- 1. 默认参数随机森林 (训练集 -> 测试集) ---
训练与预测耗时: 1.2259 秒
默认随机森林 在测试集上的分类报告:
precision recall f1-score support
0 0.76 0.96 0.85 521
1 0.78 0.31 0.45 229
accuracy 0.76 750
macro avg 0.77 0.64 0.65 750
weighted avg 0.77 0.76 0.73 750
默认随机森林 在测试集上的混淆矩阵:
--- 2. 网格搜索优化随机森林 ---
网格搜索耗时: 93.3410 秒
最佳参数: {'max_depth': 20, 'min_samples_leaf': 1, 'min_samples_split': 2, 'n_estimators': 200}
网格搜索优化后的随机森林 在测试集上的分类报告:
precision recall f1-score support
0 0.75 0.97 0.85 521
1 0.79 0.28 0.42 229
accuracy 0.76 750
macro avg 0.77 0.63 0.63 750
weighted avg 0.77 0.76 0.72 750
网格搜索优化后的随机森林 在测试集上的混淆矩阵:
[[504 17]
[164 65]]
--- 2. 贝叶斯优化随机森林 ---
贝叶斯优化耗时: 103.2901 秒
最佳参数: OrderedDict([('max_depth', 24), ('min_samples_leaf', 4), ('min_samples_split', 3), ('n_estimators', 51)])
贝叶斯优化后的随机森林 在测试集上的分类报告:
precision recall f1-score support
0 0.75 0.97 0.85 521
1 0.79 0.28 0.41 229
accuracy 0.76 750
macro avg 0.77 0.62 0.63 750
weighted avg 0.76 0.76 0.71 750
贝叶斯优化后的随机森林 在测试集上的混淆矩阵:
[[504 17]
[166 63]]
--- 3. LightGBM ---
网格搜索耗时: 24.6369 秒
最佳参数: {'max_depth': None, 'min_child_samples': 1, 'n_estimators': 50}
网格搜索优化后的LightGBM 在测试集上的分类报告:
precision recall f1-score support
0 0.76 0.96 0.85 521
1 0.78 0.29 0.43 229
accuracy 0.76 750
macro avg 0.77 0.63 0.64 750
weighted avg 0.76 0.76 0.72 750
网格搜索优化后的LightGBM 在测试集上的混淆矩阵:
[[502 19]
[162 67]]
--- 3. 贝叶斯优化LightGBM ---
贝叶斯优化耗时: 55.7114 秒
最佳参数: OrderedDict([('max_depth', 10), ('min_child_samples', 3), ('n_estimators', 50)])
贝叶斯优化后的LightGBM 在测试集上的分类报告:
precision recall f1-score support
0 0.76 0.96 0.85 521
1 0.76 0.31 0.44 229
accuracy 0.76 750
macro avg 0.76 0.63 0.64 750
weighted avg 0.76 0.76 0.72 750
贝叶斯优化后的LightGBM 在测试集上的混淆矩阵:
[[499 22]
[158 71]]
--- 4. KNN ---
网格搜索耗时: 0.7994 秒
最佳参数: {'n_neighbors': 9, 'weights': 'uniform'}
网格搜索优化后的KNN 在测试集上的分类报告:
precision recall f1-score support
0 0.71 0.89 0.79 521
1 0.39 0.16 0.23 229
accuracy 0.67 750
macro avg 0.55 0.53 0.51 750
weighted avg 0.61 0.67 0.62 750
网格搜索优化后的KNN 在测试集上的混淆矩阵:
[[463 58]
[192 37]]
--- 4. 贝叶斯优化KNN ---
贝叶斯优化耗时: 31.7997 秒
最佳参数: OrderedDict([('n_neighbors', 8), ('weights', 'uniform')])
贝叶斯优化后的KNN 在测试集上的分类报告:
precision recall f1-score support
0 0.70 0.94 0.80 521
1 0.41 0.09 0.15 229
accuracy 0.68 750
macro avg 0.56 0.52 0.48 750
weighted avg 0.61 0.68 0.60 750
贝叶斯优化后的KNN 在测试集上的混淆矩阵:
[[491 30]
[208 21]]