5.02py打卡

@浙大疏锦行
知识点复习

1.  不平衡数据集的处理策略:过采样、修改权重、修改阈值

2.  交叉验证代码

题目:从示例代码可以看到 效果没有变好,所以很多步骤都是理想是好的,但是显示并不一定可以变好。这个实验仍然有改进空间,如下。

1. 我还没做smote+过采样+修改权重的组合策略,有可能一起做会变好。

2. 我还没有调参,有可能调参后再取上述策略可能会变好

针对上面这2个探索路径,继续尝试下去,看看是否符合猜测。

结果:(遗传算法参数优化+smote过采样+阈值调参)

性能对比 (测试集上的少数类召回率 Recall):
  默认模型: 0.8621
  带权重模型: 0.9310

import pandas as pd    #用于数据处理和分析,可处理表格数据。
import numpy as np     #用于数值计算,提供了高效的数组操作。
import matplotlib.pyplot as plt    #用于绘制各种类型的图表
import seaborn as sns   #基于matplotlib的高级绘图库,能绘制更美观的统计图形。
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import StratifiedKFold, cross_validate # 引入分层 K 折和交叉验证工具
from sklearn.metrics import make_scorer, accuracy_score, precision_score, recall_score, f1_score, confusion_matrix, classification_report
import time
import warnings
warnings.filterwarnings("ignore")
# 设置中文字体(解决中文显示问题)
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就是独热编码后的特征名
# 划分训练集和测试机
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%测试集
# --- 1. 默认参数的随机森林 ---
print("--- 1. 默认参数随机森林 (训练集 -> 测试集) ---")
start_time = time.time()
rf_model_default = RandomForestClassifier(random_state=42)
rf_model_default.fit(X_train, y_train)
rf_pred_default = rf_model_default.predict(X_test)
end_time = time.time()
print(f"默认模型训练与预测耗时: {end_time - start_time:.4f} 秒")
print("\n默认随机森林 在测试集上的分类报告:")
print(classification_report(y_test, rf_pred_default))
print("默认随机森林 在测试集上的混淆矩阵:")
print(confusion_matrix(y_test, rf_pred_default))
print("-" * 50)
from deap import base, creator, tools, algorithms # DEAP是一个用于遗传算法和进化计算的Python库
import random
# --- 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 = individual
    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)
    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.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_max_depth, best_min_samples_split, best_min_samples_leaf = best_ind
