Day 13 Python Study
·
作业:
- 对其他模型采用这几种算法尝试优化超参数
- 尝试写出退火算法的背后思想和案例
# 先运行之前预处理好的代码
import pandas as pd
import pandas as pd #用于数据处理和分析,可处理表格数据。
import numpy as np #用于数值计算,提供了高效的数组操作。
import matplotlib.pyplot as plt #用于绘制各种类型的图表
import seaborn as sns #基于matplotlib的高级绘图库,能绘制更美观的统计图形。
import warnings
warnings.filterwarnings('ignore') #忽略警告信息,保持输出清洁。
# 设置中文字体(解决中文显示问题)
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%测试集
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
warnings.filterwarnings("ignore") # 忽略警告信息
# --- 1. 默认参数的LightGBM ---
print("--- 1. 默认参数LightGBM (训练集 -> 测试集) ---")
import time
start_time = time.time() # 记录开始时间
# 初始化LightGBM分类器(使用默认参数,设置随机种子保证可复现性)
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默认LightGBM 在测试集上的分类报告:")
print(classification_report(y_test, lgb_pred))
print("默认LightGBM 在测试集上的混淆矩阵:")
print(confusion_matrix(y_test, lgb_pred))

import lightgbm as lgb
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
import warnings
warnings.filterwarnings("ignore")
import time
from deap import base, creator, tools, algorithms
import random
import numpy as np
# --- 2. 遗传算法优化LightGBM ---
print("\n--- 2. 遗传算法优化LightGBM (训练集 -> 测试集) ---")
# 定义适应度函数和个体类型(最大化准确率)
creator.create("FitnessMax", base.Fitness, weights=(1.0,))
creator.create("Individual", list, fitness=creator.FitnessMax)
# 定义LightGBM核心超参数的搜索范围(根据经验调整)
# 整数参数:n_estimators(树数量)、max_depth(树深度)、num_leaves(叶子数量)、min_child_samples(叶子最小样本数)
# 浮点数参数:learning_rate(学习率)
n_estimators_range = (50, 300) # 树的数量范围
learning_rate_range = (0.01, 0.3) # 学习率范围(浮点数)
max_depth_range = (5, 15) # 树的最大深度
num_leaves_range = (20, 150) # 叶子节点数量(通常num_leaves < 2^max_depth)
min_child_samples_range = (2, 20) # 每个叶子的最小样本数
# 初始化工具盒
toolbox = base.Toolbox()
# 注册基因生成器(区分整数和浮点数参数)
toolbox.register("attr_n_estimators", random.randint, *n_estimators_range)
toolbox.register("attr_learning_rate", random.uniform, *learning_rate_range) # 浮点数生成
toolbox.register("attr_max_depth", random.randint, *max_depth_range)
toolbox.register("attr_num_leaves", random.randint, *num_leaves_range)
toolbox.register("attr_min_child_samples", random.randint, *min_child_samples_range)
# 定义个体生成器(组合5个超参数作为基因)
toolbox.register("individual", tools.initCycle, creator.Individual,
(toolbox.attr_n_estimators,
toolbox.attr_learning_rate,
toolbox.attr_max_depth,
toolbox.attr_num_leaves,
toolbox.attr_min_child_samples),
n=1) # n=1表示每个基因只取一次
# 定义种群生成器
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
# 定义评估函数(计算个体的适应度:模型在测试集上的准确率)
def evaluate(individual):
# 解包个体的超参数(顺序与基因生成器一致)
n_estimators, learning_rate, max_depth, num_leaves, min_child_samples = individual
# 初始化LightGBM模型(固定随机种子保证可复现性)
model = lgb.LGBMClassifier(
n_estimators=int(n_estimators), # 确保整数类型
learning_rate=learning_rate,
max_depth=int(max_depth),
num_leaves=int(num_leaves),
min_child_samples=int(min_child_samples),
random_state=42,
verbose=-1 # 关闭训练日志输出
)
# 训练模型并预测
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("select", tools.selTournament, tournsize=3) # 锦标赛选择
# 自定义变异操作(区分整数和浮点数参数的变异方式)
def mutate_individual(individual, indpb=0.1):
# 对每个基因进行变异(按概率)
for i in range(len(individual)):
if random.random() < indpb:
# 第0个基因:n_estimators(整数)
if i == 0:
individual[i] = random.randint(*n_estimators_range)
# 第1个基因:learning_rate(浮点数)
elif i == 1:
individual[i] = random.uniform(*learning_rate_range)
# 第2个基因:max_depth(整数)
elif i == 2:
individual[i] = random.randint(*max_depth_range)
# 第3个基因:num_leaves(整数)
elif i == 3:
individual[i] = random.randint(*num_leaves_range)
# 第4个基因:min_child_samples(整数)
elif i == 4:
individual[i] = random.randint(*min_child_samples_range)
return individual,
toolbox.register("mutate", mutate_individual, indpb=0.1) # 注册自定义变异函数
# 初始化种群(20个个体)
pop = toolbox.population(n=20)
# 遗传算法参数
NGEN = 10 # 迭代代数
CXPB = 0.5 # 交叉概率
MUTPB = 0.2 # 变异概率
start_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 = fit
# 选择下一代种群
pop = toolbox.select(offspring, k=len(pop))
end_time = time.time()
# 提取最优个体(适应度最高的参数组合)
best_ind = tools.selBest(pop, k=1)[0]
best_n_estimators, best_learning_rate, best_max_depth, best_num_leaves, best_min_child_samples = best_ind
# 输出优化结果
print(f"遗传算法优化耗时: {end_time - start_time:.4f} 秒")
print("最佳参数: ", {
'n_estimators': int(best_n_estimators),
'learning_rate': round(best_learning_rate, 4),
'max_depth': int(best_max_depth),
'num_leaves': int(best_num_leaves),
'min_child_samples': int(best_min_child_samples)
})
# 使用最优参数训练LightGBM并评估
best_model = lgb.LGBMClassifier(
n_estimators=int(best_n_estimators),
learning_rate=best_learning_rate,
max_depth=int(best_max_depth),
num_leaves=int(best_num_leaves),
min_child_samples=int(best_min_child_samples),
random_state=42,
verbose=-1
)
best_model.fit(X_train, y_train)
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))

