Spaces:
Sleeping
Sleeping
Add color legend to map figures, linear regression comparison tab, and remove emoji from UI
Browse files
app.py
CHANGED
|
@@ -3,10 +3,12 @@ import numpy as np
|
|
| 3 |
import matplotlib
|
| 4 |
matplotlib.use('Agg')
|
| 5 |
import matplotlib.pyplot as plt
|
|
|
|
| 6 |
import rasterio
|
| 7 |
import json
|
| 8 |
import os
|
| 9 |
from sklearn.neighbors import KNeighborsClassifier
|
|
|
|
| 10 |
from sklearn.preprocessing import StandardScaler
|
| 11 |
|
| 12 |
# ─────────────────────────────────────────────────────────────────────────────
|
|
@@ -132,10 +134,54 @@ def train_and_predict(student_labels, k):
|
|
| 132 |
|
| 133 |
return model_oa, model_matrix, pred_gt, y_gt, knn_ref_gt, pred_full
|
| 134 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
# ─────────────────────────────────────────────────────────────────────────────
|
| 136 |
# Visualization helpers
|
| 137 |
# ─────────────────────────────────────────────────────────────────────────────
|
| 138 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
def fig_confusion_matrix(matrix, oa, title, cmap='Blues'):
|
| 140 |
"""Generic 7×7 confusion matrix plot: predicted classes vs Ground Truth."""
|
| 141 |
short = ["Eau", "Vergers", "Δ-Cult.", "Bâti", "Irr.-Dés.", "Non-Irr.", "Sable"]
|
|
@@ -214,19 +260,19 @@ def fig_gt_maps(pred_gt, y_gt, knn_ref_gt):
|
|
| 214 |
acc = correct.mean() * 100
|
| 215 |
fig.suptitle(f"Précision de votre modèle sur les pixels de vérité terrain : {acc:.1f}%",
|
| 216 |
fontsize=12, fontweight='bold')
|
| 217 |
-
plt.tight_layout()
|
|
|
|
| 218 |
return fig
|
| 219 |
|
| 220 |
-
def fig_full_maps(
|
| 221 |
"""Full-image classification maps: EVERY pixel, not just the ~21k Ground
|
| 222 |
-
Truth locations.
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
panels =
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
]
|
| 230 |
for ax, (classes, title) in zip(axes, panels):
|
| 231 |
ax.imshow(COLORS_RGB[classes])
|
| 232 |
ax.set_title(title, fontsize=11, fontweight='bold')
|
|
@@ -235,7 +281,8 @@ def fig_full_maps(pred_full, knn_full):
|
|
| 235 |
"Classification sur l'ensemble de l'image (précision non évaluable hors vérité terrain)",
|
| 236 |
fontsize=11,
|
| 237 |
)
|
| 238 |
-
plt.tight_layout()
|
|
|
|
| 239 |
return fig
|
| 240 |
|
| 241 |
def fig_student_matrix(student_labels):
|
|
@@ -290,7 +337,7 @@ def build_results_table(student_labels):
|
|
| 290 |
t = DATA['polygon_teacher'].get(pid, 0)
|
| 291 |
s_str = f"{s} – {CLASSES.get(int(s), '?')}" if s is not None else "—"
|
| 292 |
t_str = f"{t} – {CLASSES.get(t, '?')}"
|
| 293 |
-
match = "
|
| 294 |
rows.append([pid, s_str, t_str, match])
|
| 295 |
return rows
|
| 296 |
|
|
@@ -305,7 +352,7 @@ with gr.Blocks(title="Interprétation de polygones – Vallée du Nil") as demo:
|
|
| 305 |
|
| 306 |
# ── Header ─────────────────────────────────────────────────────────────
|
| 307 |
gr.Markdown("""
|
| 308 |
-
#
|
| 309 |
|
| 310 |
**Objectif :** Interprétez visuellement chacun des 23 polygones d'entraînement,
|
| 311 |
puis soumettez vos réponses pour générer la carte et la matrice de confusion.
|
|
@@ -316,19 +363,19 @@ puis soumettez vos réponses pour générer la carte et la matrice de confusion.
|
|
| 316 |
with gr.Tabs() as tabs:
|
| 317 |
|
| 318 |
# ── Tab 1: Légende des classes ────────────────────────────────────
|
| 319 |
-
with gr.Tab("
|
| 320 |
gr.Markdown("""
|
| 321 |
## Classes d'occupation du sol
|
| 322 |
|
| 323 |
| N° | Classe | Couleur |
|
| 324 |
|----|--------|---------|
|
| 325 |
-
| 1 | Eau |
|
| 326 |
-
| 2 | Vergers |
|
| 327 |
-
| 3 | Cultures dans le Delta |
|
| 328 |
-
| 4 | Zones bâties |
|
| 329 |
-
| 5 | Cultures irriguées dans le désert |
|
| 330 |
-
| 6 | Cultures non irriguées en zone sèche |
|
| 331 |
-
| 7 | Zones sableuses |
|
| 332 |
|
| 333 |
---
|
| 334 |
**Conseils d'interprétation :**
|
|
@@ -341,7 +388,7 @@ puis soumettez vos réponses pour générer la carte et la matrice de confusion.
|
|
| 341 |
""")
|
| 342 |
|
| 343 |
# ── Tab 2: Interprétation ─────────────────────────────────────────
|
| 344 |
-
with gr.Tab("
|
| 345 |
progress_md = gr.Markdown("**0 / 23 polygones étiquetés**")
|
| 346 |
|
| 347 |
with gr.Row():
|
|
@@ -354,8 +401,8 @@ puis soumettez vos réponses pour générer la carte et la matrice de confusion.
|
|
| 354 |
height=500,
|
| 355 |
)
|
| 356 |
with gr.Row():
|
| 357 |
-
btn_prev = gr.Button("
|
| 358 |
-
btn_next = gr.Button("Suivant
|
| 359 |
jump_dropdown = gr.Dropdown(
|
| 360 |
choices=[str(i) for i in range(1, N_POLYGONS + 1)],
|
| 361 |
value="1",
|
|
@@ -377,14 +424,14 @@ puis soumettez vos réponses pour générer la carte et la matrice de confusion.
|
|
| 377 |
gr.Markdown("---")
|
| 378 |
progress_bar = gr.Markdown("**Progression : 0 / 23**")
|
| 379 |
btn_submit = gr.Button(
|
| 380 |
-
"
|
| 381 |
variant="primary",
|
| 382 |
visible=False,
|
| 383 |
size="lg",
|
| 384 |
)
|
| 385 |
|
| 386 |
# ── Tab 3: Résultats de l'interprétation ──────────────────────────
|
| 387 |
-
with gr.Tab("
|
| 388 |
results_placeholder = gr.Markdown(
|
| 389 |
"*(Les résultats apparaîtront ici après soumission)*"
|
| 390 |
)
|
|
@@ -398,7 +445,7 @@ puis soumettez vos réponses pour générer la carte et la matrice de confusion.
|
|
| 398 |
student_matrix_plot = gr.Plot(label="Votre interprétation vs Enseignant")
|
| 399 |
|
| 400 |
# ── Tab 4: Entraînement du modèle KNN ──────────────────────────────
|
| 401 |
-
with gr.Tab("
|
| 402 |
gr.Markdown("""
|
| 403 |
## Entraînez votre propre modèle KNN
|
| 404 |
|
|
@@ -412,7 +459,7 @@ pixels de vérité terrain (indépendants des polygones d'entraînement).
|
|
| 412 |
label="k (nombre de voisins)",
|
| 413 |
)
|
| 414 |
btn_train = gr.Button(
|
| 415 |
-
"
|
| 416 |
variant="primary",
|
| 417 |
size="lg",
|
| 418 |
)
|
|
@@ -435,6 +482,36 @@ pixels de vérité terrain (indépendants des polygones d'entraînement).
|
|
| 435 |
visible=False,
|
| 436 |
)
|
| 437 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 438 |
# ─────────────────────────────────────────────────────────────────────
|
| 439 |
# Event handlers
|
| 440 |
# ─────────────────────────────────────────────────────────────────────
|
|
@@ -515,8 +592,8 @@ pixels de vérité terrain (indépendants des polygones d'entraînement).
|
|
| 515 |
total = count_labeled(current_labels)
|
| 516 |
if total < N_POLYGONS:
|
| 517 |
warning = (
|
| 518 |
-
f"
|
| 519 |
-
f"Terminez l'étiquetage dans l'onglet
|
| 520 |
f"avant d'entraîner un modèle."
|
| 521 |
)
|
| 522 |
return (
|
|
@@ -541,7 +618,10 @@ pixels de vérité terrain (indépendants des polygones d'entraînement).
|
|
| 541 |
model_fig = fig_model_matrix(model_matrix, model_oa)
|
| 542 |
knn_fig = fig_knn_matrix()
|
| 543 |
map_fig = fig_gt_maps(pred_gt, y_gt, knn_ref_gt)
|
| 544 |
-
full_fig = fig_full_maps(
|
|
|
|
|
|
|
|
|
|
| 545 |
|
| 546 |
return (
|
| 547 |
gr.update(visible=False),
|
|
@@ -553,6 +633,44 @@ pixels de vérité terrain (indépendants des polygones d'entraînement).
|
|
| 553 |
gr.update(value=full_fig, visible=True),
|
| 554 |
)
|
| 555 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 556 |
# Wire up navigation (Précédent / Suivant / direct jump-to-polygon dropdown —
|
| 557 |
# all three can be used freely and repeatedly, in any order, at any time)
|
| 558 |
btn_prev.click(
|
|
@@ -615,5 +733,17 @@ pixels de vérité terrain (indépendants des polygones d'entraînement).
|
|
| 615 |
],
|
| 616 |
)
|
| 617 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 618 |
if __name__ == "__main__":
|
| 619 |
demo.launch(server_name="0.0.0.0", server_port=7860)
|
|
|
|
| 3 |
import matplotlib
|
| 4 |
matplotlib.use('Agg')
|
| 5 |
import matplotlib.pyplot as plt
|
| 6 |
+
from matplotlib.patches import Patch
|
| 7 |
import rasterio
|
| 8 |
import json
|
| 9 |
import os
|
| 10 |
from sklearn.neighbors import KNeighborsClassifier
|
| 11 |
+
from sklearn.linear_model import LinearRegression
|
| 12 |
from sklearn.preprocessing import StandardScaler
|
| 13 |
|
| 14 |
# ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
| 134 |
|
| 135 |
return model_oa, model_matrix, pred_gt, y_gt, knn_ref_gt, pred_full
|
| 136 |
|
| 137 |
+
def train_and_predict_regression(student_labels):
|
| 138 |
+
"""Train a plain linear regression on the same 23 labeled polygons, treating
|
| 139 |
+
the class numbers as a continuous target. Class numbers are nominal
|
| 140 |
+
categories, not an ordered scale, so this is the wrong tool for the job —
|
| 141 |
+
predictions are rounded to the nearest class to see just how wrong."""
|
| 142 |
+
bands = DATA['bands']
|
| 143 |
+
training_ids = DATA['training_ids']
|
| 144 |
+
ground_truth = DATA['ground_truth']
|
| 145 |
+
|
| 146 |
+
train_mask = training_ids > 0
|
| 147 |
+
X_train = bands[train_mask]
|
| 148 |
+
y_train = np.array(
|
| 149 |
+
[int(student_labels[pid - 1]) for pid in training_ids[train_mask]], dtype=np.float64
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
scaler = StandardScaler().fit(X_train)
|
| 153 |
+
reg = LinearRegression()
|
| 154 |
+
reg.fit(scaler.transform(X_train), y_train)
|
| 155 |
+
|
| 156 |
+
gt_mask = ground_truth > 0
|
| 157 |
+
X_gt = bands[gt_mask]
|
| 158 |
+
pred_gt = np.clip(np.rint(reg.predict(scaler.transform(X_gt))), 1, 7).astype(int)
|
| 159 |
+
y_gt = ground_truth[gt_mask]
|
| 160 |
+
|
| 161 |
+
model_matrix = np.zeros((7, 7), dtype=np.int64)
|
| 162 |
+
np.add.at(model_matrix, (y_gt - 1, pred_gt - 1), 1)
|
| 163 |
+
model_oa = model_matrix.diagonal().sum() / model_matrix.sum()
|
| 164 |
+
|
| 165 |
+
H, W, n_bands = bands.shape
|
| 166 |
+
raw_full = reg.predict(scaler.transform(bands.reshape(-1, n_bands)))
|
| 167 |
+
pred_full = np.clip(np.rint(raw_full), 1, 7).astype(int).reshape(H, W)
|
| 168 |
+
|
| 169 |
+
return model_oa, model_matrix, pred_full
|
| 170 |
+
|
| 171 |
# ─────────────────────────────────────────────────────────────────────────────
|
| 172 |
# Visualization helpers
|
| 173 |
# ─────────────────────────────────────────────────────────────────────────────
|
| 174 |
|
| 175 |
+
def add_class_legend(fig):
|
| 176 |
+
"""Attach the color-to-class legend directly under a map figure, so it
|
| 177 |
+
doesn't rely on the student remembering the table from the first tab."""
|
| 178 |
+
handles = [
|
| 179 |
+
Patch(facecolor=COLORS_RGB[i] / 255.0, edgecolor='none', label=f"{i} - {CLASSES[i]}")
|
| 180 |
+
for i in range(1, 8)
|
| 181 |
+
]
|
| 182 |
+
fig.legend(handles=handles, loc='lower center', ncol=4, fontsize=8,
|
| 183 |
+
frameon=False, bbox_to_anchor=(0.5, -0.02))
|
| 184 |
+
|
| 185 |
def fig_confusion_matrix(matrix, oa, title, cmap='Blues'):
|
| 186 |
"""Generic 7×7 confusion matrix plot: predicted classes vs Ground Truth."""
|
| 187 |
short = ["Eau", "Vergers", "Δ-Cult.", "Bâti", "Irr.-Dés.", "Non-Irr.", "Sable"]
|
|
|
|
| 260 |
acc = correct.mean() * 100
|
| 261 |
fig.suptitle(f"Précision de votre modèle sur les pixels de vérité terrain : {acc:.1f}%",
|
| 262 |
fontsize=12, fontweight='bold')
|
| 263 |
+
plt.tight_layout(rect=[0, 0.08, 1, 1])
|
| 264 |
+
add_class_legend(fig)
|
| 265 |
return fig
|
| 266 |
|
| 267 |
+
def fig_full_maps(*panels):
|
| 268 |
"""Full-image classification maps: EVERY pixel, not just the ~21k Ground
|
| 269 |
+
Truth locations. A model classifies the whole image — but outside Ground
|
| 270 |
+
Truth locations there is no known right answer, so accuracy can't be
|
| 271 |
+
computed there. This is purely illustrative.
|
| 272 |
+
panels: one or more (classes_2d, title) tuples."""
|
| 273 |
+
fig, axes = plt.subplots(1, len(panels), figsize=(7 * len(panels), 6.5))
|
| 274 |
+
if len(panels) == 1:
|
| 275 |
+
axes = [axes]
|
|
|
|
| 276 |
for ax, (classes, title) in zip(axes, panels):
|
| 277 |
ax.imshow(COLORS_RGB[classes])
|
| 278 |
ax.set_title(title, fontsize=11, fontweight='bold')
|
|
|
|
| 281 |
"Classification sur l'ensemble de l'image (précision non évaluable hors vérité terrain)",
|
| 282 |
fontsize=11,
|
| 283 |
)
|
| 284 |
+
plt.tight_layout(rect=[0, 0.1, 1, 0.95])
|
| 285 |
+
add_class_legend(fig)
|
| 286 |
return fig
|
| 287 |
|
| 288 |
def fig_student_matrix(student_labels):
|
|
|
|
| 337 |
t = DATA['polygon_teacher'].get(pid, 0)
|
| 338 |
s_str = f"{s} – {CLASSES.get(int(s), '?')}" if s is not None else "—"
|
| 339 |
t_str = f"{t} – {CLASSES.get(t, '?')}"
|
| 340 |
+
match = "Correct" if (s is not None and int(s) == t) else ("Incorrect" if s is not None else "—")
|
| 341 |
rows.append([pid, s_str, t_str, match])
|
| 342 |
return rows
|
| 343 |
|
|
|
|
| 352 |
|
| 353 |
# ── Header ─────────────────────────────────────────────────────────────
|
| 354 |
gr.Markdown("""
|
| 355 |
+
# Interprétation de polygones d'entraînement – Vallée du Nil
|
| 356 |
|
| 357 |
**Objectif :** Interprétez visuellement chacun des 23 polygones d'entraînement,
|
| 358 |
puis soumettez vos réponses pour générer la carte et la matrice de confusion.
|
|
|
|
| 363 |
with gr.Tabs() as tabs:
|
| 364 |
|
| 365 |
# ── Tab 1: Légende des classes ────────────────────────────────────
|
| 366 |
+
with gr.Tab("Classes d'occupation du sol"):
|
| 367 |
gr.Markdown("""
|
| 368 |
## Classes d'occupation du sol
|
| 369 |
|
| 370 |
| N° | Classe | Couleur |
|
| 371 |
|----|--------|---------|
|
| 372 |
+
| 1 | Eau | Bleu |
|
| 373 |
+
| 2 | Vergers | Vert foncé |
|
| 374 |
+
| 3 | Cultures dans le Delta | Vert clair |
|
| 375 |
+
| 4 | Zones bâties | Rouge |
|
| 376 |
+
| 5 | Cultures irriguées dans le désert | Orange |
|
| 377 |
+
| 6 | Cultures non irriguées en zone sèche | Marron |
|
| 378 |
+
| 7 | Zones sableuses | Jaune clair |
|
| 379 |
|
| 380 |
---
|
| 381 |
**Conseils d'interprétation :**
|
|
|
|
| 388 |
""")
|
| 389 |
|
| 390 |
# ── Tab 2: Interprétation ─────────────────────────────────────────
|
| 391 |
+
with gr.Tab("Interprétation des polygones"):
|
| 392 |
progress_md = gr.Markdown("**0 / 23 polygones étiquetés**")
|
| 393 |
|
| 394 |
with gr.Row():
|
|
|
|
| 401 |
height=500,
|
| 402 |
)
|
| 403 |
with gr.Row():
|
| 404 |
+
btn_prev = gr.Button("< Précédent", size="sm", variant="secondary")
|
| 405 |
+
btn_next = gr.Button("Suivant >", size="sm", variant="primary")
|
| 406 |
jump_dropdown = gr.Dropdown(
|
| 407 |
choices=[str(i) for i in range(1, N_POLYGONS + 1)],
|
| 408 |
value="1",
|
|
|
|
| 424 |
gr.Markdown("---")
|
| 425 |
progress_bar = gr.Markdown("**Progression : 0 / 23**")
|
| 426 |
btn_submit = gr.Button(
|
| 427 |
+
"Voir ma précision d'interprétation",
|
| 428 |
variant="primary",
|
| 429 |
visible=False,
|
| 430 |
size="lg",
|
| 431 |
)
|
| 432 |
|
| 433 |
# ── Tab 3: Résultats de l'interprétation ──────────────────────────
|
| 434 |
+
with gr.Tab("Résultats", id="tab_results") as tab_results:
|
| 435 |
results_placeholder = gr.Markdown(
|
| 436 |
"*(Les résultats apparaîtront ici après soumission)*"
|
| 437 |
)
|
|
|
|
| 445 |
student_matrix_plot = gr.Plot(label="Votre interprétation vs Enseignant")
|
| 446 |
|
| 447 |
# ── Tab 4: Entraînement du modèle KNN ──────────────────────────────
|
| 448 |
+
with gr.Tab("Entraînement du modèle KNN"):
|
| 449 |
gr.Markdown("""
|
| 450 |
## Entraînez votre propre modèle KNN
|
| 451 |
|
|
|
|
| 459 |
label="k (nombre de voisins)",
|
| 460 |
)
|
| 461 |
btn_train = gr.Button(
|
| 462 |
+
"Entraîner mon modèle KNN",
|
| 463 |
variant="primary",
|
| 464 |
size="lg",
|
| 465 |
)
|
|
|
|
| 482 |
visible=False,
|
| 483 |
)
|
| 484 |
|
| 485 |
+
# ── Tab 5: Régression linéaire, pour comparaison ────────────────────
|
| 486 |
+
with gr.Tab("Régression linéaire (comparaison)"):
|
| 487 |
+
gr.Markdown("""
|
| 488 |
+
## Un algorithme de régression est-il adapté à ce problème ?
|
| 489 |
+
|
| 490 |
+
Les numéros de classe (1 à 7) sont des **catégories** (nominales), pas une
|
| 491 |
+
échelle continue : la classe 4 n'est pas "le double" de la classe 2. Un
|
| 492 |
+
algorithme de régression linéaire l'ignore complètement : il essaie de
|
| 493 |
+
prédire un nombre continu (par exemple 4.37) à partir des valeurs spectrales,
|
| 494 |
+
puis on arrondit à la classe la plus proche pour pouvoir comparer.
|
| 495 |
+
|
| 496 |
+
Entraînez-le ci-dessous sur les mêmes 23 étiquettes que votre modèle KNN,
|
| 497 |
+
pour voir comment un algorithme mal adapté au problème se comporte.
|
| 498 |
+
""")
|
| 499 |
+
reg_warning_md = gr.Markdown(visible=False)
|
| 500 |
+
btn_train_reg = gr.Button(
|
| 501 |
+
"Entraîner le modèle de régression linéaire",
|
| 502 |
+
variant="primary",
|
| 503 |
+
size="lg",
|
| 504 |
+
)
|
| 505 |
+
reg_accuracy_md = gr.Markdown(visible=False)
|
| 506 |
+
reg_matrix_plot = gr.Plot(
|
| 507 |
+
label="Régression linéaire vs Vérité terrain",
|
| 508 |
+
visible=False,
|
| 509 |
+
)
|
| 510 |
+
reg_full_plot = gr.Plot(
|
| 511 |
+
label="Carte complète — régression linéaire",
|
| 512 |
+
visible=False,
|
| 513 |
+
)
|
| 514 |
+
|
| 515 |
# ─────────────────────────────────────────────────────────────────────
|
| 516 |
# Event handlers
|
| 517 |
# ─────────────────────────────────────────────────────────────────────
|
|
|
|
| 592 |
total = count_labeled(current_labels)
|
| 593 |
if total < N_POLYGONS:
|
| 594 |
warning = (
|
| 595 |
+
f"Vous n'avez étiqueté que {total}/{N_POLYGONS} polygones. "
|
| 596 |
+
f"Terminez l'étiquetage dans l'onglet *Interprétation des polygones* "
|
| 597 |
f"avant d'entraîner un modèle."
|
| 598 |
)
|
| 599 |
return (
|
|
|
|
| 618 |
model_fig = fig_model_matrix(model_matrix, model_oa)
|
| 619 |
knn_fig = fig_knn_matrix()
|
| 620 |
map_fig = fig_gt_maps(pred_gt, y_gt, knn_ref_gt)
|
| 621 |
+
full_fig = fig_full_maps(
|
| 622 |
+
(pred_full, "Votre modèle KNN — carte complète"),
|
| 623 |
+
(DATA['knn_result'], "Modèle de référence (enseignant) — carte complète"),
|
| 624 |
+
)
|
| 625 |
|
| 626 |
return (
|
| 627 |
gr.update(visible=False),
|
|
|
|
| 633 |
gr.update(value=full_fig, visible=True),
|
| 634 |
)
|
| 635 |
|
| 636 |
+
def on_train_regression(current_labels):
|
| 637 |
+
"""Train a plain linear regression on the student's own labels, to show
|
| 638 |
+
why a model not designed for categorical classes performs poorly."""
|
| 639 |
+
total = count_labeled(current_labels)
|
| 640 |
+
if total < N_POLYGONS:
|
| 641 |
+
warning = (
|
| 642 |
+
f"Vous n'avez étiqueté que {total}/{N_POLYGONS} polygones. "
|
| 643 |
+
f"Terminez l'étiquetage dans l'onglet *Interprétation des polygones* "
|
| 644 |
+
f"avant d'entraîner un modèle."
|
| 645 |
+
)
|
| 646 |
+
return (
|
| 647 |
+
gr.update(value=warning, visible=True),
|
| 648 |
+
gr.update(visible=False),
|
| 649 |
+
gr.update(visible=False),
|
| 650 |
+
gr.update(visible=False),
|
| 651 |
+
)
|
| 652 |
+
|
| 653 |
+
model_oa, model_matrix, pred_full = train_and_predict_regression(current_labels)
|
| 654 |
+
acc_text = (
|
| 655 |
+
f"**Précision globale = {model_oa*100:.1f}%**\n\n"
|
| 656 |
+
f"*(Comparez ce chiffre à la précision de votre modèle KNN dans l'onglet précédent — "
|
| 657 |
+
f"la régression linéaire prédit un nombre continu puis l'arrondit à la classe la plus "
|
| 658 |
+
f"proche, ce qui n'a pas de sens pour des catégories non ordonnées.)*"
|
| 659 |
+
)
|
| 660 |
+
matrix_fig = fig_confusion_matrix(
|
| 661 |
+
model_matrix, model_oa,
|
| 662 |
+
"Matrice de confusion – Régression linéaire vs Vérité terrain",
|
| 663 |
+
cmap='Reds',
|
| 664 |
+
)
|
| 665 |
+
full_fig = fig_full_maps((pred_full, "Régression linéaire — carte complète"))
|
| 666 |
+
|
| 667 |
+
return (
|
| 668 |
+
gr.update(visible=False),
|
| 669 |
+
gr.update(value=acc_text, visible=True),
|
| 670 |
+
gr.update(value=matrix_fig, visible=True),
|
| 671 |
+
gr.update(value=full_fig, visible=True),
|
| 672 |
+
)
|
| 673 |
+
|
| 674 |
# Wire up navigation (Précédent / Suivant / direct jump-to-polygon dropdown —
|
| 675 |
# all three can be used freely and repeatedly, in any order, at any time)
|
| 676 |
btn_prev.click(
|
|
|
|
| 733 |
],
|
| 734 |
)
|
| 735 |
|
| 736 |
+
# Wire up regression training (separate tab, for comparison against KNN)
|
| 737 |
+
btn_train_reg.click(
|
| 738 |
+
on_train_regression,
|
| 739 |
+
inputs=[labels],
|
| 740 |
+
outputs=[
|
| 741 |
+
reg_warning_md,
|
| 742 |
+
reg_accuracy_md,
|
| 743 |
+
reg_matrix_plot,
|
| 744 |
+
reg_full_plot,
|
| 745 |
+
],
|
| 746 |
+
)
|
| 747 |
+
|
| 748 |
if __name__ == "__main__":
|
| 749 |
demo.launch(server_name="0.0.0.0", server_port=7860)
|