CircleStar commited on
Commit
56e1278
·
verified ·
1 Parent(s): 1863095

Rename Delta/desert classes, redesign class legend, widen KNN k range to 10-100, add Kappa/F1 metrics and per-class pixel histograms, remove teacher-reference comparisons from model tabs

Browse files
Files changed (1) hide show
  1. app.py +153 -133
app.py CHANGED
@@ -11,23 +11,27 @@ from sklearn.neighbors import KNeighborsClassifier
11
  from sklearn.linear_model import LogisticRegression
12
  from sklearn.ensemble import RandomForestClassifier
13
  from sklearn.preprocessing import StandardScaler
 
14
 
15
  # ─────────────────────────────────────────────────────────────────────────────
16
  # Constants
17
  # ─────────────────────────────────────────────────────────────────────────────
18
  N_POLYGONS = 23
19
- K_MIN, K_MAX, K_DEFAULT = 1, 15, 5
20
 
21
  CLASSES = {
22
  1: "Eau",
23
- 2: "Vergers",
24
  3: "Cultures dans le Delta",
25
  4: "Zones bâties",
26
  5: "Cultures irriguées dans le désert",
27
- 6: "Cultures non irriguées en zone sèche",
28
  7: "Zones sableuses",
29
  }
30
 
 
 
 
31
  CLASS_CHOICES = [f"{k} - {v}" for k, v in CLASSES.items()]
32
 
33
  # index 0 = fond / non classé, 1..7 = classes ci-dessus
@@ -36,6 +40,27 @@ COLORS_RGB = np.array([
36
  [220, 50, 50], [255, 165, 0], [160, 90, 30], [240, 230, 140],
37
  ], dtype=np.uint8)
