综合python案例,最终判断的置信度有多高?

wen python案例 1

本文目录导读:

综合python案例,最终判断的置信度有多高?

  1. 完整示例:信用风险预测模型
  2. 置信度评估的核心要点

我理解您想了解综合Python案例中,最终判断的置信度评估问题,让我为您提供一个完整的示例,展示如何评估机器学习模型预测的置信度。

完整示例:信用风险预测模型

我将展示一个信用风险评估案例,包含置信度评估的多个维度。

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
from sklearn.metrics import roc_auc_score, roc_curve, confusion_matrix
from sklearn.preprocessing import StandardScaler
from sklearn.calibration import calibration_curve
from sklearn.isotonic import IsotonicRegression
import warnings
warnings.filterwarnings('ignore')
# 设置中文显示
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
print("=" * 60)
print("信用风险评估模型 - 置信度详细分析")
print("=" * 60)
# 1. 生成模拟数据
np.random.seed(42)
n_samples = 1000
# 创建特征
data = {
    'age': np.random.normal(35, 10, n_samples),
    'income': np.random.normal(60000, 20000, n_samples),
    'credit_history_length': np.random.exponential(5, n_samples),
    'debt_ratio': np.random.beta(5, 8, n_samples),
    'num_loans': np.random.poisson(2, n_samples),
    'employment_years': np.random.exponential(3, n_samples),
    'has_default_history': np.random.binomial(1, 0.15, n_samples),
    'monthly_payment_ratio': np.random.beta(4, 6, n_samples)
}
df = pd.DataFrame(data)
# 创建目标变量(带概率)
z = (2.5 - 0.05*df['age'] + 0.02*df['income']/10000 - 
     0.3*df['debt_ratio'] + 0.1*df['num_loans'] - 
     1.5*df['has_default_history'] + 
     0.05*df['employment_years'] + 
     np.random.normal(0, 1, n_samples))
prob_default = 1/(1 + np.exp(-z))
y = np.random.binomial(1, prob_default, n_samples)
df['default'] = y
print(f"数据样本数: {len(df)}")
print(f"违约比例: {y.mean():.3f}")
# 2. 数据分割
X = df.drop('default', axis=1)
y = df['default']
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y
)
print(f"训练集大小: {len(X_train)}, 测试集大小: {len(X_test)}")
# 3. 特征标准化
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
# 4. 训练多个模型
models = {
    '逻辑回归': LogisticRegression(max_iter=1000, random_state=42),
    '随机森林': RandomForestClassifier(n_estimators=100, max_depth=10, random_state=42),
    '梯度提升': GradientBoostingClassifier(n_estimators=100, learning_rate=0.1, random_state=42)
}
# 5. 计算置信度指标
results = pd.DataFrame()
conf_intervals = {}
for name, model in models.items():
    print(f"\n{'='*50}")
    print(f"模型: {name}")
    print('='*50)
    # 训练模型
    model.fit(X_train_scaled, y_train)
    # 预测概率
    y_proba = model.predict_proba(X_test_scaled)[:, 1]
    y_pred = (y_proba >= 0.5).astype(int)
    # 5.1 基础性能指标
    metrics = {
        '模型': name,
        '准确率': accuracy_score(y_test, y_pred),
        '精确率': precision_score(y_test, y_pred),
        '召回率': recall_score(y_test, y_pred),
        'F1分数': f1_score(y_test, y_pred),
        'AUC-ROC': roc_auc_score(y_test, y_proba)
    }
    results = pd.concat([results, pd.DataFrame([metrics])], ignore_index=True)
    # 5.2 交叉验证
    cv_scores = cross_val_score(model, X_train_scaled, y_train, cv=5, scoring='accuracy')
    print(f"5折交叉验证准确率: {cv_scores.mean():.4f} ± {cv_scores.std():.4f}")
    # 5.3 置信区间计算(使用正态近似)
    n_test = len(y_test)
    se = np.sqrt(metrics['准确率'] * (1 - metrics['准确率']) / n_test)
    z_value = 1.96  # 95%置信度
    ci_lower = metrics['准确率'] - z_value * se
    ci_upper = metrics['准确率'] + z_value * se
    conf_intervals[name] = (ci_lower, ci_upper)
    print(f"95%置信区间: [{ci_lower:.4f}, {ci_upper:.4f}]")
    # 5.4 预测概率分布分析
    print(f"预测概率均值: {y_proba.mean():.3f}")
    print(f"预测概率标准差: {y_proba.std():.3f}")
