Datasets:
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 +0 -1
- composites/train/label_1.png +3 -0
- composites/train/label_2.png +3 -0
- composites/train/label_3.png +3 -0
- composites/train/label_4.png +3 -0
- composites/train/label_5.png +3 -0
- composites/train/label_6.png +3 -0
- composites/train/label_7.png +3 -0
- composites/validation/label_1.png +3 -0
- composites/validation/label_2.png +3 -0
- composites/validation/label_3.png +3 -0
- composites/validation/label_4.png +3 -0
- composites/validation/label_5.png +3 -0
- composites/validation/label_6.png +3 -0
- composites/validation/label_7.png +3 -0
- scripts/iterative_clean.py +150 -0
- scripts/make_composites.py +56 -0
.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
|
composites/train/label_2.png
ADDED
|
Git LFS Details
|
composites/train/label_3.png
ADDED
|
Git LFS Details
|
composites/train/label_4.png
ADDED
|
Git LFS Details
|
composites/train/label_5.png
ADDED
|
Git LFS Details
|
composites/train/label_6.png
ADDED
|
Git LFS Details
|
composites/train/label_7.png
ADDED
|
Git LFS Details
|
composites/validation/label_1.png
ADDED
|
Git LFS Details
|
composites/validation/label_2.png
ADDED
|
Git LFS Details
|
composites/validation/label_3.png
ADDED
|
Git LFS Details
|
composites/validation/label_4.png
ADDED
|
Git LFS Details
|
composites/validation/label_5.png
ADDED
|
Git LFS Details
|
composites/validation/label_6.png
ADDED
|
Git LFS Details
|
composites/validation/label_7.png
ADDED
|
Git LFS Details
|
scripts/iterative_clean.py
ADDED
|
@@ -0,0 +1,150 @@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ch
|
| 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")
|