Upload 14 files
Browse files- .gitattributes +1 -0
- 1_json_to_csv.py +28 -0
- 2_retrieve_images_by_cc.py +19 -0
- 3_common_tags.py +33 -0
- 4_cm_onnx_inference.py +98 -0
- 5_wd_v3_onnx_inference.py +83 -0
- 6_get_labels.py +42 -0
- 7_analyze_metrics_macro.py +183 -0
- README.md +70 -0
- cm_tags.csv +0 -0
- cm_tags.json +0 -0
- cm_tags_common.csv +0 -0
- sw_tags.csv +0 -0
- sw_tags_common.csv +0 -0
- val_dataset.csv +3 -0
.gitattributes
CHANGED
|
@@ -57,3 +57,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 57 |
# Video files - compressed
|
| 58 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 59 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 57 |
# Video files - compressed
|
| 58 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 59 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
| 60 |
+
val_dataset.csv filter=lfs diff=lfs merge=lfs -text
|
1_json_to_csv.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
|
| 3 |
+
import pandas as pd
|
| 4 |
+
|
| 5 |
+
cat_name_to_db_id = {
|
| 6 |
+
"meta": 5,
|
| 7 |
+
"character": 4,
|
| 8 |
+
"copyright": 3,
|
| 9 |
+
"artist": 1,
|
| 10 |
+
"general": 0,
|
| 11 |
+
"year": 10,
|
| 12 |
+
"rating": 9,
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
with open("cm_tags.json") as f:
|
| 17 |
+
data = json.load(f)
|
| 18 |
+
|
| 19 |
+
df_list = []
|
| 20 |
+
for elem in data["idx_to_tag"]:
|
| 21 |
+
base = {"tag_id": None, "name": None, "category": None, "count": -1}
|
| 22 |
+
base["tag_id"] = elem
|
| 23 |
+
base["name"] = data["idx_to_tag"][elem]
|
| 24 |
+
base["category"] = cat_name_to_db_id[data["tag_to_category"][base["name"]]]
|
| 25 |
+
df_list.append(base)
|
| 26 |
+
|
| 27 |
+
df = pd.DataFrame.from_dict(df_list)
|
| 28 |
+
df.to_csv("cm_tags.csv", index=False)
|
2_retrieve_images_by_cc.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
import pandas as pd
|
| 3 |
+
from cheesechaser.datapool.danbooru import DanbooruNewestDataPool
|
| 4 |
+
|
| 5 |
+
existing = Path("original").glob("*")
|
| 6 |
+
existing = [int(x.stem) for x in existing]
|
| 7 |
+
|
| 8 |
+
df = pd.read_csv("val_dataset.csv")
|
| 9 |
+
want = df["id"].tolist()
|
| 10 |
+
want = list(set(want) - set(existing))
|
| 11 |
+
|
| 12 |
+
pool = DanbooruNewestDataPool()
|
| 13 |
+
|
| 14 |
+
pool.batch_download_to_directory(
|
| 15 |
+
resource_ids=want,
|
| 16 |
+
dst_dir="original",
|
| 17 |
+
max_workers=12,
|
| 18 |
+
silent=True,
|
| 19 |
+
)
|
3_common_tags.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
|
| 3 |
+
sw_tags = pd.read_csv("sw_tags.csv")
|
| 4 |
+
cm_tags = pd.read_csv("cm_tags.csv")
|
| 5 |
+
|
| 6 |
+
sw_tags["tag_idx"] = sw_tags.index
|
| 7 |
+
|
| 8 |
+
sw_tags = sw_tags.set_index("name")
|
| 9 |
+
cm_tags = cm_tags.set_index("name")
|
| 10 |
+
|
| 11 |
+
common_tags = sw_tags.index.intersection(cm_tags.index)
|
| 12 |
+
|
| 13 |
+
sw_tags = sw_tags[sw_tags.index.isin(common_tags)]
|
| 14 |
+
cm_tags = cm_tags[cm_tags.index.isin(common_tags)]
|
| 15 |
+
|
| 16 |
+
# Some tags have changed category over time,
|
| 17 |
+
# so only keep the ones where the category matches between the datasets
|
| 18 |
+
sw_tags["cm_category"] = cm_tags["category"]
|
| 19 |
+
sw_tags = sw_tags[sw_tags["category"] == sw_tags["cm_category"]]
|
| 20 |
+
sw_tags = sw_tags.drop("cm_category", axis=1)
|
| 21 |
+
|
| 22 |
+
common_tags = sw_tags.index.intersection(cm_tags.index)
|
| 23 |
+
|
| 24 |
+
sw_tags = sw_tags[sw_tags.index.isin(common_tags)]
|
| 25 |
+
cm_tags = cm_tags[cm_tags.index.isin(common_tags)]
|
| 26 |
+
|
| 27 |
+
cm_tags["tag_idx"] = cm_tags["tag_id"]
|
| 28 |
+
cm_tags["tag_id"] = sw_tags["tag_id"]
|
| 29 |
+
|
| 30 |
+
cm_tags = cm_tags.reindex(sw_tags.index)
|
| 31 |
+
|
| 32 |
+
sw_tags.to_csv("sw_tags_common.csv")
|
| 33 |
+
cm_tags.to_csv("cm_tags_common.csv")
|
4_cm_onnx_inference.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import onnxruntime as ort
|
| 5 |
+
from PIL import Image
|
| 6 |
+
from tqdm import tqdm
|
| 7 |
+
|
| 8 |
+
# Disable decompression bomb warnings 'cuz we trust danbooru images
|
| 9 |
+
Image.MAX_IMAGE_PIXELS = None
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def load_model(model_path):
|
| 13 |
+
"""Test an ONNX model with a single image"""
|
| 14 |
+
# Load ONNX model
|
| 15 |
+
print(f"Loading ONNX model from {model_path}")
|
| 16 |
+
try:
|
| 17 |
+
# Try with CUDA
|
| 18 |
+
session = ort.InferenceSession(
|
| 19 |
+
model_path,
|
| 20 |
+
providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
|
| 21 |
+
)
|
| 22 |
+
print(f"Using providers: {session.get_providers()}")
|
| 23 |
+
except Exception as e:
|
| 24 |
+
print(f"CUDA not available, using CPU: {e}")
|
| 25 |
+
session = ort.InferenceSession(model_path, providers=["CPUExecutionProvider"])
|
| 26 |
+
print(f"Using providers: {session.get_providers()}")
|
| 27 |
+
return session
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def preprocess_image(image_path, image_size=512):
|
| 31 |
+
"""Process an image for inference"""
|
| 32 |
+
try:
|
| 33 |
+
with Image.open(image_path) as img:
|
| 34 |
+
# Convert RGBA or Palette images to RGB
|
| 35 |
+
# ...while respecting transparency set in the palette
|
| 36 |
+
if img.mode in ("RGBA", "P"):
|
| 37 |
+
img = img.convert("RGBA")
|
| 38 |
+
canvas = Image.new("RGBA", img.size, (0, 0, 0))
|
| 39 |
+
canvas.alpha_composite(img)
|
| 40 |
+
img = canvas.convert("RGB")
|
| 41 |
+
|
| 42 |
+
# Get original dimensions
|
| 43 |
+
width, height = img.size
|
| 44 |
+
aspect_ratio = width / height
|
| 45 |
+
|
| 46 |
+
# Calculate new dimensions to maintain aspect ratio
|
| 47 |
+
if aspect_ratio > 1:
|
| 48 |
+
new_width = image_size
|
| 49 |
+
new_height = int(new_width / aspect_ratio)
|
| 50 |
+
else:
|
| 51 |
+
new_height = image_size
|
| 52 |
+
new_width = int(new_height * aspect_ratio)
|
| 53 |
+
|
| 54 |
+
# Resize with LANCZOS filter
|
| 55 |
+
img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
|
| 56 |
+
|
| 57 |
+
# Create new image with padding
|
| 58 |
+
new_image = Image.new("RGB", (image_size, image_size), (0, 0, 0))
|
| 59 |
+
paste_x = (image_size - new_width) // 2
|
| 60 |
+
paste_y = (image_size - new_height) // 2
|
| 61 |
+
new_image.paste(img, (paste_x, paste_y))
|
| 62 |
+
|
| 63 |
+
# Apply transforms
|
| 64 |
+
img_tensor = np.array(new_image, dtype=np.float32)
|
| 65 |
+
img_tensor = img_tensor / 255.0
|
| 66 |
+
return img_tensor
|
| 67 |
+
except Exception as e:
|
| 68 |
+
raise Exception(f"Error processing {image_path}: {str(e)}")
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def test_onnx_model(session, image_path):
|
| 72 |
+
# Preprocess image
|
| 73 |
+
img_tensor = preprocess_image(image_path)
|
| 74 |
+
|
| 75 |
+
# Add batch dimension and convert to numpy
|
| 76 |
+
img_numpy = np.transpose(img_tensor, [2, 0, 1])
|
| 77 |
+
img_numpy = np.expand_dims(img_numpy, axis=0)
|
| 78 |
+
|
| 79 |
+
# Get input name
|
| 80 |
+
input_name = session.get_inputs()[0].name
|
| 81 |
+
|
| 82 |
+
# Run inference
|
| 83 |
+
outputs = session.run(None, {input_name: img_numpy})
|
| 84 |
+
|
| 85 |
+
# Process outputs
|
| 86 |
+
initial_probs = 1.0 / (1.0 + np.exp(-outputs[0])) # Apply sigmoid
|
| 87 |
+
return initial_probs
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
if __name__ == "__main__":
|
| 91 |
+
session = load_model("camie-tagger/model_initial.onnx")
|
| 92 |
+
images = sorted(list(Path("original").glob("*")))
|
| 93 |
+
|
| 94 |
+
probs = np.zeros((len(images), 70527), dtype=np.float32)
|
| 95 |
+
for i, image_path in enumerate(tqdm(images)):
|
| 96 |
+
probs[i] = test_onnx_model(session, image_path)
|
| 97 |
+
|
| 98 |
+
np.save("cm_probs.npy", probs)
|
5_wd_v3_onnx_inference.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import onnxruntime as ort
|
| 5 |
+
from PIL import Image
|
| 6 |
+
from tqdm import tqdm
|
| 7 |
+
|
| 8 |
+
# Disable decompression bomb warnings 'cuz we trust danbooru images
|
| 9 |
+
Image.MAX_IMAGE_PIXELS = None
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def load_model(model_path):
|
| 13 |
+
"""Test an ONNX model with a single image"""
|
| 14 |
+
# Load ONNX model
|
| 15 |
+
print(f"Loading ONNX model from {model_path}")
|
| 16 |
+
try:
|
| 17 |
+
# Try with CUDA
|
| 18 |
+
session = ort.InferenceSession(
|
| 19 |
+
model_path,
|
| 20 |
+
providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
|
| 21 |
+
)
|
| 22 |
+
print(f"Using providers: {session.get_providers()}")
|
| 23 |
+
except Exception as e:
|
| 24 |
+
print(f"CUDA not available, using CPU: {e}")
|
| 25 |
+
session = ort.InferenceSession(model_path, providers=["CPUExecutionProvider"])
|
| 26 |
+
print(f"Using providers: {session.get_providers()}")
|
| 27 |
+
return session
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def preprocess_image(image_path, target_size=448):
|
| 31 |
+
image = Image.open(image_path)
|
| 32 |
+
image = image.convert(mode="RGBA")
|
| 33 |
+
|
| 34 |
+
canvas = Image.new("RGBA", image.size, (255, 255, 255))
|
| 35 |
+
canvas.alpha_composite(image)
|
| 36 |
+
image = canvas.convert("RGB")
|
| 37 |
+
|
| 38 |
+
# Pad image to square
|
| 39 |
+
image_shape = image.size
|
| 40 |
+
max_dim = max(image_shape)
|
| 41 |
+
pad_left = (max_dim - image_shape[0]) // 2
|
| 42 |
+
pad_top = (max_dim - image_shape[1]) // 2
|
| 43 |
+
|
| 44 |
+
padded_image = Image.new("RGB", (max_dim, max_dim), (255, 255, 255))
|
| 45 |
+
padded_image.paste(image, (pad_left, pad_top))
|
| 46 |
+
|
| 47 |
+
# Resize
|
| 48 |
+
if max_dim != target_size:
|
| 49 |
+
padded_image = padded_image.resize(
|
| 50 |
+
(target_size, target_size),
|
| 51 |
+
Image.BICUBIC,
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
# Convert to numpy array
|
| 55 |
+
image_array = np.asarray(padded_image, dtype=np.float32)
|
| 56 |
+
|
| 57 |
+
# Convert PIL-native RGB to BGR
|
| 58 |
+
image_array = image_array[:, :, ::-1]
|
| 59 |
+
|
| 60 |
+
return np.expand_dims(image_array, axis=0)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def test_onnx_model(session, image_path):
|
| 64 |
+
# Preprocess image
|
| 65 |
+
img_numpy = preprocess_image(image_path)
|
| 66 |
+
|
| 67 |
+
# Get input name
|
| 68 |
+
input_name = session.get_inputs()[0].name
|
| 69 |
+
|
| 70 |
+
# Run inference
|
| 71 |
+
outputs = session.run(None, {input_name: img_numpy})[0]
|
| 72 |
+
return outputs
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
if __name__ == "__main__":
|
| 76 |
+
session = load_model("wd_v3_tagger/swinv2.onnx")
|
| 77 |
+
images = sorted(list(Path("original").glob("*")))
|
| 78 |
+
|
| 79 |
+
probs = np.zeros((len(images), 10861), dtype=np.float32)
|
| 80 |
+
for i, image_path in enumerate(tqdm(images)):
|
| 81 |
+
probs[i] = test_onnx_model(session, image_path)
|
| 82 |
+
|
| 83 |
+
np.save("swinv2_probs.npy", probs)
|
6_get_labels.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pandas as pd
|
| 5 |
+
|
| 6 |
+
df = pd.read_csv("val_dataset.csv")
|
| 7 |
+
df = df.set_index("id")
|
| 8 |
+
|
| 9 |
+
images = sorted(list(Path("original").glob("*")))
|
| 10 |
+
images = [int(x.stem) for x in images]
|
| 11 |
+
df = df.loc[images]
|
| 12 |
+
|
| 13 |
+
tags = pd.read_csv("sw_tags_common.csv")
|
| 14 |
+
tags = tags["name"].tolist()
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def to_one_hot(x):
|
| 18 |
+
tag_fields = [
|
| 19 |
+
"tag_string_general",
|
| 20 |
+
"tag_string_character",
|
| 21 |
+
"tag_string_copyright",
|
| 22 |
+
"tag_string_artist",
|
| 23 |
+
"tag_string_meta",
|
| 24 |
+
]
|
| 25 |
+
|
| 26 |
+
tag_string = []
|
| 27 |
+
for tag_field in tag_fields:
|
| 28 |
+
column_content = x[tag_field]
|
| 29 |
+
if pd.isna(column_content):
|
| 30 |
+
continue
|
| 31 |
+
|
| 32 |
+
tag_string.extend(column_content.split(" "))
|
| 33 |
+
|
| 34 |
+
return np.isin(tags, tag_string)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
labels = np.zeros((len(df), len(tags)), dtype=np.uint8)
|
| 38 |
+
for i, elem in enumerate(df.iterrows()):
|
| 39 |
+
res = to_one_hot(elem[1])
|
| 40 |
+
labels[i] = res
|
| 41 |
+
|
| 42 |
+
np.save("labels.npy", labels)
|
7_analyze_metrics_macro.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import pandas as pd
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def calc_metrics(img_tags, img_probs, thresh):
|
| 9 |
+
yz = (img_tags > 0).astype(np.uint8)
|
| 10 |
+
pos = (img_probs > thresh).astype(np.uint8)
|
| 11 |
+
pct = pos + 2 * yz
|
| 12 |
+
|
| 13 |
+
FP = np.sum(pct == 1, axis=0).astype(np.float32)
|
| 14 |
+
FN = np.sum(pct == 2, axis=0).astype(np.float32)
|
| 15 |
+
TP = np.sum(pct == 3, axis=0).astype(np.float32)
|
| 16 |
+
|
| 17 |
+
recall = TP / np.maximum(TP + FN, 1e-6)
|
| 18 |
+
precision = TP / np.maximum(TP + FP, 1e-6)
|
| 19 |
+
return precision.mean(), recall.mean()
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
parser = argparse.ArgumentParser(description="Analyze output probabilities dumps")
|
| 23 |
+
parser.add_argument(
|
| 24 |
+
"-tc",
|
| 25 |
+
"--tags-csv",
|
| 26 |
+
default="sw_tags_common.csv",
|
| 27 |
+
help="Dataset name",
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
parser.add_argument(
|
| 31 |
+
"-d",
|
| 32 |
+
"--dump",
|
| 33 |
+
default="swinv2_probs.npy",
|
| 34 |
+
help="Probabilities dump",
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
parser.add_argument(
|
| 38 |
+
"-l",
|
| 39 |
+
"--labels",
|
| 40 |
+
default="labels.npy",
|
| 41 |
+
help="One-hot encoded labels dump file",
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
parser.add_argument(
|
| 45 |
+
"-s",
|
| 46 |
+
"--start-index",
|
| 47 |
+
type=int,
|
| 48 |
+
default=0,
|
| 49 |
+
help="Slice files along axis=1 starting from this index",
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
parser.add_argument(
|
| 53 |
+
"-e",
|
| 54 |
+
"--end-index",
|
| 55 |
+
type=int,
|
| 56 |
+
default=-1,
|
| 57 |
+
help="Slice files along axis=1 ending to this index",
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
parser.add_argument(
|
| 61 |
+
"-c",
|
| 62 |
+
"--category",
|
| 63 |
+
type=int,
|
| 64 |
+
default=-1,
|
| 65 |
+
help="Only analyze tags of this category (-1 = all)",
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
thresh_group = parser.add_mutually_exclusive_group()
|
| 69 |
+
thresh_group.add_argument(
|
| 70 |
+
"-a",
|
| 71 |
+
"--analyze",
|
| 72 |
+
action="store_true",
|
| 73 |
+
help="Iteratively look for the threshold where P ≈ R",
|
| 74 |
+
)
|
| 75 |
+
thresh_group.set_defaults(analyze=False)
|
| 76 |
+
|
| 77 |
+
thresh_group.add_argument(
|
| 78 |
+
"-t",
|
| 79 |
+
"--threshold",
|
| 80 |
+
type=float,
|
| 81 |
+
default=0.4,
|
| 82 |
+
help="Use this threshold to calculate the metrics",
|
| 83 |
+
)
|
| 84 |
+
args = parser.parse_args()
|
| 85 |
+
|
| 86 |
+
img_probs = np.load(args.dump)
|
| 87 |
+
img_tags = np.load(args.labels)
|
| 88 |
+
|
| 89 |
+
df = pd.read_csv(args.tags_csv)
|
| 90 |
+
indexes = df["tag_idx"].tolist()
|
| 91 |
+
img_probs = img_probs[:, indexes]
|
| 92 |
+
|
| 93 |
+
if args.category != -1:
|
| 94 |
+
indexes = np.where(df["category"] == args.category)[0]
|
| 95 |
+
img_probs = img_probs[:, indexes]
|
| 96 |
+
img_tags = img_tags[:, indexes]
|
| 97 |
+
|
| 98 |
+
end_index = args.end_index
|
| 99 |
+
if end_index == -1:
|
| 100 |
+
end_index = img_probs.shape[1]
|
| 101 |
+
|
| 102 |
+
img_probs = img_probs[:, args.start_index : end_index]
|
| 103 |
+
img_tags = img_tags[:, args.start_index : end_index]
|
| 104 |
+
|
| 105 |
+
indexes = np.where(img_tags.sum(axis=0) > 0)[0]
|
| 106 |
+
img_probs = img_probs[:, indexes]
|
| 107 |
+
img_tags = img_tags[:, indexes]
|
| 108 |
+
print(f"Final # of tags: {img_tags.shape[1]}")
|
| 109 |
+
|
| 110 |
+
assert img_probs.shape[1] > 0
|
| 111 |
+
|
| 112 |
+
if args.analyze:
|
| 113 |
+
threshold_min = 0.05
|
| 114 |
+
threshold_max = 0.95
|
| 115 |
+
|
| 116 |
+
iters = 0
|
| 117 |
+
recall = 0.0
|
| 118 |
+
precision = 1.0
|
| 119 |
+
while not np.isclose(recall, precision) and (iters < 15):
|
| 120 |
+
threshold = (threshold_max + threshold_min) / 2
|
| 121 |
+
precision, recall = calc_metrics(img_tags, img_probs, threshold)
|
| 122 |
+
if precision > recall:
|
| 123 |
+
threshold_max = threshold
|
| 124 |
+
else:
|
| 125 |
+
threshold_min = threshold
|
| 126 |
+
iters += 1
|
| 127 |
+
|
| 128 |
+
threshold = round(threshold, 4)
|
| 129 |
+
else:
|
| 130 |
+
threshold = args.threshold
|
| 131 |
+
|
| 132 |
+
pos = (img_probs > threshold).astype(np.uint8)
|
| 133 |
+
yz = (img_tags > 0).astype(np.uint8)
|
| 134 |
+
pct = pos + 2 * yz
|
| 135 |
+
|
| 136 |
+
TN = np.sum(pct == 0, axis=0).astype(np.float32)
|
| 137 |
+
FP = np.sum(pct == 1, axis=0).astype(np.float32)
|
| 138 |
+
FN = np.sum(pct == 2, axis=0).astype(np.float32)
|
| 139 |
+
TP = np.sum(pct == 3, axis=0).astype(np.float32)
|
| 140 |
+
|
| 141 |
+
recall = np.mean(TP / np.maximum(TP + FN, 1e-6))
|
| 142 |
+
precision = np.mean(TP / np.maximum(TP + FP, 1e-6))
|
| 143 |
+
accuracy = np.mean((TP + TN) / (TP + TN + FP + FN))
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def get_fbeta(beta, TP, FP, FN):
|
| 147 |
+
numerator = (1 + beta**2) * TP
|
| 148 |
+
denominator = (1 + beta**2) * TP + beta**2 * FN + FP
|
| 149 |
+
|
| 150 |
+
idx = np.where(denominator == 0)
|
| 151 |
+
numerator[idx] = 1
|
| 152 |
+
denominator[idx] = 1
|
| 153 |
+
|
| 154 |
+
return np.mean(numerator / denominator)
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def get_mcc(TP, TN, FP, FN):
|
| 158 |
+
N = TP + FN + FP + TN
|
| 159 |
+
S = (TP + FN) / N
|
| 160 |
+
P = (TP + FP) / N
|
| 161 |
+
numerator = (TP / N) - (S * P)
|
| 162 |
+
denominator = S * P * (1 - S) * (1 - P)
|
| 163 |
+
denominator = np.maximum(denominator, 1e-12)
|
| 164 |
+
denominator = np.sqrt(denominator)
|
| 165 |
+
return np.mean(numerator / denominator)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
F1 = get_fbeta(1, TP, FP, FN)
|
| 169 |
+
F2 = get_fbeta(2, TP, FP, FN)
|
| 170 |
+
|
| 171 |
+
MCC = get_mcc(TP, TN, FP, FN)
|
| 172 |
+
|
| 173 |
+
model_name = Path(args.dump).name
|
| 174 |
+
d = {
|
| 175 |
+
"thres": threshold,
|
| 176 |
+
"F1": round(float(F1), 4),
|
| 177 |
+
"F2": round(float(F2), 4),
|
| 178 |
+
"MCC": round(float(MCC), 4),
|
| 179 |
+
"A": round(float(accuracy), 4),
|
| 180 |
+
"R": round(float(recall), 4),
|
| 181 |
+
"P": round(float(precision), 4),
|
| 182 |
+
}
|
| 183 |
+
print(f"{model_name}: {str(d)}")
|
README.md
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
## What's what
|
| 2 |
+
|
| 3 |
+
`1_json_to_csv.py`:
|
| 4 |
+
- converts cm_tags.json to a csv format I'm more used to and that is easier to use with my existing tooling
|
| 5 |
+
|
| 6 |
+
`2_retrieve_images_by_cc.py`:
|
| 7 |
+
- retrieves the validation images using cheesechaser, downloads them to "original/"
|
| 8 |
+
|
| 9 |
+
`3_common_tags.py`:
|
| 10 |
+
- clean up both models tag sets to only consider the common tags; note down the indexes to use to fetch the correct tag probs from the dumps generated by the inference scripts
|
| 11 |
+
|
| 12 |
+
`4_cm_onnx_inference.py`:
|
| 13 |
+
- run inference using the ONNX model of camie-tagger, dump the activated (post-sigmoid) outputs
|
| 14 |
+
|
| 15 |
+
`5_wd_v3_onnx_inference.py`:
|
| 16 |
+
- run inference using the ONNX model of wd_v3 taggers (hardcoded to use swinv2_v3, could be made to use any of the v3 series), dump the activated outputs
|
| 17 |
+
|
| 18 |
+
`6_get_labels.py`:
|
| 19 |
+
- get one-hot encoded labels from val_dataset.csv, dumps them to "labels.npy"
|
| 20 |
+
|
| 21 |
+
`7_analyze_metrics_macro.py`:
|
| 22 |
+
- final analysis tool
|
| 23 |
+
|
| 24 |
+
## Results
|
| 25 |
+
|
| 26 |
+
Category 0: general tags - full
|
| 27 |
+
```
|
| 28 |
+
[user]$ python 7_analyze_metrics_macro.py -tc sw_tags_common.csv -c 0 -d swinv2_probs.npy -l labels.npy -a
|
| 29 |
+
Final # of tags: 7853
|
| 30 |
+
swinv2_probs.npy: {'thres': 0.2613, 'F1': 0.5386, 'F2': 0.5475, 'MCC': 0.548, 'A': 0.9972, 'R': 0.5619, 'P': 0.5619}
|
| 31 |
+
|
| 32 |
+
[user]$ python 7_analyze_metrics_macro.py -tc cm_tags_common.csv -c 0 -d cm_probs.npy -l labels.npy -a
|
| 33 |
+
Final # of tags: 7853
|
| 34 |
+
cm_probs.npy: {'thres': 0.2694, 'F1': 0.273, 'F2': 0.2835, 'MCC': 0.2859, 'A': 0.9955, 'R': 0.3075, 'P': 0.3075}
|
| 35 |
+
```
|
| 36 |
+
|
| 37 |
+
Category 0: general tags - ignoring the top 5000
|
| 38 |
+
```
|
| 39 |
+
[user]$ python 7_analyze_metrics_macro.py -tc sw_tags_common.csv -c 0 -d swinv2_probs.npy -l labels.npy -a -s 5000
|
| 40 |
+
Final # of tags: 2859
|
| 41 |
+
swinv2_probs.npy: {'thres': 0.2272, 'F1': 0.4908, 'F2': 0.5026, 'MCC': 0.5069, 'A': 0.9998, 'R': 0.5256, 'P': 0.5255}
|
| 42 |
+
|
| 43 |
+
[user]$ python 7_analyze_metrics_macro.py -tc cm_tags_common.csv -c 0 -d cm_probs.npy -l labels.npy -a -s 5000
|
| 44 |
+
Final # of tags: 2859
|
| 45 |
+
cm_probs.npy: {'thres': 0.2484, 'F1': 0.1961, 'F2': 0.2032, 'MCC': 0.2104, 'A': 0.9997, 'R': 0.2295, 'P': 0.2294}
|
| 46 |
+
```
|
| 47 |
+
|
| 48 |
+
Category 4: character tags
|
| 49 |
+
```
|
| 50 |
+
[user]$ python 7_analyze_metrics_macro.py -tc sw_tags_common.csv -c 4 -d swinv2_probs.npy -l labels.npy -a
|
| 51 |
+
Final # of tags: 2585
|
| 52 |
+
swinv2_probs.npy: {'thres': 0.3411, 'F1': 0.9464, 'F2': 0.9482, 'MCC': 0.9491, 'A': 1.0, 'R': 0.9519, 'P': 0.952}
|
| 53 |
+
|
| 54 |
+
[user]$ python 7_analyze_metrics_macro.py -tc cm_tags_common.csv -c 4 -d cm_probs.npy -l labels.npy -a
|
| 55 |
+
Final # of tags: 2585
|
| 56 |
+
cm_probs.npy: {'thres': 0.2493, 'F1': 0.7148, 'F2': 0.7226, 'MCC': 0.7266, 'A': 0.9998, 'R': 0.74, 'P': 0.7397}
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
## Caveats
|
| 60 |
+
|
| 61 |
+
The swinv2_v3 tagger has got an unfair home advantage, in that out of the 20116 validation samples, only 2908 are guaranteed to not have been part of the training set.
|
| 62 |
+
|
| 63 |
+
Gathering a more fair validation set is left as an excersise for the reader.
|
| 64 |
+
The exact datasets splits use for wd_v3 models are available here: https://huggingface.co/datasets/SmilingWolf/wdtagger-v3-seed
|
| 65 |
+
|
| 66 |
+
The analysis script removes tags that have no positive samples in the val set.
|
| 67 |
+
It would probably be a good idea to only select tags that have 5+ samples.
|
| 68 |
+
It's a fairly trivial change to make to the analysis script, if one feels so inclined.
|
| 69 |
+
|
| 70 |
+
I have only used the tags that have the exact same name and category to build the common tag set. I haven't adjusted for aliases and implications.
|
cm_tags.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
cm_tags.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
cm_tags_common.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
sw_tags.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
sw_tags_common.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
val_dataset.csv
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d1aad7975cb31a25a237f489a7036b38af6e584da5e5ecd2597f1bbf33bf616d
|
| 3 |
+
size 12932864
|