CircleStar commited on
Commit
257607f
·
verified ·
1 Parent(s): 5fb8847

Mirror KNN tab layout (confusion matrices + GT maps + full maps) for logistic regression tab, add random forest comparison tab

Browse files
Files changed (1) hide show
  1. app.py +197 -39
app.py CHANGED
@@ -9,6 +9,7 @@ import json
9
  import os
10
  from sklearn.neighbors import KNeighborsClassifier
11
  from sklearn.linear_model import LogisticRegression
 
12
  from sklearn.preprocessing import StandardScaler
13
 
14
  # ─────────────────────────────────────────────────────────────────────────────
@@ -135,17 +136,14 @@ def train_and_predict(student_labels, k):
135
  return model_oa, model_matrix, pred_gt, y_gt, knn_ref_gt, pred_full
136
 
137
  def train_and_predict_logreg(student_labels):
138
- """Train a multinomial logistic regression on the same 23 labeled polygons.
139
- Unlike plain linear regression, logistic regression IS a real classifier —
140
- it fits a separate linear decision function per class and makes no
141
- assumption that the class numbers are ordered or continuous. Its decision
142
- boundaries are linear (a hyperplane per class), unlike KNN's non-linear,
143
- non-parametric boundaries; whether that makes it more or less accurate
144
- here depends on how linearly separable the classes actually are in the
145
- spectral feature space — not something to assume in advance."""
146
  bands = DATA['bands']
147
  training_ids = DATA['training_ids']
148
  ground_truth = DATA['ground_truth']
 
149
 
150
  train_mask = training_ids > 0
151
  X_train = bands[train_mask]
@@ -159,6 +157,7 @@ def train_and_predict_logreg(student_labels):
159
  X_gt = bands[gt_mask]
160
  pred_gt = clf.predict(scaler.transform(X_gt))
161
  y_gt = ground_truth[gt_mask]
 
162
 
163
  model_matrix = np.zeros((7, 7), dtype=np.int64)
164
  np.add.at(model_matrix, (y_gt - 1, pred_gt - 1), 1)
@@ -167,7 +166,39 @@ def train_and_predict_logreg(student_labels):
167
  H, W, n_bands = bands.shape
168
  pred_full = clf.predict(scaler.transform(bands.reshape(-1, n_bands))).reshape(H, W)
169
 
170
- return model_oa, model_matrix, pred_full
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
171
 
172
  # ─────────────────────────────────────────────────────────────────────────────
173
  # Visualization helpers
@@ -448,33 +479,38 @@ puis soumettez vos réponses pour générer la carte et la matrice de confusion.
448
  # ── Tab 4: Régression logistique, algorithme de base pour comparaison ──
449
  with gr.Tab("Régression logistique (comparaison)"):
450
  gr.Markdown("""
451
- ## Un algorithme de base : la régression logistique
452
-
453
- Contrairement à la régression linéaire, la régression logistique est un vrai
454
- algorithme de classification : elle apprend une fonction de décision linéaire
455
- séparée pour chaque classe et ne suppose aucun ordre entre les numéros de
456
- classe. Sa frontière de décision reste toutefois **linéaire** (un hyperplan
457
- par classe), alors que le KNN (onglet suivant) peut apprendre des frontières
458
- de n'importe quelle forme.
459
-
460
- Entraînez-le ci-dessous sur les mêmes 23 étiquettes, et comparez sa précision
461
- à celle de votre modèle KNN dans l'onglet suivant — un modèle plus simple
462
- n'est pas automatiquement moins bon, tout dépend de si les classes sont
463
- linéairement séparables ou non dans l'espace spectral.
464
  """)
465
  logreg_warning_md = gr.Markdown(visible=False)
466
  btn_train_logreg = gr.Button(
467
- "Entraîner le modèle de régression logistique",
468
  variant="primary",
469
  size="lg",
470
  )
471
  logreg_accuracy_md = gr.Markdown(visible=False)
472
- logreg_matrix_plot = gr.Plot(
473
- label="Régression logistique vs Vérité terrain",
 
 
 
474
  visible=False,
475
  )
 
 
 
 
 
 
476
  logreg_full_plot = gr.Plot(
477
- label="Carte complète — régression logistique",
478
  visible=False,
479
  )
480
 
@@ -516,6 +552,44 @@ sur les pixels de vérité terrain (indépendants des polygones d'entraînement)
516
  visible=False,
517
  )
518
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
519
  # ─────────────────────────────────────────────────────────────────────
520
  # Event handlers
521
  # ─────────────────────────────────────────────────────────────────────
@@ -638,8 +712,8 @@ sur les pixels de vérité terrain (indépendants des polygones d'entraînement)
638
  )
639
 
640
  def on_train_logreg(current_labels):
641
- """Train a multinomial logistic regression on the student's own labels,
642
- to show how a properly-specified but linear classifier compares to KNN."""
643
  total = count_labeled(current_labels)
644
  if total < N_POLYGONS:
