予測確率

モデルに基づく確率曲線を、群ごとに 95% 信頼帯とともに説明変数の範囲にわたって描きます。

予測確率

オッズ比は感覚的にとらえにくいものですが、確率ならわかりやすくなります。このグラフはロジスティックモデルをアウトカムのスケールに戻して表示します。各曲線は、要因の1つの水準について、連続的な説明変数の範囲にわたるアウトカムの予測確率を示しており、もう1つの共変量は平均値に固定しています。帯はロジットスケールで計算してから逆変換した 95% 信頼区間なので、[0, 1] の範囲内に収まります。ラグは観測された回答者を示し、その回答をした人は上側に、そうでない人は下側に描いています。

設定は Kouloukoui, de Marcellis-Warin & Warin (2025, AI & Society) による、人工知能のリスクと便益に関する一般市民の認識の研究です。データは説明のために シミュレーション したもので、論文のデータや結果ではありません。n = 600 人の調査回答者で、アウトカムは AI を便益よりリスクが大きいと見なすかどうか、説明変数は年齢、大学の学位、AI への自己評価による親しみ度(1–5)です。モデルは二項分布の smf.glm() で、曲線は get_prediction().summary_frame() から得ています。

コードおよび図中のテキストは英語です。

predicted-probabilities.py · 46 行
ダウンロード GitHub
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
# Simulated data, set in the context of Kouloukoui, de Marcellis-Warin & Warin (2025) [kouloukoui2025ai]

# Data: 600 respondents; risky = 1 if they see AI as more risky than beneficial
rng = np.random.default_rng(2025)
n = 600
df = pd.DataFrame({"age": rng.uniform(18, 80, n), "degree": rng.binomial(1, 0.4, n),
                   "familiarity": rng.integers(1, 6, n)})
eta = -1.6 + 0.045 * df.age - 0.8 * df.degree - 0.25 * df.familiarity
df["risky"] = rng.binomial(1, 1 / (1 + np.exp(-eta)))
model = smf.glm("risky ~ age + familiarity + C(degree)", data=df,
                family=sm.families.Binomial()).fit()

# Prediction grid: age across its range, familiarity at its mean, both education groups
age = np.linspace(df.age.min(), df.age.max(), 200)
groups = {0: ("No university degree", "#007AFF"), 1: ("University degree", "#FF9500")}

fig, ax = plt.subplots(figsize=(8, 5))
for level, (name, c) in groups.items():
    grid = pd.DataFrame({"age": age, "familiarity": df.familiarity.mean(), "degree": level})
    pred = model.get_prediction(grid).summary_frame(alpha=0.05)
    ax.fill_between(age, pred.mean_ci_lower, pred.mean_ci_upper, color=c, alpha=0.13, lw=0)
    ax.plot(age, pred["mean"], color=c, lw=2.5, label=name)
    # Rug of observations: answered "more risky" (top) or not (bottom), offset per group
    obs = df[df.degree == level]
    y_rug = np.where(obs.risky == 1, 1.03 + 0.025 * level, -0.03 - 0.025 * level)
    ax.scatter(obs.age, y_rug, marker="|", s=110, lw=1, color=c, alpha=0.5, clip_on=False)

ax.legend(loc="upper left", title="Education (95% CI)", alignment="left",
          bbox_to_anchor=(0.01, 0.93))
ax.set_ylim(-0.1, 1.1)
ax.set_yticks(np.linspace(0, 1, 6), [f"{v:.0%}" for v in np.linspace(0, 1, 6)])
ax.set_xlabel("Age of respondent (years)")
ax.set_ylabel("P(AI seen as more risky than beneficial)")
ax.set_title("Older respondents, and those without a degree, see AI as riskier", pad=26)
deg = "C(degree)[T.1]"
fmt_p = lambda p: "< .001" if p < .001 else f"= {p:.3f}".replace("0.", ".")
ax.text(0, 1.02, f"Logistic regression · n = {int(model.nobs)} (simulated) · familiarity at mean · "
        f"degree OR = {np.exp(model.params[deg]):.2f}, p {fmt_p(model.pvalues[deg])} · "
        f"age OR = {np.exp(10 * model.params['age']):.2f} per 10 y",
        transform=ax.transAxes, fontsize=9.5, color="#6E6E73")
plt.show()

図にはオプションの PyStatlas スタイル を使用しています。同じ見た目にするには plt.style.use("pystatlas.mplstyle") を追加してください。

データの出典

  • Simulated data. Simulated data with a fixed random seed, created for this example.
    No real respondents, documents or measurements: the numbers only illustrate how the chart and its statistics work.
  • Kouloukoui, de Marcellis-Warin & Warin (2025), public perceptions of AI. Kouloukoui, D., de Marcellis-Warin, N., & Warin, T. (2025). Balancing risks and benefits: Public perceptions of AI through traditional surveys and social media analysis. AI & Society, 40(6), 4919–4942. https://doi.org/10.1007/s00146-025-02232-x
    The example is set in the context of this paper; unless its description says otherwise, the numbers are simulated and are not the paper's data or results.

これらの例は統計手法を説明するためのものです。項目に別の記載がない限り数値はシミュレーションであり、図のタイトルはこのシミュレーションデータで図が示す内容を述べたものです。引用した論文の知見でも、実質的な問いに対する著者の立場でもありません。結果、背景、データについては、ここに挙げた論文を参照してください。

引用方法

PyStatlas は Thierry Warin が作成・運営しています。研究や業務に役立った場合は、ぜひ引用してください。

Warin, T. (2026). Predicted probabilities. In PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences (Version 1.1.0) [Computer software]. https://warin.ca/pystatlas/regression-models/predicted-probabilities/

@misc{warin2026statlas,
  author       = {Warin, Thierry},
  title        = {PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences},
  year         = {2026},
  version      = {1.1.0},
  howpublished = {\url{https://warin.ca/pystatlas/}},
  note         = {Source code: https://github.com/warint/pystatlas}
}

回帰モデルのその他のグラフ