textray 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.
- textray/__init__.py +16 -0
- textray/core/__init__.py +5 -0
- textray/core/analyzer.py +616 -0
- textray/core/cv.py +215 -0
- textray/core/html_assets.py +133 -0
- textray/core/result.py +348 -0
- textray/core/text_utils.py +295 -0
- textray/core/validation.py +247 -0
- textray/datasets/__init__.py +5 -0
- textray/datasets/synthetic.py +147 -0
- textray/diagnostics/__init__.py +1 -0
- textray/diagnostics/artifacts.py +477 -0
- textray/diagnostics/duplicates.py +301 -0
- textray/diagnostics/embeddings.py +466 -0
- textray/diagnostics/lexical.py +718 -0
- textray/diagnostics/model_errors.py +466 -0
- textray/diagnostics/pos.py +365 -0
- textray/diagnostics/summary.py +226 -0
- textray/diagnostics/surrogates.py +485 -0
- textray/report/__init__.py +5 -0
- textray/report/builder.py +208 -0
- textray/report/templates/report.html.j2 +199 -0
- textray/visuals/__init__.py +23 -0
- textray/visuals/artifact_charts.py +280 -0
- textray/visuals/embedding_charts.py +113 -0
- textray/visuals/error_charts.py +243 -0
- textray/visuals/lexical_charts.py +491 -0
- textray/visuals/theme.py +179 -0
- textray/visuals/tree_chart.py +290 -0
- textray-0.1.0.dist-info/METADATA +483 -0
- textray-0.1.0.dist-info/RECORD +33 -0
- textray-0.1.0.dist-info/WHEEL +4 -0
- textray-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
"""Tokenization, stopword resolution, term masking, and compiled artifact patterns."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from collections.abc import Iterable
|
|
7
|
+
|
|
8
|
+
import pandas as pd
|
|
9
|
+
from sklearn.feature_extraction.text import ENGLISH_STOP_WORDS
|
|
10
|
+
|
|
11
|
+
WORD_RE = re.compile(r"\b[a-zA-Z][a-zA-Z0-9'_]{1,}\b")
|
|
12
|
+
TOKEN_RE = re.compile(r"\b\w+\b")
|
|
13
|
+
|
|
14
|
+
# Token pattern shared by every CountVectorizer / TfidfVectorizer in textray.
|
|
15
|
+
VECTORIZER_TOKEN_PATTERN = r"(?u)\b[a-zA-Z0-9][a-zA-Z0-9'_]+\b"
|
|
16
|
+
|
|
17
|
+
_MONTH_ANY = (
|
|
18
|
+
r"(?:jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|june?|july?|aug(?:ust)?|"
|
|
19
|
+
r"sep(?:t(?:ember)?)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?)"
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
# Compiled regex artifact patterns for leakage / spurious signal scanning
|
|
23
|
+
ARTIFACT_PATTERNS: dict[str, re.Pattern[str]] = {
|
|
24
|
+
# Month names. "may" and "march" are ordinary English words, and short forms such as
|
|
25
|
+
# "mar"/"dec"/"jan" are ambiguous, so those only count when next to a day number or a year.
|
|
26
|
+
"months": re.compile(
|
|
27
|
+
r"\b(?:january|february|april|june|july|august|september|october|november|december)\b"
|
|
28
|
+
r"|\b" + _MONTH_ANY + r"\.?\s+(?:\d{1,2}(?:st|nd|rd|th)?|(?:19|20)\d{2})\b"
|
|
29
|
+
r"|\b\d{1,2}(?:st|nd|rd|th)?\s+(?:of\s+)?" + _MONTH_ANY + r"\b",
|
|
30
|
+
re.IGNORECASE,
|
|
31
|
+
),
|
|
32
|
+
"numeric_dates": re.compile(
|
|
33
|
+
r"\b(?:\d{4}[-/]\d{1,2}[-/]\d{1,2}|\d{1,2}[-/]\d{1,2}[-/]\d{2,4})\b"
|
|
34
|
+
),
|
|
35
|
+
"years": re.compile(r"\b(?:19|20)\d{2}\b"),
|
|
36
|
+
"times": re.compile(r"\b\d{1,2}:\d{2}(?::\d{2})?\s*(?:am|pm|utc|est|pst)?\b", re.IGNORECASE),
|
|
37
|
+
"page_numbers": re.compile(
|
|
38
|
+
r"\b(?:page|pg\.?|p\.)\s*\d+(?:\s*(?:of|/)\s*\d+)?\b", re.IGNORECASE
|
|
39
|
+
),
|
|
40
|
+
"currency": re.compile(
|
|
41
|
+
r"(?:[$€£¥]\s*\d[\d,]*(?:\.\d+)?|\b\d[\d,]*(?:\.\d+)?\s*(?:usd|eur|gbp|dollars?)\b)",
|
|
42
|
+
re.IGNORECASE,
|
|
43
|
+
),
|
|
44
|
+
"urls": re.compile(r"(?:https?://\S+|www\.\S+)", re.IGNORECASE),
|
|
45
|
+
"emails": re.compile(r"\b[\w.+-]+@[\w-]+\.[\w.-]+\b"),
|
|
46
|
+
"ids_or_codes": re.compile(r"\b[A-Z]{2,5}[-_#]\d{2,}\b"),
|
|
47
|
+
"all_caps_words": re.compile(r"\b[A-Z]{3,}\b"),
|
|
48
|
+
"bracketed_tags": re.compile(r"\[[^\]]{2,40}\]"),
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
# ~40 high-frequency function words: removes grammatical glue but keeps negations, pronouns,
|
|
53
|
+
# modals and quantifiers, which often carry class signal (e.g. "not", "never", "you").
|
|
54
|
+
SHORT_STOP_WORDS: frozenset[str] = frozenset(
|
|
55
|
+
[
|
|
56
|
+
"a",
|
|
57
|
+
"an",
|
|
58
|
+
"and",
|
|
59
|
+
"are",
|
|
60
|
+
"as",
|
|
61
|
+
"at",
|
|
62
|
+
"be",
|
|
63
|
+
"been",
|
|
64
|
+
"being",
|
|
65
|
+
"by",
|
|
66
|
+
"for",
|
|
67
|
+
"from",
|
|
68
|
+
"had",
|
|
69
|
+
"has",
|
|
70
|
+
"have",
|
|
71
|
+
"in",
|
|
72
|
+
"into",
|
|
73
|
+
"is",
|
|
74
|
+
"it",
|
|
75
|
+
"its",
|
|
76
|
+
"of",
|
|
77
|
+
"on",
|
|
78
|
+
"or",
|
|
79
|
+
"that",
|
|
80
|
+
"the",
|
|
81
|
+
"their",
|
|
82
|
+
"them",
|
|
83
|
+
"then",
|
|
84
|
+
"there",
|
|
85
|
+
"these",
|
|
86
|
+
"they",
|
|
87
|
+
"this",
|
|
88
|
+
"those",
|
|
89
|
+
"to",
|
|
90
|
+
"was",
|
|
91
|
+
"were",
|
|
92
|
+
"which",
|
|
93
|
+
"with",
|
|
94
|
+
]
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
# scikit-learn's 318-word English list plus contractions and chatty filler common in
|
|
98
|
+
# emails, tickets and transcripts.
|
|
99
|
+
LONG_STOP_WORDS: frozenset[str] = frozenset(ENGLISH_STOP_WORDS) | frozenset(
|
|
100
|
+
[
|
|
101
|
+
"i'm",
|
|
102
|
+
"i've",
|
|
103
|
+
"i'd",
|
|
104
|
+
"i'll",
|
|
105
|
+
"you're",
|
|
106
|
+
"you've",
|
|
107
|
+
"you'd",
|
|
108
|
+
"you'll",
|
|
109
|
+
"he's",
|
|
110
|
+
"she's",
|
|
111
|
+
"it's",
|
|
112
|
+
"we're",
|
|
113
|
+
"we've",
|
|
114
|
+
"we'd",
|
|
115
|
+
"we'll",
|
|
116
|
+
"they're",
|
|
117
|
+
"they've",
|
|
118
|
+
"they'd",
|
|
119
|
+
"they'll",
|
|
120
|
+
"that's",
|
|
121
|
+
"there's",
|
|
122
|
+
"here's",
|
|
123
|
+
"what's",
|
|
124
|
+
"who's",
|
|
125
|
+
"let's",
|
|
126
|
+
"isn't",
|
|
127
|
+
"aren't",
|
|
128
|
+
"wasn't",
|
|
129
|
+
"weren't",
|
|
130
|
+
"hasn't",
|
|
131
|
+
"haven't",
|
|
132
|
+
"hadn't",
|
|
133
|
+
"doesn't",
|
|
134
|
+
"don't",
|
|
135
|
+
"didn't",
|
|
136
|
+
"won't",
|
|
137
|
+
"wouldn't",
|
|
138
|
+
"shan't",
|
|
139
|
+
"shouldn't",
|
|
140
|
+
"can't",
|
|
141
|
+
"cannot",
|
|
142
|
+
"couldn't",
|
|
143
|
+
"mustn't",
|
|
144
|
+
"im",
|
|
145
|
+
"ive",
|
|
146
|
+
"id",
|
|
147
|
+
"youre",
|
|
148
|
+
"theyre",
|
|
149
|
+
"thats",
|
|
150
|
+
"theres",
|
|
151
|
+
"dont",
|
|
152
|
+
"doesnt",
|
|
153
|
+
"didnt",
|
|
154
|
+
"isnt",
|
|
155
|
+
"arent",
|
|
156
|
+
"wasnt",
|
|
157
|
+
"werent",
|
|
158
|
+
"cant",
|
|
159
|
+
"couldnt",
|
|
160
|
+
"wouldnt",
|
|
161
|
+
"shouldnt",
|
|
162
|
+
"wont",
|
|
163
|
+
"also",
|
|
164
|
+
"just",
|
|
165
|
+
"like",
|
|
166
|
+
"really",
|
|
167
|
+
"get",
|
|
168
|
+
"got",
|
|
169
|
+
"gets",
|
|
170
|
+
"getting",
|
|
171
|
+
"go",
|
|
172
|
+
"going",
|
|
173
|
+
"goes",
|
|
174
|
+
"went",
|
|
175
|
+
"gone",
|
|
176
|
+
"make",
|
|
177
|
+
"made",
|
|
178
|
+
"makes",
|
|
179
|
+
"say",
|
|
180
|
+
"said",
|
|
181
|
+
"says",
|
|
182
|
+
"use",
|
|
183
|
+
"used",
|
|
184
|
+
"using",
|
|
185
|
+
"one",
|
|
186
|
+
"two",
|
|
187
|
+
"us",
|
|
188
|
+
"may",
|
|
189
|
+
"might",
|
|
190
|
+
"shall",
|
|
191
|
+
"would",
|
|
192
|
+
"could",
|
|
193
|
+
"ok",
|
|
194
|
+
"okay",
|
|
195
|
+
"yes",
|
|
196
|
+
"yeah",
|
|
197
|
+
"hi",
|
|
198
|
+
"hello",
|
|
199
|
+
"thanks",
|
|
200
|
+
"thank",
|
|
201
|
+
"please",
|
|
202
|
+
"regards",
|
|
203
|
+
"dear",
|
|
204
|
+
]
|
|
205
|
+
)
|
|
206
|
+
|
|
207
|
+
STOPWORD_PRESETS: dict[str, frozenset[str]] = {
|
|
208
|
+
"short": SHORT_STOP_WORDS,
|
|
209
|
+
"english": frozenset(ENGLISH_STOP_WORDS),
|
|
210
|
+
"long": LONG_STOP_WORDS,
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
# Everything the "no dates" ablation removes: month mentions, numeric dates, years and times.
|
|
215
|
+
DATE_PATTERNS: tuple[str, ...] = ("months", "numeric_dates", "years", "times")
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def strip_dates(texts: pd.Series) -> pd.Series:
|
|
219
|
+
"""Replace month mentions, numeric dates, years and clock times with a space."""
|
|
220
|
+
out = texts
|
|
221
|
+
for name in DATE_PATTERNS:
|
|
222
|
+
out = out.str.replace(ARTIFACT_PATTERNS[name], " ", regex=True)
|
|
223
|
+
return out
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def resolve_stopwords(stopwords: str | Iterable[str] | None) -> frozenset[str]:
|
|
227
|
+
"""Normalize a stopword specification into a lowercase frozenset.
|
|
228
|
+
|
|
229
|
+
Presets: ``"short"`` (~40 function words), ``"english"`` (scikit-learn's 318 words, the
|
|
230
|
+
default) and ``"long"`` (``"english"`` plus contractions and conversational filler).
|
|
231
|
+
``None`` disables stopword removal; any iterable is used as a custom list.
|
|
232
|
+
"""
|
|
233
|
+
if stopwords is None:
|
|
234
|
+
return frozenset()
|
|
235
|
+
if isinstance(stopwords, str):
|
|
236
|
+
preset = STOPWORD_PRESETS.get(stopwords.strip().lower())
|
|
237
|
+
if preset is not None:
|
|
238
|
+
return preset
|
|
239
|
+
raise ValueError(
|
|
240
|
+
f"Unsupported stopwords preset '{stopwords}'. Use one of "
|
|
241
|
+
f"{sorted(STOPWORD_PRESETS)}, None, or an iterable of words."
|
|
242
|
+
)
|
|
243
|
+
return frozenset(str(w).strip().lower() for w in stopwords if str(w).strip())
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def merge_exclude_terms(
|
|
247
|
+
base_terms: Iterable[str] | None,
|
|
248
|
+
extra_terms: Iterable[str] | None,
|
|
249
|
+
) -> tuple[str, ...]:
|
|
250
|
+
"""Combine and deduplicate excluded terms into a deterministic sorted tuple."""
|
|
251
|
+
merged: set[str] = set()
|
|
252
|
+
for src in (base_terms, extra_terms):
|
|
253
|
+
if src is None:
|
|
254
|
+
continue
|
|
255
|
+
for term in src:
|
|
256
|
+
cleaned = str(term).strip().lower()
|
|
257
|
+
if cleaned:
|
|
258
|
+
merged.add(cleaned)
|
|
259
|
+
return tuple(sorted(merged))
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def mask_terms_series(texts: pd.Series, exclude_terms: Iterable[str] | None) -> pd.Series:
|
|
263
|
+
"""Mask excluded unigrams or multi-word phrases from a text Series (case-insensitive)."""
|
|
264
|
+
terms = merge_exclude_terms(exclude_terms, None)
|
|
265
|
+
if not terms:
|
|
266
|
+
return texts
|
|
267
|
+
# Match longer phrases before shorter substrings
|
|
268
|
+
ordered = sorted(terms, key=len, reverse=True)
|
|
269
|
+
pattern = re.compile(
|
|
270
|
+
r"(?<!\w)(?:" + "|".join(re.escape(t) for t in ordered) + r")(?!\w)",
|
|
271
|
+
re.IGNORECASE,
|
|
272
|
+
)
|
|
273
|
+
return texts.str.replace(pattern, " ", regex=True)
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def tokenize_words(
|
|
277
|
+
text: str,
|
|
278
|
+
stopwords: frozenset[str] = frozenset(),
|
|
279
|
+
lowercase: bool = True,
|
|
280
|
+
) -> list[str]:
|
|
281
|
+
"""Extract alphabetic/alphanumeric word tokens from a string."""
|
|
282
|
+
tokens = WORD_RE.findall(text)
|
|
283
|
+
if lowercase:
|
|
284
|
+
tokens = [t.lower() for t in tokens]
|
|
285
|
+
if stopwords:
|
|
286
|
+
tokens = [t for t in tokens if t.lower() not in stopwords]
|
|
287
|
+
return tokens
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def truncate_snippet(text: str, max_chars: int = 180) -> str:
|
|
291
|
+
"""Compact whitespace and truncate a document for readable tooltips and tables."""
|
|
292
|
+
compact = " ".join(text.split())
|
|
293
|
+
if len(compact) <= max_chars:
|
|
294
|
+
return compact
|
|
295
|
+
return compact[: max_chars - 1].rstrip() + "…"
|
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
"""Input validation and binary label / prediction normalization."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import warnings
|
|
6
|
+
from collections.abc import Sequence
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
import numpy as np
|
|
11
|
+
import pandas as pd
|
|
12
|
+
|
|
13
|
+
_COMMON_POSITIVE_STRINGS = {
|
|
14
|
+
"1",
|
|
15
|
+
"true",
|
|
16
|
+
"yes",
|
|
17
|
+
"pos",
|
|
18
|
+
"positive",
|
|
19
|
+
"spam",
|
|
20
|
+
"fraud",
|
|
21
|
+
"urgent",
|
|
22
|
+
"toxic",
|
|
23
|
+
"churn",
|
|
24
|
+
"anomaly",
|
|
25
|
+
"target",
|
|
26
|
+
"flagged",
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True)
|
|
31
|
+
class ValidatedDataset:
|
|
32
|
+
"""Normalized internal dataset representation used by all diagnostics."""
|
|
33
|
+
|
|
34
|
+
df: pd.DataFrame
|
|
35
|
+
texts: pd.Series
|
|
36
|
+
y: np.ndarray # binary 0/1 int8 array
|
|
37
|
+
class_labels: pd.Series # display names (pos_name / neg_name)
|
|
38
|
+
positive_label: Any
|
|
39
|
+
negative_label: Any
|
|
40
|
+
pos_name: str
|
|
41
|
+
neg_name: str
|
|
42
|
+
y_pred: np.ndarray | None
|
|
43
|
+
y_proba: np.ndarray | None
|
|
44
|
+
splits: pd.Series | None
|
|
45
|
+
n_missing_text: int
|
|
46
|
+
n_dropped_null_labels: int
|
|
47
|
+
# Index labels of the analysed rows in the caller's DataFrame, in analysis order.
|
|
48
|
+
source_index: pd.Index
|
|
49
|
+
|
|
50
|
+
def index_labels(self, positions: Any) -> np.ndarray:
|
|
51
|
+
"""Map row positions in the analysed data to index labels of the caller's DataFrame.
|
|
52
|
+
|
|
53
|
+
Every ``doc_index`` / ``doc_idx_*`` column in textray results holds these labels, so
|
|
54
|
+
``df.loc[result.data["doc_index"]]`` returns the original rows even when rows with
|
|
55
|
+
missing labels were dropped, the frame was shuffled, or it has a custom index.
|
|
56
|
+
"""
|
|
57
|
+
return self.source_index.to_numpy()[np.asarray(positions, dtype=np.int64)]
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def validate_inputs(
|
|
61
|
+
df: pd.DataFrame,
|
|
62
|
+
text_col: str,
|
|
63
|
+
label_col: str,
|
|
64
|
+
positive_label: Any = None,
|
|
65
|
+
y_pred: str | Sequence[Any] | np.ndarray | pd.Series | None = None,
|
|
66
|
+
y_proba: str | Sequence[float] | np.ndarray | pd.Series | None = None,
|
|
67
|
+
split_col: str | None = None,
|
|
68
|
+
) -> ValidatedDataset:
|
|
69
|
+
"""Validate and normalize inputs for binary text classification diagnostics."""
|
|
70
|
+
if not isinstance(df, pd.DataFrame):
|
|
71
|
+
raise TypeError(f"Expected a pandas DataFrame, got {type(df).__name__}.")
|
|
72
|
+
if df.empty:
|
|
73
|
+
raise ValueError("Input DataFrame is empty.")
|
|
74
|
+
if text_col not in df.columns:
|
|
75
|
+
raise ValueError(f"text_col '{text_col}' not found in DataFrame columns.")
|
|
76
|
+
if label_col not in df.columns:
|
|
77
|
+
raise ValueError(f"label_col '{label_col}' not found in DataFrame columns.")
|
|
78
|
+
if split_col is not None and split_col not in df.columns:
|
|
79
|
+
raise ValueError(f"split_col '{split_col}' not found in DataFrame columns.")
|
|
80
|
+
|
|
81
|
+
raw_len = len(df)
|
|
82
|
+
valid_mask = df[label_col].notna().to_numpy()
|
|
83
|
+
n_dropped_null_labels = int(raw_len - valid_mask.sum())
|
|
84
|
+
|
|
85
|
+
work_df = df.loc[valid_mask].copy().reset_index(drop=True)
|
|
86
|
+
if work_df.empty:
|
|
87
|
+
raise ValueError(f"Column '{label_col}' contains only missing values.")
|
|
88
|
+
source_index = df.index[valid_mask]
|
|
89
|
+
if not source_index.is_unique:
|
|
90
|
+
warnings.warn(
|
|
91
|
+
"The DataFrame index has duplicate labels, so `doc_index` values in textray results "
|
|
92
|
+
"can match more than one row. Call `df.reset_index()` first for unique row ids.",
|
|
93
|
+
UserWarning,
|
|
94
|
+
stacklevel=3,
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
unique_labels = pd.unique(work_df[label_col]).tolist()
|
|
98
|
+
if len(unique_labels) != 2:
|
|
99
|
+
raise ValueError(
|
|
100
|
+
f"textray v0.1 supports binary classification (exactly 2 unique non-null labels), "
|
|
101
|
+
f"but '{label_col}' has {len(unique_labels)} unique values: {unique_labels[:10]}."
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
pos_label, neg_label = _resolve_binary_labels(unique_labels, positive_label)
|
|
105
|
+
pos_name = str(pos_label)
|
|
106
|
+
neg_name = str(neg_label)
|
|
107
|
+
if pos_name == neg_name:
|
|
108
|
+
pos_name = f"{pos_label!r} (pos)"
|
|
109
|
+
neg_name = f"{neg_label!r} (neg)"
|
|
110
|
+
|
|
111
|
+
y = (work_df[label_col] == pos_label).to_numpy(dtype=np.int8)
|
|
112
|
+
class_labels = pd.Series(
|
|
113
|
+
np.where(y == 1, pos_name, neg_name),
|
|
114
|
+
index=work_df.index,
|
|
115
|
+
name="class_label",
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
raw_texts = work_df[text_col]
|
|
119
|
+
n_missing_text = int(raw_texts.isna().sum())
|
|
120
|
+
texts = raw_texts.fillna("").astype(str)
|
|
121
|
+
|
|
122
|
+
# Resolve optional y_proba and y_pred
|
|
123
|
+
proba_arr = _resolve_proba(df, valid_mask, y_proba)
|
|
124
|
+
pred_arr = _resolve_pred(df, valid_mask, y_pred, pos_label, neg_label, proba_arr)
|
|
125
|
+
|
|
126
|
+
splits = work_df[split_col].astype(str) if split_col is not None else None
|
|
127
|
+
|
|
128
|
+
return ValidatedDataset(
|
|
129
|
+
df=work_df,
|
|
130
|
+
texts=texts,
|
|
131
|
+
y=y,
|
|
132
|
+
class_labels=class_labels,
|
|
133
|
+
positive_label=pos_label,
|
|
134
|
+
negative_label=neg_label,
|
|
135
|
+
pos_name=pos_name,
|
|
136
|
+
neg_name=neg_name,
|
|
137
|
+
y_pred=pred_arr,
|
|
138
|
+
y_proba=proba_arr,
|
|
139
|
+
splits=splits,
|
|
140
|
+
n_missing_text=n_missing_text,
|
|
141
|
+
n_dropped_null_labels=n_dropped_null_labels,
|
|
142
|
+
source_index=source_index,
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _resolve_binary_labels(unique_labels: list[Any], positive_label: Any) -> tuple[Any, Any]:
|
|
147
|
+
a, b = unique_labels[0], unique_labels[1]
|
|
148
|
+
|
|
149
|
+
if positive_label is not None:
|
|
150
|
+
if positive_label == a:
|
|
151
|
+
return a, b
|
|
152
|
+
if positive_label == b:
|
|
153
|
+
return b, a
|
|
154
|
+
raise ValueError(f"positive_label={positive_label!r} not found in label values {[a, b]!r}.")
|
|
155
|
+
|
|
156
|
+
# Boolean / numeric 0-1 fast paths
|
|
157
|
+
label_set = {a, b}
|
|
158
|
+
if label_set == {0, 1}:
|
|
159
|
+
return (1, 0) if not isinstance(a, bool) and not isinstance(b, bool) else (True, False)
|
|
160
|
+
if label_set == {False, True}:
|
|
161
|
+
return True, False
|
|
162
|
+
|
|
163
|
+
# Common positive string heuristics
|
|
164
|
+
a_str = str(a).strip().lower()
|
|
165
|
+
b_str = str(b).strip().lower()
|
|
166
|
+
a_is_pos = a_str in _COMMON_POSITIVE_STRINGS
|
|
167
|
+
b_is_pos = b_str in _COMMON_POSITIVE_STRINGS
|
|
168
|
+
if a_is_pos and not b_is_pos:
|
|
169
|
+
return a, b
|
|
170
|
+
if b_is_pos and not a_is_pos:
|
|
171
|
+
return b, a
|
|
172
|
+
|
|
173
|
+
# Deterministic fallback: sorted order (second is positive, matching sklearn convention)
|
|
174
|
+
try:
|
|
175
|
+
ordered = sorted([a, b])
|
|
176
|
+
return ordered[1], ordered[0]
|
|
177
|
+
except TypeError:
|
|
178
|
+
ordered_str = sorted([a, b], key=str)
|
|
179
|
+
return ordered_str[1], ordered_str[0]
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def _resolve_proba(
|
|
183
|
+
df: pd.DataFrame,
|
|
184
|
+
valid_mask: np.ndarray,
|
|
185
|
+
y_proba: str | Sequence[float] | np.ndarray | pd.Series | None,
|
|
186
|
+
) -> np.ndarray | None:
|
|
187
|
+
if y_proba is None:
|
|
188
|
+
return None
|
|
189
|
+
if isinstance(y_proba, str):
|
|
190
|
+
if y_proba not in df.columns:
|
|
191
|
+
raise ValueError(f"y_proba column '{y_proba}' not found in DataFrame.")
|
|
192
|
+
arr = df[y_proba].to_numpy(dtype=float)
|
|
193
|
+
else:
|
|
194
|
+
arr = np.asarray(y_proba, dtype=float)
|
|
195
|
+
if arr.ndim == 2 and len(arr.shape) == 2 and arr.shape[1] == 2:
|
|
196
|
+
arr = arr[:, 1]
|
|
197
|
+
if arr.ndim != 1:
|
|
198
|
+
raise ValueError(f"y_proba must be 1D (or 2D with 2 columns), got shape {arr.shape}.")
|
|
199
|
+
if len(arr) != len(df):
|
|
200
|
+
raise ValueError(
|
|
201
|
+
f"y_proba length ({len(arr)}) does not match DataFrame length ({len(df)})."
|
|
202
|
+
)
|
|
203
|
+
arr = arr[valid_mask]
|
|
204
|
+
if np.isnan(arr).any():
|
|
205
|
+
raise ValueError("y_proba contains NaN values on rows with valid labels.")
|
|
206
|
+
if (arr < 0.0).any() or (arr > 1.0).any():
|
|
207
|
+
raise ValueError("y_proba values must lie in [0.0, 1.0].")
|
|
208
|
+
return arr
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _resolve_pred(
|
|
212
|
+
df: pd.DataFrame,
|
|
213
|
+
valid_mask: np.ndarray,
|
|
214
|
+
y_pred: str | Sequence[Any] | np.ndarray | pd.Series | None,
|
|
215
|
+
pos_label: Any,
|
|
216
|
+
neg_label: Any,
|
|
217
|
+
proba_arr: np.ndarray | None,
|
|
218
|
+
) -> np.ndarray | None:
|
|
219
|
+
if y_pred is None:
|
|
220
|
+
if proba_arr is not None:
|
|
221
|
+
return (proba_arr >= 0.5).astype(np.int8)
|
|
222
|
+
return None
|
|
223
|
+
|
|
224
|
+
if isinstance(y_pred, str):
|
|
225
|
+
if y_pred not in df.columns:
|
|
226
|
+
raise ValueError(f"y_pred column '{y_pred}' not found in DataFrame.")
|
|
227
|
+
raw = df[y_pred].to_numpy()
|
|
228
|
+
else:
|
|
229
|
+
raw = np.asarray(y_pred)
|
|
230
|
+
if raw.ndim != 1:
|
|
231
|
+
raise ValueError(f"y_pred must be 1D, got shape {raw.shape}.")
|
|
232
|
+
|
|
233
|
+
if len(raw) != len(df):
|
|
234
|
+
raise ValueError(f"y_pred length ({len(raw)}) does not match DataFrame length ({len(df)}).")
|
|
235
|
+
raw = raw[valid_mask]
|
|
236
|
+
|
|
237
|
+
# Map values to 0/1 supporting either original label space or binary 0/1
|
|
238
|
+
unique_pred = set(pd.unique(raw).tolist())
|
|
239
|
+
if unique_pred.issubset({pos_label, neg_label}):
|
|
240
|
+
return (raw == pos_label).astype(np.int8)
|
|
241
|
+
if unique_pred.issubset({0, 1}):
|
|
242
|
+
return raw.astype(np.int8)
|
|
243
|
+
|
|
244
|
+
raise ValueError(
|
|
245
|
+
f"y_pred contains unrecognized labels {sorted(unique_pred, key=str)}; "
|
|
246
|
+
f"expected values in {{{neg_label!r}, {pos_label!r}}} or {{0, 1}}."
|
|
247
|
+
)
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
"""Synthetic binary text classification dataset with planted artifacts and leakage."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
import pandas as pd
|
|
7
|
+
|
|
8
|
+
_POS_TOPICS = [
|
|
9
|
+
"production database latency spiked causing checkout timeouts across regional nodes",
|
|
10
|
+
"critical authentication service outage prevented enterprise customers from signing in",
|
|
11
|
+
"memory leak in payment worker triggered repeated container restarts and failed orders",
|
|
12
|
+
"security audit flagged unauthorized token access on billing webhook endpoint",
|
|
13
|
+
"primary cluster failover stalled during peak traffic leaving queues backlogged",
|
|
14
|
+
"corrupted index in analytics pipeline broke daily revenue reconciliation reports",
|
|
15
|
+
"gateway certificate expiration disrupted mobile api requests for external partners",
|
|
16
|
+
"deadlock in inventory reservation table blocked warehouse fulfillment updates",
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
_NEG_TOPICS = [
|
|
20
|
+
"monthly newsletter highlights upcoming product webinars and community tutorials",
|
|
21
|
+
"routine documentation refresh clarifies onboarding steps for new workspace admins",
|
|
22
|
+
"quarterly design review shared updated icon library and typography spacing guide",
|
|
23
|
+
"scheduled office hours answered customer questions about dashboard export options",
|
|
24
|
+
"minor tooltip phrasing adjustment improves readability on billing settings page",
|
|
25
|
+
"team retrospective summarized sprint velocity and planned upcoming backlog grooming",
|
|
26
|
+
"training workshop introduced keyboard shortcuts and saved filter templates",
|
|
27
|
+
"general status update confirms standard maintenance window completed smoothly",
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
_SHARED_FILLERS = [
|
|
31
|
+
"please review the attached summary and share feedback with the team",
|
|
32
|
+
"engineering and operations coordinated follow up actions during the morning sync",
|
|
33
|
+
"stakeholders requested clear visibility into timeline milestones and ownership",
|
|
34
|
+
"notes were archived in the shared workspace for future reference",
|
|
35
|
+
]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def make_leaky_dataset(
|
|
39
|
+
n_samples: int = 400,
|
|
40
|
+
random_state: int = 42,
|
|
41
|
+
include_predictions: bool = True,
|
|
42
|
+
include_splits: bool = True,
|
|
43
|
+
) -> pd.DataFrame:
|
|
44
|
+
"""Generate a realistic binary text dataset with planted leakage & artifacts.
|
|
45
|
+
|
|
46
|
+
Planted diagnostics targets:
|
|
47
|
+
- **Date leakage**: ``"August 2024"`` / ``"August"`` appears disproportionately in Positive docs.
|
|
48
|
+
- **Header/footer boilerplate**: ``"[INTERNAL ESCALATION]"`` prefix & ``"Page X of 12"`` footer in Positive docs.
|
|
49
|
+
- **Structural/length bias**: Positive docs carry extra reference numbers and slightly more words.
|
|
50
|
+
- **Exact & near-duplicates**: Includes within-class duplicates, cross-class label conflicts,
|
|
51
|
+
and train/test split duplicates.
|
|
52
|
+
- **Label noise**: ~3% flipped labels to test ``label_issues()``.
|
|
53
|
+
- **Predictions** (optional): ``y_pred`` and ``y_proba`` simulating a shortcut-prone classifier.
|
|
54
|
+
|
|
55
|
+
Returns
|
|
56
|
+
-------
|
|
57
|
+
pandas.DataFrame
|
|
58
|
+
Columns: ``text``, ``label`` (``"urgent"`` / ``"routine"``), plus optional
|
|
59
|
+
``split``, ``y_proba``, and ``y_pred``.
|
|
60
|
+
"""
|
|
61
|
+
rng = np.random.default_rng(random_state)
|
|
62
|
+
n_pos = n_samples // 2
|
|
63
|
+
|
|
64
|
+
texts: list[str] = []
|
|
65
|
+
labels: list[str] = []
|
|
66
|
+
is_leaky: list[bool] = []
|
|
67
|
+
|
|
68
|
+
for i in range(n_samples):
|
|
69
|
+
pos = i < n_pos
|
|
70
|
+
label = "urgent" if pos else "routine"
|
|
71
|
+
filler = str(rng.choice(_SHARED_FILLERS))
|
|
72
|
+
|
|
73
|
+
if pos:
|
|
74
|
+
core = str(rng.choice(_POS_TOPICS))
|
|
75
|
+
extra_core = str(rng.choice(_POS_TOPICS)) if rng.random() < 0.55 else ""
|
|
76
|
+
# Planted date artifact ("August" / "August 2024") in ~68% of positive docs
|
|
77
|
+
leaky_date = rng.random() < 0.68
|
|
78
|
+
date_str = (
|
|
79
|
+
f"Filed in August 2024 (ticket INC-{rng.integers(1000, 9999)})."
|
|
80
|
+
if leaky_date
|
|
81
|
+
else f"Filed in {rng.choice(['March', 'April', 'October'])} 2024."
|
|
82
|
+
)
|
|
83
|
+
# Planted header/footer boilerplate
|
|
84
|
+
header = "[INTERNAL ESCALATION] " if rng.random() < 0.50 else ""
|
|
85
|
+
footer = f" Page {rng.integers(1, 12)} of 12." if rng.random() < 0.55 else ""
|
|
86
|
+
doc = f"{header}{core}. {extra_core} {date_str} {filler}.{footer}"
|
|
87
|
+
is_leaky.append(leaky_date)
|
|
88
|
+
else:
|
|
89
|
+
core = str(rng.choice(_NEG_TOPICS))
|
|
90
|
+
# Only ~4% of negative docs mention August
|
|
91
|
+
leaky_date = rng.random() < 0.04
|
|
92
|
+
month = (
|
|
93
|
+
"August"
|
|
94
|
+
if leaky_date
|
|
95
|
+
else str(
|
|
96
|
+
rng.choice(["January", "February", "March", "April", "May", "June", "November"])
|
|
97
|
+
)
|
|
98
|
+
)
|
|
99
|
+
doc = f"{core}. Logged in {month} 2024. {filler}."
|
|
100
|
+
is_leaky.append(leaky_date)
|
|
101
|
+
|
|
102
|
+
texts.append(" ".join(doc.split()))
|
|
103
|
+
labels.append(label)
|
|
104
|
+
|
|
105
|
+
# Plant exact duplicates and a cross-class label conflict if enough rows
|
|
106
|
+
if n_samples >= 40:
|
|
107
|
+
# Exact duplicates inside positive class
|
|
108
|
+
texts[n_pos - 1] = texts[0]
|
|
109
|
+
texts[n_pos - 2] = texts[1]
|
|
110
|
+
# Cross-class label conflict (same text labeled both urgent and routine)
|
|
111
|
+
texts[n_pos + 1] = texts[2]
|
|
112
|
+
texts[n_pos + 2] = texts[3]
|
|
113
|
+
|
|
114
|
+
df = pd.DataFrame({"text": texts, "label": labels})
|
|
115
|
+
|
|
116
|
+
# Shuffle deterministically while preserving a slight row-order skew for demo
|
|
117
|
+
perm = rng.permutation(len(df))
|
|
118
|
+
df = df.iloc[perm].reset_index(drop=True)
|
|
119
|
+
leaky_arr = np.asarray(is_leaky)[perm]
|
|
120
|
+
|
|
121
|
+
# Plant ~3% label noise
|
|
122
|
+
n_flip = max(2, int(0.03 * len(df)))
|
|
123
|
+
flip_idx = rng.choice(len(df), size=n_flip, replace=False)
|
|
124
|
+
true_is_pos = (df["label"] == "urgent").to_numpy()
|
|
125
|
+
df.loc[flip_idx, "label"] = np.where(df.loc[flip_idx, "label"] == "urgent", "routine", "urgent")
|
|
126
|
+
|
|
127
|
+
if include_splits:
|
|
128
|
+
n_train = int(0.8 * len(df))
|
|
129
|
+
splits = np.array(["train"] * n_train + ["test"] * (len(df) - n_train))
|
|
130
|
+
df["split"] = splits
|
|
131
|
+
# Plant explicit train/test duplicate leakage
|
|
132
|
+
if len(df) >= 40 and n_train < len(df) - 2:
|
|
133
|
+
df.loc[n_train, "text"] = df.loc[0, "text"]
|
|
134
|
+
df.loc[n_train, "label"] = df.loc[0, "label"]
|
|
135
|
+
df.loc[n_train + 1, "text"] = df.loc[1, "text"]
|
|
136
|
+
df.loc[n_train + 1, "label"] = df.loc[1, "label"]
|
|
137
|
+
|
|
138
|
+
if include_predictions:
|
|
139
|
+
# Simulate a model that predicts well overall, over-indexes on "August", and makes realistic errors
|
|
140
|
+
base_prob = np.where(true_is_pos, 0.80, 0.18)
|
|
141
|
+
base_prob = np.where(leaky_arr, np.clip(base_prob + 0.14, 0.02, 0.99), base_prob)
|
|
142
|
+
noise = rng.normal(0.0, 0.13, size=len(df))
|
|
143
|
+
y_proba = np.clip(base_prob + noise, 0.01, 0.99)
|
|
144
|
+
df["y_proba"] = np.round(y_proba, 4)
|
|
145
|
+
df["y_pred"] = np.where(y_proba >= 0.5, "urgent", "routine")
|
|
146
|
+
|
|
147
|
+
return df
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Diagnostic computation modules for textray."""
|