tobil commited on
Commit
148953b
·
unverified ·
1 Parent(s): 6358a94

add per-label verification composites and cleaning scripts

Browse files

- composites/train/label_N.png — racing-only training samples per digit
- composites/validation/label_N.png — racing-only val samples per digit
- scripts/make_composites.py — regenerate composites from parquet
- scripts/iterative_clean.py — multi-round cross-val + ensemble cleaning

.gitignore CHANGED
@@ -1,5 +1,4 @@
1
  raw/
2
- composites/
3
  __pycache__/
4
  *.pyc
5
  .venv/
 
1
  raw/
 
2
  __pycache__/
3
  *.pyc
4
  .venv/
composites/train/label_1.png ADDED

Git LFS Details

  • SHA256: dc443b39b63adaab0489ef3b5905323233f1fa6f86263f57ed8f8f7e1a6906b6
  • Pointer size: 131 Bytes
  • Size of remote file: 394 kB
composites/train/label_2.png ADDED

Git LFS Details

  • SHA256: af7197c0e047fb0c10725b570ee5e3229250adf7d15106e51d91d821ea311e57
  • Pointer size: 131 Bytes
  • Size of remote file: 833 kB
composites/train/label_3.png ADDED

Git LFS Details

  • SHA256: 5c30b52e7add3d0d2f3c5f8d3bef6672e4b9b1b04ad0e44991bdcb39db0e9620
  • Pointer size: 131 Bytes
  • Size of remote file: 351 kB
composites/train/label_4.png ADDED

Git LFS Details

  • SHA256: 00cc02fbf9179ff31f6e7097e1cc2b6b6bed95ef105ea743848882112c963d53
  • Pointer size: 130 Bytes
  • Size of remote file: 25.6 kB
composites/train/label_5.png ADDED

Git LFS Details

  • SHA256: 661cf24e26d9843d43e0c1a149b2d010dcdaf66a4498d9ba3e3557e4b36e871f
  • Pointer size: 131 Bytes
  • Size of remote file: 129 kB
composites/train/label_6.png ADDED

Git LFS Details

  • SHA256: f8a6d189b9847f4e8a86624ca34641492633309c0c7822bdc388759b809e45cd
  • Pointer size: 131 Bytes
  • Size of remote file: 106 kB
composites/train/label_7.png ADDED

Git LFS Details

  • SHA256: d8adf03638252be718fb720b5c7479548290a82416727ba9887192779c0e964b
  • Pointer size: 130 Bytes
  • Size of remote file: 22.9 kB
composites/validation/label_1.png ADDED

Git LFS Details

  • SHA256: 6cf98cea4210e2f7def2360c4339c8fb231e17f077fb9d5e7cc52d1114fba6fc
  • Pointer size: 130 Bytes
  • Size of remote file: 68.8 kB
composites/validation/label_2.png ADDED

Git LFS Details

  • SHA256: 9852a4de66603036dfe50883431bff029c7ee1c1a141f9c69026935d70eef1b9
  • Pointer size: 131 Bytes
  • Size of remote file: 141 kB
composites/validation/label_3.png ADDED

Git LFS Details

  • SHA256: f62b232ef71cbe63d4099dd55a278f2172e7e4fded1e7a8cd41448dc968bd591
  • Pointer size: 130 Bytes
  • Size of remote file: 62.4 kB
composites/validation/label_4.png ADDED

Git LFS Details

  • SHA256: 76600d8dc4011a3855f671f63217e1ae99db21e34de768d598a8e6583eb51379
  • Pointer size: 130 Bytes
  • Size of remote file: 14.5 kB
composites/validation/label_5.png ADDED

Git LFS Details

  • SHA256: 7059bb5468268f9b7301ccdda993c32083a602462ca0199a427daf917920f37e
  • Pointer size: 130 Bytes
  • Size of remote file: 23.5 kB
composites/validation/label_6.png ADDED

Git LFS Details

  • SHA256: e7ab3b3664edff91c5dfc970fb0e3f96f314f9f90d3880850d2609af62b74ecb
  • Pointer size: 130 Bytes
  • Size of remote file: 23.9 kB
composites/validation/label_7.png ADDED

Git LFS Details

  • SHA256: dcfdfc91f7765b239c666d2a319f6ce93ae312363fff95e6a24a193c843e5388
  • Pointer size: 129 Bytes
  • Size of remote file: 5.45 kB
