EnYa32 commited on
Commit
571b79d
·
verified ·
1 Parent(s): 5de1c92

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +32 -12
src/streamlit_app.py CHANGED
@@ -7,7 +7,8 @@ import tensorflow as tf
7
  from tensorflow.keras.applications.resnet50 import preprocess_input
8
 
9
  # ----------------- SETTINGS -----------------
10
- MODEL_PATH = "src/best_rice_resnet50.keras"
 
11
  IMG_SIZE = (224, 224)
12
 
13
  CLASS_NAMES = [
@@ -23,10 +24,10 @@ CLASS_NAMES = [
23
  def load_resnet_model():
24
  try:
25
  model = tf.keras.models.load_model(MODEL_PATH, compile=False)
 
26
  except Exception as e:
27
  st.error(f"Error loading model: {e}")
28
- model = None
29
- return model
30
 
31
 
32
  def preprocess_image(image: Image.Image) -> np.ndarray:
@@ -40,16 +41,26 @@ def preprocess_image(image: Image.Image) -> np.ndarray:
40
 
41
 
42
  def predict_image(model, image_array: np.ndarray):
 
43
  preds = model.predict(image_array, verbose=0)[0]
44
  probs = tf.nn.softmax(preds).numpy()
45
- pred_idx = int(np.argmax(probs))
46
- pred_class = CLASS_NAMES[pred_idx]
47
- pred_conf = float(probs[pred_idx])
48
 
49
- top3_idx = np.argsort(probs)[-3:][::-1]
50
- top3 = [(CLASS_NAMES[i], float(probs[i])) for i in top3_idx]
 
51
 
52
- return pred_class, pred_conf, probs, top3
 
 
 
 
 
 
 
 
 
 
 
53
 
54
 
55
  # ----------------- PAGE CONFIG -----------------
@@ -95,7 +106,16 @@ if uploaded_file is not None:
95
 
96
  if model is not None:
97
  img_array = preprocess_image(image)
98
- pred_class, pred_conf, probs, top3 = predict_image(model, img_array)
 
 
 
 
 
 
 
 
 
99
 
100
  with col2:
101
  st.subheader("Prediction")
@@ -108,12 +128,12 @@ if uploaded_file is not None:
108
 
109
  st.subheader("Class probabilities")
110
  df = pd.DataFrame(
111
- {"class": CLASS_NAMES, "probability": probs}
112
  ).set_index("class")
113
  st.bar_chart(df)
114
 
115
  with st.expander("Show probabilities as text"):
116
- for name, p in zip(CLASS_NAMES, probs):
117
  st.write(f"- {name}: {p:.2%}")
118
  else:
119
  st.info("Please upload a rice image to get a prediction.")
 
7
  from tensorflow.keras.applications.resnet50 import preprocess_input
8
 
9
  # ----------------- SETTINGS -----------------
10
+ # Falls das Modell im Root liegt, nimm: "./best_rice_resnet50.keras"
11
+ MODEL_PATH = "src/best_rice_resnet50.keras"
12
  IMG_SIZE = (224, 224)
13
 
14
  CLASS_NAMES = [
 
24
  def load_resnet_model():
25
  try:
26
  model = tf.keras.models.load_model(MODEL_PATH, compile=False)
27
+ return model
28
  except Exception as e:
29
  st.error(f"Error loading model: {e}")
30
+ return None
 
31
 
32
 
33
  def preprocess_image(image: Image.Image) -> np.ndarray:
 
41
 
42
 
43
  def predict_image(model, image_array: np.ndarray):
44
+ """Safe prediction with Top-3; robust gegen Längen-Mismatch."""
45
  preds = model.predict(image_array, verbose=0)[0]
46
  probs = tf.nn.softmax(preds).numpy()
 
 
 
47
 
48
+ n_model = len(probs)
49
+ n_labels = len(CLASS_NAMES)
50
+ n = min(n_model, n_labels)
51
 
52
+ # Hauptklasse (nur im Bereich [0, n))
53
+ main_idx = int(np.argmax(probs[:n]))
54
+ pred_class = CLASS_NAMES[main_idx]
55
+ pred_conf = float(probs[main_idx])
56
+
57
+ # Top-k (hier 3) nur im gültigen Bereich
58
+ k = min(3, n)
59
+ topk_idx = np.argsort(probs[:n])[-k:][::-1]
60
+ topk = [(CLASS_NAMES[i], float(probs[i])) for i in topk_idx]
61
+
62
+ # Nur die ersten n Wahrscheinlichkeiten zurückgeben
63
+ return pred_class, pred_conf, probs[:n], topk, n_model, n_labels
64
 
65
 
66
  # ----------------- PAGE CONFIG -----------------
 
106
 
107
  if model is not None:
108
  img_array = preprocess_image(image)
109
+ pred_class, pred_conf, probs, top3, n_model, n_labels = predict_image(
110
+ model, img_array
111
+ )
112
+
113
+ # kurze Warnung, falls Modell/Labels nicht exakt matchen
114
+ if n_model != n_labels:
115
+ st.warning(
116
+ f"Model outputs {n_model} classes, CLASS_NAMES has {n_labels}. "
117
+ f"Only the first {min(n_model, n_labels)} are shown."
118
+ )
119
 
120
  with col2:
121
  st.subheader("Prediction")
 
128
 
129
  st.subheader("Class probabilities")
130
  df = pd.DataFrame(
131
+ {"class": CLASS_NAMES[: len(probs)], "probability": probs}
132
  ).set_index("class")
133
  st.bar_chart(df)
134
 
135
  with st.expander("Show probabilities as text"):
136
+ for name, p in zip(CLASS_NAMES[: len(probs)], probs):
137
  st.write(f"- {name}: {p:.2%}")
138
  else:
139
  st.info("Please upload a rice image to get a prediction.")