# 6. 显示所有模型的性能对比
print("\n" + "="*60)
print("所有模型性能对比")
print("="*60)
print(results.to_string(index=False))
# 7. 校准度分析(预测概率的可靠性)
print("\n" + "="*60)
print("校准度分析 - 预测概率是否准确")
print("="*60)
# 选择梯度提升(或AUC最高的模型)进行详细校准
model_names = results['模型'].tolist()
auc_scores = results['AUC-ROC'].tolist()
best_model_idx = auc_scores.index(max(auc_scores))
best_model_name = model_names[best_model_idx]
print(f"最佳AUC模型: {best_model_name}")
best_model = models[best_model_name]
best_proba = best_model.predict_proba(X_test_scaled)[:, 1]
# 校准曲线
fraction_positive, mean_predicted_value = calibration_curve(
    y_test, best_proba, n_bins=10
)
# 用Brier分数评估预测的可靠性
brier_score = np.mean((best_proba - y_test)**2)
print(f"Brier分数(越低越好): {brier_score:.4f}")
# 8. 高风险预测的可信度分析
print("\n" + "="*60)
print("高风险预测的可信度分析")
print("="*60)
# 找出预测违约概率高于0.9的样本
high_risk_indices = best_proba > 0.9
high_risk_correct = np.sum(high_risk_indices & (y_test == 1))
high_risk_total = np.sum(high_risk_indices)
if high_risk_total > 0:
    precision_high_risk = high_risk_correct / high_risk_total
    print(f"高风险样本数(P>0.9): {high_risk_total}")
    print(f"其中实际违约数: {high_risk_correct}")
    print(f"高风险预测的精确率: {precision_high_risk:.4f}")
# 9. 置信度综合评分
print("\n" + "="*60)
print("综合置信度评估")
print("="*60)
# 9.1 多种评估方法结合
confidence_score = {
    '校准度': 1 - brier_score,  # Brier分数接近0则校准好
    '交叉验证一致性': cv_scores.std(),  # 标准差分越低越好
    '样本覆盖率': min(1.0, len(X_test)/500),  # 样本量
    '模型鲁棒性': 1 - abs(metrics['准确率'] - cv_scores.mean())  # 训练测试差异
}
print("各置信度维度评分:")
for dim, score in confidence_score.items():
    print(f"  {dim}: {score:.4f}")
# 9.2 最终置信度(加权平均)
weights = {
    '校准度': 0.4,
    '交叉验证一致性': 0.2,
    '样本覆盖率': 0.1,
    '模型鲁棒性': 0.3
}
final_confidence = sum(confidence_score[dim] * weights[dim] 
                      for dim in weights.keys())
print(f"\n最终置信度评分: {final_confidence:.4f}")
print(f"置信度区间: {final_confidence*100:.1f}% - {final_confidence*100:.1f}%")
# 10. 可视化
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
# 10.1 各模型AUC对比
ax1 = axes[0, 0]
bars1 = ax1.bar(results['模型'], results['AUC-ROC'], color=['#3498db', '#2ecc71', '#e74c3c'])
ax1.set_ylabel('AUC-ROC')
ax1.set_title('模型AUC-ROC对比', fontsize=12, fontweight='bold')
ax1.set_ylim(0, 1)
for bar, val in zip(bars1, results['AUC-ROC']):
    ax1.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.02, 
             f'{val:.3f}', ha='center', va='bottom')