38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  BAND_FILES = [
40
  'band_1_uv.tif', 'band_2_blue.tif', 'band_3_green.tif', 'band_4_red.tif',
41
  'band_5_nir.tif', 'band_6_swir1.tif', 'band_7_swir2.tif',
@@ -61,7 +86,6 @@ def load_data():
61
  return src.read(1)
62
 
63
  ground_truth = CLASS_REMAP_LUT[read_tif('ground_truth.tif')]
64
- knn_result = CLASS_REMAP_LUT[read_tif('knn_result.tif')]
65
  training_ids = read_tif('training_polygons.tif')
66
 
67
  bands = np.stack(
@@ -71,25 +95,14 @@ def load_data():
71
  with open(os.path.join(BASE_DIR, 'data', 'polygon_teacher_classes.json')) as f:
72
  polygon_teacher = {int(k): v for k, v in json.load(f).items()}
73
 
74
- # Pre-compute reference KNN confusion matrix (teacher labels, pixels where GT > 0)
75
- gt_flat = ground_truth.flatten()
76
- knn_flat = knn_result.flatten()
77
- valid = gt_flat > 0
78
- knn_matrix = np.zeros((7, 7), dtype=np.int64)
79
- np.add.at(knn_matrix, (gt_flat[valid] - 1, knn_flat[valid] - 1), 1)
80
- knn_oa = knn_matrix.diagonal().sum() / knn_matrix.sum()
81
-
82
  # Row/col coordinates of the Ground Truth pixels, for point-based map plots
83
  gt_rows, gt_cols = np.where(ground_truth > 0)
84
 
85
  return dict(
86
  polygon_teacher= polygon_teacher,
87
  ground_truth = ground_truth,
88
- knn_result = knn_result,
89
  training_ids = training_ids,
90
  bands = bands,
91
- knn_matrix = knn_matrix,
92
- knn_oa = knn_oa,
93
  gt_rows = gt_rows,
94
  gt_cols = gt_cols,
95
  )
@@ -106,7 +119,6 @@ def train_and_predict(student_labels, k):
106
  bands = DATA['bands']
107
  training_ids = DATA['training_ids']
108
  ground_truth = DATA['ground_truth']
109
- knn_result = DATA['knn_result']
110
 
111
  train_mask = training_ids > 0
112
  X_train = bands[train_mask]
@@ -121,7 +133,6 @@ def train_and_predict(student_labels, k):
121
  X_gt = bands[gt_mask]
122
  pred_gt = clf.predict(scaler.transform(X_gt))
123
  y_gt = ground_truth[gt_mask]
124
- knn_ref_gt = knn_result[gt_mask]
125
 
126
  model_matrix = np.zeros((7, 7), dtype=np.int64)
127
  np.add.at(model_matrix, (y_gt - 1, pred_gt - 1), 1)
@@ -133,7 +144,7 @@ def train_and_predict(student_labels, k):
133
  H, W, n_bands = bands.shape
134
  pred_full = clf.predict(scaler.transform(bands.reshape(-1, n_bands))).reshape(H, W)
135
 
136
- return model_oa, model_matrix, pred_gt, y_gt, knn_ref_gt, pred_full
137
 
138
  def train_and_predict_logreg(student_labels):
139
  """Train a multinomial logistic regression on the student's 23 labeled
@@ -143,7 +154,6 @@ def train_and_predict_logreg(student_labels):
143
  bands = DATA['bands']
144
  training_ids = DATA['training_ids']
145
  ground_truth = DATA['ground_truth']
146
- knn_result = DATA['knn_result']
147
 
148
  train_mask = training_ids > 0
149
  X_train = bands[train_mask]
@@ -157,7 +167,6 @@ def train_and_predict_logreg(student_labels):
157
  X_gt = bands[gt_mask]
158
  pred_gt = clf.predict(scaler.transform(X_gt))
159
  y_gt = ground_truth[gt_mask]
160
- knn_ref_gt = knn_result[gt_mask]
161
 
162
  model_matrix = np.zeros((7, 7), dtype=np.int64)
163
  np.add.at(model_matrix, (y_gt - 1, pred_gt - 1), 1)
@@ -166,7 +175,7 @@ def train_and_predict_logreg(student_labels):
166
  H, W, n_bands = bands.shape
167
  pred_full = clf.predict(scaler.transform(bands.reshape(-1, n_bands))).reshape(H, W)
168
 
169
- return model_oa, model_matrix, pred_gt, y_gt, knn_ref_gt, pred_full
170
 
171
  def train_and_predict_rf(student_labels):
172
  """Train a random forest on the student's 23 labeled polygons (using the
@@ -176,7 +185,6 @@ def train_and_predict_rf(student_labels):
176
  bands = DATA['bands']
177
  training_ids = DATA['training_ids']
178
  ground_truth = DATA['ground_truth']
179
- knn_result = DATA['knn_result']
180
 
181
  train_mask = training_ids > 0
182
  X_train = bands[train_mask]
@@ -189,7 +197,6 @@ def train_and_predict_rf(student_labels):
189
  X_gt = bands[gt_mask]
190
  pred_gt = clf.predict(X_gt)
191
  y_gt = ground_truth[gt_mask]
192
- knn_ref_gt = knn_result[gt_mask]
193
 
194
  model_matrix = np.zeros((7, 7), dtype=np.int64)
195
  np.add.at(model_matrix, (y_gt - 1, pred_gt - 1), 1)
@@ -198,7 +205,7 @@ def train_and_predict_rf(student_labels):
198
  H, W, n_bands = bands.shape
199
  pred_full = clf.predict(bands.reshape(-1, n_bands)).reshape(H, W)
200
 
201
- return model_oa, model_matrix, pred_gt, y_gt, knn_ref_gt, pred_full
202
 
203
  # ─────────────────────────────────────────────────────────────────────────────
204
  # Visualization helpers
@@ -216,7 +223,7 @@ def add_class_legend(fig):
216
 
217
  def fig_confusion_matrix(matrix, oa, title, cmap='Blues'):
218
  """Generic 7×7 confusion matrix plot: predicted classes vs Ground Truth."""
219
- short = ["Eau", "Vergers", "Δ-Cult.", "Bâti", "Irr.-Dés.", "Non-Irr.", "Sable"]
220
  fig, ax = plt.subplots(figsize=(9, 7))
221
 
222
  row_tot = matrix.sum(axis=1, keepdims=True)
@@ -243,14 +250,6 @@ def fig_confusion_matrix(matrix, oa, title, cmap='Blues'):
243
  plt.tight_layout()
244
  return fig
245
 
246
- def fig_knn_matrix():
247
- """Reference matrix: pre-computed KNN (trained on teacher labels) vs Ground Truth."""
248
- return fig_confusion_matrix(
249
- DATA['knn_matrix'], DATA['knn_oa'],
250
- "Matrice de confusion – Modèle de référence (enseignant) vs Vérité terrain",
251
- cmap='Blues',
252
- )
253
-
254
  def fig_model_matrix(model_matrix, model_oa):
255
  """Student's own trained KNN model vs Ground Truth."""
256
  return fig_confusion_matrix(
@@ -259,22 +258,21 @@ def fig_model_matrix(model_matrix, model_oa):
259
  cmap='Purples',
260
  )
261
 
262
- def fig_gt_maps(pred_gt, y_gt, knn_ref_gt, model_label="Votre modèle KNN"):
263
  """Point maps AT THE GROUND TRUTH PIXELS ONLY (the only place where the
264
- right answer is actually known) — Ground Truth / your model / reference
265
- model, plus a 4th panel showing exactly where your model is right (green)
266
- or wrong (red) vs Ground Truth. Only plotting these ~21k points (instead
267
- of classifying and coloring the whole image) is what makes it possible to
268
- actually see where the classification is correct."""
269
  rows = DATA['gt_rows']
270
  cols = DATA['gt_cols']
271
  correct = (pred_gt == y_gt)
272
 
273
- fig, axes = plt.subplots(1, 4, figsize=(20, 5.5))
274
  panels = [
275
  (y_gt, "Vérité terrain", None),
276
  (pred_gt, model_label, None),
277
- (knn_ref_gt, "Modèle de référence (enseignant)", None),
278
  (None, f"{model_label} : correct (vert) / erreur (rouge)", correct),
279
  ]
280
  for ax, (classes, title, correctness) in zip(axes, panels):
@@ -317,6 +315,26 @@ def fig_full_maps(*panels):
317
  add_class_legend(fig)
318
  return fig
319
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
320
  def fig_student_matrix(student_labels):
321
  """7×7 confusion matrix: student labels vs teacher labels."""
322
  matrix = np.zeros((7, 7), dtype=int)
@@ -326,7 +344,7 @@ def fig_student_matrix(student_labels):
326
  if s is not None and t > 0:
327
  matrix[t - 1][int(s) - 1] += 1
328
 
329
- short = ["Eau", "Vergers", "Δ-Cult.", "Bâti", "Irr.-Dés.", "Non-Irr.", "Sable"]
330
  fig, ax = plt.subplots(figsize=(8, 6))
331
 
332
  row_tot = matrix.sum(axis=1, keepdims=True)
@@ -396,27 +414,28 @@ puis soumettez vos réponses pour générer la carte et la matrice de confusion.
396
 
397
  # ── Tab 1: Légende des classes ────────────────────────────────────
398
  with gr.Tab("Classes d'occupation du sol"):
 
399
  gr.Markdown("""
400
- ## Classes d'occupation du sol
401
-
402
- | N° | Classe | Couleur |
403
- |----|--------|---------|
404
- | 1 | Eau | 🔵 Bleu |
405
- | 2 | Vergers | 🟢 Vert foncé |
406
- | 3 | Cultures dans le Delta | 💚 Vert clair |
407
- | 4 | Zones bâties | 🔴 Rouge |
408
- | 5 | Cultures irriguées dans le désert | 🟠 Orange |
409
- | 6 | Cultures non irriguées en zone sèche | 🟤 Marron |
410
- | 7 | Zones sableuses | 🟡 Jaune clair |
411
-
412
  ---
413
  **Conseils d'interprétation :**
414
- - L'image montre une composition colorée de l'image Landsat
415
- - Les zones bleues/sombres correspondent à l'eau
416
- - La végétation dense apparaît en vert (vergers, cultures dans le delta)
417
- - Les zones bâties apparaissent en teintes rosées ou grises
418
- - Les zones cultivées irriguées dans le désert forment des parcelles géométriques
419
- - Les zones sableuses apparaissent en jaune/beige
 
 
 
 
 
 
 
 
 
 
 
 
420
  """)
421
 
422
  # ── Tab 2: Interprétation ─────────────────────────────────────────
@@ -496,21 +515,24 @@ sur les pixels de vérité terrain (indépendants des polygones d'entraînement)
496
  size="lg",
497
  )
498
  logreg_accuracy_md = gr.Markdown(visible=False)
499
- with gr.Row(visible=False) as row_plots_logreg:
500
- logreg_matrix_plot = gr.Plot(label="Votre modèle de régression logistique vs Vérité terrain")
501
- logreg_knn_plot = gr.Plot(label="Modèle de référence (enseignant) vs Vérité terrain")
502
  logreg_map_plot = gr.Plot(
503
  label="Cartes aux emplacements de vérité terrain (seuls points où la vraie classe est connue)",
504
  visible=False,
505
  )
506
  gr.Markdown(
507
- "*(Ci-dessous : les deux modèles classifient en réalité l'image entière — "
508
  "y compris les zones sans vérité terrain. On ne peut pas y vérifier si "
509
- "c'est correct, mais on peut voir à quoi ressemble la classification complète.)*",
 
510
  visible=True,
511
  )
512
  logreg_full_plot = gr.Plot(
513
- label="Cartes de classification complètes (tous les pixels, précision non évaluable)",
 
 
 
 
514
  visible=False,
515
  )
516
 
@@ -525,7 +547,7 @@ sur les pixels de vérité terrain (indépendants des polygones d'entraînement)
525
  """)
526
  train_warning_md = gr.Markdown(visible=False)
527
  k_slider = gr.Slider(
528
- minimum=K_MIN, maximum=K_MAX, value=K_DEFAULT, step=1,
529
  label="k (nombre de voisins)",
530
  )
531
  btn_train = gr.Button(
@@ -534,21 +556,24 @@ sur les pixels de vérité terrain (indépendants des polygones d'entraînement)
534
  size="lg",
535
  )
536
  model_accuracy_md = gr.Markdown(visible=False)
537
- with gr.Row(visible=False) as row_plots_model:
538
- model_matrix_plot = gr.Plot(label="Votre modèle KNN vs Vérité terrain")
539
- knn_plot = gr.Plot(label="Modèle de référence (enseignant) vs Vérité terrain")
540
  three_panel_plot = gr.Plot(
541
  label="Cartes aux emplacements de vérité terrain (seuls points où la vraie classe est connue)",
542
  visible=False,
543
  )
544
  gr.Markdown(
545
- "*(Ci-dessous : les deux modèles classifient en réalité l'image entière — "
546
  "y compris les zones sans vérité terrain. On ne peut pas y vérifier si "
547
- "c'est correct, mais on peut voir à quoi ressemble la classification complète.)*",
 
548
  visible=True,
549
  )
550
  full_maps_plot = gr.Plot(
551
- label="Cartes de classification complètes (tous les pixels, précision non évaluable)",
 
 
 
 
552
  visible=False,
553
  )
554
 
@@ -572,21 +597,24 @@ sur les pixels de vérité terrain (indépendants des polygones d'entraînement)
572
  size="lg",
573
  )
574
  rf_accuracy_md = gr.Markdown(visible=False)
575
- with gr.Row(visible=False) as row_plots_rf:
576
- rf_matrix_plot = gr.Plot(label="Votre modèle de forêt aléatoire vs Vérité terrain")
577
- rf_knn_plot = gr.Plot(label="Modèle de référence (enseignant) vs Vérité terrain")
578
  rf_map_plot = gr.Plot(
579
  label="Cartes aux emplacements de vérité terrain (seuls points où la vraie classe est connue)",
580
  visible=False,
581
  )
582
  gr.Markdown(
583
- "*(Ci-dessous : les deux modèles classifient en réalité l'image entière — "
584
  "y compris les zones sans vérité terrain. On ne peut pas y vérifier si "
585
- "c'est correct, mais on peut voir à quoi ressemble la classification complète.)*",
 
586
  visible=True,
587
  )
588
  rf_full_plot = gr.Plot(
589
- label="Cartes de classification complètes (tous les pixels, précision non évaluable)",
 
 
 
 
590
  visible=False,
591
  )
592
 
@@ -678,37 +706,34 @@ sur les pixels de vérité terrain (indépendants des polygones d'entraînement)
678
  gr.update(value=warning, visible=True),
679
  gr.update(visible=False),
680
  gr.update(visible=False),
681
- gr.update(),
682
- gr.update(),
683
  gr.update(visible=False),
684
  gr.update(visible=False),
685
  )
686
 
687
- model_oa, model_matrix, pred_gt, y_gt, knn_ref_gt, pred_full = train_and_predict(
688
  current_labels, k
689
  )
 
 
690
  model_acc_text = (
691
- f"**Précision globale = {model_oa*100:.1f}%** "
692
- f"(évaluée sur les {len(y_gt)} pixels de vérité terrain, k={int(k)})\n\n"
693
- f"*(C'est la précision réelle d'un modèle KNN entraîné uniquement sur VOS 23 polygones étiquetés — "
694
- f"comparez-la à celle du modèle de référence de l'enseignant ci-dessous)*"
695
  )
696
  model_fig = fig_model_matrix(model_matrix, model_oa)
697
- knn_fig = fig_knn_matrix()
698
- map_fig = fig_gt_maps(pred_gt, y_gt, knn_ref_gt)
699
- full_fig = fig_full_maps(
700
- (pred_full, "Votre modèle KNN — carte complète"),
701
- (DATA['knn_result'], "Modèle de référence (enseignant) — carte complète"),
702
- )
703
 
704
  return (
705
  gr.update(visible=False),
706
  gr.update(value=model_acc_text, visible=True),
707
- gr.update(visible=True),
708
- gr.update(value=model_fig),
709
- gr.update(value=knn_fig),
710
  gr.update(value=map_fig, visible=True),
711
  gr.update(value=full_fig, visible=True),
 
712
  )
713
 
714
  def on_train_logreg(current_labels):
@@ -725,42 +750,41 @@ sur les pixels de vérité terrain (indépendants des polygones d'entraînement)
725
  gr.update(value=warning, visible=True),
726
  gr.update(visible=False),
727
  gr.update(visible=False),
728
- gr.update(),
729
- gr.update(),
730
  gr.update(visible=False),
731
  gr.update(visible=False),
732
  )
733
 
734
- model_oa, model_matrix, pred_gt, y_gt, knn_ref_gt, pred_full = train_and_predict_logreg(
735
  current_labels
736
  )
 
 
737
  model_acc_text = (
738
- f"**Précision globale = {model_oa*100:.1f}%** "
739
- f"(évaluée sur les {len(y_gt)} pixels de vérité terrain)\n\n"
740
- f"*(C'est la précision réelle d'un modèle de régression logistique entraîné uniquement "
741
- f"sur VOS 23 polygones étiquetés — comparez-la à celle du modèle de référence de "
742
- f"l'enseignant ci-dessous, et à votre modèle KNN dans l'onglet suivant)*"
743
  )
744
  model_fig = fig_confusion_matrix(
745
  model_matrix, model_oa,
746
  "Matrice de confusion – VOTRE modèle de régression logistique vs Vérité terrain",
747
  cmap='Reds',
748
  )
749
- knn_fig = fig_knn_matrix()
750
- map_fig = fig_gt_maps(pred_gt, y_gt, knn_ref_gt, model_label="Votre modèle de régression logistique")
751
- full_fig = fig_full_maps(
752
- (pred_full, "Votre modèle de régression logistique — carte complète"),
753
- (DATA['knn_result'], "Modèle de référence (enseignant) — carte complète"),
754
  )
755
 
756
  return (
757
  gr.update(visible=False),
758
  gr.update(value=model_acc_text, visible=True),
759
- gr.update(visible=True),
760
- gr.update(value=model_fig),
761
- gr.update(value=knn_fig),
762
  gr.update(value=map_fig, visible=True),
763
  gr.update(value=full_fig, visible=True),
 
764
  )
765
 
766
  def on_train_rf(current_labels):
@@ -777,42 +801,41 @@ sur les pixels de vérité terrain (indépendants des polygones d'entraînement)
777
  gr.update(value=warning, visible=True),
778
  gr.update(visible=False),
779
  gr.update(visible=False),
780
- gr.update(),
781
- gr.update(),
782
  gr.update(visible=False),
783
  gr.update(visible=False),
784
  )
785
 
786
- model_oa, model_matrix, pred_gt, y_gt, knn_ref_gt, pred_full = train_and_predict_rf(
787
  current_labels
788
  )
 
 
789
  model_acc_text = (
790
- f"**Précision globale = {model_oa*100:.1f}%** "
791
- f"(évaluée sur les {len(y_gt)} pixels de vérité terrain)\n\n"
792
- f"*(C'est la précision réelle d'une forêt aléatoire entraînée uniquement sur VOS 23 "
793
- f"polygones étiquetés — comparez-la à celle du modèle de référence de l'enseignant "
794
- f"ci-dessous, et à vos autres modèles dans les onglets précédents)*"
795
  )
796
  model_fig = fig_confusion_matrix(
797
  model_matrix, model_oa,
798
  "Matrice de confusion – VOTRE modèle de forêt aléatoire vs Vérité terrain",
799
  cmap='Oranges',
800
  )
801
- knn_fig = fig_knn_matrix()
802
- map_fig = fig_gt_maps(pred_gt, y_gt, knn_ref_gt, model_label="Votre modèle de forêt aléatoire")
803
- full_fig = fig_full_maps(
804
- (pred_full, "Votre modèle de forêt aléatoire — carte complète"),
805
- (DATA['knn_result'], "Modèle de référence (enseignant) — carte complète"),
806
  )
807
 
808
  return (
809
  gr.update(visible=False),
810
  gr.update(value=model_acc_text, visible=True),
811
- gr.update(visible=True),
812
- gr.update(value=model_fig),
813
- gr.update(value=knn_fig),
814
  gr.update(value=map_fig, visible=True),
815
  gr.update(value=full_fig, visible=True),
 
816
  )
817
 
818
  # Wire up navigation (Précédent / Suivant / direct jump-to-polygon dropdown —
@@ -869,11 +892,10 @@ sur les pixels de vérité terrain (indépendants des polygones d'entraînement)
869
  outputs=[
870
  train_warning_md,
871
  model_accuracy_md,
872
- row_plots_model,
873
  model_matrix_plot,
874
- knn_plot,
875
  three_panel_plot,
876
  full_maps_plot,
 
877
  ],
878
  )
879
 
@@ -884,11 +906,10 @@ sur les pixels de vérité terrain (indépendants des polygones d'entraînement)
884
  outputs=[
885
  logreg_warning_md,
886
  logreg_accuracy_md,
887
- row_plots_logreg,
888
  logreg_matrix_plot,
889
- logreg_knn_plot,
890
  logreg_map_plot,
891
  logreg_full_plot,
 
892
  ],
893
  )
894
 
@@ -899,11 +920,10 @@ sur les pixels de vérité terrain (indépendants des polygones d'entraînement)
899
  outputs=[
900
  rf_warning_md,
901
  rf_accuracy_md,
902
- row_plots_rf,
903
  rf_matrix_plot,
904
- rf_knn_plot,
905
  rf_map_plot,
906
  rf_full_plot,
 
907
  ],
908
  )
909
 
 
11
  from sklearn.linear_model import LogisticRegression
12
  from sklearn.ensemble import RandomForestClassifier
13
  from sklearn.preprocessing import StandardScaler
14
+ from sklearn.metrics import cohen_kappa_score, f1_score
15
 
16
  # ─────────────────────────────────────────────────────────────────────────────
17
  # Constants
18
  # ─────────────────────────────────────────────────────────────────────────────
19
  N_POLYGONS = 23
20
+ K_MIN, K_MAX, K_DEFAULT = 10, 100, 50
21
 
22
  CLASSES = {
23
  1: "Eau",
24
+ 2: "Vergers dans le Delta",
25
  3: "Cultures dans le Delta",
26
  4: "Zones bâties",
27
  5: "Cultures irriguées dans le désert",
28
+ 6: "Vergers goutte à goutte dans le désert",
29
  7: "Zones sableuses",
30
  }
31
 
32
+ # Compact labels for axis ticks / legends where the full names above don't fit.
33
+ CLASS_SHORT = ["Eau", "Vergers", "Δ-Cult.", "Bâti", "Irr.-Dés.", "G-à-G Dés.", "Sable"]
34
+
35
  CLASS_CHOICES = [f"{k} - {v}" for k, v in CLASSES.items()]
36
 
37
  # index 0 = fond / non classé, 1..7 = classes ci-dessus
 
40
  [220, 50, 50], [255, 165, 0], [160, 90, 30], [240, 230, 140],
41
  ], dtype=np.uint8)
42
 
43
+ def rgb_to_hex(rgb):
44
+ return '#{:02x}{:02x}{:02x}'.format(*rgb)
45
+
46
+ def build_class_legend_md():
47
+ """Legend table with real color swatches (matching COLORS_RGB exactly),
48
+ instead of emoji — some emoji pairs (e.g. green circle / green heart)
49
+ render too close in hue to tell classes apart."""
50
+ rows = "\n".join(
51
+ f'| {i} | {CLASSES[i]} | '
52
+ f'<span style="display:inline-block;width:16px;height:16px;'
53
+ f'background-color:{rgb_to_hex(COLORS_RGB[i])};border:1px solid #888;'
54
+ f'border-radius:3px;vertical-align:middle;"></span> |'
55
+ for i in range(1, 8)
56
+ )
57
+ return f"""## Classes d'occupation du sol
58
+
59
+ | N° | Classe | Couleur |
60
+ |----|--------|---------|
61
+ {rows}
62
+ """
63
+
64
  BAND_FILES = [
65
  'band_1_uv.tif', 'band_2_blue.tif', 'band_3_green.tif', 'band_4_red.tif',
66
  'band_5_nir.tif', 'band_6_swir1.tif', 'band_7_swir2.tif',
 
86
  return src.read(1)
87
 
88
  ground_truth = CLASS_REMAP_LUT[read_tif('ground_truth.tif')]
 
89
  training_ids = read_tif('training_polygons.tif')
90
 
91
  bands = np.stack(
 
95
  with open(os.path.join(BASE_DIR, 'data', 'polygon_teacher_classes.json')) as f:
96
  polygon_teacher = {int(k): v for k, v in json.load(f).items()}
97
 
 
 
 
 
 
 
 
 
98
  # Row/col coordinates of the Ground Truth pixels, for point-based map plots
99
  gt_rows, gt_cols = np.where(ground_truth > 0)
100
 
101
  return dict(
102
  polygon_teacher= polygon_teacher,
103
  ground_truth = ground_truth,
 
104
  training_ids = training_ids,
105
  bands = bands,
 
 
106
  gt_rows = gt_rows,
107
  gt_cols = gt_cols,
108
  )
 
119
  bands = DATA['bands']
120
  training_ids = DATA['training_ids']
121
  ground_truth = DATA['ground_truth']
 
122
 
123
  train_mask = training_ids > 0
124
  X_train = bands[train_mask]
 
133
  X_gt = bands[gt_mask]
134
  pred_gt = clf.predict(scaler.transform(X_gt))
135
  y_gt = ground_truth[gt_mask]
 
136
 
137
  model_matrix = np.zeros((7, 7), dtype=np.int64)
138
  np.add.at(model_matrix, (y_gt - 1, pred_gt - 1), 1)
 
144
  H, W, n_bands = bands.shape
145
  pred_full = clf.predict(scaler.transform(bands.reshape(-1, n_bands))).reshape(H, W)
146
 
147
+ return model_oa, model_matrix, pred_gt, y_gt, pred_full
148
 
149
  def train_and_predict_logreg(student_labels):
150
  """Train a multinomial logistic regression on the student's 23 labeled
 
154
  bands = DATA['bands']
155
  training_ids = DATA['training_ids']
156
  ground_truth = DATA['ground_truth']
 
157
 
158
  train_mask = training_ids > 0
159
  X_train = bands[train_mask]
 
167
  X_gt = bands[gt_mask]
168
  pred_gt = clf.predict(scaler.transform(X_gt))
169
  y_gt = ground_truth[gt_mask]
 
170
 
171
  model_matrix = np.zeros((7, 7), dtype=np.int64)
172
  np.add.at(model_matrix, (y_gt - 1, pred_gt - 1), 1)
 
175
  H, W, n_bands = bands.shape
176
  pred_full = clf.predict(scaler.transform(bands.reshape(-1, n_bands))).reshape(H, W)
177
 
178
+ return model_oa, model_matrix, pred_gt, y_gt, pred_full
179
 
180
  def train_and_predict_rf(student_labels):
181
  """Train a random forest on the student's 23 labeled polygons (using the
 
185
  bands = DATA['bands']
186
  training_ids = DATA['training_ids']
187
  ground_truth = DATA['ground_truth']
 
188
 
189
  train_mask = training_ids > 0
190
  X_train = bands[train_mask]
 
197
  X_gt = bands[gt_mask]
198
  pred_gt = clf.predict(X_gt)
199
  y_gt = ground_truth[gt_mask]
 
200
 
201
  model_matrix = np.zeros((7, 7), dtype=np.int64)
202
  np.add.at(model_matrix, (y_gt - 1, pred_gt - 1), 1)
 
205
  H, W, n_bands = bands.shape
206
  pred_full = clf.predict(bands.reshape(-1, n_bands)).reshape(H, W)
207
 
208
+ return model_oa, model_matrix, pred_gt, y_gt, pred_full
209
 
210
  # ─────────────────────────────────────────────────────────────────────────────
211
  # Visualization helpers
 
223
 
224
  def fig_confusion_matrix(matrix, oa, title, cmap='Blues'):
225
  """Generic 7×7 confusion matrix plot: predicted classes vs Ground Truth."""
226
+ short = CLASS_SHORT
227
  fig, ax = plt.subplots(figsize=(9, 7))
228
 
229
  row_tot = matrix.sum(axis=1, keepdims=True)
 
250
  plt.tight_layout()
251
  return fig
252
 
 
 
 
 
 
 
 
 
253
  def fig_model_matrix(model_matrix, model_oa):
254
  """Student's own trained KNN model vs Ground Truth."""
255
  return fig_confusion_matrix(
 
258
  cmap='Purples',
259
  )
260
 
261
+ def fig_gt_maps(pred_gt, y_gt, model_label="Votre modèle KNN"):
262
  """Point maps AT THE GROUND TRUTH PIXELS ONLY (the only place where the
263
+ right answer is actually known) — Ground Truth / your model, plus a 3rd
264
+ panel showing exactly where your model is right (green) or wrong (red)
265
+ vs Ground Truth. Only plotting these ~21k points (instead of classifying
266
+ and coloring the whole image) is what makes it possible to actually see
267
+ where the classification is correct."""
268
  rows = DATA['gt_rows']
269
  cols = DATA['gt_cols']
270
  correct = (pred_gt == y_gt)
271
 
272
+ fig, axes = plt.subplots(1, 3, figsize=(15, 5.5))
273
  panels = [
274
  (y_gt, "Vérité terrain", None),
275
  (pred_gt, model_label, None),
 
276
  (None, f"{model_label} : correct (vert) / erreur (rouge)", correct),
277
  ]
278
  for ax, (classes, title, correctness) in zip(axes, panels):
 
315
  add_class_legend(fig)
316
  return fig
317
 
318
+ def fig_class_histogram(pred_full, title):
319
+ """Bar chart of pixel counts per class over the FULL classification map —
320
+ lets students see effects (e.g. smoothing at large k) that only show up
321
+ at remote-sensing scale, not just in the 21k-pixel Ground Truth sample."""
322
+ counts = np.array([(pred_full == c).sum() for c in range(1, 8)])
323
+ pct = counts / counts.sum() * 100
324
+ colors = COLORS_RGB[1:8] / 255.0
325
+
326
+ fig, ax = plt.subplots(figsize=(9, 4.5))
327
+ bars = ax.bar(range(1, 8), counts, color=colors, edgecolor='#555', linewidth=0.6)
328
+ ax.set_xticks(range(1, 8))
329
+ ax.set_xticklabels([f"{i}\n{CLASS_SHORT[i-1]}" for i in range(1, 8)], fontsize=8)
330
+ ax.set_ylabel("Nombre de pixels")
331
+ ax.set_title(title, fontsize=11, fontweight='bold')
332
+ for bar, p in zip(bars, pct):
333
+ ax.text(bar.get_x() + bar.get_width() / 2, bar.get_height(),
334
+ f"{p:.1f}%", ha='center', va='bottom', fontsize=8)
335
+ plt.tight_layout()
336
+ return fig
337
+
338
  def fig_student_matrix(student_labels):
339
  """7×7 confusion matrix: student labels vs teacher labels."""
340
  matrix = np.zeros((7, 7), dtype=int)
 
344
  if s is not None and t > 0:
345
  matrix[t - 1][int(s) - 1] += 1
346
 
347
+ short = CLASS_SHORT
348
  fig, ax = plt.subplots(figsize=(8, 6))
349
 
350
  row_tot = matrix.sum(axis=1, keepdims=True)
 
414
 
415
  # ── Tab 1: Légende des classes ────────────────────────────────────
416
  with gr.Tab("Classes d'occupation du sol"):
417
+ gr.Markdown(build_class_legend_md())
418
  gr.Markdown("""
 
 
 
 
 
 
 
 
 
 
 
 
419
  ---
420
  **Conseils d'interprétation :**
421
+
422
+ 📺 [Vidéo explicative du TD](https://pod.univ-cotedazur.fr/video/22169-ctia-l3-shs-hist-geo-tld-3_4mp4/)
423
+
424
+ L'image de l'exercice est centrée sur la limite entre deux espaces géographiques très
425
+ contrastés aux marges du delta du Nil, en Égypte. À l'est, se trouve une partie du
426
+ Delta : les terres y sont influencées par l'hydrologie du fleuve — des sols fertiles,
427
+ de l'eau facilement accessible, on y distingue des bras du Nil, des zones bâties et
428
+ deux types de cultures : des vergers (palmiers dattiers et agrumes) et des cultures
429
+ au sol. À l'ouest, se trouve le début d'une zone désertique où des cultures irriguées
430
+ ont lieu dans des périmètres aménagés. On y distingue des zones très fortement
431
+ irriguées avec des cultures actives, et des zones de cultures moins exigeantes en eau
432
+ (vergers arrosés au goutte à goutte) qui, sur l'image satellite, montrent un signal
433
+ mixte des plantes et du sol sableux.
434
+
435
+ Pour une segmentation qui fonctionne bien, la classe « zone sableuse » est entendue
436
+ comme une couverture du sol, pas comme un usage du sol : même si vous devinez des
437
+ structures géométriques liées à l'agriculture, si la teinte est grise, il faut
438
+ l'interpréter comme zone sableuse.
439
  """)
440
 
441
  # ── Tab 2: Interprétation ─────────────────────────────────────────
 
515
  size="lg",
516
  )
517
  logreg_accuracy_md = gr.Markdown(visible=False)
518
+ logreg_matrix_plot = gr.Plot(label="Votre modèle de régression logistique vs Vérité terrain", visible=False)
 
 
519
  logreg_map_plot = gr.Plot(
520
  label="Cartes aux emplacements de vérité terrain (seuls points où la vraie classe est connue)",
521
  visible=False,
522
  )
523
  gr.Markdown(
524
+ "*(Ci-dessous : votre modèle classifie en réalité l'image entière — "
525
  "y compris les zones sans vérité terrain. On ne peut pas y vérifier si "
526
+ "c'est correct, mais on peut voir à quoi ressemble la classification complète, "
527
+ "ainsi que la répartition du nombre de pixels par classe.)*",
528
  visible=True,
529
  )
530
  logreg_full_plot = gr.Plot(
531
+ label="Carte de classification complète (tous les pixels, précision non évaluable)",
532
+ visible=False,
533
+ )
534
+ logreg_hist_plot = gr.Plot(
535
+ label="Histogramme du nombre de pixels par classe (carte complète)",
536
  visible=False,
537
  )
538
 
 
547
  """)
548
  train_warning_md = gr.Markdown(visible=False)
549
  k_slider = gr.Slider(
550
+ minimum=K_MIN, maximum=K_MAX, value=K_DEFAULT, step=10,
551
  label="k (nombre de voisins)",
552
  )
553
  btn_train = gr.Button(
 
556
  size="lg",
557
  )
558
  model_accuracy_md = gr.Markdown(visible=False)
559
+ model_matrix_plot = gr.Plot(label="Votre modèle KNN vs Vérité terrain", visible=False)
 
 
560
  three_panel_plot = gr.Plot(
561
  label="Cartes aux emplacements de vérité terrain (seuls points où la vraie classe est connue)",
562
  visible=False,
563
  )
564
  gr.Markdown(
565
+ "*(Ci-dessous : votre modèle classifie en réalité l'image entière — "
566
  "y compris les zones sans vérité terrain. On ne peut pas y vérifier si "
567
+ "c'est correct, mais on peut voir à quoi ressemble la classification complète, "
568
+ "ainsi que la répartition du nombre de pixels par classe.)*",
569
  visible=True,
570
  )
571
  full_maps_plot = gr.Plot(
572
+ label="Carte de classification complète (tous les pixels, précision non évaluable)",
573
+ visible=False,
574
+ )
575
+ class_hist_plot = gr.Plot(
576
+ label="Histogramme du nombre de pixels par classe (carte complète)",
577
  visible=False,
578
  )
579
 
 
597
  size="lg",
598
  )
599
  rf_accuracy_md = gr.Markdown(visible=False)
600
+ rf_matrix_plot = gr.Plot(label="Votre modèle de forêt aléatoire vs Vérité terrain", visible=False)
 
 
601
  rf_map_plot = gr.Plot(
602
  label="Cartes aux emplacements de vérité terrain (seuls points où la vraie classe est connue)",
603
  visible=False,
604
  )
605
  gr.Markdown(
606
+ "*(Ci-dessous : votre modèle classifie en réalité l'image entière — "
607
  "y compris les zones sans vérité terrain. On ne peut pas y vérifier si "
608
+ "c'est correct, mais on peut voir à quoi ressemble la classification complète, "
609
+ "ainsi que la répartition du nombre de pixels par classe.)*",
610
  visible=True,
611
  )
612
  rf_full_plot = gr.Plot(
613
+ label="Carte de classification complète (tous les pixels, précision non évaluable)",
614
+ visible=False,
615
+ )
616
+ rf_hist_plot = gr.Plot(
617
+ label="Histogramme du nombre de pixels par classe (carte complète)",
618
  visible=False,
619
  )
620
 
 
706
  gr.update(value=warning, visible=True),
707
  gr.update(visible=False),
708
  gr.update(visible=False),
709
+ gr.update(visible=False),
 
710
  gr.update(visible=False),
711
  gr.update(visible=False),
712
  )
713
 
714
+ model_oa, model_matrix, pred_gt, y_gt, pred_full = train_and_predict(
715
  current_labels, k
716
  )
717
+ kappa = cohen_kappa_score(y_gt, pred_gt)
718
+ f1 = f1_score(y_gt, pred_gt, average='macro')
719
  model_acc_text = (
720
+ f"**Précision globale = {model_oa*100:.1f}%** — "
721
+ f"**Indice Kappa = {kappa:.3f}** — **F1-score moyen = {f1:.3f}**\n\n"
722
+ f"*(évalués sur les {len(y_gt)} pixels de vérité terrain, k={int(k)} — "
723
+ f"c'est la précision réelle d'un modèle KNN entraîné uniquement sur VOS 23 polygones étiquetés)*"
724
  )
725
  model_fig = fig_model_matrix(model_matrix, model_oa)
726
+ map_fig = fig_gt_maps(pred_gt, y_gt)
727
+ full_fig = fig_full_maps((pred_full, "Votre modèle KNN — carte complète"))
728
+ hist_fig = fig_class_histogram(pred_full, "Répartition des pixels par classe — Votre modèle KNN")
 
 
 
729
 
730
  return (
731
  gr.update(visible=False),
732
  gr.update(value=model_acc_text, visible=True),
733
+ gr.update(value=model_fig, visible=True),
 
 
734
  gr.update(value=map_fig, visible=True),
735
  gr.update(value=full_fig, visible=True),
736
+ gr.update(value=hist_fig, visible=True),
737
  )
738
 
739
  def on_train_logreg(current_labels):
 
750
  gr.update(value=warning, visible=True),
751
  gr.update(visible=False),
752
  gr.update(visible=False),
753
+ gr.update(visible=False),
 
754
  gr.update(visible=False),
755
  gr.update(visible=False),
756
  )
757
 
758
+ model_oa, model_matrix, pred_gt, y_gt, pred_full = train_and_predict_logreg(
759
  current_labels
760
  )
761
+ kappa = cohen_kappa_score(y_gt, pred_gt)
762
+ f1 = f1_score(y_gt, pred_gt, average='macro')
763
  model_acc_text = (
764
+ f"**Précision globale = {model_oa*100:.1f}%** — "
765
+ f"**Indice Kappa = {kappa:.3f}** — **F1-score moyen = {f1:.3f}**\n\n"
766
+ f"*(évalués sur les {len(y_gt)} pixels de vérité terrain — "
767
+ f"c'est la précision réelle d'un modèle de régression logistique entraîné uniquement "
768
+ f"sur VOS 23 polygones étiquetés — comparez-la à votre modèle KNN dans l'onglet suivant)*"
769
  )
770
  model_fig = fig_confusion_matrix(
771
  model_matrix, model_oa,
772
  "Matrice de confusion – VOTRE modèle de régression logistique vs Vérité terrain",
773
  cmap='Reds',
774
  )
775
+ map_fig = fig_gt_maps(pred_gt, y_gt, model_label="Votre modèle de régression logistique")
776
+ full_fig = fig_full_maps((pred_full, "Votre modèle de régression logistique — carte complète"))
777
+ hist_fig = fig_class_histogram(
778
+ pred_full, "Répartition des pixels par classe — Votre modèle de régression logistique"
 
779
  )
780
 
781
  return (
782
  gr.update(visible=False),
783
  gr.update(value=model_acc_text, visible=True),
784
+ gr.update(value=model_fig, visible=True),
 
 
785
  gr.update(value=map_fig, visible=True),
786
  gr.update(value=full_fig, visible=True),
787
+ gr.update(value=hist_fig, visible=True),
788
  )
789
 
790
  def on_train_rf(current_labels):
 
801
  gr.update(value=warning, visible=True),
802
  gr.update(visible=False),
803
  gr.update(visible=False),
804
+ gr.update(visible=False),
 
805
  gr.update(visible=False),
806
  gr.update(visible=False),
807
  )
808
 
809
+ model_oa, model_matrix, pred_gt, y_gt, pred_full = train_and_predict_rf(
810
  current_labels
811
  )
812
+ kappa = cohen_kappa_score(y_gt, pred_gt)
813
+ f1 = f1_score(y_gt, pred_gt, average='macro')
814
  model_acc_text = (
815
+ f"**Précision globale = {model_oa*100:.1f}%** — "
816
+ f"**Indice Kappa = {kappa:.3f}** — **F1-score moyen = {f1:.3f}**\n\n"
817
+ f"*(évalués sur les {len(y_gt)} pixels de vérité terrain — "
818
+ f"c'est la précision réelle d'une forêt aléatoire entraînée uniquement sur VOS 23 "
819
+ f"polygones étiquetés — comparez-la à vos autres modèles dans les onglets précédents)*"
820
  )
821
  model_fig = fig_confusion_matrix(
822
  model_matrix, model_oa,
823
  "Matrice de confusion – VOTRE modèle de forêt aléatoire vs Vérité terrain",
824
  cmap='Oranges',
825
  )
826
+ map_fig = fig_gt_maps(pred_gt, y_gt, model_label="Votre modèle de forêt aléatoire")
827
+ full_fig = fig_full_maps((pred_full, "Votre modèle de forêt aléatoire — carte complète"))
828
+ hist_fig = fig_class_histogram(
829
+ pred_full, "Répartition des pixels par classe — Votre modèle de forêt aléatoire"
 
830
  )
831
 
832
  return (
833
  gr.update(visible=False),
834
  gr.update(value=model_acc_text, visible=True),
835
+ gr.update(value=model_fig, visible=True),
 
 
836
  gr.update(value=map_fig, visible=True),
837
  gr.update(value=full_fig, visible=True),
838
+ gr.update(value=hist_fig, visible=True),
839
  )
840
 
841
  # Wire up navigation (Précédent / Suivant / direct jump-to-polygon dropdown —
 
892
  outputs=[
893
  train_warning_md,
894
  model_accuracy_md,
 
895
  model_matrix_plot,
 
896
  three_panel_plot,
897
  full_maps_plot,
898
+ class_hist_plot,
899
  ],
900
  )
901
 
 
906
  outputs=[
907
  logreg_warning_md,
908
  logreg_accuracy_md,
 
909
  logreg_matrix_plot,
 
910
  logreg_map_plot,
911
  logreg_full_plot,
912
+ logreg_hist_plot,
913
  ],
914
  )
915
 
 
920
  outputs=[
921
  rf_warning_md,
922
  rf_accuracy_md,
 
923
  rf_matrix_plot,
 
924
  rf_map_plot,
925
  rf_full_plot,
926
+ rf_hist_plot,
927
  ],
928
  )
929