chirmy commited on
Commit
c5c4fe3
·
verified ·
1 Parent(s): 6ff5241

Create scripy_B3.py

Browse files
Files changed (1) hide show
  1. scripy_B3.py +116 -0
scripy_B3.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # if not torch.cuda.is_available():
31
+ # model_ckpt = torch.load(model_path, map_location=torch.device("cpu"))
32
+ # else:
33
+ # model_ckpt = torch.load(model_path)
34
+
35
+ model_ckpt = torch.load(model_path, map_location=self.device)
36
+ model.load_state_dict(model_ckpt, strict=False)
37
+ msg = model.load_state_dict(model_ckpt, strict=False)
38
+ print("load_state_dict: ", msg)
39
+ # num_features = model.get_classifier().in_features
40
+ # model.classifier = nn.Linear(num_features, number_of_categories)
41
+
42
+ return model.to(self.device).eval()
43
+
44
+ self.model = _load_model(model_name, model_path)
45
+
46
+ self.transforms = T.Compose([T.Resize((299, 299)),
47
+ T.ToTensor(),
48
+ T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])
49
+ # T.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])])
50
+
51
+
52
+ def predict_image(self, image: np.ndarray) -> list():
53
+ """Run inference using ONNX runtime.
54
+ :param image: Input image as numpy array.
55
+ :return: A list with logits and confidences.
56
+ """
57
+
58
+ # logits = self.model(self.transforms(image).unsqueeze(0).to(self.device))
59
+
60
+ self.model.eval()
61
+
62
+ outputs = self.model(self.transforms(image).unsqueeze(0).to(self.device))
63
+
64
+ _, preds = torch.max(outputs, 1)
65
+
66
+ preds = preds.cpu() # Move tensor to CPU
67
+
68
+ print("preds: ", preds)
69
+
70
+ return preds.tolist() # Convert tensor to list
71
+
72
+
73
+ def make_submission(test_metadata, model_path, model_name, output_csv_path="./submission.csv", images_root_path="/tmp/data/private_testset"):
74
+ """Make submission with given """
75
+
76
+ model = PytorchWorker(model_path, model_name)
77
+
78
+ predictions = []
79
+
80
+ for _, row in tqdm(test_metadata.iterrows(), total=len(test_metadata)):
81
+ image_path = os.path.join(images_root_path, row.image_path)
82
+
83
+ test_image = Image.open(image_path).convert("RGB")
84
+
85
+ logits = model.predict_image(test_image)
86
+
87
+ pred_class_id = logits[0] if logits[0] !=1604 else -1
88
+
89
+ predictions.append(pred_class_id)
90
+
91
+ test_metadata["class_id"] = predictions
92
+
93
+ user_pred_df = test_metadata.drop_duplicates("observation_id", keep="first")
94
+ user_pred_df[["observation_id", "class_id"]].to_csv(output_csv_path, index=None)
95
+
96
+
97
+ if __name__ == "__main__":
98
+
99
+ import zipfile
100
+
101
+ with zipfile.ZipFile("/tmp/data/private_testset.zip", 'r') as zip_ref:
102
+ zip_ref.extractall("/tmp/data")
103
+
104
+ # MODEL_PATH = './efficientnet_b3_epoch_9_delete_pre.pth' # "./efficientnet_b3_epoch_9.pth"
105
+ # MODEL_PATH = './efficientnet_b3_epoch_24_trick1.2.3_0.6067.pth'
106
+ MODEL_PATH = './efficientnet_b3_epoch_10_trick1.2.4_0.6016.pth'
107
+ MODEL_NAME = 'tf_efficientnet_b3_ns' #"tf_efficientnet_b1.ap_in1k"
108
+
109
+ metadata_file_path = "./FungiCLEF2024_TestMetadata.csv"
110
+ test_metadata = pd.read_csv(metadata_file_path)
111
+
112
+ make_submission(
113
+ test_metadata=test_metadata,
114
+ model_path=MODEL_PATH,
115
+ model_name=MODEL_NAME
116
+ )