# 10.2 模型性能指标对比
ax2 = axes[0, 1]
metrics_names = ['准确率', '精确率', '召回率', 'F1分数']
x = np.arange(len(metrics_names))
width = 0.25
for i, (name, model) in enumerate(models.items()):
    model_metrics = results[results['模型'] == name].iloc[0]
    ax2.bar(x + i*width, [model_metrics['准确率'], model_metrics['精确率'], 
                           model_metrics['召回率'], model_metrics['F1分数']], 
            width, label=name)
ax2.set_xlabel('指标')
ax2.set_ylabel('分数')
ax2.set_title('模型性能指标对比', fontsize=12, fontweight='bold')
ax2.legend()
ax2.set_xticks(x + width)
ax2.set_xticklabels(metrics_names)
ax2.set_ylim(0, 1)
# 10.3 校准曲线
ax3 = axes[1, 0]
ax3.plot([0, 1], [0, 1], linestyle='--', color='gray', label='完美校准')
ax3.plot(mean_predicted_value, fraction_positive, 'o-', color='blue', label=best_model_name)
ax3.set_xlabel('预测概率')
ax3.set_ylabel('实际频率')
ax3.set_title('校准曲线分析', fontsize=12, fontweight='bold')
ax3.legend()
ax3.set_xlim(0, 1.1)
ax3.set_ylim(0, 1.1)
# 10.4 置信区间图
ax4 = axes[1, 1]
for i, (name, (low, high)) in enumerate(conf_intervals.items()):
    acc = results[results['模型'] == name]['准确率'].values[0]
    ax4.errorbar(i, acc, yerr=[[acc-low], [high-acc]], fmt='o', 
                capsize=5, capthick=2, markersize=10)
ax4.set_xticks(range(len(conf_intervals)))
ax4.set_xticklabels(conf_intervals.keys())
ax4.set_ylabel('准确率')
ax4.set_title('模型精度置信区间(95%)', fontsize=12, fontweight='bold')
ax4.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig('confidence_analysis.png', dpi=100)
plt.show()
# 11. 最终结论
print("\n" + "="*60)
print("最终结论")
print("="*60)
print(f"""
    根据综合分析:
    1. 最佳模型: {best_model_name}
    2. AUC-ROC分数: {max(auc_scores):.3f}
    3. 置信区间: [{conf_intervals[best_model_name][0]:.3f}, 
                 {conf_intervals[best_model_name][1]:.3f}]
    4. 校准质量评分: {1 - brier_score:.3f}
    5. 交叉验证稳定性: {cv_scores.std():.4f}
    综合置信度等级: {"高" if final_confidence > 0.8 else 
                      "中" if final_confidence > 0.6 else "低"}
    建议:
    - 置信度较高(>0.8):模型可以在业务中使用,但需持续监控
    - 置信度中(0.6-0.8):模型基本可用,需人工审核关键决策
    - 置信度低(<0.6):不建议直接使用,需改进特征或获取更多数据
""")

置信度评估的核心要点

多维评估指标

  • AUC-ROC:衡量模型区分能力(0.7-0.8为可接受)
  • 校准度:预测概率是否准确反映实际事件频率
  • Brier分数:综合评价预测的准确性(越低越好)

稳定性验证

  • 交叉验证:比较不同数据划分下性能的稳定性
  • 置信区间:给出性能指标的波动范围
  • 训练/测试差异:检查过拟合程度

置信度提升方法

# 方法1:使用集成学习
from sklearn.ensemble import VotingClassifier
# 方法2:概率校准
from sklearn.calibration import CalibratedClassifierCV
calibrated_model = CalibratedClassifierCV(base_model, cv=5, method='isotonic')
# 方法3:增加数据量或特征
# 方法4:使用贝叶斯方法计算后验概率

实际操作建议

  • 置信度 ≥ 0.9:可用于自动化决策
  • 置信度 0.7-0.9:建议人工复核高风险建议
  • 置信度 < 0.7:仅作为参考,不直接用于决策

这个案例展示了如何从多个维度评估模型预测的可靠性,并给出合理的置信度分数,实际应用中,您可能需要根据业务场景调整权重和阈值。

抱歉,评论功能暂时关闭!