bauckluc commited on
Commit
3286d29
1 Parent(s): 0d3db03

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +20 -21
app.py CHANGED
@@ -6,34 +6,23 @@ from PIL import Image
6
  model_path = "DogClassifier2.2.keras"
7
  model = tf.keras.models.load_model(model_path)
8
 
9
- # Ensure the model's output layer is correct
10
- if not isinstance(model.layers[-1], tf.keras.layers.Softmax):
11
- print("The last layer of the model is not a Softmax layer. The model might not be properly configured.")
12
-
13
  # Define the core prediction function
14
  def predict_bmwX(image):
15
  # Preprocess image
16
  image = Image.fromarray(image.astype('uint8')) # Convert numpy array to PIL image
17
  image = image.convert("RGB") # Ensure the image is in RGB format
18
  image = image.resize((150, 150)) # Resize the image to 150x150
19
- image = np.array(image) / 255.0 # Normalize the image
20
  image = np.expand_dims(image, axis=0) # Add batch dimension
21
 
22
  # Predict
23
- raw_prediction = model.predict(image)
24
-
25
- # Debug statement to check the raw prediction values
26
- print(f"Raw prediction: {raw_prediction}")
27
 
28
- # Apply softmax to get probabilities for each class if not already applied
29
- if raw_prediction.shape[-1] != 1:
30
- prediction = tf.nn.softmax(raw_prediction).numpy()[0]
31
- else:
32
- prediction = raw_prediction[0]
33
 
34
- # Debug statement to check the shape of the prediction
35
- print(f"Prediction after softmax: {prediction}")
36
- print(f"Sum of probabilities: {np.sum(prediction)}")
37
 
38
  # Define class names
39
  class_names = ['Afghan', 'African Wild Dog', 'Airedale', 'American Hairless', 'American Spaniel', 'Basenji', 'Basset', 'Beagle',
@@ -47,11 +36,21 @@ def predict_bmwX(image):
47
  'Shiba Inu', 'Shih-Tzu', 'Siberian Husky', 'Vizsla', 'Yorkie']
48
 
49
  # Check if the number of predictions matches the number of class names
50
- if len(prediction) != len(class_names):
51
- return f"Error: Number of model outputs ({len(prediction)}) does not match number of class names ({len(class_names)})."
52
 
 
 
 
 
 
 
 
 
 
 
53
  # Create a dictionary with the probabilities for each dog breed
54
- prediction_dict = {class_names[i]: np.round(float(prediction[i]), 2) for i in range(len(class_names))}
55
 
56
  # Sort the dictionary by value in descending order and get the top 3 classes
57
  sorted_predictions = dict(sorted(prediction_dict.items(), key=lambda item: item[1], reverse=True))
@@ -63,5 +62,5 @@ iface = gr.Interface(
63
  fn=predict_bmwX,
64
  inputs=input_image,
65
  outputs=gr.Label(),
66
- description="A simple dog breed classification model.")
67
  iface.launch(share=True)
 
6
  model_path = "DogClassifier2.2.keras"
7
  model = tf.keras.models.load_model(model_path)
8
 
 
 
 
 
9
  # Define the core prediction function
10
  def predict_bmwX(image):
11
  # Preprocess image
12
  image = Image.fromarray(image.astype('uint8')) # Convert numpy array to PIL image
13
  image = image.convert("RGB") # Ensure the image is in RGB format
14
  image = image.resize((150, 150)) # Resize the image to 150x150
15
+ image = np.array(image)
16
  image = np.expand_dims(image, axis=0) # Add batch dimension
17
 
18
  # Predict
19
+ prediction = model.predict(image)
 
 
 
20
 
21
+ # Apply softmax to get probabilities for each class
22
+ prediction = tf.nn.softmax(prediction)
 
 
 
23
 
24
+ # Print prediction probabilities to the console
25
+ print("Prediction probabilities:", prediction)
 
26
 
27
  # Define class names
28
  class_names = ['Afghan', 'African Wild Dog', 'Airedale', 'American Hairless', 'American Spaniel', 'Basenji', 'Basset', 'Beagle',
 
36
  'Shiba Inu', 'Shih-Tzu', 'Siberian Husky', 'Vizsla', 'Yorkie']
37
 
38
  # Check if the number of predictions matches the number of class names
39
+ if len(prediction[0]) != len(class_names):
40
+ return f"Error: Number of model outputs ({len(prediction[0])}) does not match number of class names ({len(class_names)})."
41
 
42
+ # Apply threshold and set probabilities lower than 0.015 to 0.0
43
+ threshold = 0.015
44
+ prediction = np.array(prediction)
45
+ prediction[prediction < threshold] = 0.0
46
+
47
+ # Recalculate the probabilities
48
+ total_probability = np.sum(prediction)
49
+ if total_probability > 0:
50
+ prediction = prediction / total_probability
51
+
52
  # Create a dictionary with the probabilities for each dog breed
53
+ prediction_dict = {class_names[i]: np.round(float(prediction[0][i]), 2) for i in range(len(class_names))}
54
 
55
  # Sort the dictionary by value in descending order and get the top 3 classes
56
  sorted_predictions = dict(sorted(prediction_dict.items(), key=lambda item: item[1], reverse=True))
 
62
  fn=predict_bmwX,
63
  inputs=input_image,
64
  outputs=gr.Label(),
65
+ description="A simple MLP classification model for image classification using the MNIST dataset.")
66
  iface.launch(share=True)