import lightgbm as lgb
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
import warnings
warnings.filterwarnings("ignore")
import time
import random
import numpy as np
# --- 2. 粒子群优化算法优化LightGBM ---
print("\n--- 2. 粒子群优化算法优化LightGBM (训练集 -> 测试集) ---")
# 定义适应度函数:参数组合→模型准确率
def fitness_function(params):
# 解包参数(顺序与bounds一致):n_estimators, learning_rate, max_depth, num_leaves, min_child_samples
n_estimators, learning_rate, max_depth, num_leaves, min_child_samples = params
# 初始化LightGBM模型(整数参数强制转换,浮点数直接使用)
model = lgb.LGBMClassifier(
n_estimators=int(n_estimators), # 树的数量(整数)
learning_rate=learning_rate, # 学习率(浮点数)
max_depth=int(max_depth), # 树深度(整数)
num_leaves=int(num_leaves), # 叶子数量(整数)
min_child_samples=int(min_child_samples), # 叶子最小样本数(整数)
random_state=42,
verbose=-1 # 关闭训练日志
)
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_params = len(bounds) # 超参数数量(此处为5个)
# 初始化粒子位置(在参数范围内随机生成)
particles = np.array([
[random.uniform(bounds[i][0], bounds[i][1]) for i in range(num_params)]
for _ in range(num_particles)
])
# 初始化速度(全为0)
velocities = np.zeros((num_particles, num_params))
# 初始化个体最佳位置和适应度
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、r2用于平衡认知和社会学习)
r1 = np.random.random((num_particles, num_params))
r2 = np.random.random((num_particles, num_params))
# 更新速度(惯性+认知项+社会项)
velocities = w * velocities + c1 * r1 * (personal_best - particles) + c2 * r2 * (global_best - particles)
# 更新位置
particles = particles + velocities
# 边界处理:确保参数在预设范围内
for 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_fitness
personal_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
# LightGBM超参数范围(根据模型特性调整)
# 顺序:n_estimators(树数量)、learning_rate(学习率)、max_depth(树深度)、num_leaves(叶子数)、min_child_samples(叶子最小样本数)
bounds = [
(50, 300), # n_estimators(整数范围)
(0.01, 0.3), # learning_rate(浮点数范围,LightGBM核心参数)
(5, 15), # max_depth(控制树深度,防止过拟合)
(20, 150), # num_leaves(叶子数量,通常小于2^max_depth)
(2, 20) # min_child_samples(叶子最小样本数,防止过拟合)
]
# 粒子群算法参数(保持与原逻辑一致)
num_particles = 20 # 粒子数量
num_iterations = 10 # 迭代次数
c1 = 1.5 # 认知学习因子
c2 = 1.5 # 社会学习因子
w = 0.5 # 惯性权重
# 运行PSO优化
start_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]),
'learning_rate': round(best_params[1], 4), # 浮点数保留4位小数
'max_depth': int(best_params[2]),
'num_leaves': int(best_params[3]),
'min_child_samples': int(best_params[4])
})
# 使用最佳参数训练LightGBM并评估
best_model = lgb.LGBMClassifier(
n_estimators=int(best_params[0]),
learning_rate=best_params[1],
max_depth=int(best_params[2]),
num_leaves=int(best_params[3]),
min_child_samples=int(best_params[4]),
random_state=42,
verbose=-1
)
best_model.fit(X_train, y_train)
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))

更多推荐
所有评论(0)