645
  warning = (
@@ -651,27 +725,93 @@ sur les pixels de vérité terrain (indépendants des polygones d'entraînement)
651
  gr.update(value=warning, visible=True),
652
  gr.update(visible=False),
653
  gr.update(visible=False),
 
 
 
654
  gr.update(visible=False),
655
  )
656
 
657
- model_oa, model_matrix, pred_full = train_and_predict_logreg(current_labels)
658
- acc_text = (
659
- f"**Précision globale = {model_oa*100:.1f}%**\n\n"
660
- f"*(Comparez ce chiffre à la précision de votre modèle KNN dans l'onglet suivant — "
661
- f"la régression logistique est un vrai classifieur, mais sa frontière de décision "
662
- f"reste linéaire, contrairement au KNN.)*"
663
  )
664
- matrix_fig = fig_confusion_matrix(
 
 
 
 
 
 
 
665
  model_matrix, model_oa,
666
- "Matrice de confusion – Régression logistique vs Vérité terrain",
667
  cmap='Reds',
668
  )
669
- full_fig = fig_full_maps((pred_full, "Régression logistique — carte complète"))
 
 
 
 
 
670
 
671
  return (
672
  gr.update(visible=False),
673
- gr.update(value=acc_text, visible=True),
674
- gr.update(value=matrix_fig, visible=True),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
675
  gr.update(value=full_fig, visible=True),
676
  )
677
 
@@ -744,10 +884,28 @@ sur les pixels de vérité terrain (indépendants des polygones d'entraînement)
744
  outputs=[
745
  logreg_warning_md,
746
  logreg_accuracy_md,
 
747
  logreg_matrix_plot,
 
 
748
  logreg_full_plot,
749
  ],
750
  )
751
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
752
  if __name__ == "__main__":
753
  demo.launch(server_name="0.0.0.0", server_port=7860)
 
9
  import os
10
  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
  # ─────────────────────────────────────────────────────────────────────────────
 
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
140
+ polygons (using the real spectral bands), then evaluate it only at the
141
+ Ground Truth pixel locations — same protocol as the KNN model, so the two
142
+ are directly comparable."""
 
 
 
 
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
  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
  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
173
+ real spectral bands), then evaluate it only at the Ground Truth pixel
174
+ locations — same protocol as the KNN model, so the two are directly
175
+ comparable. No feature scaling needed: tree splits are scale-invariant."""
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]
183
+ y_train = np.array([int(student_labels[pid - 1]) for pid in training_ids[train_mask]])
184
+
185
+ clf = RandomForestClassifier(n_estimators=200, n_jobs=-1, random_state=0)
186
+ clf.fit(X_train, y_train)
187
+
188
+ gt_mask = ground_truth > 0
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)
196
+ model_oa = model_matrix.diagonal().sum() / model_matrix.sum()
197
+
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
 
479
  # ── Tab 4: Régression logistique, algorithme de base pour comparaison ──
480
  with gr.Tab("Régression logistique (comparaison)"):
481
  gr.Markdown("""
482
+ ## Entraînez un modèle de régression logistique
483
+
484
+ La régression logistique est un algorithme de classification : pour chaque
485
+ pixel, elle calcule à partir des 7 bandes spectrales une probabilité
486
+ d'appartenance à chacune des 7 classes, et retient la plus probable.
487
+
488
+ Ce modèle est entraîné sur **vos** 23 étiquettes (onglet Interprétation)
489
+ combinées aux vraies valeurs spectrales des 7 bandes satellite, puis évalué
490
+ sur les pixels de vérité terrain (indépendants des polygones d'entraînement).
 
 
 
 
491
  """)
492
  logreg_warning_md = gr.Markdown(visible=False)
493
  btn_train_logreg = gr.Button(
494
+ "Entraîner mon modèle de régression logistique",
495
  variant="primary",
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
 
 
552
  visible=False,
553
  )
554
 
555
+ # ── Tab 6: Forêt aléatoire, second algorithme pour comparaison ─────
556
+ with gr.Tab("Forêt aléatoire (comparaison)"):
557
+ gr.Markdown("""
558
+ ## Entraînez un modèle de forêt aléatoire (Random Forest)
559
+
560
+ Une forêt aléatoire entraîne un grand nombre d'arbres de décision, chacun sur
561
+ un sous-échantillon aléatoire des données, puis fait voter l'ensemble : chaque
562
+ pixel est classé selon la classe majoritaire parmi tous les arbres.
563
+
564
+ Ce modèle est entraîné sur **vos** 23 étiquettes (onglet Interprétation)
565
+ combinées aux vraies valeurs spectrales des 7 bandes satellite, puis évalué
566
+ sur les pixels de vérité terrain (indépendants des polygones d'entraînement).
567
+ """)
568
+ rf_warning_md = gr.Markdown(visible=False)
569
+ btn_train_rf = gr.Button(
570
+ "Entraîner mon modèle de forêt aléatoire",
571
+ variant="primary",
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
+
593
  # ─────────────────────────────────────────────────────────────────────
594
  # Event handlers
595
  # ─────────────────────────────────────────────────────────────────────
 
712
  )
713
 
714
  def on_train_logreg(current_labels):
715
+ """Train a logistic regression model on the student's own labels,
716
+ then evaluate it against Ground Truth — same layout as the KNN tab."""
717
  total = count_labeled(current_labels)
718
  if total < N_POLYGONS:
719
  warning = (
 
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)
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):
767
+ """Train a random forest on the student's own labels, then evaluate it
768
+ against Ground Truth — same layout as the KNN tab."""
769
+ total = count_labeled(current_labels)
770
+ if total < N_POLYGONS:
771
+ warning = (
772
+ f"Vous n'avez étiqueté que {total}/{N_POLYGONS} polygones. "
773
+ f"Terminez l'étiquetage dans l'onglet *Interprétation des polygones* "
774
+ f"avant d'entraîner un modèle."
775
+ )
776
+ return (
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)
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
 
 
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
 
895
+ # Wire up random forest training (separate tab, for comparison against KNN)
896
+ btn_train_rf.click(
897
+ on_train_rf,
898
+ inputs=[labels],
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
+
910
  if __name__ == "__main__":
911
  demo.launch(server_name="0.0.0.0", server_port=7860)