From 5323e6c71af30238b120a51f1ef504757e2aeecb Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 23:51:38 +0530 Subject: [PATCH] Add classic-ml-vs-llm module: Tribuo 4.3.2 and Smile 7.3.0 text classifiers, a zero-shot LLM client and a cost model Seeded synthetic support tickets in five categories; Tribuo and Smile logistic regression and Smile naive Bayes against a majority baseline; skewed classes, train/test duplicates, vocabulary drift and the three different answers to a ticket of unseen words; a zero-shot client for OpenAI-compatible endpoints tested against a fake endpoint (no model was called) and a cost formula with assumed prices. Every figure is written to output/ by the tests that assert it. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_017ic4b69H5rTewUKPyhGS8r --- README.md | 2 + classic-ml-vs-llm/README.md | 31 +++ classic-ml-vs-llm/output/01-dataset.txt | 23 +++ classic-ml-vs-llm/output/02-models.txt | 15 ++ .../output/03-confusion-tribuo.txt | 15 ++ classic-ml-vs-llm/output/04-imbalance.txt | 6 + classic-ml-vs-llm/output/05-duplicates.txt | 6 + .../output/06-vocabulary-drift.txt | 8 + .../output/07-no-known-words.txt | 8 + classic-ml-vs-llm/output/08-llm-harness.txt | 22 +++ classic-ml-vs-llm/output/09-cost-model.txt | 18 ++ .../output/10-class-file-versions.txt | 5 + classic-ml-vs-llm/pom.xml | 50 +++++ classic-ml-vs-llm/scripts/run-all.sh | 8 + .../java/com/ankurm/classicml/Category.java | 4 + .../java/com/ankurm/classicml/CostModel.java | 22 +++ .../ankurm/classicml/MajorityBaseline.java | 21 ++ .../java/com/ankurm/classicml/Metrics.java | 81 ++++++++ .../ankurm/classicml/SmileClassifiers.java | 112 +++++++++++ .../java/com/ankurm/classicml/Splits.java | 60 ++++++ .../com/ankurm/classicml/TextClassifier.java | 14 ++ .../java/com/ankurm/classicml/Ticket.java | 4 + .../com/ankurm/classicml/TicketGenerator.java | 180 ++++++++++++++++++ .../java/com/ankurm/classicml/Tokens.java | 17 ++ .../ankurm/classicml/TribuoClassifier.java | 72 +++++++ .../com/ankurm/classicml/ZeroShotLlm.java | 87 +++++++++ .../com/ankurm/classicml/ZeroShotPrompt.java | 30 +++ .../classicml/ClassFileVersionTest.java | 38 ++++ .../com/ankurm/classicml/CostModelTest.java | 44 +++++ .../com/ankurm/classicml/DatasetTest.java | 48 +++++ .../java/com/ankurm/classicml/Fixtures.java | 66 +++++++ .../com/ankurm/classicml/LlmHarnessTest.java | 87 +++++++++ .../java/com/ankurm/classicml/ModelsTest.java | 62 ++++++ .../ankurm/classicml/NoKnownWordsTest.java | 46 +++++ .../com/ankurm/classicml/PitfallsTest.java | 91 +++++++++ .../java/com/ankurm/classicml/Transcript.java | 41 ++++ pom.xml | 1 + 37 files changed, 1445 insertions(+) create mode 100644 classic-ml-vs-llm/README.md create mode 100644 classic-ml-vs-llm/output/01-dataset.txt create mode 100644 classic-ml-vs-llm/output/02-models.txt create mode 100644 classic-ml-vs-llm/output/03-confusion-tribuo.txt create mode 100644 classic-ml-vs-llm/output/04-imbalance.txt create mode 100644 classic-ml-vs-llm/output/05-duplicates.txt create mode 100644 classic-ml-vs-llm/output/06-vocabulary-drift.txt create mode 100644 classic-ml-vs-llm/output/07-no-known-words.txt create mode 100644 classic-ml-vs-llm/output/08-llm-harness.txt create mode 100644 classic-ml-vs-llm/output/09-cost-model.txt create mode 100644 classic-ml-vs-llm/output/10-class-file-versions.txt create mode 100644 classic-ml-vs-llm/pom.xml create mode 100755 classic-ml-vs-llm/scripts/run-all.sh create mode 100644 classic-ml-vs-llm/src/main/java/com/ankurm/classicml/Category.java create mode 100644 classic-ml-vs-llm/src/main/java/com/ankurm/classicml/CostModel.java create mode 100644 classic-ml-vs-llm/src/main/java/com/ankurm/classicml/MajorityBaseline.java create mode 100644 classic-ml-vs-llm/src/main/java/com/ankurm/classicml/Metrics.java create mode 100644 classic-ml-vs-llm/src/main/java/com/ankurm/classicml/SmileClassifiers.java create mode 100644 classic-ml-vs-llm/src/main/java/com/ankurm/classicml/Splits.java create mode 100644 classic-ml-vs-llm/src/main/java/com/ankurm/classicml/TextClassifier.java create mode 100644 classic-ml-vs-llm/src/main/java/com/ankurm/classicml/Ticket.java create mode 100644 classic-ml-vs-llm/src/main/java/com/ankurm/classicml/TicketGenerator.java create mode 100644 classic-ml-vs-llm/src/main/java/com/ankurm/classicml/Tokens.java create mode 100644 classic-ml-vs-llm/src/main/java/com/ankurm/classicml/TribuoClassifier.java create mode 100644 classic-ml-vs-llm/src/main/java/com/ankurm/classicml/ZeroShotLlm.java create mode 100644 classic-ml-vs-llm/src/main/java/com/ankurm/classicml/ZeroShotPrompt.java create mode 100644 classic-ml-vs-llm/src/test/java/com/ankurm/classicml/ClassFileVersionTest.java create mode 100644 classic-ml-vs-llm/src/test/java/com/ankurm/classicml/CostModelTest.java create mode 100644 classic-ml-vs-llm/src/test/java/com/ankurm/classicml/DatasetTest.java create mode 100644 classic-ml-vs-llm/src/test/java/com/ankurm/classicml/Fixtures.java create mode 100644 classic-ml-vs-llm/src/test/java/com/ankurm/classicml/LlmHarnessTest.java create mode 100644 classic-ml-vs-llm/src/test/java/com/ankurm/classicml/ModelsTest.java create mode 100644 classic-ml-vs-llm/src/test/java/com/ankurm/classicml/NoKnownWordsTest.java create mode 100644 classic-ml-vs-llm/src/test/java/com/ankurm/classicml/PitfallsTest.java create mode 100644 classic-ml-vs-llm/src/test/java/com/ankurm/classicml/Transcript.java diff --git a/README.md b/README.md index baa322c..cae22e6 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ facts, so the build fails when a claim stops being true. | `code-search-mcp` | Build a Code-Search MCP Server for Your Java Monorepo (JavaParser + Embeddings) | JavaParser indexes a four-module sample monorepo, a swappable `Embedder` (offline hashing or any `/v1/embeddings` endpoint) ranks methods by what they do, `find_usages` compares name matching with the symbol solver, and the three tools are served on the 2026-07-28 stateless spec with the 2.2.0 modern SDK, tested over raw HTTP, two server instances and the SDK client | | `release-notes-ai` | AI Release Notes and PR Descriptions in Java: JGit, Spring AI and Gitea | JGit reads a real repository, commits are grouped by Conventional Commit type, release notes and a version bump are computed in code, a Spring AI model writes only the opening paragraph behind a guard that rejects invented PR numbers and hashes, and a Gitea client creates or updates the release and PR so a rerun edits instead of failing; tested with a stub model and a local fake Gitea | | `log-anomaly` | AI Log Anomaly Detection for Spring Boot: Embeddings and Clustering | a parser for Spring Boot's own log layout, template mining, an `Embedder` seam (offline hashing or any `/v1/embeddings` endpoint), k-means over normal templates, a novel-template detector and a rate-spike detector with their measured blind spots, incidents, and a summary prompt that is 0.4% of the raw window; tested on seeded synthetic logs and on a log file Spring Boot 4.2.0 wrote itself | +| `classic-ml-vs-llm` | Text Classification in Java Without an LLM: Tribuo vs Smile vs a Zero-Shot LLM | 3000 seeded synthetic support tickets in five categories; Tribuo and Smile logistic regression and Smile naive Bayes against a majority baseline, with accuracy, macro-F1, latency and model size; skewed classes, train/test duplicates, vocabulary drift and the three different answers to a ticket of unseen words; a zero-shot LLM client tested against a fake endpoint (no model was called) and a cost formula with assumed prices | ## Versions (verified on Maven Central, 2026-10-11) @@ -48,6 +49,7 @@ facts, so the build fails when a claim stops being true. | Spring Boot / Spring AI / MCP Java SDK (`mcp-stateless`) | 4.2.0 / 2.1.0 / 2.2.0 | verified on Maven Central 2026-11-22; this module overrides the Spring versions above | | MCP Java SDK / JavaParser (`code-search-mcp`) | 2.2.0 / 3.28.2 | verified on Maven Central 2026-11-25; `code-search-mcp` only. The 2026-07-28 "modern" server API (`io.modelcontextprotocol.modern`) is in `mcp-core` 2.2.0; JavaParser 3.28.2 cannot resolve calls to implicit record accessors | | Spring Boot (`log-anomaly`) | 4.2.0 | verified on Maven Central 2026-12-01; `log-anomaly` only. No Spring AI and no model download: the embedder and the summariser are seams, tested offline | +| Tribuo `tribuo-classification-sgd` / Smile `smile-core` | 4.3.2 / 7.3.0 | verified on Maven Central 2026-12-01; `classic-ml-vs-llm` only. Tribuo is Apache-2.0 and Java 8 bytecode; Smile 7.3.0 is GPL-3.0-or-later or a commercial licence, and its bytecode needs Java 25 | | JDK | 25 LTS | | | JUnit | 6.1.3 | | diff --git a/classic-ml-vs-llm/README.md b/classic-ml-vs-llm/README.md new file mode 100644 index 0000000..636d9f0 --- /dev/null +++ b/classic-ml-vs-llm/README.md @@ -0,0 +1,31 @@ +# classic-ml-vs-llm + +Companion module for the ankurm.com post *Text Classification in Java Without an LLM: Tribuo vs Smile vs a Zero-Shot LLM*. + +Five support-ticket categories, a seeded generator for 3000 synthetic tickets, three classic classifiers +(Tribuo `LogisticRegression`, Smile `LogisticRegression`, Smile `DiscreteNaiveBayes`), a majority-class baseline, and a +zero-shot client for any OpenAI-compatible endpoint. Every figure in the post comes from `output/`, written by the tests. + +```bash +export JAVA_HOME=/path/to/jdk-25 # Smile 7.3.0 is compiled for Java 25 +scripts/run-all.sh # or: mvn test -pl classic-ml-vs-llm +``` + +**The data is synthetic.** Accuracy on it measures the harness, not your tickets. **No LLM was called** while this module was +written: `ZeroShotLlm` is tested against a local fake endpoint, so no LLM accuracy figure exists here. To measure one, call +`new ZeroShotLlm(baseUrl, model, apiKey).score(test)` on `Fixtures.SPLIT.test()` against your own endpoint. + +| Output | Shows | +|---|---| +| `01-dataset.txt` | class counts, train/test duplicates, sample tickets | +| `02-models.txt` | accuracy, macro-F1, training time, latency, model size; Tribuo's evaluator against ours | +| `03-confusion-tribuo.txt` | confusion matrix and per-class precision/recall | +| `04-imbalance.txt` | accuracy against macro-F1 on skewed classes | +| `05-duplicates.txt` | accuracy on tickets seen in training against unseen ones | +| `06-vocabulary-drift.txt` | the drop when the wording changes | +| `07-no-known-words.txt` | three libraries, three behaviours on a ticket of unseen words | +| `08-llm-harness.txt` | request shape and reply guard, against a fake endpoint | +| `09-cost-model.txt` | cost formula with assumed prices | +| `10-class-file-versions.txt` | the Java version each library's bytecode needs | + +Timing columns drift between runs and machines. Accuracy and F1 are deterministic. diff --git a/classic-ml-vs-llm/output/01-dataset.txt b/classic-ml-vs-llm/output/01-dataset.txt new file mode 100644 index 0000000..640b6ab --- /dev/null +++ b/classic-ml-vs-llm/output/01-dataset.txt @@ -0,0 +1,23 @@ +# The synthetic ticket set and its split +generator: seed 42, 3000 tickets, 15% carry a second complaint from another class, 12% have a typo, +3% have a randomly wrong label (human labelling noise) + +## Class counts +class train test +BILLING 474 118 +ACCESS 474 118 +BUG 484 121 +FEATURE 485 121 +CANCEL 484 121 +total 2401 599 + +## Exact duplicates between train and test +test tickets whose normalised text also appears in train: 122 of 599 + +## Six tickets, first six of the test set +BUG | Search returns an empty list although the data exists. Also, I was charged twice for this month. +BUG | Hello, The app freezes on the dashboard. The order number ends 4471. Thank you +BILLING | Good morning, My invoice shows the wrong amount. I am on the Pro plan. Thanks. +BUG | Hello, The app freezes on the dashboard. I am using Chrome on Windows. Please advise. +BILLING | Good morning, There is a charge on my statement I do not recognise. My account email is on file. Thank you +ACCESS | Urgent: The reset password email nevre arrives. Regards, Priya diff --git a/classic-ml-vs-llm/output/02-models.txt b/classic-ml-vs-llm/output/02-models.txt new file mode 100644 index 0000000..eb4296a --- /dev/null +++ b/classic-ml-vs-llm/output/02-models.txt @@ -0,0 +1,15 @@ +# Three classic classifiers and a baseline on the same split +dataset: 3000 synthetic tickets, 2401 train / 599 test, 5 balanced classes (see 01-dataset.txt) +timings are from one run on one machine and drift between runs; accuracy and F1 do not + +model accuracy macro-F1 train ms median us p99 us model KB +Majority-class baseline 0.2020 0.0672 5 0.1 0.4 - +Tribuo LogisticRegression (SGD) 0.9232 0.9233 1141 13.9 93.2 58.9 +Smile LogisticRegression 0.9182 0.9182 2796 7.3 45.2 10.1 +Smile DiscreteNaiveBayes 0.9048 0.9049 49 7.5 31.9 16.9 + +## Tribuo's own evaluator against ours +Tribuo LabelEvaluator accuracy : 0.9232 +harness Metrics accuracy : 0.9232 +Tribuo LabelEvaluator macro F1 : 0.9233 +harness Metrics macro F1 : 0.9233 diff --git a/classic-ml-vs-llm/output/03-confusion-tribuo.txt b/classic-ml-vs-llm/output/03-confusion-tribuo.txt new file mode 100644 index 0000000..34ae7a4 --- /dev/null +++ b/classic-ml-vs-llm/output/03-confusion-tribuo.txt @@ -0,0 +1,15 @@ +# Tribuo logistic regression: where the mistakes go +rows are the true category, columns the predicted one + +actual\pred BILLING ACCESS BUG FEATURE CANCEL +BILLING 108 1 3 2 4 +ACCESS 1 111 3 2 1 +BUG 1 1 116 1 2 +FEATURE 2 4 5 107 3 +CANCEL 1 4 5 0 111 + +BILLING precision 0.956 recall 0.915 F1 0.935 +ACCESS precision 0.917 recall 0.941 F1 0.929 +BUG precision 0.879 recall 0.959 F1 0.917 +FEATURE precision 0.955 recall 0.884 F1 0.918 +CANCEL precision 0.917 recall 0.917 F1 0.917 diff --git a/classic-ml-vs-llm/output/04-imbalance.txt b/classic-ml-vs-llm/output/04-imbalance.txt new file mode 100644 index 0000000..024c62e --- /dev/null +++ b/classic-ml-vs-llm/output/04-imbalance.txt @@ -0,0 +1,6 @@ +# Skewed classes: accuracy against macro-F1 +class mix 55% BILLING, 25% ACCESS, 12% BUG, 6% FEATURE, 2% CANCEL; 2399 train / 601 test + +model accuracy macro-F1 CANCEL recall +Majority-class baseline 0.5308 0.1387 0.000 +Tribuo LogisticRegression (SGD) 0.9318 0.9083 0.800 diff --git a/classic-ml-vs-llm/output/05-duplicates.txt b/classic-ml-vs-llm/output/05-duplicates.txt new file mode 100644 index 0000000..e8ca3cf --- /dev/null +++ b/classic-ml-vs-llm/output/05-duplicates.txt @@ -0,0 +1,6 @@ +# Tickets the model has already seen +Tribuo logistic regression, balanced split from 02-models.txt + +test tickets also in train : 122 accuracy 0.9836 +test tickets never seen : 477 accuracy 0.9078 +whole test set : 599 accuracy 0.9232 diff --git a/classic-ml-vs-llm/output/06-vocabulary-drift.txt b/classic-ml-vs-llm/output/06-vocabulary-drift.txt new file mode 100644 index 0000000..0724c98 --- /dev/null +++ b/classic-ml-vs-llm/output/06-vocabulary-drift.txt @@ -0,0 +1,8 @@ +# Tickets that use words the model never saw +trained on the balanced set; tested on 1000 new tickets where ACCESS and BUG use new wording +(passkey, magic link, device verification, editor glitches, widget flickers, sync spinner) + +model normal drifted ACCESS rec. BUG rec. +Tribuo LogisticRegression (SGD) 0.9232 0.6990 0.580 0.172 +Smile LogisticRegression 0.9182 0.6970 0.488 0.263 +Smile DiscreteNaiveBayes 0.9048 0.7190 0.605 0.239 diff --git a/classic-ml-vs-llm/output/07-no-known-words.txt b/classic-ml-vs-llm/output/07-no-known-words.txt new file mode 100644 index 0000000..ace69a6 --- /dev/null +++ b/classic-ml-vs-llm/output/07-no-known-words.txt @@ -0,0 +1,8 @@ +# A ticket made only of words the model has never seen +input: "Device verification loops forever." (none of these words occur in the training tickets) + +Tribuo LogisticRegression raw : throws IllegalArgumentException: No features found in Example ArrayExample(...) +Smile LogisticRegression raw : returns class index 1 (ACCESS), a guess from the intercepts alone +Smile DiscreteNaiveBayes raw : returns -2147483648 (Integer.MIN_VALUE, not a class index) + +harness wrappers (predict) : null / null / null (null = no answer, counted as wrong) diff --git a/classic-ml-vs-llm/output/08-llm-harness.txt b/classic-ml-vs-llm/output/08-llm-harness.txt new file mode 100644 index 0000000..02d1980 --- /dev/null +++ b/classic-ml-vs-llm/output/08-llm-harness.txt @@ -0,0 +1,22 @@ +# Zero-shot client against a fake endpoint (wiring only, no model) +NO LLM WAS CALLED. A local server returns scripted replies, so this shows request shape and reply handling. + +## Reply guard, ZeroShotLlm.parse +"BILLING" -> BILLING (accepted) +"Access." -> ACCESS (accepted) +"The category is Bug" -> BUG (accepted) +"BILLING or CANCEL" -> (none) (rejected: two categories) +"I think this is a refund request" -> (none) (rejected: no category name) +"" -> (none) (rejected: empty) + +## Five scripted replies through the real HTTP client +scripted: BILLING, ACCESS, Probably BUG., FEATURE or BILLING, CANCEL +right 4 of 5, unparseable 1 (the ambiguous reply counts as wrong, never as a guess) + +## The first request body, verbatim +{"model":"any-model","temperature":0,"max_tokens":8,"messages":[{"role":"system","content":"You classify customer support tickets. Reply with exactly one word from this list and nothing else: BILLING, ACCESS, BUG, FEATURE, CANCEL. BILLING is about charges, invoices and refunds. ACCESS is about login, passwords and locked accounts. BUG is about something that is broken. FEATURE is a request for something new. CANCEL is about ending a subscription or account."},{"role":"user","content":"Ticket: I was charged twice for this month.\nCategory:"}]} +Authorization header: Bearer test-key + +## Prompt size across the real test tickets (estimate: characters / 4) +instruction alone : 93 tokens +average per ticket : 117.9 tokens (instruction + ticket) diff --git a/classic-ml-vs-llm/output/09-cost-model.txt b/classic-ml-vs-llm/output/09-cost-model.txt new file mode 100644 index 0000000..81acf80 --- /dev/null +++ b/classic-ml-vs-llm/output/09-cost-model.txt @@ -0,0 +1,18 @@ +# What a million tickets cost: a formula, not a price list +EVERY PRICE BELOW IS AN ASSUMPTION. Replace the three rate cards with the ones you actually pay. +inputs: 117.9 prompt tokens per ticket (estimate), 3 output tokens, 1,000,000 tickets + + +## LLM, billed per token (output priced at 5x input in every row) +assumed $ per 1M input tokens $ per 1M tickets +0.10 13.29 +1.00 132.92 +3.00 398.76 + +## Classic model, in-process on one CPU core +measured median predict (Tribuo, 02-models.txt run): 13.9 microseconds +assumed core price: $0.05 per core-hour +core-seconds for 1M tickets: 13.9 cost: $0.0002 + +Not in either number: training and labelling for the classic model, retries and rate limits for the LLM, +and the engineer-hours for both. They usually decide the real comparison. diff --git a/classic-ml-vs-llm/output/10-class-file-versions.txt b/classic-ml-vs-llm/output/10-class-file-versions.txt new file mode 100644 index 0000000..716a1e6 --- /dev/null +++ b/classic-ml-vs-llm/output/10-class-file-versions.txt @@ -0,0 +1,5 @@ +# The Java version each library's bytecode needs +class-file major version 52 = Java 8, 61 = Java 17, 65 = Java 21, 69 = Java 25 + +Tribuo 4.3.2 org.tribuo.Model major 52 (Java 8) +Smile 7.3.0 smile.classification.Maxent major 69 (Java 25) diff --git a/classic-ml-vs-llm/pom.xml b/classic-ml-vs-llm/pom.xml new file mode 100644 index 0000000..aba05dc --- /dev/null +++ b/classic-ml-vs-llm/pom.xml @@ -0,0 +1,50 @@ + + + 4.0.0 + + + com.ankurm.agents + java-ai-agents + 1.0.0 + + + classic-ml-vs-llm + Text classification in Java without an LLM: Tribuo vs Smile vs a zero-shot LLM + + + + 4.3.2 + 7.3.0 + + + + + org.tribuo + tribuo-classification-sgd + ${tribuo.version} + + + com.github.haifengl + smile-core + ${smile.version} + + + org.slf4j + slf4j-simple + ${slf4j.version} + + + org.junit.jupiter + junit-jupiter + test + + + org.assertj + assertj-core + ${assertj.version} + test + + + diff --git a/classic-ml-vs-llm/scripts/run-all.sh b/classic-ml-vs-llm/scripts/run-all.sh new file mode 100755 index 0000000..855c7e2 --- /dev/null +++ b/classic-ml-vs-llm/scripts/run-all.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +# Regenerates every file in classic-ml-vs-llm/output/ by running the tests that assert the same facts. +# Needs JDK 25 (Smile 7.3.0's bytecode is Java 25) and Maven. No network after the first dependency download, no API key. +set -euo pipefail +cd "$(dirname "$0")/../.." +rm -f classic-ml-vs-llm/output/*.txt +mvn -B -pl classic-ml-vs-llm test +ls -1 classic-ml-vs-llm/output diff --git a/classic-ml-vs-llm/src/main/java/com/ankurm/classicml/Category.java b/classic-ml-vs-llm/src/main/java/com/ankurm/classicml/Category.java new file mode 100644 index 0000000..03a836c --- /dev/null +++ b/classic-ml-vs-llm/src/main/java/com/ankurm/classicml/Category.java @@ -0,0 +1,4 @@ +package com.ankurm.classicml; + +/** The five ticket categories used throughout the module. */ +public enum Category { BILLING, ACCESS, BUG, FEATURE, CANCEL } diff --git a/classic-ml-vs-llm/src/main/java/com/ankurm/classicml/CostModel.java b/classic-ml-vs-llm/src/main/java/com/ankurm/classicml/CostModel.java new file mode 100644 index 0000000..d44764e --- /dev/null +++ b/classic-ml-vs-llm/src/main/java/com/ankurm/classicml/CostModel.java @@ -0,0 +1,22 @@ +package com.ankurm.classicml; + +/** + * A plain cost model, not a measurement. Every price is a parameter you must replace with the rate card you + * actually pay; the tests print the formula's output for a few round numbers so the shape is visible. + */ +public final class CostModel { + + private CostModel() { } + + /** Dollars to classify {@code tickets} tickets through an LLM billed per million tokens. */ + public static double llmDollars(long tickets, double promptTokens, double outputTokens, + double dollarsPerMillionInput, double dollarsPerMillionOutput) { + return tickets * (promptTokens * dollarsPerMillionInput + outputTokens * dollarsPerMillionOutput) / 1_000_000.0; + } + + /** Dollars of CPU time to classify {@code tickets} tickets in-process on one core billed per hour. */ + public static double cpuDollars(long tickets, double microsPerTicket, double dollarsPerCoreHour) { + double coreSeconds = tickets * microsPerTicket / 1_000_000.0; + return coreSeconds / 3600.0 * dollarsPerCoreHour; + } +} diff --git a/classic-ml-vs-llm/src/main/java/com/ankurm/classicml/MajorityBaseline.java b/classic-ml-vs-llm/src/main/java/com/ankurm/classicml/MajorityBaseline.java new file mode 100644 index 0000000..7eeb02e --- /dev/null +++ b/classic-ml-vs-llm/src/main/java/com/ankurm/classicml/MajorityBaseline.java @@ -0,0 +1,21 @@ +package com.ankurm.classicml; + +import java.util.EnumMap; +import java.util.List; +import java.util.Map; + +/** Always answers the commonest training label. If a model cannot beat this, it has learned nothing. */ +public final class MajorityBaseline implements TextClassifier { + + private Category majority = Category.BILLING; + + @Override public String name() { return "Majority-class baseline"; } + + @Override public void train(List train) { + Map n = new EnumMap<>(Category.class); + for (Ticket t : train) n.merge(t.label(), 1, Integer::sum); + majority = n.entrySet().stream().max(Map.Entry.comparingByValue()).orElseThrow().getKey(); + } + + @Override public Category predict(String text) { return majority; } +} diff --git a/classic-ml-vs-llm/src/main/java/com/ankurm/classicml/Metrics.java b/classic-ml-vs-llm/src/main/java/com/ankurm/classicml/Metrics.java new file mode 100644 index 0000000..22f9b10 --- /dev/null +++ b/classic-ml-vs-llm/src/main/java/com/ankurm/classicml/Metrics.java @@ -0,0 +1,81 @@ +package com.ankurm.classicml; + +import java.util.List; +import java.util.Locale; + +/** Accuracy, per-class precision/recall/F1 and the confusion matrix, computed once for every contender. */ +public final class Metrics { + + private final int k = Category.values().length; + /** confusion[actual][predicted] */ + private final int[][] confusion = new int[k][k]; + private final int[] support = new int[k]; + private int total; + private int unanswered; + + public static Metrics of(TextClassifier model, List test) { + Metrics m = new Metrics(); + for (Ticket t : test) m.add(t.label(), model.predict(t.text())); + return m; + } + + public static Metrics ofPredictions(List actual, List predicted) { + Metrics m = new Metrics(); + for (int i = 0; i < actual.size(); i++) m.add(actual.get(i), predicted.get(i)); + return m; + } + + void add(Category actual, Category predicted) { + support[actual.ordinal()]++; + if (predicted == null) unanswered++; + else confusion[actual.ordinal()][predicted.ordinal()]++; + total++; + } + + /** Tickets the model declined to answer. They count against accuracy and recall. */ + public int unanswered() { return unanswered; } + + public int total() { return total; } + + public int[][] confusion() { return confusion; } + + public double accuracy() { + int right = 0; + for (int i = 0; i < k; i++) right += confusion[i][i]; + return total == 0 ? 0 : (double) right / total; + } + + public double precision(Category c) { + int i = c.ordinal(), predicted = 0; + for (int a = 0; a < k; a++) predicted += confusion[a][i]; + return predicted == 0 ? 0 : (double) confusion[i][i] / predicted; + } + + public double recall(Category c) { + int i = c.ordinal(); + return support[i] == 0 ? 0 : (double) confusion[i][i] / support[i]; + } + + public double f1(Category c) { + double p = precision(c), r = recall(c); + return p + r == 0 ? 0 : 2 * p * r / (p + r); + } + + /** Unweighted mean of per-class F1. A class with no support counts as 0, which is the strict reading. */ + public double macroF1() { + double s = 0; + for (Category c : Category.values()) s += f1(c); + return s / k; + } + + public String confusionTable() { + StringBuilder sb = new StringBuilder(); + sb.append(String.format(Locale.ROOT, "%-10s", "actual\\pred")); + for (Category c : Category.values()) sb.append(String.format(Locale.ROOT, "%9s", c)); + for (Category a : Category.values()) { + sb.append('\n').append(String.format(Locale.ROOT, "%-11s", a)); + for (Category p : Category.values()) sb.append(String.format(Locale.ROOT, "%9d", confusion[a.ordinal()][p.ordinal()])); + } + return sb.toString(); + } +} diff --git a/classic-ml-vs-llm/src/main/java/com/ankurm/classicml/SmileClassifiers.java b/classic-ml-vs-llm/src/main/java/com/ankurm/classicml/SmileClassifiers.java new file mode 100644 index 0000000..d400f0a --- /dev/null +++ b/classic-ml-vs-llm/src/main/java/com/ankurm/classicml/SmileClassifiers.java @@ -0,0 +1,112 @@ +package com.ankurm.classicml; + +import smile.classification.DiscreteNaiveBayes; +import smile.classification.LogisticRegression; +import smile.feature.extraction.BagOfWords; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Smile 7.3.0. Two classifiers share one {@link BagOfWords} vocabulary built from the training tickets only: + * a multinomial logistic regression on dense counts, and a multinomial naive Bayes on the same counts. + */ +public final class SmileClassifiers { + + private SmileClassifiers() { } + + /** Words seen at least {@code minCount} times in training, in a stable order. */ + static String[] vocabulary(List train, int minCount) { + Map n = new HashMap<>(); + for (Ticket t : train) for (String w : Tokens.of(t.text())) n.merge(w, 1, Integer::sum); + List words = new ArrayList<>(); + n.forEach((w, c) -> { if (c >= minCount) words.add(w); }); + words.sort(null); + return words.toArray(String[]::new); + } + + /** Multinomial logistic regression, the same model family as the Tribuo contender. */ + public static final class Logistic implements TextClassifier { + private BagOfWords bow; + private String[] vocab; + private LogisticRegression model; + + @Override public String name() { return "Smile LogisticRegression"; } + + @Override public void train(List train) { + vocab = vocabulary(train, 2); + bow = new BagOfWords(Tokens::of, vocab); + double[][] x = new double[train.size()][]; + int[] y = new int[train.size()]; + for (int i = 0; i < x.length; i++) { + x[i] = toDouble(bow.apply(train.get(i).text())); + y[i] = train.get(i).label().ordinal(); + } + model = LogisticRegression.fit(x, y); + } + + /** Returns {@code null} when no word of the ticket is in the vocabulary: the library would answer from the bias alone. */ + @Override public Category predict(String text) { + return allZero(bow.apply(text)) ? null : Category.values()[rawPredict(text)]; + } + + /** Calls Smile directly. With no known words this silently returns whichever class the intercepts favour. */ + public int rawPredict(String text) { + return model.predict(toDouble(bow.apply(text))); + } + + public LogisticRegression model() { return model; } + + /** What you would have to ship: the fitted model and the vocabulary that maps words to columns. */ + public Object[] shippable() { return new Object[] {model, vocab}; } + } + + /** Multinomial naive Bayes: no optimiser at all, one pass over the counts. */ + public static final class NaiveBayes implements TextClassifier { + private BagOfWords bow; + private String[] vocab; + private DiscreteNaiveBayes model; + + @Override public String name() { return "Smile DiscreteNaiveBayes"; } + + @Override public void train(List train) { + vocab = vocabulary(train, 2); + bow = new BagOfWords(Tokens::of, vocab); + model = new DiscreteNaiveBayes(DiscreteNaiveBayes.Model.MULTINOMIAL, Category.values().length, vocab.length); + int[][] x = new int[train.size()][]; + int[] y = new int[train.size()]; + for (int i = 0; i < x.length; i++) { + x[i] = bow.apply(train.get(i).text()); + y[i] = train.get(i).label().ordinal(); + } + model.update(x, y); + } + + /** Returns {@code null} when no word of the ticket is in the vocabulary: the library would return a sentinel. */ + @Override public Category predict(String text) { + return allZero(bow.apply(text)) ? null : Category.values()[rawPredict(text)]; + } + + /** Calls Smile directly. With no known words this returns {@link Integer#MIN_VALUE}, not a class index. */ + public int rawPredict(String text) { + return model.predict(bow.apply(text)); + } + + public DiscreteNaiveBayes model() { return model; } + + public Object[] shippable() { return new Object[] {model, vocab}; } + } + + private static boolean allZero(int[] counts) { + for (int c : counts) if (c != 0) return false; + return true; + } + + private static double[] toDouble(int[] counts) { + double[] d = new double[counts.length]; + for (int i = 0; i < d.length; i++) d[i] = counts[i]; + return d; + } +} diff --git a/classic-ml-vs-llm/src/main/java/com/ankurm/classicml/Splits.java b/classic-ml-vs-llm/src/main/java/com/ankurm/classicml/Splits.java new file mode 100644 index 0000000..e8153fe --- /dev/null +++ b/classic-ml-vs-llm/src/main/java/com/ankurm/classicml/Splits.java @@ -0,0 +1,60 @@ +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; + } +} diff --git a/classic-ml-vs-llm/src/main/java/com/ankurm/classicml/TextClassifier.java b/classic-ml-vs-llm/src/main/java/com/ankurm/classicml/TextClassifier.java new file mode 100644 index 0000000..c335771 --- /dev/null +++ b/classic-ml-vs-llm/src/main/java/com/ankurm/classicml/TextClassifier.java @@ -0,0 +1,14 @@ +package com.ankurm.classicml; + +import java.util.List; + +/** The one contract every contender implements, so the harness measures them identically. */ +public interface TextClassifier { + + String name(); + + void train(List train); + + /** The category, or {@code null} when the model has no basis to answer (counted as wrong by {@link Metrics}). */ + Category predict(String text); +} diff --git a/classic-ml-vs-llm/src/main/java/com/ankurm/classicml/Ticket.java b/classic-ml-vs-llm/src/main/java/com/ankurm/classicml/Ticket.java new file mode 100644 index 0000000..325850a --- /dev/null +++ b/classic-ml-vs-llm/src/main/java/com/ankurm/classicml/Ticket.java @@ -0,0 +1,4 @@ +package com.ankurm.classicml; + +/** One support ticket: free text and the category a human assigned to it. */ +public record Ticket(String text, Category label) { } diff --git a/classic-ml-vs-llm/src/main/java/com/ankurm/classicml/TicketGenerator.java b/classic-ml-vs-llm/src/main/java/com/ankurm/classicml/TicketGenerator.java new file mode 100644 index 0000000..93fd919 --- /dev/null +++ b/classic-ml-vs-llm/src/main/java/com/ankurm/classicml/TicketGenerator.java @@ -0,0 +1,180 @@ +package com.ankurm.classicml; + +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.Random; + +/** + * A seeded generator of synthetic support tickets. The data is fake on purpose: it makes every number in the post + * reproducible, and the knobs ({@link Options}) let the tests break the data in the ways real data breaks. + * + *

