Spaces:
Sleeping
Sleeping
Update predict.py
Browse files- predict.py +25 -32
predict.py
CHANGED
|
@@ -1,27 +1,29 @@
|
|
| 1 |
-
|
| 2 |
import argparse
|
| 3 |
import numpy as np
|
| 4 |
from pathlib import Path
|
| 5 |
from PIL import Image
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
CLASS_NAMES = ["buildings", "forest", "glacier", "mountain", "sea", "street"]
|
| 8 |
-
IMAGE_SIZE
|
| 9 |
MEAN = [0.485, 0.456, 0.406]
|
| 10 |
-
STD
|
| 11 |
|
| 12 |
|
| 13 |
-
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 14 |
-
# PyTorch Prediction
|
| 15 |
-
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 16 |
|
|
|
|
| 17 |
def predict_pytorch(image_path: str, model_path: str = "sara_model.pth") -> dict:
|
| 18 |
-
import torch
|
| 19 |
-
from torchvision import transforms
|
| 20 |
-
from model_pytorch import SaraCNN
|
| 21 |
-
|
| 22 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 23 |
|
| 24 |
-
checkpoint
|
| 25 |
class_names = checkpoint.get("class_names", CLASS_NAMES)
|
| 26 |
|
| 27 |
model = SaraCNN(num_classes=len(class_names))
|
|
@@ -35,14 +37,14 @@ def predict_pytorch(image_path: str, model_path: str = "sara_model.pth") -> dict
|
|
| 35 |
transforms.Normalize(MEAN, STD),
|
| 36 |
])
|
| 37 |
|
| 38 |
-
img
|
| 39 |
tensor = transform(img).unsqueeze(0).to(device)
|
| 40 |
|
| 41 |
with torch.no_grad():
|
| 42 |
logits = model(tensor)
|
| 43 |
-
probs
|
| 44 |
|
| 45 |
-
idx
|
| 46 |
pred_class = class_names[idx]
|
| 47 |
confidence = float(probs[idx])
|
| 48 |
|
|
@@ -56,25 +58,18 @@ def predict_pytorch(image_path: str, model_path: str = "sara_model.pth") -> dict
|
|
| 56 |
}
|
| 57 |
|
| 58 |
|
| 59 |
-
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 60 |
-
# TensorFlow Prediction
|
| 61 |
-
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 62 |
|
|
|
|
| 63 |
def predict_tensorflow(image_path: str, model_path: str = "sara_model.keras") -> dict:
|
| 64 |
-
import tensorflow as tf
|
| 65 |
-
import numpy as np
|
| 66 |
-
|
| 67 |
-
# Format .h5 = compatible toutes versions Keras, chargement simple
|
| 68 |
model = tf.keras.models.load_model(model_path, compile=False)
|
| 69 |
|
| 70 |
-
# PrΓ©traitement
|
| 71 |
img = tf.keras.utils.load_img(image_path, target_size=(150, 150))
|
| 72 |
arr = tf.keras.utils.img_to_array(img) / 255.0
|
| 73 |
arr = np.expand_dims(arr, axis=0)
|
| 74 |
|
| 75 |
-
|
| 76 |
-
probs
|
| 77 |
-
idx
|
| 78 |
pred_class = CLASS_NAMES[idx]
|
| 79 |
confidence = float(probs[idx])
|
| 80 |
|
|
@@ -88,9 +83,7 @@ def predict_tensorflow(image_path: str, model_path: str = "sara_model.keras") ->
|
|
| 88 |
}
|
| 89 |
|
| 90 |
|
| 91 |
-
|
| 92 |
-
# CLI
|
| 93 |
-
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 94 |
|
| 95 |
if __name__ == "__main__":
|
| 96 |
parser = argparse.ArgumentParser()
|
|
@@ -100,15 +93,15 @@ if __name__ == "__main__":
|
|
| 100 |
args = parser.parse_args()
|
| 101 |
|
| 102 |
if args.model == "pytorch":
|
| 103 |
-
path
|
| 104 |
result = predict_pytorch(args.image, model_path=path)
|
| 105 |
else:
|
| 106 |
-
path
|
| 107 |
result = predict_tensorflow(args.image, model_path=path)
|
| 108 |
|
| 109 |
print(f"\n Classe : {result['predicted_class']}")
|
| 110 |
-
print(f"
|
| 111 |
-
print("\n
|
| 112 |
for cls, prob in sorted(result["all_probabilities"].items(), key=lambda x: -x[1]):
|
| 113 |
bar = " " * int(prob / 5)
|
| 114 |
print(f" {cls:<12} {prob:6.2f}% {bar}")
|
|
|
|
|
|
|
| 1 |
import argparse
|
| 2 |
import numpy as np
|
| 3 |
from pathlib import Path
|
| 4 |
from PIL import Image
|
| 5 |
+
import tensorflow as tf
|
| 6 |
+
import numpy as np
|
| 7 |
+
import torch
|
| 8 |
+
from torchvision import transforms
|
| 9 |
+
from model_pytorch import SaraCNN
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
|
| 14 |
|
| 15 |
CLASS_NAMES = ["buildings", "forest", "glacier", "mountain", "sea", "street"]
|
| 16 |
+
IMAGE_SIZE = (150, 150)
|
| 17 |
MEAN = [0.485, 0.456, 0.406]
|
| 18 |
+
STD = [0.229, 0.224, 0.225]
|
| 19 |
|
| 20 |
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
+
# PyTorch Prediction
|
| 23 |
def predict_pytorch(image_path: str, model_path: str = "sara_model.pth") -> dict:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 25 |
|
| 26 |
+
checkpoint = torch.load(model_path, map_location=device)
|
| 27 |
class_names = checkpoint.get("class_names", CLASS_NAMES)
|
| 28 |
|
| 29 |
model = SaraCNN(num_classes=len(class_names))
|
|
|
|
| 37 |
transforms.Normalize(MEAN, STD),
|
| 38 |
])
|
| 39 |
|
| 40 |
+
img = Image.open(image_path).convert("RGB")
|
| 41 |
tensor = transform(img).unsqueeze(0).to(device)
|
| 42 |
|
| 43 |
with torch.no_grad():
|
| 44 |
logits = model(tensor)
|
| 45 |
+
probs = torch.softmax(logits, dim=1).squeeze().cpu().numpy()
|
| 46 |
|
| 47 |
+
idx = int(np.argmax(probs))
|
| 48 |
pred_class = class_names[idx]
|
| 49 |
confidence = float(probs[idx])
|
| 50 |
|
|
|
|
| 58 |
}
|
| 59 |
|
| 60 |
|
|
|
|
|
|
|
|
|
|
| 61 |
|
| 62 |
+
# TensorFlow Prediction
|
| 63 |
def predict_tensorflow(image_path: str, model_path: str = "sara_model.keras") -> dict:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
model = tf.keras.models.load_model(model_path, compile=False)
|
| 65 |
|
|
|
|
| 66 |
img = tf.keras.utils.load_img(image_path, target_size=(150, 150))
|
| 67 |
arr = tf.keras.utils.img_to_array(img) / 255.0
|
| 68 |
arr = np.expand_dims(arr, axis=0)
|
| 69 |
|
| 70 |
+
|
| 71 |
+
probs = model.predict(arr, verbose=0)[0]
|
| 72 |
+
idx = int(np.argmax(probs))
|
| 73 |
pred_class = CLASS_NAMES[idx]
|
| 74 |
confidence = float(probs[idx])
|
| 75 |
|
|
|
|
| 83 |
}
|
| 84 |
|
| 85 |
|
| 86 |
+
|
|
|
|
|
|
|
| 87 |
|
| 88 |
if __name__ == "__main__":
|
| 89 |
parser = argparse.ArgumentParser()
|
|
|
|
| 93 |
args = parser.parse_args()
|
| 94 |
|
| 95 |
if args.model == "pytorch":
|
| 96 |
+
path = args.model_path or "sara_model.pth"
|
| 97 |
result = predict_pytorch(args.image, model_path=path)
|
| 98 |
else:
|
| 99 |
+
path = args.model_path or "sara_model.keras"
|
| 100 |
result = predict_tensorflow(args.image, model_path=path)
|
| 101 |
|
| 102 |
print(f"\n Classe : {result['predicted_class']}")
|
| 103 |
+
print(f" Confidence : {result['confidence']}%")
|
| 104 |
+
print("\n All probabilities :")
|
| 105 |
for cls, prob in sorted(result["all_probabilities"].items(), key=lambda x: -x[1]):
|
| 106 |
bar = " " * int(prob / 5)
|
| 107 |
print(f" {cls:<12} {prob:6.2f}% {bar}")
|