File size: 6,190 Bytes
f9ed2b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
#!/usr/bin/env python3
'Fit and evaluate an eight-class real-image-source classifier on frozen CLIP features.'

from __future__ import annotations

import argparse
import csv
import json
import random
import sys
from collections import defaultdict
from pathlib import Path

import numpy as np
import torch
import torch.nn.functional as F
import torchvision.transforms as T
from PIL import Image
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, balanced_accuracy_score, classification_report
from torch.utils.data import DataLoader, Dataset
from tqdm import tqdm

try:
    import clip
except ImportError:
    raise ImportError("Please install clip: pip install git+https://github.com/openai/CLIP.git")


PROJECT_ROOT = Path(__file__).resolve().parents[2]
ARTIFACT_ROOT = PROJECT_ROOT / "artifacts"
DEFAULT_SPLIT_DIR = ARTIFACT_ROOT / "metadata" / "fixed_split"
CLIP_MEAN = [0.48145466, 0.4578275, 0.40821073]
CLIP_STD = [0.26862954, 0.26130258, 0.27577711]

csv.field_size_limit(min(sys.maxsize, 2_147_483_647))


class RealSourceDataset(Dataset):
    def __init__(self, rows: list[dict[str, str]], label_to_idx: dict[str, int], transform):
        self.rows = rows
        self.label_to_idx = label_to_idx
        self.transform = transform

    def __len__(self) -> int:
        return len(self.rows)

    def __getitem__(self, idx: int):
        row = self.rows[idx]
        image = Image.open(row["image_path"]).convert("RGB")
        return self.transform(image), self.label_to_idx[row["source_dataset"]]


def read_rows(path: Path) -> list[dict[str, str]]:
    with path.open("r", newline="", encoding="utf-8") as f:
        return list(csv.DictReader(f))


def sample_per_source(rows: list[dict[str, str]], per_source: int | None, seed: int) -> list[dict[str, str]]:
    grouped: dict[str, list[dict[str, str]]] = defaultdict(list)
    for row in rows:
        grouped[row["source_dataset"]].append(row)
    rng = random.Random(seed)
    selected = []
    for source in sorted(grouped):
        source_rows = list(grouped[source])
        rng.shuffle(source_rows)
        if per_source is not None:
            source_rows = source_rows[:per_source]
        selected.extend(source_rows)
    return selected


def make_transform() -> T.Compose:
    return T.Compose([
        T.Resize(int(224 * 1.15)),
        T.CenterCrop(224),
        T.ToTensor(),
        T.Normalize(CLIP_MEAN, CLIP_STD),
    ])


@torch.no_grad()
def extract_features(model, loader, device: torch.device) -> tuple[np.ndarray, np.ndarray]:
    features = []
    labels = []
    for images, y in tqdm(loader, desc="Extracting real-source features"):
        images = images.to(device)
        feat = model.encode_image(images).float()
        feat = F.normalize(feat, dim=-1)
        features.append(feat.cpu().numpy())
        labels.append(y.numpy())
    return np.concatenate(features, axis=0), np.concatenate(labels, axis=0)


def main() -> None:
    parser = argparse.ArgumentParser(description="training real-source bias control.")
    parser.add_argument("--real-train-csv", type=Path, default=DEFAULT_SPLIT_DIR / "real_train_pool.csv")
    parser.add_argument("--real-val-csv", type=Path, default=DEFAULT_SPLIT_DIR / "real_validation.csv")
    parser.add_argument("--train-per-source", type=int, default=5000)
    parser.add_argument("--val-per-source", type=int, default=1000)
    parser.add_argument("--batch-size", type=int, default=128)
    parser.add_argument("--num-workers", type=int, default=8)
    parser.add_argument("--device", type=str, default="cuda")
    parser.add_argument("--seed", type=int, default=42)
    parser.add_argument("--output", type=Path, default=ARTIFACT_ROOT / "results" / "training" / "real_source_bias_clip_logreg.json")
    args = parser.parse_args()

    random.seed(args.seed)
    np.random.seed(args.seed)
    torch.manual_seed(args.seed)
    device = torch.device(args.device if torch.cuda.is_available() else "cpu")

    train_rows = sample_per_source(read_rows(args.real_train_csv), args.train_per_source, args.seed)
    val_rows = sample_per_source(read_rows(args.real_val_csv), args.val_per_source, args.seed)
    labels = sorted({row["source_dataset"] for row in train_rows + val_rows})
    label_to_idx = {label: idx for idx, label in enumerate(labels)}
    idx_to_label = {idx: label for label, idx in label_to_idx.items()}

    model, _ = clip.load("ViT-L/14", device=device)
    model.eval()
    transform = make_transform()
    train_loader = DataLoader(
        RealSourceDataset(train_rows, label_to_idx, transform),
        batch_size=args.batch_size,
        shuffle=False,
        num_workers=args.num_workers,
        pin_memory=True,
    )
    val_loader = DataLoader(
        RealSourceDataset(val_rows, label_to_idx, transform),
        batch_size=args.batch_size,
        shuffle=False,
        num_workers=args.num_workers,
        pin_memory=True,
    )

    x_train, y_train = extract_features(model, train_loader, device)
    x_val, y_val = extract_features(model, val_loader, device)
    clf = LogisticRegression(max_iter=1000, C=1.0, solver="lbfgs")
    clf.fit(x_train, y_train)
    pred = clf.predict(x_val)

    report = classification_report(
        y_val,
        pred,
        target_names=[idx_to_label[i] for i in range(len(idx_to_label))],
        output_dict=True,
        zero_division=0,
    )
    result = {
        "seed": args.seed,
        "train_per_source": args.train_per_source,
        "val_per_source": args.val_per_source,
        "labels": idx_to_label,
        "accuracy": float(accuracy_score(y_val, pred)),
        "balanced_accuracy": float(balanced_accuracy_score(y_val, pred)),
        "classification_report": report,
    }
    args.output.parent.mkdir(parents=True, exist_ok=True)
    with args.output.open("w", encoding="utf-8") as f:
        json.dump(result, f, indent=2, ensure_ascii=False)
    print(json.dumps(result, indent=2, ensure_ascii=False))


if __name__ == "__main__":
    main()