Create script_fuse_with_baseline.py
Browse files- script_fuse_with_baseline.py +123 -0
script_fuse_with_baseline.py
ADDED
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
self.model.eval()
|
58 |
+
outputs = self.model(self.transforms(image).unsqueeze(0).to(self.device))
|
59 |
+
return outputs.cpu() # Convert tensor to list
|
60 |
+
|
61 |
+
|
62 |
+
def make_submission(test_metadata, model_path, model_path2, model_name, model_name2, output_csv_path="./submission.csv", images_root_path="/tmp/data/private_testset"):
|
63 |
+
"""Make submission with given """
|
64 |
+
model = PytorchWorker(model_path, model_name, number_of_categories=1604)
|
65 |
+
model2 = PytorchWorker(model_path2, model_name2)
|
66 |
+
|
67 |
+
predictions = []
|
68 |
+
correct_max_values = []
|
69 |
+
incorrect_max_values = []
|
70 |
+
|
71 |
+
for _, row in tqdm(test_metadata.iterrows(), total=len(test_metadata)):
|
72 |
+
image_path = os.path.join(images_root_path, row.image_path)
|
73 |
+
test_image = Image.open(image_path).convert("RGB")
|
74 |
+
|
75 |
+
outputs = model.predict_image(test_image)
|
76 |
+
outputs2 = model2.predict_image(test_image)
|
77 |
+
|
78 |
+
# max_value = torch.max(outputs+outputs2)
|
79 |
+
_, preds = torch.max(outputs, 1) # baseline
|
80 |
+
_, preds2 = torch.max(outputs2, 1) # 1.4.3
|
81 |
+
|
82 |
+
pred_class_id = preds.tolist()
|
83 |
+
pred_class_id2 = preds2.tolist()
|
84 |
+
# max_value2 = torch.max(outputs2)
|
85 |
+
|
86 |
+
pred_class_id = pred_class_id[0] if pred_class_id2[0] != 1604 else -1
|
87 |
+
|
88 |
+
predictions.append(pred_class_id)
|
89 |
+
|
90 |
+
test_metadata["class_id"] = predictions
|
91 |
+
|
92 |
+
user_pred_df = test_metadata.drop_duplicates("observation_id", keep="first")
|
93 |
+
user_pred_df[["observation_id", "class_id"]].to_csv(output_csv_path, index=None)
|
94 |
+
|
95 |
+
|
96 |
+
if __name__ == "__main__":
|
97 |
+
|
98 |
+
import zipfile
|
99 |
+
|
100 |
+
with zipfile.ZipFile("/tmp/data/private_testset.zip", 'r') as zip_ref:
|
101 |
+
zip_ref.extractall("/tmp/data")
|
102 |
+
|
103 |
+
# MODEL_PATH = './efficientnet_b3_epoch_9_delete_pre.pth' # "./efficientnet_b3_epoch_9.pth"
|
104 |
+
# MODEL_PATH = './efficientnet_b3_epoch_24_trick1.2.3_0.6067.pth'
|
105 |
+
# MODEL_PATH = './efficientnet_b3_epoch_10_trick1.2.4_0.6016.pth'
|
106 |
+
# MODEL_PATH = './efficientnet_b3_epoch_3_trick1.2.3_a0.6067_l5.6311.pth'
|
107 |
+
# MODEL_PATH = './efficientnet_b3_epoch_21_trick1.2.5_a0.7237_l17.1662.pth'
|
108 |
+
# MODEL_PATH = './efficientnet_b3_epoch_21_trcik1.5.2.pth'
|
109 |
+
# MODEL_PATH = './efficientnet_b3_epoch_28_1.4.3.pth'
|
110 |
+
MODEL_PATH = './pytorch_model.bin'
|
111 |
+
MODEL_PATH2 = './efficientnet_b3_epoch_28_1.4.3.pth'
|
112 |
+
MODEL_NAME = "tf_efficientnet_b1_ap"
|
113 |
+
MODEL_NAME2 = "tf_efficientnet_b3_ns"
|
114 |
+
metadata_file_path = "./FungiCLEF2024_TestMetadata.csv"
|
115 |
+
test_metadata = pd.read_csv(metadata_file_path)
|
116 |
+
|
117 |
+
make_submission(
|
118 |
+
test_metadata=test_metadata,
|
119 |
+
model_path=MODEL_PATH,
|
120 |
+
model_path2=MODEL_PATH2,
|
121 |
+
model_name=MODEL_NAME,
|
122 |
+
model_name2=MODEL_NAME2
|
123 |
+
)
|