Datasets:
File size: 3,802 Bytes
ac53f17 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 | """Generate example grids of false positives and false negatives."""
import pickle
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from PIL import Image
from sklearn.model_selection import train_test_split
from pathlib import Path
OUT_DIR = Path(__file__).parent
CLF_PATH = OUT_DIR / "laion_natural_img_clf_vitl14.pkl"
DATA_PATH = Path("/home/jroth/photograph_detector/scripts/outputs/extract_openai_vitl14_features/clip_vitl14_features_labeled.pkl")
PROJECT_ROOT = Path("/home/jroth/photograph_detector")
THRESHOLD = 0.7
N_EXAMPLES = 12 # per category
COLS = 4
ROWS = 3
def load_image(path, max_size=256):
try:
img = Image.open(path).convert("RGB")
img.thumbnail((max_size, max_size))
return img
except Exception:
return Image.new("RGB", (max_size, max_size), color="gray")
def make_grid(image_paths, scores, true_labels, title, out_path):
fig, axes = plt.subplots(ROWS, COLS, figsize=(COLS * 3.2, ROWS * 3.2 + 0.8))
fig.suptitle(title, fontsize=14, fontweight="bold", y=1.01)
for idx, ax in enumerate(axes.flat):
if idx < len(image_paths):
img = load_image(image_paths[idx])
ax.imshow(img)
label_str = "natural" if true_labels[idx] == 1 else "non-natural"
ax.set_title(f"score: {scores[idx]:.2f}\ntrue: {label_str}", fontsize=9)
ax.axis("off")
fig.tight_layout()
fig.savefig(out_path, dpi=200, bbox_inches="tight")
plt.close()
print(f"Saved {out_path.name} ({len(image_paths)} examples)")
def main():
with open(CLF_PATH, "rb") as f:
clf = pickle.load(f)
with open(DATA_PATH, "rb") as f:
data = pickle.load(f)
features = data["features"]
labels = data["labels"]
image_paths = data["image_paths"]
# Resolve relative paths
image_paths = [
str(PROJECT_ROOT / p) if not Path(p).is_absolute() else p
for p in image_paths
]
# Same split as training
(train_feat, test_feat,
train_labels, test_labels,
train_paths, test_paths) = train_test_split(
features, labels, image_paths,
test_size=0.2, random_state=42
)
test_scores = clf.predict_proba(test_feat)[:, 1]
test_preds = (test_scores >= THRESHOLD).astype(int)
# False positives: predicted natural (score >= 0.7) but truly non-natural
fp_mask = (test_preds == 1) & (test_labels == 0)
fp_indices = np.where(fp_mask)[0]
# Sort by score descending (most confident false positives first)
fp_indices = fp_indices[np.argsort(-test_scores[fp_indices])][:N_EXAMPLES]
# False negatives: predicted non-natural (score < 0.7) but truly natural
fn_mask = (test_preds == 0) & (test_labels == 1)
fn_indices = np.where(fn_mask)[0]
# Sort by score ascending (most confident false negatives first)
fn_indices = fn_indices[np.argsort(test_scores[fn_indices])][:N_EXAMPLES]
print(f"Total false positives at t={THRESHOLD}: {fp_mask.sum()}")
print(f"Total false negatives at t={THRESHOLD}: {fn_mask.sum()}")
fp_paths = [test_paths[i] for i in fp_indices]
fp_scores = test_scores[fp_indices]
fp_labels = test_labels[fp_indices]
fn_paths = [test_paths[i] for i in fn_indices]
fn_scores = test_scores[fn_indices]
fn_labels = test_labels[fn_indices]
make_grid(
fp_paths, fp_scores, fp_labels,
f"False Positives (threshold = {THRESHOLD})\nPredicted natural, actually non-natural",
OUT_DIR / "false_positives.png",
)
make_grid(
fn_paths, fn_scores, fn_labels,
f"False Negatives (threshold = {THRESHOLD})\nPredicted non-natural, actually natural",
OUT_DIR / "false_negatives.png",
)
print("Done!")
if __name__ == "__main__":
main()
|