Matthew Ford commited on
Commit
46e1263
·
1 Parent(s): 860ae82

character grouping diagnostic: 26-class J=0.793, 5-superclass J=1.000, recommend pause labels

Browse files

Former-commit-id: ddf9c4b4e155c3c4e8f9f7eff22b4b03ab16c040
Former-commit-id: 68916c7a8f2d063dbcc28737709a421734bc96b7

artifacts/character_grouping_diagnostic_v8.json ADDED
The diff for this file is too large to render. See raw diff
 
artifacts/character_grouping_diagnostic_v8.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Character grouping diagnostic v8
2
+
3
+ Primary snapshot: `v8_2_clause_guard_dominance` (`data/odour_character_labels_v8_2_clause_guard_dominance.jsonl`).
4
+
5
+ | Axis | classes | mean pairwise Jaccard | delta vs 26 |
6
+ | --- | ---: | ---: | ---: |
7
+ | 26-class | 26 | 0.793 | baseline |
8
+ | six_superclass | 5 | 1.000 | +0.207 |
9
+ | eight_superclass | 8 | 1.000 | +0.207 |
10
+
11
+ Recommendation: **Do not expand character labels yet. The tested superclass schemes do not materially lower genre overlap versus 26 classes (best 1.000 vs 0.793); character remains non-discriminative on this data.**
12
+
13
+ No new sourcing or label expansion was performed.
scripts/character_grouping_diagnostic_v8.py ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Character superclass grouping diagnostic for existing labels only.
3
+
4
+ Diagnostics only: no new sourcing, no label expansion, no dataset assembly,
5
+ no training, and no upload.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from collections import Counter, defaultdict
10
+ import json
11
+ from pathlib import Path
12
+ import sys
13
+ from typing import Any
14
+
15
+ ROOT = Path(__file__).resolve().parents[1]
16
+ DATA = ROOT / "data"
17
+ ARTIFACTS = ROOT / "artifacts"
18
+ OUT_JSON = ARTIFACTS / "character_grouping_diagnostic_v8.json"
19
+ OUT_MD = ARTIFACTS / "character_grouping_diagnostic_v8.md"
20
+
21
+ sys.path.insert(0, str(ROOT / "scripts"))
22
+ import build_odour_taxonomy_census_v8 as census # noqa: E402
23
+
24
+
25
+ LABEL_SNAPSHOTS = {
26
+ "v8_2": DATA / "odour_character_labels_v8_2.jsonl",
27
+ "v8_2_clause_guard": DATA / "odour_character_labels_v8_2_clause_guard.jsonl",
28
+ "v8_2_clause_guard_dominance": DATA / "odour_character_labels_v8_2_clause_guard_dominance.jsonl",
29
+ }
30
+
31
+
32
+ GROUPINGS: dict[str, dict[str, Any]] = {
33
+ "six_superclass": {
34
+ "justification": (
35
+ "Collapses the 26-letter taxonomy into perfumery families: fresh/top-note, floral, "
36
+ "edible/gourmand, balsamic/woody/fixative, warm/spicy/animalic/smoky, and solvent carriers."
37
+ ),
38
+ "mapping": {
39
+ "A": "fresh_citrus_green",
40
+ "B": "fresh_citrus_green",
41
+ "C": "fresh_citrus_green",
42
+ "F": "fresh_citrus_green",
43
+ "G": "fresh_citrus_green",
44
+ "H": "fresh_citrus_green",
45
+ "K": "fresh_citrus_green",
46
+ "L": "floral",
47
+ "I": "floral",
48
+ "J": "floral",
49
+ "M": "floral",
50
+ "N": "floral",
51
+ "O": "floral",
52
+ "R": "floral",
53
+ "D": "edible_gourmand",
54
+ "E": "edible_gourmand",
55
+ "P": "edible_gourmand",
56
+ "V": "edible_gourmand",
57
+ "Q": "balsamic_woody_mossy",
58
+ "W": "balsamic_woody_mossy",
59
+ "X": "balsamic_woody_mossy",
60
+ "Y": "balsamic_woody_mossy",
61
+ "S": "animalic_spicy_smoky",
62
+ "T": "animalic_spicy_smoky",
63
+ "U": "animalic_spicy_smoky",
64
+ "Z": "carrier",
65
+ },
66
+ },
67
+ "eight_superclass": {
68
+ "justification": (
69
+ "Keeps fruit/citrus/green fresh notes separate from aromatic cool herbs, splits gourmand "
70
+ "from phenolic/savory edible, and keeps musk/animal/smoke separate from spice."
71
+ ),
72
+ "mapping": {
73
+ "A": "fresh_citrus_green_fruit",
74
+ "C": "fresh_citrus_green_fruit",
75
+ "F": "fresh_citrus_green_fruit",
76
+ "G": "fresh_citrus_green_fruit",
77
+ "B": "aromatic_cool_herbal",
78
+ "H": "aromatic_cool_herbal",
79
+ "K": "aromatic_cool_herbal",
80
+ "I": "floral",
81
+ "J": "floral",
82
+ "L": "floral",
83
+ "M": "floral",
84
+ "N": "floral",
85
+ "O": "floral",
86
+ "R": "floral",
87
+ "D": "gourmand_sweet",
88
+ "V": "gourmand_sweet",
89
+ "E": "savory_phenolic",
90
+ "P": "savory_phenolic",
91
+ "Q": "balsamic_woody_mossy",
92
+ "W": "balsamic_woody_mossy",
93
+ "Y": "balsamic_woody_mossy",
94
+ "S": "spice",
95
+ "T": "animalic_musk_smoke",
96
+ "U": "animalic_musk_smoke",
97
+ "X": "animalic_musk_smoke",
98
+ "Z": "carrier",
99
+ },
100
+ },
101
+ }
102
+
103
+
104
+ def load_jsonl(path: Path) -> list[dict[str, Any]]:
105
+ return [json.loads(line) for line in path.read_text().splitlines() if line.strip()]
106
+
107
+
108
+ def label_codes(label: dict[str, Any]) -> set[str]:
109
+ codes = label.get("class_codes")
110
+ if isinstance(codes, list):
111
+ return {str(code) for code in codes}
112
+ code = label.get("class_code")
113
+ return {str(code)} if code else set()
114
+
115
+
116
+ def transform_labels(labels: dict[str, dict[str, Any]], mapping: dict[str, str]) -> dict[str, dict[str, Any]]:
117
+ out = {}
118
+ for cas, label in labels.items():
119
+ super_codes = sorted({mapping[code] for code in label_codes(label) if code in mapping and mapping[code] != "carrier"})
120
+ if not super_codes:
121
+ continue
122
+ out[cas] = {
123
+ **label,
124
+ "class_code": super_codes[0],
125
+ "class_codes": super_codes,
126
+ "original_class_codes": sorted(label_codes(label)),
127
+ "grouping": "superclass",
128
+ }
129
+ return out
130
+
131
+
132
+ def formula_character_sets(records: list[dict[str, Any]], labels: dict[str, dict[str, Any]]) -> dict[str, list[set[str]]]:
133
+ by_genre: dict[str, list[set[str]]] = defaultdict(list)
134
+ for record in records:
135
+ if record.get("is_control"):
136
+ continue
137
+ genre = record.get("genre") or record.get("metadata", {}).get("generation_strategy") or "unknown"
138
+ chars = set()
139
+ for comp in census.formula_components(record):
140
+ label = labels.get(str(comp.get("cas")))
141
+ if label:
142
+ chars.update(code for code in label_codes(label) if code != "Z" and code != "carrier")
143
+ if chars:
144
+ by_genre[genre].append(chars)
145
+ return by_genre
146
+
147
+
148
+ def discrimination_probe(records: list[dict[str, Any]], labels: dict[str, dict[str, Any]], axis_name: str) -> dict[str, Any]:
149
+ by_genre = formula_character_sets(records, labels)
150
+ genre_profiles: dict[str, set[str]] = {}
151
+ threshold = 0.05
152
+ for genre, sets in sorted(by_genre.items()):
153
+ if len(sets) < 10:
154
+ continue
155
+ counts = Counter(code for s in sets for code in s)
156
+ genre_profiles[genre] = {code for code, count in counts.items() if count / len(sets) >= threshold}
157
+
158
+ pairwise = []
159
+ genres = sorted(genre_profiles)
160
+ for i, left in enumerate(genres):
161
+ for right in genres[i + 1:]:
162
+ a, b = genre_profiles[left], genre_profiles[right]
163
+ pairwise.append({
164
+ "left": left,
165
+ "right": right,
166
+ "jaccard": len(a & b) / max(1, len(a | b)),
167
+ "intersection": sorted(a & b),
168
+ "union": sorted(a | b),
169
+ })
170
+ mean_jaccard = sum(p["jaccard"] for p in pairwise) / len(pairwise) if pairwise else None
171
+ return {
172
+ "method": f"per-genre formula-level set Jaccard over {axis_name}; class active if present in >=5% of labelled formulas for genre",
173
+ "formula_labelled_by_genre": {k: len(v) for k, v in by_genre.items()},
174
+ "genre_profiles": {k: sorted(v) for k, v in genre_profiles.items()},
175
+ "pairwise": pairwise,
176
+ "mean_pairwise_jaccard": mean_jaccard,
177
+ }
178
+
179
+
180
+ def evaluate_snapshot(name: str, path: Path, records: list[dict[str, Any]]) -> dict[str, Any]:
181
+ rows = load_jsonl(path)
182
+ labels = {row["cas"]: row for row in rows}
183
+ base = discrimination_probe(records, labels, "26-class character labels")
184
+ group_results = {}
185
+ for grouping_name, spec in GROUPINGS.items():
186
+ grouped = transform_labels(labels, spec["mapping"])
187
+ group_results[grouping_name] = {
188
+ "justification": spec["justification"],
189
+ "n_superclasses": len({v for v in spec["mapping"].values() if v != "carrier"}),
190
+ "class_to_superclass": spec["mapping"],
191
+ "discrimination_precheck": discrimination_probe(records, grouped, grouping_name),
192
+ }
193
+ best_group_name = min(
194
+ group_results,
195
+ key=lambda g: group_results[g]["discrimination_precheck"]["mean_pairwise_jaccard"]
196
+ if group_results[g]["discrimination_precheck"]["mean_pairwise_jaccard"] is not None
197
+ else float("inf"),
198
+ )
199
+ best_j = group_results[best_group_name]["discrimination_precheck"]["mean_pairwise_jaccard"]
200
+ base_j = base["mean_pairwise_jaccard"]
201
+ material_improvement = base_j is not None and best_j is not None and best_j <= base_j - 0.05
202
+ return {
203
+ "label_snapshot": name,
204
+ "label_path": str(path.relative_to(ROOT)),
205
+ "label_count": len(rows),
206
+ "twenty_six_class": base,
207
+ "groupings": group_results,
208
+ "best_grouping": best_group_name,
209
+ "best_grouping_mean_pairwise_jaccard": best_j,
210
+ "materially_better_than_26_class": material_improvement,
211
+ }
212
+
213
+
214
+ def recommendation(primary: dict[str, Any]) -> str:
215
+ base_j = primary["twenty_six_class"]["mean_pairwise_jaccard"]
216
+ best_j = primary["best_grouping_mean_pairwise_jaccard"]
217
+ if primary["materially_better_than_26_class"]:
218
+ return (
219
+ f"Collapse character target to {primary['best_grouping']} before any label expansion; "
220
+ f"mean Jaccard improves from {base_j:.3f} to {best_j:.3f}."
221
+ )
222
+ return (
223
+ "Do not expand character labels yet. The tested superclass schemes do not materially lower "
224
+ f"genre overlap versus 26 classes (best {best_j:.3f} vs {base_j:.3f}); character remains "
225
+ "non-discriminative on this data."
226
+ )
227
+
228
+
229
+ def write_markdown(report: dict[str, Any]) -> None:
230
+ primary = report["primary_snapshot_result"]
231
+ rows = []
232
+ base_j = primary["twenty_six_class"]["mean_pairwise_jaccard"]
233
+ rows.append(f"| 26-class | 26 | {base_j:.3f} | baseline |")
234
+ for name, result in primary["groupings"].items():
235
+ j = result["discrimination_precheck"]["mean_pairwise_jaccard"]
236
+ delta = j - base_j
237
+ rows.append(f"| {name} | {result['n_superclasses']} | {j:.3f} | {delta:+.3f} |")
238
+ md = [
239
+ "# Character grouping diagnostic v8",
240
+ "",
241
+ f"Primary snapshot: `{primary['label_snapshot']}` (`{primary['label_path']}`).",
242
+ "",
243
+ "| Axis | classes | mean pairwise Jaccard | delta vs 26 |",
244
+ "| --- | ---: | ---: | ---: |",
245
+ *rows,
246
+ "",
247
+ f"Recommendation: **{report['recommendation']}**",
248
+ "",
249
+ "No new sourcing or label expansion was performed.",
250
+ ]
251
+ OUT_MD.write_text("\n".join(md) + "\n", encoding="utf-8")
252
+
253
+
254
+ def main() -> None:
255
+ records = census.load_formula_records()
256
+ snapshots = {
257
+ name: evaluate_snapshot(name, path, records)
258
+ for name, path in LABEL_SNAPSHOTS.items()
259
+ if path.exists()
260
+ }
261
+ primary_name = "v8_2_clause_guard_dominance"
262
+ primary = snapshots[primary_name]
263
+ report = {
264
+ "pimt_version": "v8",
265
+ "diagnostic": "character_grouping_existing_labels_only",
266
+ "primary_snapshot": primary_name,
267
+ "primary_snapshot_result": primary,
268
+ "all_snapshot_results": snapshots,
269
+ "recommendation": recommendation(primary),
270
+ "stop": "NO_NEW_SOURCING_NO_LABEL_EXPANSION_NO_DATASET_ASSEMBLY_NO_TRAINING_NO_HF_UPLOAD",
271
+ }
272
+ OUT_JSON.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8")
273
+ write_markdown(report)
274
+ print(json.dumps({
275
+ "primary_snapshot": primary_name,
276
+ "twenty_six_class_jaccard": primary["twenty_six_class"]["mean_pairwise_jaccard"],
277
+ "best_grouping": primary["best_grouping"],
278
+ "best_grouping_jaccard": primary["best_grouping_mean_pairwise_jaccard"],
279
+ "materially_better_than_26_class": primary["materially_better_than_26_class"],
280
+ "recommendation": report["recommendation"],
281
+ }, indent=2, sort_keys=True))
282
+
283
+
284
+ if __name__ == "__main__":
285
+ main()