scontess commited on
Commit
b5b6de6
Β·
1 Parent(s): a16d3e9
Files changed (1) hide show
  1. src/streamlit_app.py +37 -34
src/streamlit_app.py CHANGED
@@ -9,6 +9,7 @@ from tensorflow.keras.layers import Dense, Flatten
9
  from tensorflow.keras.models import Model, load_model
10
  from datasets import load_dataset
11
  import matplotlib.pyplot as plt
 
12
  from sklearn.metrics import confusion_matrix, classification_report
13
  import seaborn as sns
14
  from huggingface_hub import HfApi
@@ -41,10 +42,14 @@ for i, sample in enumerate(dataset):
41
  image_list.append(image.numpy())
42
  label_list.append(np.array(sample["label"]))
43
 
44
- X_train = np.array(image_list)
45
- y_train = np.array(label_list)
46
 
47
- st.write(f"βœ… Scaricate e preprocessate {len(X_train)} immagini da `tiny-imagenet/64x64`!")
 
 
 
 
48
 
49
  # πŸ“Œ Caricamento del modello
50
  if os.path.exists("Silva.h5"):
@@ -65,12 +70,8 @@ else:
65
  model = Model(inputs=base_model.input, outputs=output)
66
  model.compile(optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"])
67
 
68
- # πŸ“Œ Training con barra di progresso
69
- progress_bar = st.progress(0)
70
- status_text = st.empty()
71
- start_time = time.time()
72
-
73
- history = model.fit(X_train, y_train, epochs=10)
74
 
75
  st.write("βœ… Addestramento completato!")
76
 
@@ -78,36 +79,38 @@ else:
78
  model.save("Silva.h5")
79
  st.write("βœ… Modello salvato come `Silva.h5`!")
80
 
81
- # πŸ“Œ Calcolo delle metriche
82
- y_pred = np.argmax(model.predict(X_train), axis=1)
83
- accuracy = np.mean(y_pred == y_train)
84
- rmse = np.sqrt(np.mean((y_pred - y_train) ** 2))
85
- report = classification_report(y_train, y_pred, output_dict=True)
86
-
87
- recall = report["weighted avg"]["recall"]
88
- precision = report["weighted avg"]["precision"]
89
- f1_score = report["weighted avg"]["f1-score"]
90
-
91
- st.write(f"πŸ“Š **Accuracy:** {accuracy:.4f}")
92
- st.write(f"πŸ“Š **RMSE:** {rmse:.4f}")
93
- st.write(f"πŸ“Š **Precision:** {precision:.4f}")
94
- st.write(f"πŸ“Š **Recall:** {recall:.4f}")
95
- st.write(f"πŸ“Š **F1-Score:** {f1_score:.4f}")
96
-
97
- # πŸ“Œ Bottone per generare la matrice di confusione
98
- if st.button("πŸ”Ž Genera matrice di confusione"):
99
- conf_matrix = confusion_matrix(y_train, y_pred)
100
  fig, ax = plt.subplots(figsize=(10, 7))
101
- sns.heatmap(conf_matrix, annot=True, cmap="Blues", fmt="d", ax=ax)
102
  st.pyplot(fig)
103
  st.write("βœ… Matrice di confusione generata!")
104
 
105
- # πŸ“Œ Grafico per Loss e Accuracy
106
  fig, ax = plt.subplots(1, 2, figsize=(12, 5))
107
- ax[0].plot(history.history["loss"], label="Loss")
108
- ax[1].plot(history.history["accuracy"], label="Accuracy")
109
- ax[0].set_title("Loss durante il training")
110
- ax[1].set_title("Accuracy durante il training")
 
 
111
  ax[0].legend()
112
  ax[1].legend()
113
  st.pyplot(fig)
 
9
  from tensorflow.keras.models import Model, load_model
10
  from datasets import load_dataset
11
  import matplotlib.pyplot as plt
12
+ from sklearn.model_selection import train_test_split
13
  from sklearn.metrics import confusion_matrix, classification_report
14
  import seaborn as sns
15
  from huggingface_hub import HfApi
 
42
  image_list.append(image.numpy())
43
  label_list.append(np.array(sample["label"]))
44
 
45
+ X = np.array(image_list)
46
+ y = np.array(label_list)
47
 
48
+ # πŸ“Œ Suddivisione dataset: 80% training, 20% validation
49
+ X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42)
50
+
51
+ st.write(f"πŸ“Š **Training:** {X_train.shape[0]} immagini")
52
+ st.write(f"πŸ“Š **Validation:** {X_val.shape[0]} immagini")
53
 
54
  # πŸ“Œ Caricamento del modello
55
  if os.path.exists("Silva.h5"):
 
70
  model = Model(inputs=base_model.input, outputs=output)
71
  model.compile(optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"])
72
 
73
+ # πŸ“Œ Training con monitoraggio validazione
74
+ history = model.fit(X_train, y_train, epochs=10, validation_data=(X_val, y_val))
 
 
 
 
75
 
76
  st.write("βœ… Addestramento completato!")
77
 
 
79
  model.save("Silva.h5")
80
  st.write("βœ… Modello salvato come `Silva.h5`!")
81
 
82
+ # πŸ“Œ Calcolo delle metriche sulla validazione
83
+ y_pred_val = np.argmax(model.predict(X_val), axis=1)
84
+ accuracy_val = np.mean(y_pred_val == y_val)
85
+ rmse_val = np.sqrt(np.mean((y_pred_val - y_val) ** 2))
86
+ report_val = classification_report(y_val, y_pred_val, output_dict=True)
87
+
88
+ recall_val = report_val["weighted avg"]["recall"]
89
+ precision_val = report_val["weighted avg"]["precision"]
90
+ f1_score_val = report_val["weighted avg"]["f1-score"]
91
+
92
+ st.write(f"πŸ“Š **Validation Accuracy:** {accuracy_val:.4f}")
93
+ st.write(f"πŸ“Š **Validation RMSE:** {rmse_val:.4f}")
94
+ st.write(f"πŸ“Š **Validation Precision:** {precision_val:.4f}")
95
+ st.write(f"πŸ“Š **Validation Recall:** {recall_val:.4f}")
96
+ st.write(f"πŸ“Š **Validation F1-Score:** {f1_score_val:.4f}")
97
+
98
+ # πŸ“Œ Bottone per generare la matrice di confusione sulla validazione
99
+ if st.button("πŸ”Ž Genera matrice di confusione per validazione"):
100
+ conf_matrix_val = confusion_matrix(y_val, y_pred_val)
101
  fig, ax = plt.subplots(figsize=(10, 7))
102
+ sns.heatmap(conf_matrix_val, annot=True, cmap="Blues", fmt="d", ax=ax)
103
  st.pyplot(fig)
104
  st.write("βœ… Matrice di confusione generata!")
105
 
106
+ # πŸ“Œ Grafico per Loss e Accuracy con validazione
107
  fig, ax = plt.subplots(1, 2, figsize=(12, 5))
108
+ ax[0].plot(history.history["loss"], label="Training Loss")
109
+ ax[0].plot(history.history["val_loss"], label="Validation Loss")
110
+ ax[1].plot(history.history["accuracy"], label="Training Accuracy")
111
+ ax[1].plot(history.history["val_accuracy"], label="Validation Accuracy")
112
+ ax[0].set_title("Loss durante il training e validazione")
113
+ ax[1].set_title("Accuracy durante il training e validazione")
114
  ax[0].legend()
115
  ax[1].legend()
116
  st.pyplot(fig)