Spaces:
Runtime error
Runtime error
scontess
commited on
Commit
Β·
b5b6de6
1
Parent(s):
a16d3e9
dopopull
Browse files- 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 |
-
|
45 |
-
|
46 |
|
47 |
-
|
|
|
|
|
|
|
|
|
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
|
69 |
-
|
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 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
st.write(f"π **Accuracy:** {
|
92 |
-
st.write(f"π **RMSE:** {
|
93 |
-
st.write(f"π **Precision:** {
|
94 |
-
st.write(f"π **Recall:** {
|
95 |
-
st.write(f"π **F1-Score:** {
|
96 |
-
|
97 |
-
# π Bottone per generare la matrice di confusione
|
98 |
-
if st.button("π Genera matrice di confusione"):
|
99 |
-
|
100 |
fig, ax = plt.subplots(figsize=(10, 7))
|
101 |
-
sns.heatmap(
|
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[
|
109 |
-
ax[
|
110 |
-
ax[1].
|
|
|
|
|
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)
|