MRBagherifar commited on
Commit
8807ed9
·
verified ·
1 Parent(s): 7bb6754

Update script.py

Browse files
Files changed (1) hide show
  1. script.py +86 -6
script.py CHANGED
@@ -1,6 +1,86 @@
1
- {
2
- "cells": [],
3
- "metadata": {},
4
- "nbformat": 4,
5
- "nbformat_minor": 5
6
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import numpy as np
3
+ from PIL import Image
4
+ import onnxruntime as ort
5
+ import os
6
+ from tqdm import tqdm
7
+
8
+
9
+ def is_gpu_available():
10
+ """Check if the python package `onnxruntime-gpu` is installed."""
11
+ return ort.get_device() == "GPU"
12
+
13
+
14
+ class ONNXWorker:
15
+ """Run inference using ONNX runtime."""
16
+
17
+ def __init__(self, onnx_path: str):
18
+ print("Setting up ONNX runtime session.")
19
+ self.use_gpu = is_gpu_available()
20
+ if self.use_gpu:
21
+ providers = ["CUDAExecutionProvider", "CPUExecutionProvider"]
22
+ else:
23
+ providers = ["CPUExecutionProvider"]
24
+
25
+ print(f"Using {providers}")
26
+ self.ort_session = ort.InferenceSession(onnx_path, providers=providers)
27
+
28
+ def _resize_image(self, image: np.ndarray) -> np.ndarray:
29
+ """
30
+ :param image:
31
+ :return:
32
+ """
33
+
34
+ newsize = (300, 300)
35
+ im1 = im1.resize(newsize)
36
+
37
+ def predict_image(self, image: np.ndarray) -> list():
38
+ """Run inference using ONNX runtime.
39
+ :param image: Input image as numpy array.
40
+ :return: A list with logits and confidences.
41
+ """
42
+
43
+ logits, _ = self.ort_session.run(None, {"input": image.astype(dtype=np.uint8)})
44
+
45
+ return logits.tolist()
46
+
47
+
48
+ def make_submission(test_metadata, model_path, output_csv_path="./submission.csv", images_root_path="/tmp/data/private_testset"):
49
+ """Make submission with given """
50
+
51
+ model = ONNXWorker(model_path)
52
+
53
+ predictions = []
54
+
55
+ for _, row in tqdm(test_metadata.iterrows(), total=len(test_metadata)):
56
+ image_path = os.path.join(images_root_path, row.filename)
57
+
58
+ test_image = Image.open(image_path).convert("RGB")
59
+ test_image_resized = np.asarray(test_image.resize((256, 256)))
60
+
61
+ logits = model.predict_image(test_image_resized)
62
+
63
+ predictions.append(np.argmax(logits))
64
+
65
+ test_metadata["class_id"] = predictions
66
+
67
+ user_pred_df = test_metadata.drop_duplicates("observation_id", keep="first")
68
+ user_pred_df[["observation_id", "class_id"]].to_csv(output_csv_path, index=None)
69
+
70
+
71
+ if __name__ == "__main__":
72
+
73
+ import zipfile
74
+
75
+ with zipfile.ZipFile("/tmp/data/private_testset.zip", 'r') as zip_ref:
76
+ zip_ref.extractall("/tmp/data")
77
+
78
+ ONNX_MODEL_PATH = "./swinv2_tiny_window16_256.onnx"
79
+
80
+ metadata_file_path = "./SnakeCLEF2024-TestMetadata.csv"
81
+ test_metadata = pd.read_csv(metadata_file_path)
82
+
83
+ make_submission(
84
+ test_metadata=test_metadata,
85
+ model_path=ONNX_MODEL_PATH,
86
+ )