day12:遗传算法及常见优化算法分享
遗传算法这些常见优化算法简直是 “宝藏素材”!用好了,轻轻松松就能填满论文一整节内容;要是研究透彻,甚至能独立撑起一整个章节。今天不打算深入展开,有个基础认知就行。等之后写论文真要用到这些算法了,咱们再一起深入钻研!
一、数据预处理与模型基线搭建
老规矩,先运行之前预处理好的代码。咱们的目标是用这些优化算法找到机器学习模型的最佳超参数,所以得先把数据准备好,跑一个基线模型出来。
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('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("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].fillna(mode_value, inplace=True) #用众数填充该列的缺失值,inplace=True表示直接在原数据上修改。# 最开始也说了 很多调参函数自带交叉验证,甚至是必选的参数,你如果想要不交叉反而实现起来会麻烦很多
# 所以这里我们还是只划分一次数据集
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_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # 80%训练集,20%测试集
数据处理完了,接下来用随机森林分类器跑个基线模型。我给大家加了个time
库,记录一下训练和预测的耗时,这样以后别人跑代码心里也有个数。
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)
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("默认随机森林 在测试集上的混淆矩阵:")
print(confusion_matrix(y_test, rf_pred))
运行结果如下:
这个就是咱们的基线模型结果了,接下来就靠优化算法来超越它!
二、核心思想:优化算法的 “寻宝逻辑”
在说具体算法之前,先和大家唠唠这些启发式算法的核心思想。咱们的目标是找到一组超参数,让机器学习模型在某个指标(比如验证集准确率)上表现最好。这就好比在一片复杂的大山上找最高峰,但这座山的地形特别复杂,没有现成的地图(也就是不知道参数空间每一处的精确梯度)。而这些启发式算法就像是一群聪明的 “探险家”,它们各自用不同的策略去寻找这座最高峰。有的模仿生物进化,有的模拟物理现象,总之各有各的绝活。
三、遗传算法:生物进化的奇妙映射
遗传算法(Genetic Algorithm - GA)的灵感来源于生物进化,也就是达尔文提出的 “适者生存” 理论。我是这么理解的:把不同的超参数组合想象成一群 “个体”。那些在验证集上表现好的个体,就像自然界里适应环境的生物,更有机会 “繁殖”—— 说白了,就是它们的参数组合会被借鉴和混合,产生新的参数组合。在这个过程中,还可能发生 “变异”,也就是参数会随机地小改动。而表现差的个体,就慢慢被淘汰了。这样一代一代进化下去,整个种群就会越来越适应环境,咱们也就一步步逼近最佳超参数了。这种算法给我的感觉就是在大范围 “撒网” 搜索,特别适合参数空间很大、情况很复杂的场景。下面是用遗传算法优化随机森林的代码,这里用了DEAP
库,它是专门用来搞遗传算法和进化计算的。
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")
import time
from deap import base, creator, tools, algorithms # DEAP是一个用于遗传算法和进化计算的Python库
import random
import numpy as np# --- 2. 遗传算法优化随机森林 ---
print("\n--- 2. 遗传算法优化随机森林 (训练集 -> 测试集) ---")# 定义适应度函数和个体类型
creator.create("FitnessMax", base.Fitness, weights=(1.0,))
creator.create("Individual", list, fitness=creator.FitnessMax)# 定义超参数范围
n_estimators_range = (50, 200)
max_depth_range = (10, 30)
min_samples_split_range = (2, 10)
min_samples_leaf_range = (1, 4)# 初始化工具盒
toolbox = base.Toolbox()# 定义基因生成器
toolbox.register("attr_n_estimators", random.randint, *n_estimators_range)
toolbox.register("attr_max_depth", random.randint, *max_depth_range)
toolbox.register("attr_min_samples_split", random.randint, *min_samples_split_range)
toolbox.register("attr_min_samples_leaf", random.randint, *min_samples_leaf_range)# 定义个体生成器
toolbox.register("individual", tools.initCycle, creator.Individual,(toolbox.attr_n_estimators, toolbox.attr_max_depth,toolbox.attr_min_samples_split, toolbox.attr_min_samples_leaf), n=1)# 定义种群生成器
toolbox.register("population", tools.initRepeat, list, toolbox.individual)# 定义评估函数
def evaluate(individual):n_estimators, max_depth, min_samples_split, min_samples_leaf = individualmodel = RandomForestClassifier(n_estimators=n_estimators,max_depth=max_depth,min_samples_split=min_samples_split,min_samples_leaf=min_samples_leaf,random_state=42)model.fit(X_train, y_train)y_pred = model.predict(X_test)accuracy = accuracy_score(y_test, y_pred)return accuracy,# 注册评估函数
toolbox.register("evaluate", evaluate)# 注册遗传操作
toolbox.register("mate", tools.cxTwoPoint)
toolbox.register("mutate", tools.mutUniformInt, low=[n_estimators_range[0], max_depth_range[0],min_samples_split_range[0], min_samples_leaf_range[0]],up=[n_estimators_range[1], max_depth_range[1],min_samples_split_range[1], min_samples_leaf_range[1]], indpb=0.1)
toolbox.register("select", tools.selTournament, tournsize=3)# 初始化种群
pop = toolbox.population(n=20)# 遗传算法参数
NGEN = 10
CXPB = 0.5
MUTPB = 0.2start_time = time.time()
# 运行遗传算法
for gen in range(NGEN):offspring = algorithms.varAnd(pop, toolbox, cxpb=CXPB, mutpb=MUTPB)fits = toolbox.map(toolbox.evaluate, offspring)for fit, ind in zip(fits, offspring):ind.fitness.values = fitpop = toolbox.select(offspring, k=len(pop))end_time = time.time()# 找到最优个体
best_ind = tools.selBest(pop, k=1)[0]
best_n_estimators, best_max_depth, best_min_samples_split, best_min_samples_leaf = best_indprint(f"遗传算法优化耗时: {end_time - start_time:.4f} 秒")
print("最佳参数: ", {'n_estimators': best_n_estimators,'max_depth': best_max_depth,'min_samples_split': best_min_samples_split,'min_samples_leaf': best_min_samples_leaf
})# 使用最佳参数的模型进行预测
best_model = RandomForestClassifier(n_estimators=best_n_estimators,max_depth=best_max_depth,min_samples_split=best_min_samples_split,min_samples_leaf=best_min_samples_leaf,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))
运行结果如下:
--- 2. 遗传算法优化随机森林 (训练集 -> 测试集) ---
遗传算法优化耗时: 251.5941 秒
最佳参数: {'n_estimators': 158, 'max_depth': 25, 'min_samples_split': 10, 'min_samples_leaf': 1}遗传算法优化后的随机森林 在测试集上的分类报告:precision recall f1-score support0 0.77 0.98 0.86 10591 0.83 0.28 0.42 441accuracy 0.77 1500macro avg 0.80 0.63 0.64 1500
weighted avg 0.79 0.77 0.73 1500遗传算法优化后的随机森林 在测试集上的混淆矩阵:
[[1034 25][ 316 125]]
不过说实话,这段代码看着确实复杂,而且复用性也不高。就算我花时间搞懂了,对我的提升也有限,因为很难基于它做改进。所以我觉得,在 AI 时代,咱们没必要死磕这些代码细节。咱们只需要关注三个重点:输入输出的数据格式、算法的原理和适用场景、模型的大致实现逻辑(如果用得少,这部分甚至可以跳过,直接让 AI 帮忙)。
四、粒子群优化:鸟群觅食的智慧
粒子群优化(Particle Swarm Optimization - PSO)的灵感来自鸟群或鱼群觅食。想象一下,每个超参数组合都是一只 “粒子鸟”,它们在参数空间里 “飞来飞去”。每只鸟都会记住自己飞过的最好位置,同时也会参考整个鸟群发现的最好位置,然后综合这两个信息,调整自己的飞行方向和速度,当然这个过程也会带点随机性。
这种算法给我的感觉就是一群探险家一边探索,一边互相分享信息,大家齐心协力找目标。而且通常来说,它收敛的速度比遗传算法还要快一些。
粒子群方法的思想比较简单,所以甚至可以不调库自己实现。
# --- 2. 粒子群优化算法优化随机森林 ---
print("\n--- 2. 粒子群优化算法优化随机森林 (训练集 -> 测试集) ---")# 定义适应度函数,本质就是构建了一个函数实现 参数--> 评估指标的映射
def fitness_function(params): n_estimators, max_depth, min_samples_split, min_samples_leaf = params # 序列解包,允许你将一个可迭代对象(如列表、元组、字符串等)中的元素依次赋值给多个变量。model = RandomForestClassifier(n_estimators=int(n_estimators),max_depth=int(max_depth),min_samples_split=int(min_samples_split),min_samples_leaf=int(min_samples_leaf),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 pso(num_particles, num_iterations, c1, c2, w, bounds): # 粒子群优化算法核心函数# num_particles:粒子的数量,即算法中用于搜索最优解的个体数量。# num_iterations:迭代次数,算法运行的最大循环次数。# c1:认知学习因子,用于控制粒子向自身历史最佳位置移动的程度。# c2:社会学习因子,用于控制粒子向全局最佳位置移动的程度。# w:惯性权重,控制粒子的惯性,影响粒子在搜索空间中的移动速度和方向。# bounds:超参数的取值范围,是一个包含多个元组的列表,每个元组表示一个超参数的最小值和最大值。num_params = len(bounds) particles = np.array([[random.uniform(bounds[i][0], bounds[i][1]) for i in range(num_params)] for _ inrange(num_particles)])velocities = np.array([[0] * num_params for _ in range(num_particles)])personal_best = particles.copy()personal_best_fitness = np.array([fitness_function(p) for p in particles])global_best_index = np.argmax(personal_best_fitness)global_best = personal_best[global_best_index]global_best_fitness = personal_best_fitness[global_best_index]for _ in range(num_iterations):r1 = np.array([[random.random() for _ in range(num_params)] for _ in range(num_particles)])r2 = np.array([[random.random() for _ in range(num_params)] for _ in range(num_particles)])velocities = w * velocities + c1 * r1 * (personal_best - particles) + c2 * r2 * (global_best - particles)particles = particles + velocitiesfor i in range(num_particles):for j in range(num_params):if particles[i][j] < bounds[j][0]:particles[i][j] = bounds[j][0]elif particles[i][j] > bounds[j][1]:particles[i][j] = bounds[j][1]fitness_values = np.array([fitness_function(p) for p in particles])improved_indices = fitness_values > personal_best_fitnesspersonal_best[improved_indices] = particles[improved_indices]personal_best_fitness[improved_indices] = fitness_values[improved_indices]current_best_index = np.argmax(personal_best_fitness)if personal_best_fitness[current_best_index] > global_best_fitness:global_best = personal_best[current_best_index]global_best_fitness = personal_best_fitness[current_best_index]return global_best, global_best_fitness# 超参数范围
bounds = [(50, 200), (10, 30), (2, 10), (1, 4)] # n_estimators, max_depth, min_samples_split, min_samples_leaf# 粒子群优化算法参数
num_particles = 20
num_iterations = 10
c1 = 1.5
c2 = 1.5
w = 0.5start_time = time.time()
best_params, best_fitness = pso(num_particles, num_iterations, c1, c2, w, bounds)
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)
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))
运行结果如下:
--- 2. 粒子群优化算法优化随机森林 (训练集 -> 测试集) ---
粒子群优化算法优化耗时: 374.1755 秒
最佳参数: {'n_estimators': 200, 'max_depth': 18, 'min_samples_split': 4, 'min_samples_leaf': 1}粒子群优化算法优化后的随机森林 在测试集上的分类报告:precision recall f1-score support0 0.77 0.98 0.86 10591 0.83 0.29 0.43 441accuracy 0.77 1500macro avg 0.80 0.63 0.64 1500
weighted avg 0.79 0.77 0.73 1500粒子群优化算法优化后的随机森林 在测试集上的混淆矩阵:
[[1034 25][ 315 126]]
五、退火算法:模拟退火的奇妙探索
模拟退火(Simulated Annealing - SA)的灵感来源于金属冶炼中的退火过程,也就是通过缓慢冷却使金属达到最低能量稳定态。
简单理解这个算法就是,从一个随机的超参数组合开始,然后随机尝试对参数进行一点改变。如果新的参数组合能让模型表现更好,那就直接接受它;但如果新组合反而更差了,也还是有一定概率接受它,尤其是在算法执行的早期,也就是 “高温” 阶段。随着算法的运行,这个接受较差解的概率会像温度下降一样,慢慢变小。
这种算法就像一个一开始有点 “冲动” 的探险家,愿意去尝试一些看起来不太好的路径,这样做是为了避免陷入局部最优的困境;而到了后期,它就变得越来越 “保守”,专注于在当前找到的较好区域附近进行精细搜索,所以它很擅长避免陷入局部最优解。
# --- 2. 模拟退火算法优化随机森林 ---
print("\n--- 2. 模拟退火算法优化随机森林 (训练集 -> 测试集) ---")# 定义适应度函数
def fitness_function(params): n_estimators, max_depth, min_samples_split, min_samples_leaf = paramsmodel = RandomForestClassifier(n_estimators=int(n_estimators),max_depth=int(max_depth),min_samples_split=int(min_samples_split),min_samples_leaf=int(min_samples_leaf),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(initial_solution, bounds, initial_temp, final_temp, alpha):current_solution = initial_solutioncurrent_fitness = fitness_function(current_solution)best_solution = current_solutionbest_fitness = current_fitnesstemp = initial_tempwhile temp > final_temp:# 生成邻域解neighbor_solution = []for i in range(len(current_solution)):new_val = current_solution[i] + random.uniform(-1, 1) * (bounds[i][1] - bounds[i][0]) * 0.1new_val = max(bounds[i][0], min(bounds[i][1], new_val))neighbor_solution.append(new_val)neighbor_fitness = fitness_function(neighbor_solution)delta_fitness = neighbor_fitness - current_fitnessif delta_fitness > 0 or random.random() < np.exp(delta_fitness / temp):current_solution = neighbor_solutioncurrent_fitness = neighbor_fitnessif current_fitness > best_fitness:best_solution = current_solutionbest_fitness = current_fitnesstemp *= alphareturn 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 # 温度衰减系数# 初始化初始解
initial_solution = [random.uniform(bounds[i][0], bounds[i][1]) for i in range(len(bounds))]start_time = time.time()
best_params, best_fitness = simulated_annealing(initial_solution, bounds, initial_temp, final_temp, alpha)
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)
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))
运行结果如下:
--- 2. 模拟退火算法优化随机森林 (训练集 -> 测试集) ---
模拟退火算法优化耗时: 129.1660 秒
最佳参数: {'n_estimators': 98, 'max_depth': 16, 'min_samples_split': 7, 'min_samples_leaf': 2}模拟退火算法优化后的随机森林 在测试集上的分类报告:precision recall f1-score support0 0.77 0.98 0.86 10591 0.86 0.29 0.43 441accuracy 0.78 1500macro avg 0.82 0.63 0.65 1500
weighted avg 0.80 0.78 0.73 1500模拟退火算法优化后的随机森林 在测试集上的混淆矩阵:
[[1039 20][ 315 126]]
@浙大疏锦行