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 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b69H5rTewUKPyhGS8r
This commit is contained in:
@@ -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 | |
|
||||
|
||||
|
||||
@@ -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.
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -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.
|
||||
@@ -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)
|
||||
@@ -0,0 +1,50 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<parent>
|
||||
<groupId>com.ankurm.agents</groupId>
|
||||
<artifactId>java-ai-agents</artifactId>
|
||||
<version>1.0.0</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>classic-ml-vs-llm</artifactId>
|
||||
<name>Text classification in Java without an LLM: Tribuo vs Smile vs a zero-shot LLM</name>
|
||||
|
||||
<properties>
|
||||
<!-- Verified on Maven Central 2026-12-01 -->
|
||||
<tribuo.version>4.3.2</tribuo.version>
|
||||
<smile.version>7.3.0</smile.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.tribuo</groupId>
|
||||
<artifactId>tribuo-classification-sgd</artifactId>
|
||||
<version>${tribuo.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.github.haifengl</groupId>
|
||||
<artifactId>smile-core</artifactId>
|
||||
<version>${smile.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.slf4j</groupId>
|
||||
<artifactId>slf4j-simple</artifactId>
|
||||
<version>${slf4j.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.assertj</groupId>
|
||||
<artifactId>assertj-core</artifactId>
|
||||
<version>${assertj.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
Executable
+8
@@ -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
|
||||
@@ -0,0 +1,4 @@
|
||||
package com.ankurm.classicml;
|
||||
|
||||
/** The five ticket categories used throughout the module. */
|
||||
public enum Category { BILLING, ACCESS, BUG, FEATURE, CANCEL }
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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<Ticket> train) {
|
||||
Map<Category, Integer> 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; }
|
||||
}
|
||||
@@ -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<Ticket> test) {
|
||||
Metrics m = new Metrics();
|
||||
for (Ticket t : test) m.add(t.label(), model.predict(t.text()));
|
||||
return m;
|
||||
}
|
||||
|
||||
public static Metrics ofPredictions(List<Category> actual, List<Category> 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();
|
||||
}
|
||||
}
|
||||
@@ -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<Ticket> train, int minCount) {
|
||||
Map<String, Integer> n = new HashMap<>();
|
||||
for (Ticket t : train) for (String w : Tokens.of(t.text())) n.merge(w, 1, Integer::sum);
|
||||
List<String> 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<Ticket> 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<Ticket> 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;
|
||||
}
|
||||
}
|
||||
@@ -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<Ticket> train, List<Ticket> test) { }
|
||||
|
||||
private Splits() { }
|
||||
|
||||
/** Splits per category so every class keeps the same share in both halves. */
|
||||
public static Split stratified(List<Ticket> all, double trainShare, long seed) {
|
||||
Map<Category, List<Ticket>> byClass = new EnumMap<>(Category.class);
|
||||
for (Ticket t : all) byClass.computeIfAbsent(t.label(), k -> new ArrayList<>()).add(t);
|
||||
List<Ticket> train = new ArrayList<>();
|
||||
List<Ticket> test = new ArrayList<>();
|
||||
Random rnd = new Random(seed);
|
||||
for (List<Ticket> 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<Ticket> testSeenInTraining(Split s) {
|
||||
Set<String> seen = new HashSet<>();
|
||||
for (Ticket t : s.train()) seen.add(key(t.text()));
|
||||
List<Ticket> 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<Ticket> testUnseen(Split s) {
|
||||
Set<String> seen = new HashSet<>();
|
||||
for (Ticket t : s.train()) seen.add(key(t.text()));
|
||||
List<Ticket> fresh = new ArrayList<>();
|
||||
for (Ticket t : s.test()) if (!seen.contains(key(t.text()))) fresh.add(t);
|
||||
return fresh;
|
||||
}
|
||||
}
|
||||
@@ -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<Ticket> train);
|
||||
|
||||
/** The category, or {@code null} when the model has no basis to answer (counted as wrong by {@link Metrics}). */
|
||||
Category predict(String text);
|
||||
}
|
||||
@@ -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) { }
|
||||
@@ -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.
|
||||
*
|
||||
* <p>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<Category, Double> weights,
|
||||
double crossRate, double typoRate, double labelNoise, boolean drift) {
|
||||
|
||||
public static Options balanced(long seed, int count) {
|
||||
Map<Category, Double> 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<Category, Double> 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<Category, List<String>> CORE = new EnumMap<>(Category.class);
|
||||
private static final Map<Category, List<String>> 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<String> OPENERS = List.of("Hi team,", "Hello,", "Urgent:", "Please help.", "", "Good morning,");
|
||||
private static final List<String> 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<String> 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<Ticket> 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<Ticket> 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<String> drifted = DRIFTED.get(label);
|
||||
if (o.drift() && drifted != null) return drifted.get(rnd.nextInt(drifted.size()));
|
||||
List<String> 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);
|
||||
}
|
||||
}
|
||||
@@ -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(" ");
|
||||
}
|
||||
}
|
||||
@@ -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<Label> extractor =
|
||||
new TextFeatureExtractorImpl<>(new BasicPipeline(new BreakIteratorTokenizer(Locale.US), 1));
|
||||
|
||||
private org.tribuo.Model<Label> model;
|
||||
private MutableDataset<Label> trainingSet;
|
||||
|
||||
@Override public String name() { return "Tribuo LogisticRegression (SGD)"; }
|
||||
|
||||
@Override public void train(List<Ticket> train) {
|
||||
trainingSet = dataset(train);
|
||||
model = new LogisticRegressionTrainer().train(trainingSet);
|
||||
}
|
||||
|
||||
/** Returns {@code null} when no word of the ticket was in the training vocabulary, because Tribuo refuses to guess. */
|
||||
@Override public Category predict(String text) {
|
||||
try {
|
||||
return Category.valueOf(rawPredict(text));
|
||||
} catch (IllegalArgumentException noKnownFeatures) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Calls Tribuo directly. Throws {@link IllegalArgumentException} ("No features found in Example") on unknown words. */
|
||||
public String rawPredict(String text) {
|
||||
Prediction<Label> p = model.predict(extractor.extract(new Label(Label.UNKNOWN), normalise(text)));
|
||||
return p.getOutput().getLabel();
|
||||
}
|
||||
|
||||
/** The trained Tribuo model, for the evaluator cross-check and for serialisation size. */
|
||||
public org.tribuo.Model<Label> model() { return model; }
|
||||
|
||||
/** Builds a Tribuo dataset from tickets; the evaluator needs this form for the test set. */
|
||||
public MutableDataset<Label> dataset(List<Ticket> tickets) {
|
||||
MutableDataset<Label> ds = new MutableDataset<>(new SimpleDataSourceProvenance("tickets", labels), labels);
|
||||
for (Ticket t : tickets) {
|
||||
ds.add(extractor.extract(new Label(t.label().name()), normalise(t.text())));
|
||||
}
|
||||
return ds;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hands Tribuo exactly the tokens the Smile models see. Left alone, {@code BasicPipeline} with a
|
||||
* {@code BreakIteratorTokenizer} turns "." "," and "!" into features, which would make the comparison unfair.
|
||||
*/
|
||||
private static String normalise(String text) {
|
||||
return String.join(" ", Tokens.of(text));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package com.ankurm.classicml;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.time.Duration;
|
||||
import java.util.EnumSet;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* A zero-shot classifier over any OpenAI-compatible {@code /v1/chat/completions} endpoint (a hosted API, Ollama,
|
||||
* vLLM, llama.cpp). It sends the instruction and the ticket, and refuses to guess when the reply is not exactly
|
||||
* one known category.
|
||||
*/
|
||||
public final class ZeroShotLlm {
|
||||
|
||||
private static final Pattern CONTENT = Pattern.compile("\"content\"\\s*:\\s*\"((?:[^\"\\\\]|\\\\.)*)\"");
|
||||
|
||||
private final HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
|
||||
private final String baseUrl;
|
||||
private final String model;
|
||||
private final String apiKey;
|
||||
|
||||
public ZeroShotLlm(String baseUrl, String model, String apiKey) {
|
||||
this.baseUrl = baseUrl.endsWith("/") ? baseUrl.substring(0, baseUrl.length() - 1) : baseUrl;
|
||||
this.model = model;
|
||||
this.apiKey = apiKey;
|
||||
}
|
||||
|
||||
/** The category the model chose, or empty when the reply was not exactly one known category. */
|
||||
public Optional<Category> classify(String ticketText) throws IOException, InterruptedException {
|
||||
String body = "{\"model\":\"" + esc(model) + "\",\"temperature\":0,\"max_tokens\":8,\"messages\":["
|
||||
+ "{\"role\":\"system\",\"content\":\"" + esc(ZeroShotPrompt.SYSTEM) + "\"},"
|
||||
+ "{\"role\":\"user\",\"content\":\"" + esc(ZeroShotPrompt.user(ticketText)) + "\"}]}";
|
||||
HttpRequest.Builder req = HttpRequest.newBuilder(URI.create(baseUrl + "/v1/chat/completions"))
|
||||
.timeout(Duration.ofSeconds(60))
|
||||
.header("Content-Type", "application/json")
|
||||
.POST(HttpRequest.BodyPublishers.ofString(body));
|
||||
if (apiKey != null && !apiKey.isBlank()) req.header("Authorization", "Bearer " + apiKey);
|
||||
HttpResponse<String> res = http.send(req.build(), HttpResponse.BodyHandlers.ofString());
|
||||
if (res.statusCode() != 200) throw new IOException("HTTP " + res.statusCode() + ": " + res.body());
|
||||
Matcher m = CONTENT.matcher(res.body());
|
||||
return m.find() ? parse(unesc(m.group(1))) : Optional.empty();
|
||||
}
|
||||
|
||||
/**
|
||||
* Accepts a reply only when exactly one category name appears in it, ignoring case and punctuation.
|
||||
* "Billing." is accepted; "It could be BILLING or CANCEL" and "I think this is a refund" are not.
|
||||
*/
|
||||
public static Optional<Category> parse(String reply) {
|
||||
Set<Category> found = EnumSet.noneOf(Category.class);
|
||||
String upper = reply.toUpperCase();
|
||||
for (Category c : Category.values()) {
|
||||
if (Pattern.compile("\\b" + c.name() + "\\b").matcher(upper).find()) found.add(c);
|
||||
}
|
||||
return found.size() == 1 ? Optional.of(found.iterator().next()) : Optional.empty();
|
||||
}
|
||||
|
||||
/** Scores a test set; a reply that cannot be parsed counts as wrong, never as a guess. */
|
||||
public Score score(List<Ticket> test) throws IOException, InterruptedException {
|
||||
int right = 0, unparseable = 0;
|
||||
for (Ticket t : test) {
|
||||
Optional<Category> c = classify(t.text());
|
||||
if (c.isEmpty()) unparseable++;
|
||||
else if (c.get() == t.label()) right++;
|
||||
}
|
||||
return new Score(test.size(), right, unparseable);
|
||||
}
|
||||
|
||||
public record Score(int total, int right, int unparseable) {
|
||||
public double accuracy() { return total == 0 ? 0 : (double) right / total; }
|
||||
}
|
||||
|
||||
private static String esc(String s) {
|
||||
return s.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n");
|
||||
}
|
||||
|
||||
private static String unesc(String s) {
|
||||
return s.replace("\\n", "\n").replace("\\\"", "\"").replace("\\\\", "\\");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.ankurm.classicml;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/** The zero-shot instruction, built once, and a rough token estimate for it. */
|
||||
public final class ZeroShotPrompt {
|
||||
|
||||
public static final String SYSTEM =
|
||||
"You classify customer support tickets. Reply with exactly one word from this list and nothing else: "
|
||||
+ Arrays.stream(Category.values()).map(Enum::name).collect(Collectors.joining(", "))
|
||||
+ ". 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.";
|
||||
|
||||
private ZeroShotPrompt() { }
|
||||
|
||||
public static String user(String ticketText) {
|
||||
return "Ticket: " + ticketText + "\nCategory:";
|
||||
}
|
||||
|
||||
/** About four characters per English token. An estimate, not a tokeniser: real counts differ by model. */
|
||||
public static int estimateTokens(String text) {
|
||||
return (int) Math.ceil(text.length() / 4.0);
|
||||
}
|
||||
|
||||
public static int estimatePromptTokens(String ticketText) {
|
||||
return estimateTokens(SYSTEM) + estimateTokens(user(ticketText));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.ankurm.classicml;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.io.DataInputStream;
|
||||
import java.io.InputStream;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/** Reads the class-file version out of one class from each library, so "needs Java N" is measured, not remembered. */
|
||||
class ClassFileVersionTest {
|
||||
|
||||
@Test
|
||||
void whichJavaDoesEachLibraryNeed() throws Exception {
|
||||
int tribuo = major("org/tribuo/Model.class");
|
||||
int smile = major("smile/classification/Maxent.class");
|
||||
|
||||
Transcript t = new Transcript("10-class-file-versions.txt", "The Java version each library's bytecode needs");
|
||||
t.line("class-file major version 52 = Java 8, 61 = Java 17, 65 = Java 21, 69 = Java 25");
|
||||
t.blank();
|
||||
t.line("Tribuo 4.3.2 org.tribuo.Model major " + tribuo + " (Java " + (tribuo - 44) + ")");
|
||||
t.line("Smile 7.3.0 smile.classification.Maxent major " + smile + " (Java " + (smile - 44) + ")");
|
||||
t.write();
|
||||
|
||||
assertThat(tribuo).isEqualTo(52);
|
||||
assertThat(smile).isEqualTo(69);
|
||||
}
|
||||
|
||||
private static int major(String resource) throws Exception {
|
||||
try (InputStream in = ClassLoader.getSystemResourceAsStream(resource)) {
|
||||
assertThat(in).as(resource).isNotNull();
|
||||
DataInputStream d = new DataInputStream(in);
|
||||
d.readInt(); // magic
|
||||
d.readUnsignedShort(); // minor
|
||||
return d.readUnsignedShort();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.ankurm.classicml;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class CostModelTest {
|
||||
|
||||
@Test
|
||||
void theFormulaForAMillionTickets() throws Exception {
|
||||
double promptTokens = Fixtures.SPLIT.test().stream()
|
||||
.mapToInt(k -> ZeroShotPrompt.estimatePromptTokens(k.text())).average().orElseThrow();
|
||||
double outputTokens = 3;
|
||||
double tribuoMicros = Fixtures.R_TRIBUO.medianMicros();
|
||||
double coreHour = 0.05;
|
||||
|
||||
Transcript t = new Transcript("09-cost-model.txt", "What a million tickets cost: a formula, not a price list");
|
||||
t.line("EVERY PRICE BELOW IS AN ASSUMPTION. Replace the three rate cards with the ones you actually pay.");
|
||||
t.line(String.format(Locale.ROOT, "inputs: %.1f prompt tokens per ticket (estimate), %.0f output tokens, 1,000,000 tickets", promptTokens, outputTokens));
|
||||
t.blank();
|
||||
t.section("LLM, billed per token (output priced at 5x input in every row)");
|
||||
t.line(String.format(Locale.ROOT, "%-34s %14s", "assumed $ per 1M input tokens", "$ per 1M tickets"));
|
||||
double last = 0;
|
||||
for (double in : new double[] {0.10, 1.00, 3.00}) {
|
||||
double d = CostModel.llmDollars(1_000_000, promptTokens, outputTokens, in, in * 5);
|
||||
t.line(String.format(Locale.ROOT, "%-34s %14.2f", String.format(Locale.ROOT, "%.2f", in), d));
|
||||
assertThat(d).isGreaterThan(last);
|
||||
last = d;
|
||||
}
|
||||
t.section("Classic model, in-process on one CPU core");
|
||||
double cpu = CostModel.cpuDollars(1_000_000, tribuoMicros, coreHour);
|
||||
t.line(String.format(Locale.ROOT, "measured median predict (Tribuo, 02-models.txt run): %.1f microseconds", tribuoMicros));
|
||||
t.line(String.format(Locale.ROOT, "assumed core price: $%.2f per core-hour", coreHour));
|
||||
t.line(String.format(Locale.ROOT, "core-seconds for 1M tickets: %.1f cost: $%.4f", 1_000_000 * tribuoMicros / 1e6, cpu));
|
||||
t.blank();
|
||||
t.line("Not in either number: training and labelling for the classic model, retries and rate limits for the LLM,");
|
||||
t.line("and the engineer-hours for both. They usually decide the real comparison.");
|
||||
t.write();
|
||||
|
||||
assertThat(cpu).isLessThan(CostModel.llmDollars(1_000_000, promptTokens, outputTokens, 0.10, 0.50));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.ankurm.classicml;
|
||||
|
||||
import com.ankurm.classicml.TicketGenerator.Options;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.EnumMap;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
import static com.ankurm.classicml.Fixtures.*;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class DatasetTest {
|
||||
|
||||
@Test
|
||||
void theDatasetIsReproducibleAndSplitHonestly() throws Exception {
|
||||
assertThat(TicketGenerator.generate(Options.balanced(42, 3000))).isEqualTo(ALL);
|
||||
assertThat(TicketGenerator.generate(Options.balanced(43, 3000))).isNotEqualTo(ALL);
|
||||
|
||||
Transcript t = new Transcript("01-dataset.txt", "The synthetic ticket set and its split");
|
||||
t.line("generator: seed 42, 3000 tickets, 15% carry a second complaint from another class, 12% have a typo,");
|
||||
t.line("3% have a randomly wrong label (human labelling noise)");
|
||||
t.section("Class counts");
|
||||
t.line(String.format(Locale.ROOT, "%-9s %6s %6s", "class", "train", "test"));
|
||||
for (Category c : Category.values()) {
|
||||
t.line(String.format(Locale.ROOT, "%-9s %6d %6d", c, count(SPLIT.train(), c), count(SPLIT.test(), c)));
|
||||
}
|
||||
t.line(String.format(Locale.ROOT, "%-9s %6d %6d", "total", SPLIT.train().size(), SPLIT.test().size()));
|
||||
|
||||
t.section("Exact duplicates between train and test");
|
||||
int seen = Splits.testSeenInTraining(SPLIT).size();
|
||||
t.line("test tickets whose normalised text also appears in train: " + seen + " of " + SPLIT.test().size());
|
||||
|
||||
t.section("Six tickets, first six of the test set");
|
||||
for (int i = 0; i < 6; i++) {
|
||||
Ticket k = SPLIT.test().get(i);
|
||||
t.line(String.format(Locale.ROOT, "%-8s | %s", k.label(), k.text()));
|
||||
}
|
||||
t.write();
|
||||
|
||||
assertThat(SPLIT.train().size() + SPLIT.test().size()).isEqualTo(3000);
|
||||
assertThat(seen).isGreaterThan(0);
|
||||
}
|
||||
|
||||
private static long count(java.util.List<Ticket> l, Category c) {
|
||||
return l.stream().filter(k -> k.label() == c).count();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.ankurm.classicml;
|
||||
|
||||
import com.ankurm.classicml.TicketGenerator.Options;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.ObjectOutputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/** One balanced dataset and one training run per contender, shared by every test class in the JVM. */
|
||||
final class Fixtures {
|
||||
|
||||
static final List<Ticket> ALL = TicketGenerator.generate(Options.balanced(42, 3000));
|
||||
static final Splits.Split SPLIT = Splits.stratified(ALL, 0.8, 7);
|
||||
|
||||
static final TribuoClassifier TRIBUO = new TribuoClassifier();
|
||||
static final SmileClassifiers.Logistic SMILE_LR = new SmileClassifiers.Logistic();
|
||||
static final SmileClassifiers.NaiveBayes SMILE_NB = new SmileClassifiers.NaiveBayes();
|
||||
static final MajorityBaseline BASELINE = new MajorityBaseline();
|
||||
|
||||
static final Run R_BASE = run(BASELINE, SPLIT);
|
||||
static final Run R_TRIBUO = run(TRIBUO, SPLIT);
|
||||
static final Run R_SMILE_LR = run(SMILE_LR, SPLIT);
|
||||
static final Run R_SMILE_NB = run(SMILE_NB, SPLIT);
|
||||
|
||||
private Fixtures() { }
|
||||
|
||||
/** One contender trained and timed. Timings vary between runs and machines; accuracy does not. */
|
||||
record Run(TextClassifier model, long trainMillis, double medianMicros, double p99Micros, Metrics metrics) { }
|
||||
|
||||
static Run run(TextClassifier model, Splits.Split s) {
|
||||
long t0 = System.nanoTime();
|
||||
model.train(s.train());
|
||||
long trainMs = (System.nanoTime() - t0) / 1_000_000;
|
||||
// Warm the JIT first so the numbers describe steady state, which is what a service sees.
|
||||
for (int i = 0; i < 300; i++) model.predict(s.test().get(i % s.test().size()).text());
|
||||
double[] us = new double[s.test().size()];
|
||||
for (int i = 0; i < us.length; i++) {
|
||||
long a = System.nanoTime();
|
||||
model.predict(s.test().get(i).text());
|
||||
us[i] = (System.nanoTime() - a) / 1000.0;
|
||||
}
|
||||
Arrays.sort(us);
|
||||
return new Run(model, trainMs, us[us.length / 2], us[(int) (us.length * 0.99)], Metrics.of(model, s.test()));
|
||||
}
|
||||
|
||||
/** Bytes of the artefact you would deploy. Tribuo writes its own protobuf format; Smile uses Java serialisation. */
|
||||
static long modelBytes(Object shippableOrTribuoModel) throws Exception {
|
||||
if (shippableOrTribuoModel instanceof org.tribuo.Model<?> m) {
|
||||
Path f = Files.createTempFile("tribuo", ".model");
|
||||
try {
|
||||
m.serializeToFile(f);
|
||||
return Files.size(f);
|
||||
} finally {
|
||||
Files.deleteIfExists(f);
|
||||
}
|
||||
}
|
||||
ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
||||
try (ObjectOutputStream oos = new ObjectOutputStream(bos)) {
|
||||
oos.writeObject(shippableOrTribuoModel);
|
||||
}
|
||||
return bos.size();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package com.ankurm.classicml;
|
||||
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Deque;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* Tests the zero-shot client against a local fake endpoint. This proves the wiring and the reply guard. It says
|
||||
* nothing about how accurate any real model is: no model was called while this module was written.
|
||||
*/
|
||||
class LlmHarnessTest {
|
||||
|
||||
@Test
|
||||
void theReplyGuardAcceptsOneCategoryAndNothingElse() throws Exception {
|
||||
Transcript t = new Transcript("08-llm-harness.txt", "Zero-shot client against a fake endpoint (wiring only, no model)");
|
||||
t.line("NO LLM WAS CALLED. A local server returns scripted replies, so this shows request shape and reply handling.");
|
||||
|
||||
String[][] replies = {
|
||||
{"BILLING", "accepted"}, {"Access.", "accepted"}, {"The category is Bug", "accepted"},
|
||||
{"BILLING or CANCEL", "rejected: two categories"}, {"I think this is a refund request", "rejected: no category name"},
|
||||
{"", "rejected: empty"}};
|
||||
t.section("Reply guard, ZeroShotLlm.parse");
|
||||
for (String[] r : replies) {
|
||||
Optional<Category> c = ZeroShotLlm.parse(r[0]);
|
||||
t.line(String.format("%-34s -> %-9s (%s)", "\"" + r[0] + "\"", c.map(Enum::name).orElse("(none)"), r[1]));
|
||||
assertThat(c.isPresent()).isEqualTo(r[1].startsWith("accepted"));
|
||||
}
|
||||
|
||||
Deque<String> script = new ArrayDeque<>(List.of("BILLING", "ACCESS", "Probably BUG.", "FEATURE or BILLING", "CANCEL"));
|
||||
List<String> bodies = new ArrayList<>();
|
||||
List<String> auth = new ArrayList<>();
|
||||
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
server.createContext("/v1/chat/completions", ex -> {
|
||||
bodies.add(new String(ex.getRequestBody().readAllBytes(), StandardCharsets.UTF_8));
|
||||
auth.add(ex.getRequestHeaders().getFirst("Authorization"));
|
||||
byte[] out = ("{\"choices\":[{\"message\":{\"role\":\"assistant\",\"content\":\"" + script.poll() + "\"}}]}")
|
||||
.getBytes(StandardCharsets.UTF_8);
|
||||
ex.getResponseHeaders().add("Content-Type", "application/json");
|
||||
ex.sendResponseHeaders(200, out.length);
|
||||
ex.getResponseBody().write(out);
|
||||
ex.close();
|
||||
});
|
||||
server.start();
|
||||
try {
|
||||
ZeroShotLlm llm = new ZeroShotLlm("http://127.0.0.1:" + server.getAddress().getPort(), "any-model", "test-key");
|
||||
List<Ticket> five = List.of(
|
||||
new Ticket("I was charged twice for this month.", Category.BILLING),
|
||||
new Ticket("The reset password email never arrives.", Category.ACCESS),
|
||||
new Ticket("The app freezes on the dashboard.", Category.BUG),
|
||||
new Ticket("Please add an option to export to excel.", Category.FEATURE),
|
||||
new Ticket("I want to cancel my subscription.", Category.CANCEL));
|
||||
ZeroShotLlm.Score s = llm.score(five);
|
||||
|
||||
t.section("Five scripted replies through the real HTTP client");
|
||||
t.line("scripted: BILLING, ACCESS, Probably BUG., FEATURE or BILLING, CANCEL");
|
||||
t.line("right " + s.right() + " of " + s.total() + ", unparseable " + s.unparseable()
|
||||
+ " (the ambiguous reply counts as wrong, never as a guess)");
|
||||
t.section("The first request body, verbatim");
|
||||
t.line(bodies.get(0));
|
||||
t.line("Authorization header: " + auth.get(0));
|
||||
|
||||
assertThat(s.right()).isEqualTo(4);
|
||||
assertThat(s.unparseable()).isEqualTo(1);
|
||||
assertThat(bodies.get(0)).contains("\"temperature\":0").contains("Ticket: I was charged twice");
|
||||
assertThat(auth.get(0)).isEqualTo("Bearer test-key");
|
||||
} finally {
|
||||
server.stop(0);
|
||||
}
|
||||
|
||||
t.section("Prompt size across the real test tickets (estimate: characters / 4)");
|
||||
double avg = Fixtures.SPLIT.test().stream().mapToInt(k -> ZeroShotPrompt.estimatePromptTokens(k.text())).average().orElseThrow();
|
||||
t.line("instruction alone : " + ZeroShotPrompt.estimateTokens(ZeroShotPrompt.SYSTEM) + " tokens");
|
||||
t.line(String.format("average per ticket : %.1f tokens (instruction + ticket)", avg));
|
||||
t.write();
|
||||
|
||||
assertThat(avg).isBetween(60.0, 140.0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.ankurm.classicml;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.tribuo.classification.evaluation.LabelEvaluation;
|
||||
import org.tribuo.classification.evaluation.LabelEvaluator;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
import static com.ankurm.classicml.Fixtures.*;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.within;
|
||||
|
||||
class ModelsTest {
|
||||
|
||||
@Test
|
||||
void contendersOnTheBalancedSplit() throws Exception {
|
||||
Transcript t = new Transcript("02-models.txt", "Three classic classifiers and a baseline on the same split");
|
||||
t.line("dataset: 3000 synthetic tickets, " + SPLIT.train().size() + " train / " + SPLIT.test().size() + " test, 5 balanced classes (see 01-dataset.txt)");
|
||||
t.line("timings are from one run on one machine and drift between runs; accuracy and F1 do not");
|
||||
t.blank();
|
||||
t.line(String.format(Locale.ROOT, "%-34s %8s %9s %9s %11s %9s %10s",
|
||||
"model", "accuracy", "macro-F1", "train ms", "median us", "p99 us", "model KB"));
|
||||
Object[][] rows = {
|
||||
{R_BASE, null},
|
||||
{R_TRIBUO, TRIBUO.model()},
|
||||
{R_SMILE_LR, SMILE_LR.shippable()},
|
||||
{R_SMILE_NB, SMILE_NB.shippable()}};
|
||||
for (Object[] row : rows) {
|
||||
Run r = (Run) row[0];
|
||||
String kb = row[1] == null ? "-" : String.format(Locale.ROOT, "%.1f", modelBytes(row[1]) / 1024.0);
|
||||
t.line(String.format(Locale.ROOT, "%-34s %8.4f %9.4f %9d %11.1f %9.1f %10s",
|
||||
r.model().name(), r.metrics().accuracy(), r.metrics().macroF1(),
|
||||
r.trainMillis(), r.medianMicros(), r.p99Micros(), kb));
|
||||
}
|
||||
|
||||
t.section("Tribuo's own evaluator against ours");
|
||||
LabelEvaluation ev = new LabelEvaluator().evaluate(TRIBUO.model(), TRIBUO.dataset(SPLIT.test()));
|
||||
t.line(String.format(Locale.ROOT, "Tribuo LabelEvaluator accuracy : %.4f", ev.accuracy()));
|
||||
t.line(String.format(Locale.ROOT, "harness Metrics accuracy : %.4f", R_TRIBUO.metrics().accuracy()));
|
||||
t.line(String.format(Locale.ROOT, "Tribuo LabelEvaluator macro F1 : %.4f", ev.macroAveragedF1()));
|
||||
t.line(String.format(Locale.ROOT, "harness Metrics macro F1 : %.4f", R_TRIBUO.metrics().macroF1()));
|
||||
t.write();
|
||||
|
||||
Transcript c = new Transcript("03-confusion-tribuo.txt", "Tribuo logistic regression: where the mistakes go");
|
||||
c.line("rows are the true category, columns the predicted one");
|
||||
c.blank();
|
||||
c.line(R_TRIBUO.metrics().confusionTable());
|
||||
c.blank();
|
||||
for (Category cat : Category.values()) {
|
||||
c.line(String.format(Locale.ROOT, "%-8s precision %.3f recall %.3f F1 %.3f", cat,
|
||||
R_TRIBUO.metrics().precision(cat), R_TRIBUO.metrics().recall(cat), R_TRIBUO.metrics().f1(cat)));
|
||||
}
|
||||
c.write();
|
||||
|
||||
assertThat(R_BASE.metrics().accuracy()).isLessThan(0.30);
|
||||
for (Run r : new Run[] {R_TRIBUO, R_SMILE_LR, R_SMILE_NB}) {
|
||||
assertThat(r.metrics().accuracy()).isGreaterThan(0.85);
|
||||
assertThat(r.metrics().macroF1()).isGreaterThan(R_BASE.metrics().macroF1() + 0.5);
|
||||
}
|
||||
assertThat(ev.accuracy()).isCloseTo(R_TRIBUO.metrics().accuracy(), within(1e-9));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.ankurm.classicml;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
import static com.ankurm.classicml.Fixtures.*;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
/** What each library does with a ticket whose words it has never seen. The three answers are all different. */
|
||||
class NoKnownWordsTest {
|
||||
|
||||
private static final String UNSEEN = "Device verification loops forever.";
|
||||
|
||||
@Test
|
||||
void threeLibrariesThreeBehaviours() throws Exception {
|
||||
Transcript t = new Transcript("07-no-known-words.txt", "A ticket made only of words the model has never seen");
|
||||
t.line("input: \"" + UNSEEN + "\" (none of these words occur in the training tickets)");
|
||||
t.blank();
|
||||
|
||||
String tribuo;
|
||||
try {
|
||||
tribuo = TRIBUO.rawPredict(UNSEEN);
|
||||
} catch (IllegalArgumentException e) {
|
||||
tribuo = "throws IllegalArgumentException: " + e.getMessage().replaceAll("ArrayExample.*", "ArrayExample(...)");
|
||||
}
|
||||
int lr = SMILE_LR.rawPredict(UNSEEN);
|
||||
int nb = SMILE_NB.rawPredict(UNSEEN);
|
||||
t.line("Tribuo LogisticRegression raw : " + tribuo);
|
||||
t.line("Smile LogisticRegression raw : returns class index " + lr + " (" + Category.values()[lr] + "), a guess from the intercepts alone");
|
||||
t.line("Smile DiscreteNaiveBayes raw : returns " + nb + " (Integer.MIN_VALUE, not a class index)");
|
||||
t.blank();
|
||||
t.line("harness wrappers (predict) : " + TRIBUO.predict(UNSEEN) + " / " + SMILE_LR.predict(UNSEEN) + " / " + SMILE_NB.predict(UNSEEN)
|
||||
+ " (null = no answer, counted as wrong)");
|
||||
t.write();
|
||||
|
||||
assertThatThrownBy(() -> TRIBUO.rawPredict(UNSEEN)).isInstanceOf(IllegalArgumentException.class)
|
||||
.hasMessageContaining("No features found");
|
||||
assertThat(nb).isEqualTo(Integer.MIN_VALUE);
|
||||
assertThat(lr).isBetween(0, Category.values().length - 1);
|
||||
assertThat(TRIBUO.predict(UNSEEN)).isNull();
|
||||
assertThat(SMILE_LR.predict(UNSEEN)).isNull();
|
||||
assertThat(SMILE_NB.predict(UNSEEN)).isNull();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package com.ankurm.classicml;
|
||||
|
||||
import com.ankurm.classicml.TicketGenerator.Options;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.EnumMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
import com.ankurm.classicml.Fixtures.Run;
|
||||
|
||||
import static com.ankurm.classicml.Fixtures.*;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/** Three ways a good-looking number goes wrong. Each test records the evidence in output/. */
|
||||
class PitfallsTest {
|
||||
|
||||
@Test
|
||||
void accuracyLiesWhenClassesAreSkewed() throws Exception {
|
||||
Map<Category, Double> w = new EnumMap<>(Category.class);
|
||||
w.put(Category.BILLING, 0.55);
|
||||
w.put(Category.ACCESS, 0.25);
|
||||
w.put(Category.BUG, 0.12);
|
||||
w.put(Category.FEATURE, 0.06);
|
||||
w.put(Category.CANCEL, 0.02);
|
||||
List<Ticket> skewed = TicketGenerator.generate(Options.balanced(11, 3000).withWeights(w));
|
||||
Splits.Split s = Splits.stratified(skewed, 0.8, 7);
|
||||
|
||||
Run base = Fixtures.run(new MajorityBaseline(), s);
|
||||
Run tribuo = Fixtures.run(new TribuoClassifier(), s);
|
||||
|
||||
Transcript t = new Transcript("04-imbalance.txt", "Skewed classes: accuracy against macro-F1");
|
||||
t.line("class mix 55% BILLING, 25% ACCESS, 12% BUG, 6% FEATURE, 2% CANCEL; " + s.train().size() + " train / " + s.test().size() + " test");
|
||||
t.blank();
|
||||
t.line(String.format(Locale.ROOT, "%-34s %8s %9s %14s", "model", "accuracy", "macro-F1", "CANCEL recall"));
|
||||
for (Run r : new Run[] {base, tribuo}) {
|
||||
t.line(String.format(Locale.ROOT, "%-34s %8.4f %9.4f %14.3f", r.model().name(),
|
||||
r.metrics().accuracy(), r.metrics().macroF1(), r.metrics().recall(Category.CANCEL)));
|
||||
}
|
||||
t.write();
|
||||
|
||||
// A model that always says BILLING scores above 50% accuracy and has a macro-F1 near 0.14.
|
||||
assertThat(base.metrics().accuracy()).isGreaterThan(0.5);
|
||||
assertThat(base.metrics().macroF1()).isLessThan(0.2);
|
||||
assertThat(tribuo.metrics().macroF1()).isGreaterThan(0.8);
|
||||
}
|
||||
|
||||
@Test
|
||||
void duplicatesInTheTestSetFlatterTheModel() throws Exception {
|
||||
Run r = R_TRIBUO;
|
||||
List<Ticket> seen = Splits.testSeenInTraining(SPLIT);
|
||||
List<Ticket> fresh = Splits.testUnseen(SPLIT);
|
||||
double accSeen = acc(r.model(), seen), accFresh = acc(r.model(), fresh);
|
||||
|
||||
Transcript t = new Transcript("05-duplicates.txt", "Tickets the model has already seen");
|
||||
t.line("Tribuo logistic regression, balanced split from 02-models.txt");
|
||||
t.blank();
|
||||
t.line(String.format(Locale.ROOT, "test tickets also in train : %4d accuracy %.4f", seen.size(), accSeen));
|
||||
t.line(String.format(Locale.ROOT, "test tickets never seen : %4d accuracy %.4f", fresh.size(), accFresh));
|
||||
t.line(String.format(Locale.ROOT, "whole test set : %4d accuracy %.4f", SPLIT.test().size(), r.metrics().accuracy()));
|
||||
t.write();
|
||||
|
||||
assertThat(seen.size() + fresh.size()).isEqualTo(SPLIT.test().size());
|
||||
assertThat(accSeen).isGreaterThanOrEqualTo(accFresh);
|
||||
}
|
||||
|
||||
@Test
|
||||
void newVocabularyBreaksAClassicModelAndTheNumbersShowIt() throws Exception {
|
||||
List<Ticket> drifted = TicketGenerator.generate(Options.balanced(99, 1000).withDrift(true));
|
||||
Transcript t = new Transcript("06-vocabulary-drift.txt", "Tickets that use words the model never saw");
|
||||
t.line("trained on the balanced set; tested on 1000 new tickets where ACCESS and BUG use new wording");
|
||||
t.line("(passkey, magic link, device verification, editor glitches, widget flickers, sync spinner)");
|
||||
t.blank();
|
||||
t.line(String.format(Locale.ROOT, "%-34s %9s %9s %12s %12s", "model", "normal", "drifted", "ACCESS rec.", "BUG rec."));
|
||||
double tribuoNormal = 0, tribuoDrift = 0;
|
||||
for (Run r : new Run[] {R_TRIBUO, R_SMILE_LR, R_SMILE_NB}) {
|
||||
Metrics m = Metrics.of(r.model(), drifted);
|
||||
t.line(String.format(Locale.ROOT, "%-34s %9.4f %9.4f %12.3f %12.3f", r.model().name(),
|
||||
r.metrics().accuracy(), m.accuracy(), m.recall(Category.ACCESS), m.recall(Category.BUG)));
|
||||
if (r.model() == TRIBUO) { tribuoNormal = r.metrics().accuracy(); tribuoDrift = m.accuracy(); }
|
||||
}
|
||||
t.write();
|
||||
|
||||
assertThat(tribuoDrift).isLessThan(tribuoNormal - 0.05);
|
||||
}
|
||||
|
||||
private static double acc(TextClassifier m, List<Ticket> tickets) {
|
||||
return Metrics.of(m, tickets).accuracy();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.ankurm.classicml;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/** Collects lines and writes {@code output/NN-name.txt}, so the test that asserts a fact is the test that records it. */
|
||||
final class Transcript {
|
||||
|
||||
private final List<String> lines = new ArrayList<>();
|
||||
private final String file;
|
||||
|
||||
Transcript(String file, String title) {
|
||||
this.file = file;
|
||||
lines.add("# " + title);
|
||||
}
|
||||
|
||||
Transcript line(String s) {
|
||||
lines.add(s);
|
||||
return this;
|
||||
}
|
||||
|
||||
Transcript blank() {
|
||||
lines.add("");
|
||||
return this;
|
||||
}
|
||||
|
||||
Transcript section(String s) {
|
||||
lines.add("");
|
||||
lines.add("## " + s);
|
||||
return this;
|
||||
}
|
||||
|
||||
void write() throws IOException {
|
||||
Path dir = Path.of("output");
|
||||
Files.createDirectories(dir);
|
||||
Files.write(dir.resolve(file), lines);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user