TingTing1999 commited on
Commit
6e8e572
·
verified ·
1 Parent(s): b8805dc

Create script.py

Browse files
Files changed (1) hide show
  1. script.py +109 -0
script.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import numpy as np
3
+ import onnxruntime as ort
4
+ import os
5
+ from tqdm import tqdm
6
+ import timm
7
+ import torchvision.transforms as T
8
+ from PIL import Image
9
+ import torch
10
+ import torch.nn as nn
11
+
12
+ def is_gpu_available():
13
+ """Check if the python package `onnxruntime-gpu` is installed."""
14
+ return torch.cuda.is_available()
15
+
16
+
17
+ class PytorchWorker:
18
+ """Run inference using ONNX runtime."""
19
+
20
+ def __init__(self, model_path: str, model_name: str, number_of_categories: int = 1605):
21
+
22
+ def _load_model(model_name, model_path):
23
+
24
+ print("Setting up Pytorch Model")
25
+ self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
26
+ print(f"Using devide: {self.device}")
27
+
28
+ model = timm.create_model(model_name, num_classes=number_of_categories, pretrained=False)
29
+
30
+ model_ckpt = torch.load(model_path, map_location=self.device)
31
+ model.load_state_dict(model_ckpt, strict=False)
32
+ msg = model.load_state_dict(model_ckpt, strict=False)
33
+ print("load_state_dict: ", msg)
34
+ # num_features = model.get_classifier().in_features
35
+ # model.classifier = nn.Linear(num_features, number_of_categories)
36
+
37
+ return model.to(self.device).eval()
38
+
39
+ self.model = _load_model(model_name, model_path)
40
+
41
+ self.transforms = T.Compose([T.Resize((299, 299)),
42
+ T.ToTensor(),
43
+ T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])
44
+ # T.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])])
45
+
46
+
47
+ def predict_image(self, image: np.ndarray) -> list():
48
+ """Run inference using ONNX runtime.
49
+ :param image: Input image as numpy array.
50
+ :return: A list with logits and confidences.
51
+ """
52
+
53
+ # logits = self.model(self.transforms(image).unsqueeze(0).to(self.device))
54
+
55
+ self.model.eval()
56
+
57
+ outputs = self.model(self.transforms(image).unsqueeze(0).to(self.device))
58
+
59
+ _, preds = torch.max(outputs, 1)
60
+
61
+ preds = preds.cpu() # Move tensor to CPU
62
+
63
+ print("preds: ", preds)
64
+
65
+ return preds.tolist() # Convert tensor to list
66
+
67
+
68
+ def make_submission(test_metadata, model_path, model_name, output_csv_path="./submission.csv", images_root_path="/tmp/data/private_testset"):
69
+ """Make submission with given """
70
+
71
+ model = PytorchWorker(model_path, model_name)
72
+
73
+ predictions = []
74
+
75
+ for _, row in tqdm(test_metadata.iterrows(), total=len(test_metadata)):
76
+ image_path = os.path.join(images_root_path, row.image_path)
77
+
78
+ test_image = Image.open(image_path).convert("RGB")
79
+
80
+ logits = model.predict_image(test_image)
81
+
82
+ pred_class_id = logits[0] if logits[0] !=1604 else -1
83
+
84
+ predictions.append(pred_class_id)
85
+
86
+ test_metadata["class_id"] = predictions
87
+
88
+ user_pred_df = test_metadata.drop_duplicates("observation_id", keep="first")
89
+ user_pred_df[["observation_id", "class_id"]].to_csv(output_csv_path, index=None)
90
+
91
+
92
+ if __name__ == "__main__":
93
+
94
+ import zipfile
95
+
96
+ with zipfile.ZipFile("/tmp/data/private_testset.zip", 'r') as zip_ref:
97
+ zip_ref.extractall("/tmp/data")
98
+
99
+ MODEL_PATH = './e21_t152.pth'
100
+ MODEL_NAME = 'tf_efficientnet_b3_ns' #"tf_efficientnet_b1.ap_in1k"
101
+
102
+ metadata_file_path = "./FungiCLEF2024_TestMetadata.csv"
103
+ test_metadata = pd.read_csv(metadata_file_path)
104
+
105
+ make_submission(
106
+ test_metadata=test_metadata,
107
+ model_path=MODEL_PATH,
108
+ model_name=MODEL_NAME
109
+ )