打卡第十四天

关于修改权重和分类阈值的部分

默认参数随机森林模型, 带权重的随机森林+交叉验证+使用权重训练最终模型并在测试集上做出预测。最终对比总结。

首先是默认参数随机森林模型代码

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)

然后是带权重的随机森林加交叉验证(基于训练集)

rint("--- 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)

具体过程: 

 然后是对加权重的模型进行训练,并作出预测

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)

最后对比总结

rint("性能对比 (测试集上的少数类召回率 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、付费专栏及课程。

余额充值