知识点复习
1. 不平衡数据集的处理策略:过采样、修改权重、修改阈值
2. 交叉验证代码
过采样
- 过采样一般包含2种做法:随机采样和SMOTE
- 过采样是把少的类别补充和多的类别一样多,欠采样是把多的类别减少和少的类别一样
- 一般都是缺数据,所以很少用欠采样
随机过采样ROS
# 需要安装imbalanced-learn库
# 这个库是专门用于处理不平衡数据集的,提供了多种重采样方法
# !pip install -U imbalanced-learn
# 以下是添加的过采样代码
# 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)
# 训练随机森林模型(使用随机过采样后的训练集)
rf_model_ros = RandomForestClassifier(random_state=42)
start_time_ros = time.time()
rf_model_ros.fit(X_train_ros, y_train_ros)
end_time_ros = time.time()
print(f"随机过采样后训练与预测耗时: {end_time_ros - start_time_ros:.4f} 秒")
# 在测试集上预测
rf_pred_ros = rf_model_ros.predict(X_test)
print("\n随机过采样后随机森林 在测试集上的分类报告:")
print(classification_report(y_test, rf_pred_ros))
print("随机过采样后随机森林 在测试集上的混淆矩阵:")
print(confusion_matrix(y_test, rf_pred_ros))
SMOTE
# 2. 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过采样后的训练集)
rf_model_smote = RandomForestClassifier(random_state=42)
start_time_smote = time.time()
rf_model_smote.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 = rf_model_smote.predict(X_test)
print("\nSMOTE过采样后随机森林 在测试集上的分类报告:")
print(classification_report(y_test, rf_pred_smote))
print("SMOTE过采样后随机森林 在测试集上的混淆矩阵:")
print(confusion_matrix(y_test, rf_pred_smote))
修改权重
在处理类别不平衡的数据集时,标准机器学习算法(如默认的随机森林)可能会过度偏向多数类,导致对少数类的预测性能很差。为了解决这个问题,常用的策略包括在数据层面(采样)和算法层面进行调整。本文重点讨论两种算法层面的方法:**修改类别权重**和**修改分类阈值**。
挑战:标准算法的优化目标(如最小化整体误差)会使其优先拟合多数类,因为这样做能更快地降低总误差。
后果:对少数类样本的识别能力不足(低召回率),即使整体准确率看起来很高。
目标: 提高模型对少数类的预测性能,通常关注召回率(Recall)、F1分数(F1-Score)、AUC-PR等指标。
方法一:修改类别权重
方法二:修改分类阈值
import numpy as np # 引入 numpy 用于计算平均值等
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")
# 假设 X_train, y_train, X_test, y_test 已经准备好
# X_train, y_train 用于交叉验证和最终模型训练
# X_test, y_test 用于最终评估
# --- 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)
# --- 2. 带权重的随机森林 + 交叉验证 (在训练集上进行CV) ---
print("--- 2. 带权重随机森林 + 交叉验证 (在训练集上进行) ---")
# 确定少数类标签 (非常重要!)
# 假设是二分类问题,我们需要知道哪个是少数类标签才能正确解读 recall, precision, f1
# 例如,如果标签是 0 和 1,可以这样查看:
counts = np.bincount(y_train)
minority_label = np.argmin(counts) # 找到计数最少的类别的标签
majority_label = np.argmax(counts)
print(f"训练集中各类别数量: {counts}")
print(f"少数类标签: {minority_label}, 多数类标签: {majority_label}")
# !!下面的 scorer 将使用这个 minority_label !!
# 定义带权重的模型
rf_model_weighted = RandomForestClassifier(
random_state=42,
class_weight='balanced' # 关键:自动根据类别频率调整权重
# class_weight={minority_label: 10, majority_label: 1} # 或者可以手动设置权重字典
)
# 设置交叉验证策略 (使用 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(
random_state=42,
class_weight='balanced'
)
rf_model_weighted_final.fit(X_train, y_train) # 在整个训练集上训练
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带权重随机森林 在测试集上的分类报告:")
# 确保 classification_report 也关注少数类 (可以通过 target_names 参数指定标签名称)
# 或者直接查看报告中少数类标签对应的行
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}")