arapreplab 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. arapreplab/__init__.py +2 -0
  2. arapreplab/__main__.py +13 -0
  3. arapreplab/core/__init__.py +21 -0
  4. arapreplab/core/audit.py +120 -0
  5. arapreplab/core/auto.py +171 -0
  6. arapreplab/core/dialect.py +92 -0
  7. arapreplab/core/experiment.py +364 -0
  8. arapreplab/core/final_model.py +113 -0
  9. arapreplab/core/labels.py +53 -0
  10. arapreplab/core/models.py +67 -0
  11. arapreplab/core/negation.py +51 -0
  12. arapreplab/core/normalize.py +145 -0
  13. arapreplab/core/pipeline.py +110 -0
  14. arapreplab/core/seed.py +18 -0
  15. arapreplab/core/stats.py +66 -0
  16. arapreplab/core/stemming.py +83 -0
  17. arapreplab/core/stopwords.py +34 -0
  18. arapreplab/core/topics.py +72 -0
  19. arapreplab/core/transformer.py +258 -0
  20. arapreplab/data/__init__.py +1 -0
  21. arapreplab/data/sample_reviews.csv +601 -0
  22. arapreplab/gui/__init__.py +1 -0
  23. arapreplab/gui/app.py +270 -0
  24. arapreplab/gui/auto_window.py +183 -0
  25. arapreplab/gui/help_text.py +82 -0
  26. arapreplab/gui/rtl.py +54 -0
  27. arapreplab/gui/state.py +80 -0
  28. arapreplab/gui/tabs/__init__.py +1 -0
  29. arapreplab/gui/tabs/cleaning_tab.py +125 -0
  30. arapreplab/gui/tabs/data_tab.py +164 -0
  31. arapreplab/gui/tabs/experiment_tab.py +259 -0
  32. arapreplab/gui/tabs/export_tab.py +274 -0
  33. arapreplab/gui/tabs/results_tab.py +155 -0
  34. arapreplab/gui/tabs/topics_tab.py +99 -0
  35. arapreplab/gui/tabs/transformer_tab.py +212 -0
  36. arapreplab/gui/widgets.py +123 -0
  37. arapreplab/gui/worker.py +71 -0
  38. arapreplab/io/__init__.py +10 -0
  39. arapreplab/io/action_log.py +249 -0
  40. arapreplab/io/console.py +17 -0
  41. arapreplab/io/loaders.py +97 -0
  42. arapreplab/io/reports.py +116 -0
  43. arapreplab/io/session.py +69 -0
  44. arapreplab-0.1.0.dist-info/METADATA +271 -0
  45. arapreplab-0.1.0.dist-info/RECORD +49 -0
  46. arapreplab-0.1.0.dist-info/WHEEL +5 -0
  47. arapreplab-0.1.0.dist-info/entry_points.txt +2 -0
  48. arapreplab-0.1.0.dist-info/licenses/LICENSE +21 -0
  49. arapreplab-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,364 @@