scripts/iterative_clean.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Iterative dataset cleaning: cross-val clean train 3x, then ensemble-clean val."""
2
+
3
+ import numpy as np
4
+ import pandas as pd
5
+ import io
6
+ import torch
7
+ import torch.nn as nn
8
+ import torch.optim as optim
9
+ from torch.utils.data import DataLoader, TensorDataset
10
+ from PIL import Image
11
+ from sklearn.model_selection import StratifiedKFold
12
+ from datasets import Dataset, Image as HFImage
13
+
14
+ if __name__ != "__main__":
15
+ import sys; sys.exit(0)
16
+
17
+
18
+ class SmallCNN(nn.Module):
19
+ def __init__(self):
20
+ super().__init__()
21
+ self.features = nn.Sequential(
22
+ nn.Conv2d(1, 32, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
23
+ nn.Conv2d(32, 64, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
24
+ nn.Conv2d(64, 128, 3, padding=1), nn.ReLU(), nn.AdaptiveAvgPool2d(4))
25
+ self.classifier = nn.Sequential(
26
+ nn.Flatten(), nn.Linear(128 * 16, 256), nn.ReLU(), nn.Dropout(0.3), nn.Linear(256, 10))
27
+
28
+ def forward(self, x):
29
+ return self.classifier(self.features(x))
30
+
31
+
32
+ def load_images(df):
33
+ imgs = []
34
+ for _, row in df.iterrows():
35
+ img = Image.open(io.BytesIO(row["image"]["bytes"])).convert("L")
36
+ imgs.append(np.array(img, dtype=np.float32) / 255.0)
37
+ return np.stack(imgs)[:, np.newaxis, :, :]
38
+
39
+
40
+ def crossval_predict(X, y, n_splits=5, epochs=30):
41
+ pred_probs = np.zeros((len(X), 10))
42
+ skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)
43
+ for fold, (tr, va) in enumerate(skf.split(X, y)):
44
+ print(f" fold {fold + 1}/{n_splits}...", flush=True)
45
+ model = SmallCNN()
46
+ opt = optim.Adam(model.parameters(), lr=1e-3)
47
+ crit = nn.CrossEntropyLoss()
48
+ loader = DataLoader(
49
+ TensorDataset(torch.tensor(X[tr]), torch.tensor(y[tr], dtype=torch.long)),
50
+ batch_size=64, shuffle=True)
51
+ model.train()
52
+ for _ in range(epochs):
53
+ for xb, yb in loader:
54
+ opt.zero_grad()
55
+ crit(model(xb), yb).backward()
56
+ opt.step()
57
+ model.eval()
58
+ with torch.no_grad():
59
+ pred_probs[va] = torch.softmax(model(torch.tensor(X[va])), dim=1).numpy()
60
+ return pred_probs
61
+
62
+
63
+ def clean_round(df, round_num, conf_threshold=0.6):
64
+ print(f"\n=== Round {round_num}: cross-val clean ({len(df)} samples) ===", flush=True)
65
+ X = load_images(df)
66
+ y = df["label"].values
67
+
68
+ pred_probs = crossval_predict(X, y)
69
+ preds = pred_probs.argmax(axis=1)
70
+ acc = (preds == y).mean()
71
+ print(f" OOF accuracy: {acc:.3f}")
72
+
73
+ conf = pred_probs.max(axis=1)
74
+ bad = (preds != y) & (conf > conf_threshold)
75
+ print(f" Removing {bad.sum()} samples (conf > {conf_threshold})")
76
+
77
+ for label in range(10):
78
+ mask = (y == label) & bad
79
+ if mask.sum() > 0:
80
+ pred_dist = pd.Series(preds[mask]).value_counts().to_dict()
81
+ print(f" label={label}: drop {mask.sum()} -> model says {pred_dist}")
82
+
83
+ return df[~bad].reset_index(drop=True), acc
84
+
85
+
86
+ # === Iterative train cleaning ===
87
+ train_df = pd.read_parquet("data/train-00000-of-00001.parquet")
88
+
89
+ for round_num in range(1, 4):
90
+ train_df, acc = clean_round(train_df, round_num)
91
+ if acc > 0.97:
92
+ print(" Accuracy high enough, stopping early")
93
+ break
94
+
95
+ print(f"\nFinal train: {len(train_df)}")
96
+ print(pd.crosstab(train_df["label"], train_df["source"]))
97
+
98
+ # === Ensemble clean val ===
99
+ print(f"\n=== Cleaning val with 7-model ensemble ===", flush=True)
100
+ X_train = load_images(train_df)
101
+ y_train = train_df["label"].values
102
+
103
+ val_df = pd.read_parquet("data/validation-00000-of-00001.parquet")
104
+ X_val = load_images(val_df)
105
+ y_val = val_df["label"].values
106
+
107
+ val_probs = np.zeros((len(X_val), 10))
108
+ for i in range(7):
109
+ print(f" model {i + 1}/7...", flush=True)
110
+ model = SmallCNN()
111
+ opt = optim.Adam(model.parameters(), lr=1e-3)
112
+ crit = nn.CrossEntropyLoss()
113
+ idx = np.random.choice(len(X_train), len(X_train), replace=True)
114
+ loader = DataLoader(
115
+ TensorDataset(torch.tensor(X_train[idx]), torch.tensor(y_train[idx], dtype=torch.long)),
116
+ batch_size=64, shuffle=True)
117
+ model.train()
118
+ for _ in range(30):
119
+ for xb, yb in loader:
120
+ opt.zero_grad()
121
+ crit(model(xb), yb).backward()
122
+ opt.step()
123
+ model.eval()
124
+ with torch.no_grad():
125
+ val_probs += torch.softmax(model(torch.tensor(X_val)), dim=1).numpy()
126
+
127
+ val_probs /= 7
128
+ val_pred = val_probs.argmax(axis=1)
129
+ val_conf = val_probs.max(axis=1)
130
+ print(f" Val accuracy vs labels: {(val_pred == y_val).mean():.3f}")
131
+
132
+ bad_val = (val_pred != y_val) & (val_conf > 0.7)
133
+ print(f" Removing {bad_val.sum()} val samples")
134
+ for label in range(10):
135
+ mask = (y_val == label) & bad_val
136
+ if mask.sum() > 0:
137
+ pred_dist = pd.Series(val_pred[mask]).value_counts().to_dict()
138
+ print(f" label={label}: drop {mask.sum()} -> model says {pred_dist}")
139
+
140
+ val_final = val_df[~bad_val].reset_index(drop=True)
141
+ print(f"\nFinal val: {len(val_final)}")
142
+ print(pd.crosstab(val_final["label"], val_final["source"]))
143
+
144
+ # === Write ===
145
+ for name, df in [("train", train_df), ("validation", val_final)]:
146
+ ds = Dataset.from_pandas(df.reset_index(drop=True))
147
+ ds = ds.cast_column("image", HFImage())
148
+ ds.to_parquet(f"data/{name}-00000-of-00001.parquet")
149
+
150
+ print("\nDone!")
scripts/make_composites.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generate per-label composite verification images from the dataset.
2
+
3
+ Creates composites/<split>/label_<N>.png for each digit and split.
4
+ These are checked into the repo for visual verification.
5
+
6
+ Usage:
7
+ uv run python scripts/make_composites.py
8
+ """
9
+
10
+ import os
11
+ import io
12
+ import pandas as pd
13
+ from PIL import Image
14
+
15
+ if __name__ != "__main__":
16
+ import sys; sys.exit(0)
17
+
18
+ CELL = 36
19
+ MAX_COLS = 50
20
+
21
+
22
+ def make_composite(images, cell=CELL, max_cols=MAX_COLS):
23
+ if not images:
24
+ return None
25
+ cols = min(max_cols, len(images))
26
+ rows = (len(images) + cols - 1) // cols
27
+ sheet = Image.new("L", (cols * cell, rows * cell), 0)
28
+ for idx, img in enumerate(images):
29
+ r, c = idx // cols, idx % cols
30
+ sheet.paste(img.resize((cell, cell)), (c * cell, r * cell))
31
+ return sheet
32
+
33
+
34
+ for split in ["train", "validation"]:
35
+ df = pd.read_parquet(f"data/{split}-00000-of-00001.parquet")
36
+ out_dir = f"composites/{split}"
37
+ os.makedirs(out_dir, exist_ok=True)
38
+
39
+ for label in sorted(df["label"].unique()):
40
+ subset = df[df["label"] == label]
41
+ # Only racing sources (skip mnist, racing_aug)
42
+ racing = subset[~subset["source"].isin(["mnist", "racing_aug"])]
43
+ if len(racing) == 0:
44
+ continue
45
+
46
+ images = [
47
+ Image.open(io.BytesIO(row["image"]["bytes"])).convert("L")
48
+ for _, row in racing.iterrows()
49
+ ]
50
+ sheet = make_composite(images)
51
+ if sheet:
52
+ path = f"{out_dir}/label_{label}.png"
53
+ sheet.save(path)
54
+ print(f"{split} label={label}: {len(images)} racing images -> {path}")
55
+
56
+ print("\nDone")