package com.ankurm.classicml; import java.util.ArrayList; import java.util.Collections; import java.util.EnumMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Random; import java.util.Set; /** Stratified train/test split, plus the duplicate check that keeps the split honest. */ public final class Splits { public record Split(List train, List test) { } private Splits() { } /** Splits per category so every class keeps the same share in both halves. */ public static Split stratified(List all, double trainShare, long seed) { Map> byClass = new EnumMap<>(Category.class); for (Ticket t : all) byClass.computeIfAbsent(t.label(), k -> new ArrayList<>()).add(t); List train = new ArrayList<>(); List test = new ArrayList<>(); Random rnd = new Random(seed); for (List group : byClass.values()) { Collections.shuffle(group, rnd); int cut = (int) Math.round(group.size() * trainShare); train.addAll(group.subList(0, cut)); test.addAll(group.subList(cut, group.size())); } Collections.shuffle(train, rnd); Collections.shuffle(test, rnd); return new Split(train, test); } /** Lower-cases and collapses whitespace so "Hi team" and "hi team" count as the same ticket. */ public static String key(String text) { return text.toLowerCase(Locale.ROOT).replaceAll("\\s+", " ").trim(); } /** Test tickets whose normalised text also occurs in training: the model has already seen them. */ public static List testSeenInTraining(Split s) { Set seen = new HashSet<>(); for (Ticket t : s.train()) seen.add(key(t.text())); List dup = new ArrayList<>(); for (Ticket t : s.test()) if (seen.contains(key(t.text()))) dup.add(t); return dup; } /** Test tickets that never occur in training. */ public static List testUnseen(Split s) { Set seen = new HashSet<>(); for (Ticket t : s.train()) seen.add(key(t.text())); List fresh = new ArrayList<>(); for (Ticket t : s.test()) if (!seen.contains(key(t.text()))) fresh.add(t); return fresh; } }