超参数调整专题2
- 三种启发式算法的示例代码:遗传算法、粒子群算法、退火算法
- 学习优化算法的思路(避免浪费无效时间)
作业:今天以自由探索的思路为主,尝试检索资料、视频、文档,用尽可能简短但是清晰的语言看是否能说清楚这三种算法每种算法的实现逻辑,帮助更深入的理解。
退火算法:
物理类比:金属退火过程中,高温时原子活动剧烈,随着温度降低逐渐趋于稳定,形成低能态晶体。
算法映射:
温度:控制搜索过程中的随机性(高温时允许接受劣解,低温时趋向稳定)。
能量函数(目标函数):需最小化的目标(如损失函数、路径长度等)。
基本思路
初始化:设定初始温度 initial_temp、终止温度 final_temp、温度衰减系数 alpha、最大迭代次数 max_iter 以及初始解。
邻域搜索:在当前解的邻域内随机生成一个新解。
(1)邻域搜索(Perturbation)
定义:在当前解附近生成新解的随机扰动方法。
示例:
旅行商问题(TSP):交换两个城市的顺序。
函数优化:在当前点附近随机偏移(如 x′=x+ϵx′=x+ϵ
计算适应度:分别计算当前解和新解的适应度(目标函数值)。
判断是否接受新解:如果新解的适应度优于当前解,则接受新解。
如果新解的适应度差于当前解,则以一定的概率接受新解,这个概率与当前温度和适应度差值有关,温度越高,接受较差解的概率越大。
温度衰减:按照温度衰减系数 alpha 降低温度。
(3)降温策略
指数降温:Tk+1=α⋅TkTk+1 =α⋅Tk (常用,简单但需调参)。
自适应降温:根据搜索过程动态调整 αα。
终止条件判断:当温度低于终止温度时,算法终止,输出当前最优解。
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("默认随机森林 在测试集上的混淆矩阵:") # 打印混淆矩阵
#退火算法
# --- 2. 模拟退火算法优化随机森林 ---
print("\n--- 2. 模拟退火算法优化随机森林 (训练集 -> 测试集) ---")
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 numpy as np #用于数值计算,提供了高效的数组操作。
import random #用于生成随机数
import math #用于数学计算
import time #用于时间相关的操作
import warnings #用于忽略警告信息
warnings.filterwarnings("ignore") # 忽略所有警告信息
# 定义模拟退火算法的目标函数,这里我们以准确率作为目标函数
def objective_function(params): #定义目标函数,params是一个包含超参数的列表,这里我们假设params是一个包含4个元素的列表,分别是n_estimators, max_depth, min_samples_split, min_samples_leaf
n_estimators, max_depth, min_samples_split, min_samples_leaf = params # 解包params列表,分别赋值给n_estimators, max_depth, min_samples_split, min_samples_leaf
model = RandomForestClassifier(n_estimators=n_estimators, max_depth=max_depth, min_samples_split=min_samples_split, min_samples_leaf=min_samples_leaf, random_state=42) # 创建随机森林分类器,random_state=42用于设置随机种子,保证每次运行结果一致
model.fit(X_train, y_train) # 在训练集上训练
y_pred = model.predict(X_test) # 在测试集上预测
accuracy = accuracy_score(y_test, y_pred) # 计算准确率
return accuracy # 返回准确率
# 模拟退火算法实现
# 模拟退火算法实现
def simulated_annealing(objective_function, bounds, initial_temp, final_temp, alpha, max_iter): #定义模拟退火算法,objective_function是目标函数,bounds是超参数的取值范围,initial_temp是初始温度,final_temp是终止温度,alpha是温度衰减系数,max_iter是最大迭代次数
# 初始化当前解,强制转换为整数
current_solution = [int(random.uniform(bounds[i][0], bounds[i][1])) for i in range(len(bounds))]
current_fitness = objective_function(current_solution) # 计算当前解的适应度
best_solution = current_solution # 初始化最佳解
best_fitness = current_fitness # 初始化最佳适应度
temp = initial_temp # 初始化温度
while temp > final_temp: # 当温度大于终止温度时,继续迭代
# 生成邻域解
neighbor_solution = [] # 初始化邻域解
for i in range(len(current_solution)): # 遍历当前解的每个元素
# 生成邻域解并强制转换为整数
neighbor_solution.append(int(current_solution[i] + random.uniform(-1, 1)))
# 限制邻域解在bounds范围内
neighbor_solution = [max(bounds[i][0], min(bounds[i][1], neighbor_solution[i])) for i in range(len(bounds))] # 限制邻域解在bounds范围内
neighbor_fitness = objective_function(neighbor_solution) # 计算邻域解的适应度
delta_fitness = neighbor_fitness - current_fitness # 计算适应度差
if delta_fitness > 0 or random.random() < math.exp(delta_fitness / temp): # 如果适应度差大于0或者随机数小于exp(delta_fitness / temp),则接受邻域解
current_solution = neighbor_solution # 更新当前解
current_fitness = neighbor_fitness # 更新当前适应度
if current_fitness > best_fitness: # 如果当前适应度大于最佳适应度,则更新最佳解和最佳适应度
best_solution = current_solution # 更新最佳解
best_fitness = current_fitness # 更新最佳适应度
temp *= alpha # 温度衰减
return best_solution, best_fitness # 返回最佳解和最佳适应度
# 超参数范围
bounds = [(50, 200), (10, 30), (2, 10), (1, 4)] # n_estimators, max_depth, min_samples_split, min_samples_leaf的取值范围
# 模拟退火算法参数
initial_temp = 100 # 初始温度
final_temp = 0.1 # 终止温度
alpha = 0.95 # 温度衰减系数
max_iter = 100 # 最大迭代次数
# 运行模拟退火算法
start_time = time.time() # 记录开始时间
best_params, best_fitness = simulated_annealing(objective_function, bounds, initial_temp, final_temp, alpha, max_iter) # 运行模拟退火算法
end_time = time.time() # 记录结束时间
print(f"模拟退火算法优化耗时: {end_time - start_time:.4f} 秒") # 打印优化耗时
print("最佳参数: ", { # 打印最佳参数
'n_estimators': int(best_params[0]), # 强制转换为整数
'max_depth': int(best_params[1]), # 强制转换为整数
'min_samples_split': int(best_params[2]), # 强制转换为整数
'min_samples_leaf': int(best_params[3]) # 强制转换为整数
})
# 使用最佳参数的模型进行预测
best_model = RandomForestClassifier(n_estimators=int(best_params[0]), max_depth=int(best_params[1]), min_samples_split=int(best_params[2]), min_samples_leaf=int(best_params[3]), random_state=42) # 创建随机森林分类器,random_state=42用于设置随机种子,保证每次运行结果一致
best_model.fit(X_train, y_train) # 在训练集上训练
best_pred = best_model.predict(X_test) # 在测试集上预测
print("\n模拟退火算法优化后的随机森林 在测试集上的分类报告:") # 打印分类报告
print(classification_report(y_test, best_pred)) # 打印分类报告
print("模拟退火算法优化后的随机森林 在测试集上的混淆矩阵:") # 打印混淆矩阵
print(confusion_matrix(y_test, best_pred)) # 打印混淆矩阵
输出:
--- 1. 默认参数随机森林 (训练集 -> 测试集) ---
训练与预测耗时: 0.9238 秒
默认随机森林 在测试集上的分类报告:
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. 模拟退火算法优化随机森林 (训练集 -> 测试集) ---
模拟退火算法优化耗时: 125.0997 秒
最佳参数: {'n_estimators': 165, 'max_depth': 15, 'min_samples_split': 2, 'min_samples_leaf': 1}
模拟退火算法优化后的随机森林 在测试集上的分类报告:
precision recall f1-score support
0 0.75 0.98 0.85 521
1 0.89 0.27 0.41 229
accuracy 0.77 750
macro avg 0.82 0.63 0.63 750
weighted avg 0.79 0.77 0.72 750
模拟退火算法优化后的随机森林 在测试集上的混淆矩阵:
[[513 8]
[167 62]]