print(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))
# 1. 随机过采样
from imblearn.over_sampling import RandomOverSampler
ros = RandomOverSampler(random_state=42) # 创建随机过采样对象
X_train_ros, y_train_ros = ros.fit_resample(X_train, y_train) # 对训练集进行随机过采样
print("随机过采样后训练集的形状:", X_train_ros.shape, y_train_ros.shape) 
# 训练随机森林模型(使用随机过采样后的训练集)
start_time_ros = time.time()
best_model.fit(X_train_ros, y_train_ros)
end_time_ros = time.time()
print(f"随机过采样后训练与预测耗时: {end_time_ros - start_time_ros:.4f} 秒")
# 在测试集上预测
rf_pred_ros = best_model.predict(X_test)
print("\n随机过采样后随机森林 在测试集上的分类报告:")
print(classification_report(y_test, rf_pred_ros))
print("随机过采样后随机森林 在测试集上的混淆矩阵:")
print(confusion_matrix(y_test, rf_pred_ros))
# SMOTE过采样
from imblearn.over_sampling import SMOTE 
smote = SMOTE(random_state=42)
X_train_smote, y_train_smote = smote.fit_resample(X_train, y_train)
print("SMOTE过采样后训练集的形状:", X_train_smote.shape, y_train_smote.shape)
# 训练随机森林模型(使用SMOTE过采样后的训练集)
start_time_smote = time.time()
best_model.fit(X_train_smote, y_train_smote)
end_time_smote = time.time()
print(f"SMOTE过采样后训练与预测耗时: {end_time_smote - start_time_smote:.4f} 秒")
# 在测试集上预测
rf_pred_smote = best_model.predict(X_test)
print("\nSMOTE过采样后随机森林 在测试集上的分类报告:")
print(classification_report(y_test, rf_pred_smote))
print("SMOTE过采样后随机森林 在测试集上的混淆矩阵:")
print(confusion_matrix(y_test, rf_pred_smote))
# --- 2. 带权重的随机森林 + 交叉验证 (在训练集上进行CV) ---
print("--- 2. 带权重随机森林 + 交叉验证 (在训练集上进行) ---")
# 确定少数类标签
counts = np.bincount(y_train)
minority_label = np.argmin(counts) # 找到计数最少的类别的标签
majority_label = np.argmax(counts)
print(f"训练集中各类别数量: {counts}")
print(f"少数类标签: {minority_label}, 多数类标签: {majority_label}")
# 定义带权重的模型
rf_model_weighted = 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,
    class_weight='balanced'
)
from sklearn.model_selection import StratifiedKFold, cross_validate # 引入分层 K 折和交叉验证工具
# 设置交叉验证策略 (使用 StratifiedKFold 保证每折类别比例相似)
cv_strategy = StratifiedKFold(n_splits=5, shuffle=True, random_state=42) # 5折交叉验证
# 定义用于交叉验证的评估指标
# 特别关注少数类的指标,使用 make_scorer 指定 pos_label
# 注意:如果你的少数类标签不是 1,需要修改 pos_label
scoring = {
    'accuracy': 'accuracy',
    'precision_minority': make_scorer(precision_score, pos_label=minority_label, zero_division=0),
    'recall_minority': make_scorer(recall_score, pos_label=minority_label),
    'f1_minority': make_scorer(f1_score, pos_label=minority_label)
}
print(f"开始进行 {cv_strategy.get_n_splits()} 折交叉验证...")
start_time_cv = time.time()
# 执行交叉验证 (在 X_train, y_train 上进行)
# cross_validate 会自动完成训练和评估过程
cv_results = cross_validate(
    estimator=rf_model_weighted,
    X=X_train,
    y=y_train,
    cv=cv_strategy,
    scoring=scoring,
    n_jobs=-1, # 使用所有可用的 CPU 核心
    return_train_score=False # 通常我们更关心测试折的得分
)
end_time_cv = time.time()
print(f"交叉验证耗时: {end_time_cv - start_time_cv:.4f} 秒")
# 打印交叉验证结果的平均值
print("\n带权重随机森林 交叉验证平均性能 (基于训练集划分):")
for metric_name, scores in cv_results.items():
    if metric_name.startswith('test_'): # 我们关心的是在验证折上的表现
        # 提取指标名称(去掉 'test_' 前缀)
        clean_metric_name = metric_name.split('test_')[1]
        print(f"  平均 {clean_metric_name}: {np.mean(scores):.4f} (+/- {np.std(scores):.4f})")
print("-" * 50)
# --- 3. 使用权重训练最终模型,并在测试集上评估 ---
print("--- 3. 训练最终的带权重模型 (整个训练集) 并在测试集上评估 ---")
start_time_final = time.time()
# 使用与交叉验证中相同的设置来训练最终模型
rf_model_weighted_final = 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,
    class_weight={minority_label: 3, majority_label: 1} 
)
rf_model_weighted_final.fit(X_train_smote, y_train_smote) # 在整个训练集上训练
rf_pred_weighted = rf_model_weighted_final.predict(X_test) # 在测试集上预测
end_time_final = time.time()
print(f"最终带权重模型训练与预测耗时: {end_time_final - start_time_final:.4f} 秒")
print("\n带权重随机森林 在测试集上的分类报告:")
print(classification_report(y_test, rf_pred_weighted, target_names=[f'Class {majority_label}', f'Class {minority_label}'])) 
print("带权重随机森林 在测试集上的混淆矩阵:")
print(confusion_matrix(y_test, rf_pred_weighted))
print("-" * 50)
# 对比总结 (简单示例)
print("性能对比 (测试集上的少数类召回率 Recall):")
recall_default = recall_score(y_test, rf_pred_default, pos_label=minority_label)
recall_weighted = recall_score(y_test, rf_pred_weighted, pos_label=minority_label)
print(f"  默认模型: {recall_default:.4f}")
print(f"  带权重模型: {recall_weighted:.4f}")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值