You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

统计图名称查询及Matplotlib绘制方法咨询(含Logistic Regression需求)

问题解答

一、图表名称

你提到的这类图表是校准曲线(Calibration Curve/Calibration Plot),主要用于评估分类模型(如Logistic回归)的预测概率与实际事件发生概率的一致性。图中通常包含:

  • 理想校准线(y=x,代表预测概率完全匹配实际概率)
  • 模型校准曲线(展示模型预测概率对应的实际事件发生频率)
  • 部分版本会添加置信区间或分组观测的实际频率点

二、Python Matplotlib绘制Logistic回归校准曲线示例

以下是结合scikit-learn训练模型、用Matplotlib绘制校准曲线的完整代码,同时包含Logistic回归的结果展示:

1. 导入依赖库

import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.calibration import calibration_curve
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, roc_auc_score

2. 生成数据并训练Logistic回归模型

# 生成二分类模拟数据集
X, y = make_classification(n_samples=10000, n_features=10, n_informative=5, random_state=42)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 训练Logistic回归模型
log_reg = LogisticRegression(max_iter=1000, random_state=42)
log_reg.fit(X_train, y_train)

# 获取测试集的预测概率与预测类别
y_proba = log_reg.predict_proba(X_test)[:, 1]
y_pred = log_reg.predict(X_test)

3. 绘制校准曲线

# 计算校准曲线的实际频率与预测概率分组数据
prob_true, prob_pred = calibration_curve(y_test, y_proba, n_bins=10, strategy='uniform')

# 绘图
plt.figure(figsize=(8, 8))
# 绘制理想校准线
plt.plot([0, 1], [0, 1], "k--", label="Ideal Calibration")
# 绘制模型校准曲线
plt.plot(prob_pred, prob_true, "s-", label="Logistic Regression")
# 叠加分组实际频率散点
plt.scatter(prob_pred, prob_true, c='crimson', s=60, zorder=6)

# 设置图表样式
plt.xlabel("Predicted Probability")
plt.ylabel("Actual Event Probability")
plt.title("Calibration Curve for Logistic Regression")
plt.legend(loc="lower right")
plt.grid(alpha=0.3)
plt.xlim(0, 1)
plt.ylim(0, 1)

plt.show()

4. 展示Logistic回归核心评估结果

accuracy = accuracy_score(y_test, y_pred)
roc_auc = roc_auc_score(y_test, y_proba)

print(f"Logistic Regression Accuracy: {accuracy:.4f}")
print(f"Logistic Regression ROC-AUC: {roc_auc:.4f}")

补充说明

  • calibration_curve函数通过将预测概率分组(n_bins控制分组数),计算每组的实际事件发生频率,生成校准曲线数据;若需要更平滑的曲线,可尝试strategy='quantile'按分位数分组。
  • 若使用真实业务数据,只需替换模拟数据生成部分,直接传入你的特征矩阵与标签即可。

内容的提问来源于stack exchange,提问作者anoy_2395

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 08:25:02