1
+ """The preprocessing experiment.
2
+
3
+ Every configuration is trained and scored on the same repeated stratified
4
+ k-fold splits. The effect of one choice, such as "normalize alef", is then
5
+ measured from pairs of configurations that differ only in that choice. Each
6
+ effect gets a corrected resampled t-test and a Holm-adjusted p-value, which
7
+ tells the user which steps help on their data and which differences are noise.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import itertools
12
+ import time
13
+ from dataclasses import asdict, dataclass, field
14
+ from typing import Callable, Dict, List, Optional, Sequence, Tuple
15
+
16
+ import numpy as np
17
+ from sklearn.dummy import DummyClassifier
18
+ from sklearn.metrics import accuracy_score, balanced_accuracy_score, f1_score
19
+ from sklearn.model_selection import RepeatedStratifiedKFold
20
+
21
+ from .labels import check_classes, label_array
22
+ from .models import build_pipeline
23
+ from .normalize import STEP_ORDER
24
+ from .pipeline import NEGATION_KEY, STOPWORDS_KEY, PreprocessConfig
25
+ from .stats import corrected_resampled_ttest, holm_correction
26
+
27
+ METRICS = ("f1_macro", "accuracy", "balanced_accuracy")
28
+ ProgressFn = Callable[[int, int, str], None]
29
+ StopFn = Callable[[], bool]
30
+
31
+
32
+ class ExperimentCancelled(RuntimeError):
33
+ """Raised when the user cancels a running experiment."""
34
+
35
+
36
+ @dataclass
37
+ class ExperimentSettings:
38
+ """What to test and how.
39
+
40
+ Attributes:
41
+ factors: binary choices to test (normalization step keys and/or
42
+ ``"remove_stopwords"``).
43
+ stemmers: stemmer levels to test (``"none"`` is the reference level).
44
+ design: ``"screening"`` (baseline, one-on, all-on, leave-one-out;
45
+ grows linearly) or ``"factorial"`` (every combination).
46
+ model, features: see :mod:`arapreplab.core.models`.
47
+ n_splits, n_repeats: repeated stratified k-fold CV.
48
+ seed: global random seed (splits and models).
49
+ metric: primary metric used for effects and ranking.
50
+ alpha: significance level after Holm correction.
51
+ max_configs: safety limit for the factorial design.
52
+ """
53
+
54
+ factors: Tuple[str, ...] = tuple(STEP_ORDER) + (STOPWORDS_KEY, NEGATION_KEY)
55
+ stemmers: Tuple[str, ...] = ("none", "light", "isri")
56
+ design: str = "screening"
57
+ model: str = "svm"
58
+ features: str = "word_1_2"
59
+ n_splits: int = 5
60
+ n_repeats: int = 5
61
+ seed: int = 42
62
+ metric: str = "f1_macro"
63
+ alpha: float = 0.05
64
+ max_configs: int = 400
65
+
66
+ def __post_init__(self) -> None:
67
+ valid = set(STEP_ORDER) | {STOPWORDS_KEY, NEGATION_KEY}
68
+ bad = set(self.factors) - valid
69
+ if bad:
70
+ raise ValueError(f"Unknown factors: {sorted(bad)}")
71
+ if self.design not in ("screening", "factorial"):
72
+ raise ValueError("design must be 'screening' or 'factorial'")
73
+ if self.metric not in METRICS:
74
+ raise ValueError(f"metric must be one of {METRICS}")
75
+ if "none" not in self.stemmers:
76
+ self.stemmers = ("none",) + tuple(self.stemmers)
77
+ self.factors = tuple(dict.fromkeys(self.factors))
78
+ self.stemmers = tuple(dict.fromkeys(self.stemmers))
79
+
80
+ def to_dict(self) -> Dict[str, object]:
81
+ d = asdict(self)
82
+ d["factors"] = list(self.factors)
83
+ d["stemmers"] = list(self.stemmers)
84
+ return d
85
+
86
+
87
+ @dataclass
88
+ class ConfigScore:
89
+ config: PreprocessConfig
90
+ fold_scores: Dict[str, List[float]]
91
+
92
+ def mean(self, metric: str) -> float:
93
+ """Mean score over all folds."""
94
+ return float(np.mean(self.fold_scores[metric]))
95
+
96
+ def std(self, metric: str) -> float:
97
+ """Standard deviation of the score over folds."""
98
+ return float(np.std(self.fold_scores[metric], ddof=1))
99
+
100
+ def to_dict(self) -> Dict[str, object]:
101
+ return {
102
+ "config": self.config.to_dict(),
103
+ "label": self.config.label(),
104
+ "mean": {m: self.mean(m) for m in self.fold_scores},
105
+ "std": {m: self.std(m) for m in self.fold_scores},
106
+ "fold_scores": self.fold_scores,
107
+ }
108
+
109
+
110
+ @dataclass
111
+ class Effect:
112
+ factor: str
113
+ level: str
114
+ mean_diff: float
115
+ ci_low: float
116
+ ci_high: float
117
+ p_value: float
118
+ p_holm: float
119
+ n_pairs: int
120
+ verdict: str = ""
121
+
122
+ def to_dict(self) -> Dict[str, object]:
123
+ return asdict(self)
124
+
125
+
126
+ @dataclass
127
+ class ExperimentResult:
128
+ settings: ExperimentSettings
129
+ scores: List[ConfigScore]
130
+ effects: List[Effect]
131
+ best: ConfigScore
132
+ baseline: ConfigScore
133
+ best_vs_baseline: Dict[str, float]
134
+ full_vs_baseline: Optional[Dict[str, float]]
135
+ dummy: Dict[str, float]
136
+ n_docs: int
137
+ class_counts: Dict[str, int]
138
+ runtime_s: float
139
+ warnings: List[str] = field(default_factory=list)
140
+
141
+ def ranked(self, metric: Optional[str] = None) -> List[ConfigScore]:
142
+ """Configurations sorted from best to worst on the given metric."""
143
+ m = metric or self.settings.metric
144
+ return sorted(self.scores, key=lambda s: s.mean(m), reverse=True)
145
+
146
+ def to_dict(self) -> Dict[str, object]:
147
+ m = self.settings.metric
148
+ return {
149
+ "settings": self.settings.to_dict(),
150
+ "n_docs": self.n_docs,
151
+ "class_counts": self.class_counts,
152
+ "runtime_s": self.runtime_s,
153
+ "dummy_baseline": self.dummy,
154
+ "best": self.best.to_dict(),
155
+ "raw_baseline": self.baseline.to_dict(),
156
+ "best_vs_baseline": self.best_vs_baseline,
157
+ "full_vs_baseline": self.full_vs_baseline,
158
+ "effects": [e.to_dict() for e in self.effects],
159
+ "ranking": [s.to_dict() for s in self.ranked(m)],
160
+ "warnings": self.warnings,
161
+ }
162
+
163
+
164
+ def generate_configs(settings: ExperimentSettings) -> List[PreprocessConfig]:
165
+ """Configurations evaluated for the chosen design (deduplicated, ordered)."""
166
+ factors = list(settings.factors)
167
+ subsets: List[Tuple[str, ...]]
168
+ if settings.design == "factorial":
169
+ n = (2 ** len(factors)) * len(settings.stemmers)
170
+ if n > settings.max_configs:
171
+ raise ValueError(
172
+ f"Factorial design needs {n} configurations (limit {settings.max_configs}). "
173
+ "Select fewer steps or use the screening design."
174
+ )
175
+ subsets = [tuple(c) for r in range(len(factors) + 1) for c in itertools.combinations(factors, r)]
176
+ else:
177
+ full = tuple(factors)
178
+ subsets = [()] + [(f,) for f in factors] + [full] + [tuple(x for x in full if x != f) for f in factors]
179
+ configs: List[PreprocessConfig] = []
180
+ seen = set()
181
+ for stemmer in settings.stemmers:
182
+ for sub in subsets:
183
+ cfg = PreprocessConfig(
184
+ steps=tuple(x for x in sub if x not in (STOPWORDS_KEY, NEGATION_KEY)),
185
+ stopwords=STOPWORDS_KEY in sub,
186
+ negation=NEGATION_KEY in sub,
187
+ stemmer=stemmer,
188
+ )
189
+ if cfg not in seen:
190
+ seen.add(cfg)
191
+ configs.append(cfg)
192
+ return configs
193
+
194
+
195
+ def _scores(y_true, y_pred) -> Dict[str, float]:
196
+ return {
197
+ "f1_macro": float(f1_score(y_true, y_pred, average="macro", zero_division=0)),
198
+ "accuracy": float(accuracy_score(y_true, y_pred)),
199
+ "balanced_accuracy": float(balanced_accuracy_score(y_true, y_pred)),
200
+ }
201
+
202
+
203
+ def run_experiment(
204
+ texts: Sequence[str],
205
+ labels: Sequence[object],
206
+ settings: Optional[ExperimentSettings] = None,
207
+ progress: Optional[ProgressFn] = None,
208
+ should_stop: Optional[StopFn] = None,
209
+ ) -> ExperimentResult:
210
+ """Run the full preprocessing experiment.
211
+
212
+ Args:
213
+ texts: raw documents.
214
+ labels: class labels (two or more classes).
215
+ settings: what to test (defaults to all steps, screening design).
216
+ progress: optional callback ``(done, total, message)`` for GUIs.
217
+ should_stop: optional callable; return True to cancel.
218
+ """
219
+ settings = settings or ExperimentSettings()
220
+ t0 = time.perf_counter()
221
+ texts = ["" if t is None else str(t) for t in texts]
222
+ y = label_array(labels)
223
+ if len(texts) != len(y):
224
+ raise ValueError("texts and labels must have the same length")
225
+ check_classes(y, settings.n_splits)
226
+ classes, counts = np.unique(y, return_counts=True)
227
+
228
+ configs = generate_configs(settings)
229
+ cv = RepeatedStratifiedKFold(n_splits=settings.n_splits, n_repeats=settings.n_repeats,
230
+ random_state=settings.seed)
231
+ splits = list(cv.split(np.zeros(len(y)), y))
232
+ total = len(configs) * len(splits)
233
+ done = 0
234
+ warnings: List[str] = []
235
+
236
+ # reference: majority-class predictor on the same folds
237
+ dummy_folds: Dict[str, List[float]] = {m: [] for m in METRICS}
238
+ for tr, te in splits:
239
+ clf = DummyClassifier(strategy="most_frequent").fit(np.zeros((len(tr), 1)), y[tr])
240
+ for m, v in _scores(y[te], clf.predict(np.zeros((len(te), 1)))).items():
241
+ dummy_folds[m].append(v)
242
+ dummy = {m: float(np.mean(v)) for m, v in dummy_folds.items()}
243
+
244
+ results: List[ConfigScore] = []
245
+ text_arr = np.asarray(texts, dtype=object)
246
+ for cfg in configs:
247
+ if should_stop and should_stop():
248
+ raise ExperimentCancelled("Experiment cancelled by user")
249
+ Xp = np.asarray(cfg.transform(text_arr), dtype=object)
250
+ if all(not t for t in Xp):
251
+ warnings.append(f"Configuration '{cfg.label()}' produced only empty texts; skipped.")
252
+ done += len(splits)
253
+ continue
254
+ folds: Dict[str, List[float]] = {m: [] for m in METRICS}
255
+ for tr, te in splits:
256
+ if should_stop and should_stop():
257
+ raise ExperimentCancelled("Experiment cancelled by user")
258
+ pipe = build_pipeline(settings.model, settings.features, settings.seed)
259
+ pipe.fit(Xp[tr], y[tr])
260
+ for m, v in _scores(y[te], pipe.predict(Xp[te])).items():
261
+ folds[m].append(v)
262
+ done += 1
263
+ if progress:
264
+ progress(done, total, cfg.label())
265
+ results.append(ConfigScore(cfg, folds))
266
+
267
+ if not results:
268
+ raise ValueError("Every configuration produced empty texts.")
269
+
270
+ n_test = int(np.mean([len(te) for _, te in splits]))
271
+ n_train = int(np.mean([len(tr) for tr, _ in splits]))
272
+ effects = estimate_effects(results, settings, n_train, n_test)
273
+
274
+ metric = settings.metric
275
+ best = max(results, key=lambda s: s.mean(metric))
276
+ raw = PreprocessConfig()
277
+ baseline = next((s for s in results if s.config == raw), results[0])
278
+ def compare(a: ConfigScore, b: ConfigScore) -> Dict[str, float]:
279
+ """Corrected t-test of a minus b over the shared folds."""
280
+ diffs = np.asarray(a.fold_scores[metric]) - np.asarray(b.fold_scores[metric])
281
+ tt = corrected_resampled_ttest(diffs, n_train, n_test, settings.alpha)
282
+ return {"mean_diff": tt.mean_diff, "ci_low": tt.ci_low, "ci_high": tt.ci_high, "p_value": tt.p_value}
283
+
284
+ # The best configuration is picked after looking at every score, so this
285
+ # gap is optimistic. It is reported for information, not as a test.
286
+ best_vs_baseline = dict(compare(best, baseline), selected_from=len(results))
287
+
288
+ # A comparison fixed before the run: every tested step on, no stemming,
289
+ # against raw text. This one is a fair test.
290
+ full = PreprocessConfig(steps=tuple(f for f in settings.factors if f not in (STOPWORDS_KEY, NEGATION_KEY)),
291
+ stopwords=STOPWORDS_KEY in settings.factors,
292
+ negation=NEGATION_KEY in settings.factors, stemmer="none")
293
+ full_score = next((s for s in results if s.config == full), None)
294
+ full_vs_baseline = dict(compare(full_score, baseline), label=full.label()) if full_score else None
295
+
296
+ n_rounds = settings.n_splits * settings.n_repeats
297
+ if n_rounds < 10:
298
+ warnings.append(f"Only {n_rounds} train/test rounds. Effects this small need at least 10 rounds "
299
+ "(for example 5 folds x 2 repeats) before they can be trusted.")
300
+
301
+ if best.mean(metric) >= 0.999:
302
+ warnings.append("Near-perfect score: check for duplicate texts or label leakage (see the data audit).")
303
+ if metric == "accuracy" and dummy["accuracy"] > 0.8:
304
+ warnings.append("Classes are imbalanced: accuracy is misleading, prefer macro-F1.")
305
+
306
+ return ExperimentResult(
307
+ settings=settings,
308
+ scores=results,
309
+ effects=effects,
310
+ best=best,
311
+ baseline=baseline,
312
+ best_vs_baseline=best_vs_baseline,
313
+ full_vs_baseline=full_vs_baseline,
314
+ dummy=dummy,
315
+ n_docs=len(texts),
316
+ class_counts={str(c): int(n) for c, n in zip(classes, counts)},
317
+ runtime_s=time.perf_counter() - t0,
318
+ warnings=warnings,
319
+ )
320
+
321
+
322
+ def _without(factors: Dict[str, object], name: str) -> Tuple:
323
+ return tuple(sorted((k, v) for k, v in factors.items() if k != name))
324
+
325
+
326
+ def estimate_effects(results: List[ConfigScore], settings: ExperimentSettings,
327
+ n_train: int, n_test: int) -> List[Effect]:
328
+ """Effect of each choice, from matched configuration pairs that differ only in it."""
329
+ metric = settings.metric
330
+ by_factors = [(r.config.factors(), np.asarray(r.fold_scores[metric])) for r in results]
331
+ raw_effects: List[Tuple[str, str, np.ndarray]] = []
332
+
333
+ def collect(name: str, on_level, off_level) -> Optional[np.ndarray]:
334
+ """Per-fold score differences for every pair that differs only in this factor."""
335
+ off = {_without(f, name): s for f, s in by_factors if f[name] == off_level}
336
+ diffs = [s - off[_without(f, name)] for f, s in by_factors
337
+ if f[name] == on_level and _without(f, name) in off]
338
+ return np.vstack(diffs) if diffs else None
339
+
340
+ for name in settings.factors:
341
+ d = collect(name, True, False)
342
+ if d is not None:
343
+ raw_effects.append((name, "on", d))
344
+ for level in settings.stemmers:
345
+ if level == "none":
346
+ continue
347
+ d = collect("stemmer", level, "none")
348
+ if d is not None:
349
+ raw_effects.append(("stemmer", level, d))
350
+
351
+ tests = [(n, lvl, d.shape[0], corrected_resampled_ttest(d.mean(axis=0), n_train, n_test, settings.alpha))
352
+ for n, lvl, d in raw_effects]
353
+ adj = holm_correction([t.p_value for *_, t in tests])
354
+ effects: List[Effect] = []
355
+ for (name, level, n_pairs, t), p_adj in zip(tests, adj):
356
+ if p_adj < settings.alpha and t.mean_diff > 0:
357
+ verdict = "helps"
358
+ elif p_adj < settings.alpha and t.mean_diff < 0:
359
+ verdict = "hurts"
360
+ else:
361
+ verdict = "no clear effect"
362
+ effects.append(Effect(name, level, t.mean_diff, t.ci_low, t.ci_high, t.p_value, p_adj, n_pairs, verdict))
363
+ effects.sort(key=lambda e: e.mean_diff, reverse=True)
364
+ return effects
@@ -0,0 +1,113 @@
1
+ """Train the chosen configuration on all data and predict new texts."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import dataclass
5
+ from pathlib import Path
6
+ from typing import List, Sequence, Tuple, Union
7
+
8
+ import joblib
9
+ import numpy as np
10
+ from sklearn.metrics import accuracy_score, confusion_matrix, f1_score
11
+ from sklearn.model_selection import StratifiedKFold, cross_val_predict
12
+ from sklearn.pipeline import Pipeline
13
+
14
+ from .labels import check_classes, label_array
15
+ from .models import build_pipeline
16
+
17
+ EMPTY_TEXTS = ("This cleaning setup removes every word from the texts, so there is nothing left to learn from. "
18
+ "Untick some steps (for example Remove digits or the stopwords) and try again.")
19
+
20
+
21
+ def _fit(pipe: Pipeline, X, y) -> Pipeline:
22
+ """Fit, turning scikit-learn's 'empty vocabulary' error into a message people can act on."""
23
+ try:
24
+ return pipe.fit(X, y)
25
+ except ValueError as exc:
26
+ if "empty vocabulary" in str(exc):
27
+ raise ValueError(EMPTY_TEXTS) from exc
28
+ raise
29
+ from .pipeline import PreprocessConfig
30
+
31
+
32
+ @dataclass
33
+ class FinalModel:
34
+ config: PreprocessConfig
35
+ pipeline: Pipeline
36
+ model: str
37
+ features: str
38
+ seed: int
39
+
40
+ def predict(self, texts: Sequence[str]) -> List[str]:
41
+ """Clean the texts the same way as in training, then predict their labels."""
42
+ return [str(p) for p in self.pipeline.predict(self.config.transform(texts))]
43
+
44
+ def save(self, path: Union[str, Path]) -> Path:
45
+ """Save the model, its cleaning configuration and settings with joblib."""
46
+ path = Path(path)
47
+ joblib.dump({"config": self.config.to_dict(), "pipeline": self.pipeline, "model": self.model,
48
+ "features": self.features, "seed": self.seed}, path)
49
+ return path
50
+
51
+ @classmethod
52
+ def load(cls, path: Union[str, Path]) -> "FinalModel":
53
+ """Load a model saved with save."""
54
+ d = joblib.load(path)
55
+ return cls(PreprocessConfig.from_dict(d["config"]), d["pipeline"], d["model"], d["features"], d["seed"])
56
+
57
+
58
+ def train_final(texts: Sequence[str], labels: Sequence[object], config: PreprocessConfig,
59
+ model: str = "svm", features: str = "word_1_2", seed: int = 42) -> FinalModel:
60
+ """Fit preprocessing + TF-IDF + classifier on the whole dataset."""
61
+ pipe = build_pipeline(model, features, seed)
62
+ _fit(pipe, np.asarray(config.transform(texts), dtype=object), label_array(labels))
63
+ return FinalModel(config, pipe, model, features, seed)
64
+
65
+
66
+ @dataclass
67
+ class ModelCheck:
68
+ """Held-out predictions for every text, from one round of stratified k-fold."""
69
+
70
+ classes: List[str]
71
+ matrix: List[List[int]]
72
+ scores: dict
73
+ mistakes: List[Tuple[str, str, str]]
74
+ n_splits: int
75
+
76
+ def table(self) -> str:
77
+ """Confusion matrix as plain text: rows are the true labels, columns the predictions."""
78
+ w = max(8, *(len(c) for c in self.classes)) + 2
79
+ lines = ["true \\ predicted".ljust(w + 4) + "".join(c.rjust(w) for c in self.classes)]
80
+ for c, row in zip(self.classes, self.matrix):
81
+ lines.append(c.ljust(w + 4) + "".join(str(v).rjust(w) for v in row))
82
+ return "\n".join(lines)
83
+
84
+ def to_dict(self) -> dict:
85
+ return {"classes": self.classes, "matrix": self.matrix, "scores": self.scores, "n_splits": self.n_splits,
86
+ "n_mistakes": len(self.mistakes)}
87
+
88
+
89
+ def check_model(texts: Sequence[str], labels: Sequence[object], config: PreprocessConfig, model: str = "svm",
90
+ features: str = "word_1_2", seed: int = 42, n_splits: int = 5) -> ModelCheck:
91
+ """Predict every text with a model that did not see it, and collect the mistakes.
92
+
93
+ Each text is predicted by a model trained on the other folds, so the confusion matrix shows how the
94
+ setup does on new data, not on the data it was trained on.
95
+ """
96
+ texts = ["" if t is None else str(t) for t in texts]
97
+ y = label_array(labels)
98
+ check_classes(y, n_splits)
99
+ Xp = np.asarray(config.transform(texts), dtype=object)
100
+ cv = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=seed)
101
+ if not any(t.strip() for t in Xp):
102
+ raise ValueError(EMPTY_TEXTS)
103
+ try:
104
+ pred = cross_val_predict(build_pipeline(model, features, seed), Xp, y, cv=cv)
105
+ except ValueError as exc:
106
+ if "empty vocabulary" in str(exc):
107
+ raise ValueError(EMPTY_TEXTS) from exc
108
+ raise
109
+ classes = sorted(np.unique(y).tolist())
110
+ matrix = confusion_matrix(y, pred, labels=classes).tolist()
111
+ scores = {"f1_macro": float(f1_score(y, pred, average="macro")), "accuracy": float(accuracy_score(y, pred))}
112
+ mistakes = [(t, str(a), str(b)) for t, a, b in zip(texts, y, pred) if a != b]
113
+ return ModelCheck(classes, matrix, scores, mistakes, n_splits)
@@ -0,0 +1,53 @@
1
+ """Tidy class labels and check that every class is big enough."""
2
+ from __future__ import annotations
3
+
4
+ from collections import Counter
5
+ from typing import Dict, List, Sequence, Tuple
6
+
7
+ import numpy as np
8
+
9
+
10
+ def _as_text(v: object) -> str:
11
+ """Label as text; whole-number floats lose their ".0", so 1 and 1.0 are the same class."""
12
+ if isinstance(v, float) and v.is_integer():
13
+ return str(int(v))
14
+ if hasattr(v, "item"): # numpy numbers
15
+ return _as_text(v.item())
16
+ return str(v)
17
+
18
+
19
+ def clean_labels(labels: Sequence[object]) -> Tuple[List[str], Dict[str, str]]:
20
+ """Strip spaces from labels and merge ones that differ only in capital letters.
21
+
22
+ Labels typed by hand often come as "positive", " positive" and "Positive". These are one class, so
23
+ each group gets its most common spelling.
24
+
25
+ Returns:
26
+ the cleaned labels, and a mapping from every spelling that was changed to the one it became.
27
+ """
28
+ stripped = [" ".join(_as_text(v).split()) for v in labels]
29
+ counts = Counter(stripped)
30
+ groups: Dict[str, List[str]] = {}
31
+ for spelling in counts:
32
+ groups.setdefault(spelling.casefold(), []).append(spelling)
33
+ canonical = {s: max(group, key=lambda g: (counts[g], g)) for group in groups.values() for s in group}
34
+ cleaned = [canonical[s] for s in stripped]
35
+ changed = {str(raw): new for raw, new in zip(labels, cleaned) if _as_text(raw) != new}
36
+ return cleaned, changed
37
+
38
+
39
+ def label_array(labels: Sequence[object]) -> np.ndarray:
40
+ """Cleaned labels as a numpy array of strings."""
41
+ return np.asarray(clean_labels(labels)[0])
42
+
43
+
44
+ def check_classes(y: np.ndarray, n_splits: int) -> None:
45
+ """Raise a clear error if there are fewer than two classes or a class is too small for the folds."""
46
+ classes, counts = np.unique(y, return_counts=True)
47
+ if classes.size < 2:
48
+ raise ValueError("The label column has only one class. A model needs at least two to tell apart.")
49
+ small = [(c, n) for c, n in zip(classes, counts) if n < n_splits]
50
+ if small:
51
+ names = ", ".join(f"'{c}' ({n} texts)" for c, n in small)
52
+ raise ValueError(f"Too few texts in {names}. Each class needs at least {n_splits} texts, one for each "
53
+ f"fold. Remove or merge that class in your file, or choose fewer folds in tab 3.")
@@ -0,0 +1,67 @@
1
+ """Model and feature registries (all scikit-learn, CPU only)."""
2
+ from __future__ import annotations
3
+
4
+ from typing import Callable, Dict
5
+
6
+ from sklearn.base import ClassifierMixin
7
+ from sklearn.feature_extraction.text import TfidfVectorizer
8
+ from sklearn.linear_model import LogisticRegression
9
+ from sklearn.naive_bayes import ComplementNB
10
+ from sklearn.pipeline import Pipeline
11
+ from sklearn.svm import LinearSVC
12
+
13
+
14
+ def _logreg(seed: int) -> ClassifierMixin:
15
+ return LogisticRegression(max_iter=2000, class_weight="balanced", random_state=seed)
16
+
17
+
18
+ def _svm(seed: int) -> ClassifierMixin:
19
+ return LinearSVC(class_weight="balanced", random_state=seed)
20
+
21
+
22
+ def _cnb(seed: int) -> ClassifierMixin: # deterministic, seed unused
23
+ return ComplementNB()
24
+
25
+
26
+ MODELS: Dict[str, Callable[[int], ClassifierMixin]] = {
27
+ "svm": _svm,
28
+ "logreg": _logreg,
29
+ "complement_nb": _cnb,
30
+ }
31
+
32
+ MODEL_LABELS = {
33
+ "svm": "Linear SVM",
34
+ "logreg": "Logistic regression",
35
+ "complement_nb": "Complement naive Bayes",
36
+ }
37
+
38
+ FEATURES: Dict[str, Dict[str, object]] = {
39
+ "word_1_2": {"analyzer": "word", "ngram_range": (1, 2), "min_df": 1, "sublinear_tf": True},
40
+ "word_1": {"analyzer": "word", "ngram_range": (1, 1), "min_df": 1, "sublinear_tf": True},
41
+ "char_2_5": {"analyzer": "char_wb", "ngram_range": (2, 5), "min_df": 2, "sublinear_tf": True},
42
+ }
43
+
44
+ FEATURE_LABELS = {
45
+ "word_1_2": "Word unigrams + bigrams (TF-IDF)",
46
+ "word_1": "Word unigrams (TF-IDF)",
47
+ "char_2_5": "Character 2-5-grams (TF-IDF)",
48
+ }
49
+
50
+
51
+ def register_model(name: str, factory: Callable[[int], ClassifierMixin], label: str = "") -> None:
52
+ """Register a custom scikit-learn compatible classifier factory ``seed -> estimator``."""
53
+ MODELS[name] = factory
54
+ MODEL_LABELS[name] = label or name
55
+
56
+
57
+ def build_pipeline(model: str = "svm", features: str = "word_1_2", seed: int = 42) -> Pipeline:
58
+ """TF-IDF + classifier. The vectorizer is fitted inside each CV fold (no leakage)."""
59
+ if model not in MODELS:
60
+ raise KeyError(f"Unknown model {model!r}; choose from {list(MODELS)}")
61
+ if features not in FEATURES:
62
+ raise KeyError(f"Unknown features {features!r}; choose from {list(FEATURES)}")
63
+ params = dict(FEATURES[features])
64
+ if params["analyzer"] == "word":
65
+ params["token_pattern"] = r"(?u)\b\w+\b" # keep one-letter words such as و
66
+ vec = TfidfVectorizer(**params)
67
+ return Pipeline([("tfidf", vec), ("clf", MODELS[model](seed))])
@@ -0,0 +1,51 @@
1
+ """Negation marking.
2
+
3
+ A bag-of-words model reads "مش طيب" (not good) as the word "طيب" (good) plus a
4
+ word that tells it little. Marking the words that follow a negation turns
5
+ them into different features: "مش طيب" becomes "مش NEG_طيب", so the model can
6
+ learn that "NEG_طيب" points the other way.
7
+
8
+ This is the classic approach of Das and Chen (2001) and Pang, Lee and
9
+ Vaithyanathan (2002), adapted to Arabic negation words in MSA and the main
10
+ dialects. The scope is the next two words. On our test sentences a scope of
11
+ two words got more negated sentences right than one or three, with no change
12
+ in the cross-validated score.
13
+
14
+ Known gaps: "ما" also starts exclamations (ما أجمل = how beautiful); negation
15
+ written joined to the verb (مابنصح) is not split; and when small words such as
16
+ بس (but) have already been removed, the two words can reach past the end of
17
+ the negated phrase. The experiment measures whether the step helps on a given
18
+ dataset, so these cases show up in the results instead of being assumed away.
19
+ """
20
+ from __future__ import annotations
21
+
22
+ from .dialect import _lookup_key
23
+
24
+ MARK = "NEG_"
25
+
26
+ #: MSA and dialect negation words. ماشي is left out on purpose: in Egyptian it means "okay".
27
+ NEGATIONS = frozenset(
28
+ "ما مش مو مب مفيش مافي مافيش ماكانش مانيش لا ولا لم لن ليس لست ليست ليسوا".split()
29
+ )
30
+ _NEG_KEYS = frozenset(_lookup_key(w) for w in NEGATIONS)
31
+
32
+
33
+ def is_negation(token: str) -> bool:
34
+ """True if the token is a negation word, whatever its alef or hamza spelling."""
35
+ return _lookup_key(token) in _NEG_KEYS
36
+
37
+
38
+ def mark_negation(text: str, scope: int = 2) -> str:
39
+ """Prefix the ``scope`` words after each negation word with ``NEG_``."""
40
+ out = []
41
+ left = 0
42
+ for token in text.split():
43
+ if is_negation(token):
44
+ out.append(token)
45
+ left = scope
46
+ elif left:
47
+ out.append(token if token.startswith(MARK) else MARK + token)
48
+ left -= 1
49
+ else:
50
+ out.append(token)
51
+ return " ".join(out)