Abdus Samad Mizi commited on
Commit
b6a481f
·
1 Parent(s): 59340dd

"modify model.py"

Browse files
Files changed (1) hide show
  1. model.py +25 -9
model.py CHANGED
@@ -5,24 +5,31 @@ from PIL import Image
5
  import pickle
6
 
7
  def load_model():
 
 
 
8
  # Load label mapping
9
  with open("model/label_maps.pkl", "rb") as f:
10
  label_maps = pickle.load(f)
11
-
12
- # Extract class names cleanly
13
- if isinstance(next(iter(label_maps.values())), str): # e.g., {0: "dry"}
 
14
  class_names = list(label_maps.values())
15
- elif isinstance(next(iter(label_maps.values())), dict): # e.g., {"dry": 0, "oily": 1}
 
16
  class_names = list(next(iter(label_maps.values())).keys())
17
  else:
18
  raise ValueError("Unexpected format in label_maps.pkl")
19
 
20
- # Load full model
21
  model = torch.load("model/best_skin_model_entire.pth", map_location="cpu")
22
  model.eval()
 
 
23
  return model, class_names
24
 
25
- # Preprocessing pipeline
26
  preprocess = transforms.Compose([
27
  transforms.Resize(256),
28
  transforms.CenterCrop(224),
@@ -32,16 +39,25 @@ preprocess = transforms.Compose([
32
  ])
33
 
34
  def predict(model, image: Image.Image, class_names):
35
- img_tensor = preprocess(image).unsqueeze(0)
 
 
 
 
36
  with torch.no_grad():
37
  outputs = model(img_tensor)
38
  probs = torch.nn.functional.softmax(outputs[0], dim=0)
39
-
 
 
 
 
40
  predictions = [
41
  {"class": class_names[i], "confidence": round(float(probs[i]), 4)}
42
- for i in range(len(class_names))
43
  ]
44
  predictions.sort(key=lambda x: x["confidence"], reverse=True)
 
45
  return {
46
  "predictions": predictions,
47
  "top_class": predictions[0]["class"]
 
5
  import pickle
6
 
7
  def load_model():
8
+ """
9
+ Load the trained PyTorch model and class labels.
10
+ """
11
  # Load label mapping
12
  with open("model/label_maps.pkl", "rb") as f:
13
  label_maps = pickle.load(f)
14
+
15
+ # Extract class names based on label_maps format
16
+ if isinstance(next(iter(label_maps.values())), str):
17
+ # Example: {0: "dry", 1: "oily"}
18
  class_names = list(label_maps.values())
19
+ elif isinstance(next(iter(label_maps.values())), dict):
20
+ # Example: {"dry": 0, "oily": 1}
21
  class_names = list(next(iter(label_maps.values())).keys())
22
  else:
23
  raise ValueError("Unexpected format in label_maps.pkl")
24
 
25
+ # Load the trained PyTorch model
26
  model = torch.load("model/best_skin_model_entire.pth", map_location="cpu")
27
  model.eval()
28
+
29
+ print(f"✅ Model loaded with {len(class_names)} classes: {class_names}")
30
  return model, class_names
31
 
32
+ # Image preprocessing pipeline (matches training setup)
33
  preprocess = transforms.Compose([
34
  transforms.Resize(256),
35
  transforms.CenterCrop(224),
 
39
  ])
40
 
41
  def predict(model, image: Image.Image, class_names):
42
+ """
43
+ Perform prediction on a single image and return top class and probabilities.
44
+ """
45
+ img_tensor = preprocess(image).unsqueeze(0) # Add batch dimension
46
+
47
  with torch.no_grad():
48
  outputs = model(img_tensor)
49
  probs = torch.nn.functional.softmax(outputs[0], dim=0)
50
+
51
+ # Ensure number of classes matches model output size
52
+ num_classes = probs.shape[0]
53
+ class_names = class_names[:num_classes]
54
+
55
  predictions = [
56
  {"class": class_names[i], "confidence": round(float(probs[i]), 4)}
57
+ for i in range(num_classes)
58
  ]
59
  predictions.sort(key=lambda x: x["confidence"], reverse=True)
60
+
61
  return {
62
  "predictions": predictions,
63
  "top_class": predictions[0]["class"]