Probabilités prédites
Courbes de probabilité issues du modèle, avec rubans d'IC à 95 %, selon un prédicteur et par groupe.

Les rapports de cotes sont difficiles à appréhender ; les probabilités, non. Ce graphique ramène un modèle logistique à l'échelle de la variable réponse : chaque courbe est la probabilité prédite de l'événement sur l'étendue d'un prédicteur continu, pour un niveau d'un facteur, l'autre covariable étant fixée à sa moyenne. Les rubans sont des intervalles de confiance à 95 % calculés sur l'échelle logit puis retransformés, de sorte qu'ils restent dans [0, 1]. Les tirets marginaux montrent les répondants observés — en haut s'ils ont donné cette réponse, en bas sinon.
Le contexte est celui de Kouloukoui, de Marcellis-Warin & Warin (2025, AI & Society) : la perception par le public des risques et des bénéfices de l'intelligence artificielle. Les données sont simulées à des fins d'illustration — ce ne sont ni les données ni les résultats de l'article : n = 600 répondants à une enquête ; la variable réponse indique s'ils jugent l'IA plus risquée que bénéfique, et les prédicteurs sont l'âge, un diplôme universitaire et la familiarité déclarée avec l'IA (1–5). Le modèle est un smf.glm() binomial ; les courbes proviennent de get_prediction().summary_frame().
Le code et le texte à l'intérieur des figures sont en anglais.
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()
# Predicted probabilities: the R equivalent of plot.py
# Simulated data, set in the context of Kouloukoui, de Marcellis-Warin & Warin (2025) [kouloukoui2025ai]
# R and NumPy draw different random numbers, so the values differ slightly from the Python figure.
library(ggplot2)
set.seed(2025)
# Data: 600 respondents; risky = 1 if they see AI as more risky than beneficial
n <- 600
df <- data.frame(age = runif(n, 18, 80), degree = rbinom(n, 1, 0.4),
familiarity = sample(1:5, n, replace = TRUE))
eta <- with(df, -1.6 + 0.045 * age - 0.8 * degree - 0.25 * familiarity)
df$risky <- rbinom(n, 1, plogis(eta))
model <- glm(risky ~ age + familiarity + factor(degree), family = binomial, data = df)
# Prediction grid: age across its range, familiarity at its mean, both education groups
# (ggeffects / marginaleffects are not installed: predict() on the logit scale, then plogis(),
# so the 95% band stays inside [0, 1])
groups <- c("No university degree", "University degree")
palette <- c("#007AFF", "#FF9500")
grid <- expand.grid(age = seq(min(df$age), max(df$age), length.out = 200),
familiarity = mean(df$familiarity), degree = 0:1)
pr <- predict(model, grid, type = "link", se.fit = TRUE)
grid$fit <- plogis(pr$fit)
grid$low <- plogis(pr$fit - qnorm(0.975) * pr$se.fit)
grid$high <- plogis(pr$fit + qnorm(0.975) * pr$se.fit)
grid$group <- factor(groups[grid$degree + 1], groups)
# Rug of observations: answered "more risky" (top) or not (bottom), offset per group
df$group <- factor(groups[df$degree + 1], groups)
df$y_rug <- ifelse(df$risky == 1, 1.03 + 0.025 * df$degree, -0.03 - 0.025 * df$degree)
deg <- "factor(degree)1"
p_deg <- summary(model)$coefficients[deg, 4]
fmt_p <- function(p) if (p < .001) "< .001" else sub("0\\.", ".", sprintf("= %.3f", p))
p <- ggplot(grid, aes(age, fit, colour = group, fill = group)) +
geom_ribbon(aes(ymin = low, ymax = high), alpha = 0.13, colour = NA) +
geom_line(linewidth = 1.2) +
geom_point(data = df, aes(age, y_rug), shape = "|", size = 3, alpha = 0.5, show.legend = FALSE) +
scale_colour_manual("Education (95% CI)", values = palette) +
scale_fill_manual("Education (95% CI)", values = palette) +
scale_y_continuous(breaks = seq(0, 1, 0.2), labels = scales::percent) +
coord_cartesian(ylim = c(-0.08, 1.08)) +
labs(title = "Older respondents, and those without a degree, see AI as riskier",
subtitle = sprintf("Logistic regression · n = %d (simulated) · familiarity at mean · degree OR = %.2f, p %s · age OR = %.2f per 10 y",
nobs(model), exp(coef(model)[deg]), fmt_p(p_deg), exp(10 * coef(model)["age"])),
x = "Age of respondent (years)", y = "P(AI seen as more risky than beneficial)") +
theme_minimal(base_size = 11) +
theme(plot.title = element_text(face = "bold"),
plot.title.position = "plot",
plot.subtitle = element_text(size = 8.5, colour = "#6E6E73"),
panel.grid.minor = element_blank(),
legend.position = "inside", legend.position.inside = c(0.02, 0.86),
legend.justification = c(0, 1),
legend.background = element_rect(fill = "white", colour = "#E5E5EA", linewidth = 0.3))
print(p)
Les figures utilisent le style PyStatlas (facultatif) : ajoutez plt.style.use("pystatlas.mplstyle") pour obtenir exactement le même rendu.
Source des données
- 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.
Les exemples illustrent des méthodes statistiques. Leurs chiffres sont simulés, sauf mention contraire dans l'entrée, et leurs titres décrivent ce que chaque figure montre dans ces données simulées — ni les résultats des articles cités, ni la position de l'auteur sur la question de fond. Pour les résultats, le contexte et les données, reportez-vous aux articles cités ici.
Comment citer
PyStatlas est créé et maintenu par Thierry Warin. S'il vous a été utile dans vos travaux, merci de le citer.
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}
}Plus dans Modèles de régression
Graphique des coefficients
Estimations de régression avec intervalles de confiance à 95 %, une ligne par terme.
ggstats::ggcoef_model()Graphique en forêt des rapports de cotes
Rapports de cotes d'une régression logistique sur échelle logarithmique, accompagnés d'un tableau RC [IC à 95 %].
ggstats::ggcoef_model(exponentiate = TRUE)Comparaison de modèles emboîtés
Coefficients de trois régressions emboîtées de l'IDE côte à côte, pour voir comment les estimations bougent quand un bloc UE est ajouté.
ggstats::ggcoef_compare()