Real tickets are messier than these. Read the accuracy figures as "what the harness measures", never as + * "what you will get on your own tickets". + */ +public final class TicketGenerator { + + /** Knobs for one dataset. {@code weights} are relative class frequencies. */ + public record Options(long seed, int count, Map weights, + double crossRate, double typoRate, double labelNoise, boolean drift) { + + public static Options balanced(long seed, int count) { + Map w = new EnumMap<>(Category.class); + for (Category c : Category.values()) w.put(c, 1.0); + return new Options(seed, count, w, 0.15, 0.12, 0.03, false); + } + + public Options withWeights(Map w) { + return new Options(seed, count, w, crossRate, typoRate, labelNoise, drift); + } + + public Options withDrift(boolean d) { + return new Options(seed, count, weights, crossRate, typoRate, labelNoise, d); + } + + public Options withSeed(long s) { + return new Options(s, count, weights, crossRate, typoRate, labelNoise, drift); + } + } + + private static final Map> CORE = new EnumMap<>(Category.class); + private static final Map> DRIFTED = new EnumMap<>(Category.class); + + static { + CORE.put(Category.BILLING, List.of( + "I was charged twice for this month", + "my invoice shows the wrong amount", + "please refund the duplicate payment", + "the card on file was declined but I was still billed", + "I need a GST invoice for last quarter", + "why did the price of my plan go up", + "my payment failed and the account shows overdue", + "there is a charge on my statement I do not recognise")); + CORE.put(Category.ACCESS, List.of( + "I cannot log in with my password", + "the reset password email never arrives", + "my account is locked after too many attempts", + "the two factor code is not accepted", + "I get logged out every few minutes", + "the single sign on page shows access denied", + "I lost the phone with my authenticator app", + "my invite link says it has expired")); + CORE.put(Category.BUG, List.of( + "the export button does nothing when I click it", + "the page crashes with an error when I save", + "the app freezes on the dashboard", + "search returns an empty list although the data exists", + "the report shows wrong totals after a refresh", + "uploading a file fails with error 500", + "the mobile app closes right after opening", + "notifications arrive twice for the same event")); + CORE.put(Category.FEATURE, List.of( + "it would be great to have a dark mode", + "please add an option to export to excel", + "can you support bulk edit for items", + "we need an api for webhooks", + "would you consider adding a calendar view", + "please allow custom fields on tickets", + "an option to schedule reports would help us", + "can you add support for single sign on")); + CORE.put(Category.CANCEL, List.of( + "I want to cancel my subscription", + "please close my account and delete my data", + "how do I stop the auto renewal", + "we are moving to another tool and will not renew", + "please downgrade me to the free plan", + "cancel my plan before the next billing date", + "I no longer need this service", + "end my trial without charging me")); + + // Vocabulary the model never saw in training: new products and new words for old problems. + DRIFTED.put(Category.ACCESS, List.of( + "my passkey is not recognised on the new laptop", + "the magic link bounces back to the sign in page", + "device verification loops forever")); + DRIFTED.put(Category.BUG, List.of( + "the new editor glitches when I paste text", + "the widget flickers and then disappears", + "the sync spinner never stops")); + } + + private static final List OPENERS = List.of("Hi team,", "Hello,", "Urgent:", "Please help.", "", "Good morning,"); + private static final List CONTEXT = List.of( + "I am on the Pro plan.", "This started yesterday.", "I am using the mobile app.", + "I am using Chrome on Windows.", "My account email is on file.", "The order number ends 4471.", "", ""); + private static final List CLOSERS = List.of("Thanks.", "Please advise.", "Regards, Priya", "", "Thank you", ""); + + private TicketGenerator() { } + + /** Generates {@code options.count()} tickets. The same options always produce the same list. */ + public static List generate(Options o) { + Random rnd = new Random(o.seed()); + Category[] cats = Category.values(); + double total = 0; + for (Category c : cats) total += o.weights().getOrDefault(c, 0.0); + + List out = new ArrayList<>(o.count()); + for (int i = 0; i < o.count(); i++) { + Category label = pick(cats, o, total, rnd); + String core = corePhrase(label, o, rnd); + StringBuilder sb = new StringBuilder(); + append(sb, OPENERS.get(rnd.nextInt(OPENERS.size()))); + append(sb, capitalise(core) + "."); + if (rnd.nextDouble() < o.crossRate()) { + Category other = cats[rnd.nextInt(cats.length)]; + if (other != label) append(sb, "Also, " + CORE.get(other).get(rnd.nextInt(8)) + "."); + } + append(sb, CONTEXT.get(rnd.nextInt(CONTEXT.size()))); + append(sb, CLOSERS.get(rnd.nextInt(CLOSERS.size()))); + String text = sb.toString().trim(); + if (rnd.nextDouble() < o.typoRate()) text = typo(text, rnd); + + Category recorded = label; + if (rnd.nextDouble() < o.labelNoise()) recorded = cats[rnd.nextInt(cats.length)]; + out.add(new Ticket(text, recorded)); + } + return out; + } + + private static Category pick(Category[] cats, Options o, double total, Random rnd) { + double r = rnd.nextDouble() * total; + for (Category c : cats) { + r -= o.weights().getOrDefault(c, 0.0); + if (r <= 0) return c; + } + return cats[cats.length - 1]; + } + + private static String corePhrase(Category label, Options o, Random rnd) { + List drifted = DRIFTED.get(label); + if (o.drift() && drifted != null) return drifted.get(rnd.nextInt(drifted.size())); + List pool = CORE.get(label); + return pool.get(rnd.nextInt(pool.size())); + } + + private static void append(StringBuilder sb, String part) { + if (part.isEmpty()) return; + if (!sb.isEmpty()) sb.append(' '); + sb.append(part); + } + + private static String capitalise(String s) { + return Character.toUpperCase(s.charAt(0)) + s.substring(1); + } + + /** Swaps two adjacent letters inside one word, the commonest typing slip. */ + private static String typo(String text, Random rnd) { + String[] words = text.split(" "); + int w = rnd.nextInt(words.length); + char[] c = words[w].toCharArray(); + if (c.length >= 4) { + int k = 1 + rnd.nextInt(c.length - 2); + char t = c[k]; + c[k] = c[k + 1]; + c[k + 1] = t; + words[w] = new String(c); + } + return String.join(" ", words); + } +} diff --git a/classic-ml-vs-llm/src/main/java/com/ankurm/classicml/Tokens.java b/classic-ml-vs-llm/src/main/java/com/ankurm/classicml/Tokens.java new file mode 100644 index 0000000..f3dd91d --- /dev/null +++ b/classic-ml-vs-llm/src/main/java/com/ankurm/classicml/Tokens.java @@ -0,0 +1,17 @@ +package com.ankurm.classicml; + +import java.util.Locale; +import java.util.regex.Pattern; + +/** Lower-cased word tokens, shared by every classic model so the comparison is about the library, not the tokeniser. */ +public final class Tokens { + + private static final Pattern NON_LETTER = Pattern.compile("[^a-z0-9]+"); + + private Tokens() { } + + public static String[] of(String text) { + String t = NON_LETTER.matcher(text.toLowerCase(Locale.ROOT)).replaceAll(" ").trim(); + return t.isEmpty() ? new String[0] : t.split(" "); + } +} diff --git a/classic-ml-vs-llm/src/main/java/com/ankurm/classicml/TribuoClassifier.java b/classic-ml-vs-llm/src/main/java/com/ankurm/classicml/TribuoClassifier.java new file mode 100644 index 0000000..9a1cab6 --- /dev/null +++ b/classic-ml-vs-llm/src/main/java/com/ankurm/classicml/TribuoClassifier.java @@ -0,0 +1,72 @@ +package com.ankurm.classicml; + +import org.tribuo.Example; +import org.tribuo.MutableDataset; +import org.tribuo.Prediction; +import org.tribuo.classification.Label; +import org.tribuo.classification.LabelFactory; +import org.tribuo.classification.sgd.linear.LogisticRegressionTrainer; +import org.tribuo.data.text.TextFeatureExtractor; +import org.tribuo.data.text.impl.BasicPipeline; +import org.tribuo.data.text.impl.TextFeatureExtractorImpl; +import org.tribuo.provenance.SimpleDataSourceProvenance; +import org.tribuo.util.tokens.impl.BreakIteratorTokenizer; + +import java.util.List; +import java.util.Locale; + +/** + * Tribuo 4.3.2: text becomes {@link Example}s through a {@link BasicPipeline} (tokeniser plus n-gram size), + * and {@link LogisticRegressionTrainer} fits a multinomial logistic regression by SGD. + */ +public final class TribuoClassifier implements TextClassifier { + + private final LabelFactory labels = new LabelFactory(); + private final TextFeatureExtractor