yolo_detect / hard_train.py
Shreypai's picture
Upload folder using huggingface_hub
c2b4e9c verified
Raw History Blame Contribute Delete
6.34 kB
"""
Bidirectional hard-negative mining for can/bottle confusion.
Workflow:
1. Runs prediction on the val set using your trained model.
2. Finds images where a true can wasn't predicted as can (can_confused),
and images where a true bottle wasn't predicted as bottle (bottle_confused).
3. Balances the two lists so neither direction dominates.
4. Copies the matching images + ground-truth labels into your train folder
(prefixed so they don't collide with existing filenames).
IMPORTANT:
- Edit the CONFIG section below before running.
- This copies from VAL into TRAIN. After running this, your val set is
partially "seen" by the model in the next training run — use your
TEST set as the honest measure of whether this helped.
- Always retrain from scratch afterwards, not resumed, so the new
hard negatives get a fair influence on the whole training run.
"""
import os
import random
import shutil
from ultralytics import YOLO
# ------------------------- CONFIG (edit these) -------------------------
MODEL_PATH = r"C:\Users\shrey\Downloads\dataset\runs\detect\train\weights\best.pt" # your trained checkpoint
DATA_YAML = r"C:\Users\shrey\Downloads\dataset\data.yaml" # not strictly needed for predict, but handy to keep here
VAL_IMG_DIR = r"C:\Users\shrey\Downloads\dataset\images\val"
VAL_LBL_DIR = r"C:\Users\shrey\Downloads\dataset\labels\val"
TRAIN_IMG_DIR = r"C:\Users\shrey\Downloads\dataset\images\train"
TRAIN_LBL_DIR = r"C:\Users\shrey\Downloads\dataset\labels\train"
N
# Class IDs -- confirm these match your data.yaml 'names' order (0-indexed)
BOTTLE_ID = "0"
CAN_ID = "1"
# PAPER_ID = "2" # not used here, but included for reference
PREDICT_CONF = 0.25 # realistic deployment threshold for finding genuine failures
PREDICT_OUTPUT_DIR = "predict_analysis"
PREDICT_RUN_NAME = "val_preds"
RANDOM_SEED = 42
IMG_EXTS = [".jpg", ".png", ".jpeg"]
# -------------------------------------------------------------------------
def run_predictions():
"""Step 1: run the model on val images, save predicted labels as .txt files."""
print("Running predictions on val set...")
model = YOLO(MODEL_PATH)
model.predict(
source=VAL_IMG_DIR,
conf=PREDICT_CONF,
save=False,
save_txt=True,
save_conf=True,
project=PREDICT_OUTPUT_DIR,
name=PREDICT_RUN_NAME,
exist_ok=True,
)
pred_dir = os.path.join(PREDICT_OUTPUT_DIR, PREDICT_RUN_NAME, "labels")
print(f"Predictions saved to: {pred_dir}")
return pred_dir
def find_confused_images(pred_dir):
"""Step 2: compare ground truth vs predictions, per class, per image."""
can_confused = []
bottle_confused = []
for fname in os.listdir(VAL_LBL_DIR):
if not fname.endswith(".txt"):
continue
gt_path = os.path.join(VAL_LBL_DIR, fname)
pred_path = os.path.join(pred_dir, fname)
with open(gt_path) as f:
gt_classes = set(line.strip().split()[0] for line in f if line.strip())
pred_classes = set()
if os.path.exists(pred_path):
with open(pred_path) as f:
pred_classes = set(line.strip().split()[0] for line in f if line.strip())
stem = fname[:-4] # strip ".txt"
if CAN_ID in gt_classes and CAN_ID not in pred_classes:
can_confused.append(stem)
if BOTTLE_ID in gt_classes and BOTTLE_ID not in pred_classes:
bottle_confused.append(stem)
print(f"Can confused (true can, not predicted as can): {len(can_confused)}")
print(f"Bottle confused (true bottle, not predicted as bottle): {len(bottle_confused)}")
return can_confused, bottle_confused
def balance_lists(can_confused, bottle_confused):
"""Step 3: subsample the larger list so neither direction dominates the correction."""
random.seed(RANDOM_SEED)
ratio = (
f"{len(can_confused)}:{len(bottle_confused)}"
if bottle_confused
else f"{len(can_confused)}:0"
)
print(f"Ratio can:bottle confused = {ratio}")
max_count = min(len(can_confused), len(bottle_confused))
can_sample = (
random.sample(can_confused, max_count) if len(can_confused) > max_count else can_confused
)
bottle_sample = (
random.sample(bottle_confused, max_count)
if len(bottle_confused) > max_count
else bottle_confused
)
print(f"Using {len(can_sample)} can hard negatives and {len(bottle_sample)} bottle hard negatives (balanced).")
return can_sample, bottle_sample
def copy_hardnegs(stem_list, prefix):
"""Step 4: copy the image + ground-truth label from val into train, with a prefix."""
copied = 0
for stem in stem_list:
copied_img = False
for ext in IMG_EXTS:
src_img = os.path.join(VAL_IMG_DIR, stem + ext)
if os.path.exists(src_img):
shutil.copy(src_img, os.path.join(TRAIN_IMG_DIR, f"{prefix}_{stem}{ext}"))
copied_img = True
break
src_lbl = os.path.join(VAL_LBL_DIR, stem + ".txt")
copied_lbl = False
if os.path.exists(src_lbl):
shutil.copy(src_lbl, os.path.join(TRAIN_LBL_DIR, f"{prefix}_{stem}.txt"))
copied_lbl = True
if copied_img and copied_lbl:
copied += 1
print(f"Copied {copied}/{len(stem_list)} '{prefix}' hard negatives into train.")
return copied
def main():
pred_dir = run_predictions()
can_confused, bottle_confused = find_confused_images(pred_dir)
can_sample, bottle_sample = balance_lists(can_confused, bottle_confused)
copy_hardnegs(can_sample, "hardneg_can")
copy_hardnegs(bottle_sample, "hardneg_bottle")
print("\nDone. Next steps:")
print("1. Sanity check: new train image/label counts should be old count + "
f"{len(can_sample) + len(bottle_sample)} (roughly).")
print("2. Retrain FROM SCRATCH (not resumed) on the updated train folder.")
print("3. Evaluate on TEST set (not val) for the honest read -- "
"val now contains some of these same images duplicated into train.")
if __name__ == "__main__":
main()