relaion2b-natural / classifier /generate_error_examples.py
andropar's picture
Add trained naturalness classifier with weights, diagnostics, and evaluation
ac53f17 verified
"""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()