strable 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 (119) hide show
  1. strable/__init__.py +13 -0
  2. strable/data/folds/aca-federal-upper-limits-wide.parquet +0 -0
  3. strable/data/folds/aijob_ai-ml-ds-salaries.parquet +0 -0
  4. strable/data/folds/animalandveterinary-event.parquet +0 -0
  5. strable/data/folds/antenna-structure-registration.parquet +0 -0
  6. strable/data/folds/awarded-grants.parquet +0 -0
  7. strable/data/folds/beer-ratings.parquet +0 -0
  8. strable/data/folds/broadband-availability.parquet +0 -0
  9. strable/data/folds/california-houses.parquet +0 -0
  10. strable/data/folds/child-adult-healthcare-quality.parquet +0 -0
  11. strable/data/folds/china-overseas-finance-inventory.parquet +0 -0
  12. strable/data/folds/chocolate-bar-ratings.parquet +0 -0
  13. strable/data/folds/clear-corpus.parquet +0 -0
  14. strable/data/folds/cohort-default-rate.parquet +0 -0
  15. strable/data/folds/college-creditcard-marketing.parquet +0 -0
  16. strable/data/folds/college-deposit-product-marketing.parquet +0 -0
  17. strable/data/folds/colleges-and-universities.parquet +0 -0
  18. strable/data/folds/commitments-in-trust-funds.parquet +0 -0
  19. strable/data/folds/community-banking_wide.parquet +0 -0
  20. strable/data/folds/conflict-events_wide.parquet +0 -0
  21. strable/data/folds/contract-awards-investment-project-financing.parquet +0 -0
  22. strable/data/folds/contributions-to-financial-intermediary-funds.parquet +0 -0
  23. strable/data/folds/corporate-procurement-contract-awards.parquet +0 -0
  24. strable/data/folds/cosmetic-event.parquet +0 -0
  25. strable/data/folds/covid-clinical-trials.parquet +0 -0
  26. strable/data/folds/device-classification.parquet +0 -0
  27. strable/data/folds/device-covid19serology.parquet +0 -0
  28. strable/data/folds/device-pma.parquet +0 -0
  29. strable/data/folds/disbursements-in-trust-funds.parquet +0 -0
  30. strable/data/folds/discretionary-grant.parquet +0 -0
  31. strable/data/folds/drug-drugsfda.parquet +0 -0
  32. strable/data/folds/drug-enforcement.parquet +0 -0
  33. strable/data/folds/drug-ndc.parquet +0 -0
  34. strable/data/folds/drug-shortages.parquet +0 -0
  35. strable/data/folds/electric-generating-plants.parquet +0 -0
  36. strable/data/folds/electric-retail-service-territories.parquet +0 -0
  37. strable/data/folds/external-clinician-dashboard.parquet +0 -0
  38. strable/data/folds/financial-intermediary-funds-cash-transfers.parquet +0 -0
  39. strable/data/folds/financial-intermediary-funds-commitments.parquet +0 -0
  40. strable/data/folds/financial-intermediary-funds-funding-decisions.parquet +0 -0
  41. strable/data/folds/financial-management.parquet +0 -0
  42. strable/data/folds/financial-product-complaint.parquet +0 -0
  43. strable/data/folds/first-time-nadac-rates.parquet +0 -0
  44. strable/data/folds/food-enforcement.parquet +0 -0
  45. strable/data/folds/food-event.parquet +0 -0
  46. strable/data/folds/food-prices_wide.parquet +0 -0
  47. strable/data/folds/foreign-gift-and-contract.parquet +0 -0
  48. strable/data/folds/fts-funding.parquet +0 -0
  49. strable/data/folds/fts-requirement-and-funding.parquet +0 -0
  50. strable/data/folds/gainful-employment.parquet +0 -0
  51. strable/data/folds/global-dams-database.parquet +0 -0
  52. strable/data/folds/global-power-plant.parquet +0 -0
  53. strable/data/folds/grant.parquet +0 -0
  54. strable/data/folds/health-professional-shortage-areas.parquet +0 -0
  55. strable/data/folds/historic-perimeters-wildfires.parquet +0 -0
  56. strable/data/folds/historical-earthquake-locations.parquet +0 -0
  57. strable/data/folds/historical-volcanic-locations.parquet +0 -0
  58. strable/data/folds/hospitals.parquet +0 -0
  59. strable/data/folds/hypertension-control-wide.parquet +0 -0
  60. strable/data/folds/ibrd-statement-loans-guarantees.parquet +0 -0
  61. strable/data/folds/ida-statement-credits-grants-guarantees.parquet +0 -0
  62. strable/data/folds/ifc-advisory-services-projects.parquet +0 -0
  63. strable/data/folds/ifc-investment-service-projects.parquet +0 -0
  64. strable/data/folds/industry-payments-entity.parquet +0 -0
  65. strable/data/folds/industry-payments-project.parquet +0 -0
  66. strable/data/folds/insurance-company-complaints.parquet +0 -0
  67. strable/data/folds/journal-ranking_wide.parquet +0 -0
  68. strable/data/folds/kickstarter-projects.parquet +0 -0
  69. strable/data/folds/lending-club-loan.parquet +0 -0
  70. strable/data/folds/local-government-renewable-action.parquet +0 -0
  71. strable/data/folds/local-law-enforcements.parquet +0 -0
  72. strable/data/folds/managed-care-enrollment.parquet +0 -0
  73. strable/data/folds/manifest.json +1090 -0
  74. strable/data/folds/media-ranking_wide.parquet +0 -0
  75. strable/data/folds/medically-underserved-areas-populations.parquet +0 -0
  76. strable/data/folds/medicines.parquet +0 -0
  77. strable/data/folds/mercari.parquet +0 -0
  78. strable/data/folds/meta-critic_whisky.parquet +0 -0
  79. strable/data/folds/michelin-ratings.parquet +0 -0
  80. strable/data/folds/miga-issued-projects.parquet +0 -0
  81. strable/data/folds/mlr-summary-reports.parquet +0 -0
  82. strable/data/folds/mobile-home-parks.parquet +0 -0
  83. strable/data/folds/museums.parquet +0 -0
  84. strable/data/folds/national-average-drug-acquisition-cost.parquet +0 -0
  85. strable/data/folds/oil-natural-gas-platform.parquet +0 -0
  86. strable/data/folds/orphan-designations.parquet +0 -0
  87. strable/data/folds/osha-accidents.parquet +0 -0
  88. strable/data/folds/paediatric-investigation-plan.parquet +0 -0
  89. strable/data/folds/pol-terminal.parquet +0 -0
  90. strable/data/folds/power-plants.parquet +0 -0
  91. strable/data/folds/prepaid-financial-product.parquet +0 -0
  92. strable/data/folds/prison-boundaries.parquet +0 -0
  93. strable/data/folds/ramen-ratings.parquet +0 -0
  94. strable/data/folds/rasff_window.parquet +0 -0
  95. strable/data/folds/rasnf_notification_list.parquet +0 -0
  96. strable/data/folds/recipient-executed-grants-commitments-disbursements.parquet +0 -0
  97. strable/data/folds/schools.parquet +0 -0
  98. strable/data/folds/sf-building-permits.parquet +0 -0
  99. strable/data/folds/summary-of-deposit_wide.parquet +0 -0
  100. strable/data/folds/tax-incentives.parquet +0 -0
  101. strable/data/folds/terms-cc-plans.parquet +0 -0
  102. strable/data/folds/tobacco-problem.parquet +0 -0
  103. strable/data/folds/total-contributions-ibrd-ida-ifc.parquet +0 -0
  104. strable/data/folds/transmission-lines.parquet +0 -0
  105. strable/data/folds/transmission-towers.parquet +0 -0
  106. strable/data/folds/us-school-bus-fleet.parquet +0 -0
  107. strable/data/folds/vehicles.parquet +0 -0
  108. strable/data/folds/wine-dataset.parquet +0 -0
  109. strable/data/folds/workforce-demographics-wide.parquet +0 -0
  110. strable/data/folds/yelp_business.parquet +0 -0
  111. strable/datasets.py +92 -0
  112. strable/encoders.py +25 -0
  113. strable/evaluation.py +110 -0
  114. strable/taxonomy.py +156 -0
  115. strable-0.1.0.dist-info/METADATA +467 -0
  116. strable-0.1.0.dist-info/RECORD +119 -0
  117. strable-0.1.0.dist-info/WHEEL +5 -0
  118. strable-0.1.0.dist-info/licenses/LICENSE +29 -0
  119. strable-0.1.0.dist-info/top_level.txt +1 -0
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
strable/datasets.py ADDED
@@ -0,0 +1,92 @@
1
+ """The 108 STRABLE tables and their cross-validation folds.
2
+
3
+ The tables come from the Hugging Face dataset inria-soda/STRABLE-benchmark at a pinned revision and
4
+ are cached by huggingface_hub. The folds ship with the package: ``data/folds/<table>.parquet`` gives,
5
+ for each row of the table, the outer fold (0, 1 or 2) that tests it. They are the STRABLE
6
+ leaderboard's folds (``splits/`` of gblayer/strable-leaderboard), computed as in the paper:
7
+ RepeatedKFold for regression, RepeatedStratifiedKFold for classification, 3 splits, 1 repeat,
8
+ seed 1234, on the row order of ``data.parquet``. ``data/folds/manifest.json`` is the leaderboard's
9
+ manifest: the dataset revision, the seed, the scikit-learn version, and per table the task, the row
10
+ count and the SHA-256 of ``data.parquet``.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ from functools import cache
17
+ from pathlib import Path
18
+
19
+ import numpy as np
20
+ import pandas as pd
21
+ from huggingface_hub import hf_hub_download
22
+
23
+ HF_DATASET = "inria-soda/STRABLE-benchmark"
24
+ HF_REVISION = "335c0a77595d4a9ddd86f46dc9c3b414f63a09a8" # 2026-06-11, the leaderboard's revision
25
+ FOLDS_DIR = Path(__file__).resolve().parent / "data" / "folds"
26
+ N_FOLDS = 3
27
+
28
+ # config.json task names -> task names used here and on the leaderboard
29
+ TASKS = {"regression": "regression", "b-classification": "binary", "m-classification": "multiclass"}
30
+ TASK_GROUPS = {"regression": ("regression",), "binary": ("binary",), "multiclass": ("multiclass",),
31
+ "classification": ("binary", "multiclass")}
32
+
33
+
34
+ @cache
35
+ def _manifest() -> dict:
36
+ return json.loads((FOLDS_DIR / "manifest.json").read_text())["tables"]
37
+
38
+
39
+ def _check_name(name: str) -> None:
40
+ if name not in _manifest():
41
+ raise ValueError(f"unknown table {name!r}; strable.list_tables() gives the 108 names")
42
+
43
+
44
+ def list_tables(task: str | None = None) -> list[str]:
45
+ """Names of the 108 tables, sorted.
46
+
47
+ ``task`` keeps the tables of one task: "regression", "binary", "multiclass", or
48
+ "classification" for both binary and multiclass.
49
+ """
50
+ if task is not None and task not in TASK_GROUPS:
51
+ raise ValueError(f"task must be one of {sorted(TASK_GROUPS)}, got {task!r}")
52
+ return sorted(name for name, info in _manifest().items() if task is None or info["task"] in TASK_GROUPS[task])
53
+
54
+
55
+ def load_table(name: str, data_dir: str | Path | None = None) -> tuple[pd.DataFrame, np.ndarray, str]:
56
+ """Return ``(X, y, task)`` for one table.
57
+
58
+ ``X`` holds every column but the target, rows in the order of ``data.parquet``, which the folds
59
+ rely on. ``task`` is "regression", "binary" or "multiclass". Classification labels are encoded
60
+ as 0..K-1 in the sorted order of the original labels, as in the paper.
61
+
62
+ The two files of the table are downloaded from Hugging Face at the pinned revision and cached by
63
+ huggingface_hub (``HF_HOME``). With ``data_dir``, they are read from
64
+ ``<data_dir>/<name>/data.parquet`` and ``config.json`` instead, for example a local copy of
65
+ the dataset.
66
+ """
67
+ _check_name(name)
68
+ if data_dir is not None:
69
+ folder = Path(data_dir) / name
70
+ table_path, config_path = folder / "data.parquet", folder / "config.json"
71
+ else:
72
+ kwargs = dict(repo_id=HF_DATASET, repo_type="dataset", revision=HF_REVISION)
73
+ table_path = hf_hub_download(filename=f"{name}/data.parquet", **kwargs)
74
+ config_path = hf_hub_download(filename=f"{name}/config.json", **kwargs)
75
+ config = json.loads(Path(config_path).read_text())
76
+ data = pd.read_parquet(table_path)
77
+ target, task = config["target_name"], TASKS[config["task"]]
78
+ y = data[target].to_numpy()
79
+ if task != "regression":
80
+ y = np.unique(y, return_inverse=True)[1]
81
+ return data.drop(columns=target), y, task
82
+
83
+
84
+ def get_folds(name: str) -> list[tuple[np.ndarray, np.ndarray]]:
85
+ """The benchmark's 3 outer folds of one table, as ``(train_idx, test_idx)`` pairs.
86
+
87
+ Positions are row numbers of the table that ``load_table`` returns, in increasing order. Every
88
+ row is a test row in exactly one fold. These are the folds of the paper and of the leaderboard.
89
+ """
90
+ _check_name(name)
91
+ outer = pd.read_parquet(FOLDS_DIR / f"{name}.parquet")["outer_fold"].to_numpy()
92
+ return [(np.flatnonzero(outer != k), np.flatnonzero(outer == k)) for k in range(N_FOLDS)]
strable/encoders.py ADDED
@@ -0,0 +1,25 @@
1
+ """The paper's Tf-Idf string encoder."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from sklearn.pipeline import make_pipeline
6
+
7
+ SEED = 1234
8
+ N_COMPONENTS = 30
9
+
10
+
11
+ def tfidf(random_state: int = SEED):
12
+ """The paper's Tf-Idf encoder, as on the STRABLE leaderboard: a table in, numbers out.
13
+
14
+ A first TableVectorizer, the cleaner, parses the table (dates become numbers) and leaves the
15
+ strings as they are. A second one encodes each string column with at least 40 distinct values
16
+ into 30 numbers with skrub's StringEncoder (Tf-Idf of character 3-4-grams, then a truncated
17
+ SVD), one-hot encodes the other string columns, and passes every number, dates included,
18
+ through a SquashingScaler.
19
+ """
20
+ from skrub import SquashingScaler, StringEncoder, TableVectorizer # imported here: skrub is slow to import
21
+
22
+ cleaner = TableVectorizer(cardinality_threshold=0, high_cardinality="passthrough")
23
+ encoder = TableVectorizer(high_cardinality=StringEncoder(n_components=N_COMPONENTS, random_state=random_state),
24
+ numeric=SquashingScaler())
25
+ return make_pipeline(cleaner, encoder)
strable/evaluation.py ADDED
@@ -0,0 +1,110 @@
1
+ """Score a scikit-learn pipeline on STRABLE tables, with the leaderboard's protocol and metrics.
2
+
3
+ Per table and outer fold: fit a fresh clone of the pipeline on the training rows, predict the test
4
+ rows and score them. R² for regression. ROC-AUC for classification, from ``predict_proba``: the
5
+ positive-class column for binary tasks; for multiclass tasks, the one-vs-rest macro average of the
6
+ softmax of the probabilities, as in the paper and on the leaderboard.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import time
12
+ import warnings
13
+
14
+ import numpy as np
15
+ import pandas as pd
16
+ from sklearn.base import clone, is_classifier, is_regressor
17
+ from sklearn.metrics import r2_score, roc_auc_score
18
+
19
+ from .datasets import get_folds, list_tables, load_table
20
+
21
+
22
+ def _softmax(x: np.ndarray) -> np.ndarray:
23
+ """Row-wise softmax, computed as scipy.special.softmax(x, axis=1)."""
24
+ e = np.exp(x - x.max(axis=1, keepdims=True))
25
+ return e / e.sum(axis=1, keepdims=True)
26
+
27
+
28
+ def fold_score(task: str, y_true, pred=None, proba=None, classes=None) -> float:
29
+ """R² of ``pred`` for regression; ROC-AUC of ``proba`` for classification.
30
+
31
+ ``proba`` has one column per class, in the order of ``classes`` (the sorted training labels).
32
+ Binary: the positive-class column. Multiclass: one-vs-rest macro AUC of the row-wise softmax of
33
+ ``proba`` (``reshape_pred_output`` in the paper's src/utils_evaluation.py).
34
+ """
35
+ if task == "regression":
36
+ return float(r2_score(y_true, pred))
37
+ proba = np.asarray(proba, dtype=float)
38
+ if task == "binary":
39
+ return float(roc_auc_score(np.asarray(y_true) == classes[1], proba[:, 1]))
40
+ return float(roc_auc_score(y_true, _softmax(proba), multi_class="ovr", average="macro", labels=classes))
41
+
42
+
43
+ def checked_score(task: str, y_train, y_test, pred=None, proba=None, classes=None) -> float:
44
+ """``fold_score`` after the leaderboard's checks of the predictions; raises ValueError."""
45
+ n = len(y_test)
46
+ if task == "regression":
47
+ pred = np.asarray(pred, dtype=float)
48
+ if pred.shape != (n,):
49
+ raise ValueError(f"predict returned shape {pred.shape}, expected ({n},)")
50
+ if not np.isfinite(pred).all():
51
+ raise ValueError("predict returned NaN or infinite values")
52
+ return fold_score(task, y_test, pred=pred)
53
+ classes, proba = np.asarray(classes), np.asarray(proba, dtype=float)
54
+ if classes.tolist() != sorted(np.unique(y_train).tolist()):
55
+ raise ValueError("classes_ must be the sorted training labels")
56
+ if proba.shape != (n, len(classes)):
57
+ raise ValueError(f"predict_proba returned shape {proba.shape}, expected ({n}, {len(classes)})")
58
+ if not (np.isfinite(proba).all() and (proba >= 0).all()):
59
+ raise ValueError("probabilities must be finite and non-negative")
60
+ if not np.allclose(proba.sum(axis=1), 1, atol=1e-4):
61
+ raise ValueError("probabilities must sum to 1 per row")
62
+ return fold_score(task, y_test, proba=proba, classes=classes)
63
+
64
+
65
+ def _default_tables(pipeline) -> list[str]:
66
+ if is_regressor(pipeline):
67
+ return list_tables("regression")
68
+ if is_classifier(pipeline):
69
+ return list_tables("classification")
70
+ raise ValueError("pass tables=...: the pipeline is neither a scikit-learn regressor nor a classifier")
71
+
72
+
73
+ def evaluate(pipeline, tables: str | list[str] | None = None, data_dir=None) -> pd.DataFrame:
74
+ """Scores of ``pipeline`` on every outer fold of ``tables``, one row per fold.
75
+
76
+ ``pipeline`` is a scikit-learn estimator that takes the raw table (a DataFrame with strings,
77
+ numbers and dates), for example ``make_pipeline(strable.encoders.tfidf(), RidgeCV())``. A
78
+ classifier needs ``predict_proba`` and ``classes_``. ``tables`` is one table name or a list of
79
+ names; by default, every regression table for a regressor and every classification table for a
80
+ classifier. ``data_dir`` is passed to ``load_table``.
81
+
82
+ Columns: ``table``, ``task``, ``fold``, ``score`` (R² for regression, ROC-AUC for
83
+ classification; higher is better), ``n_train``, ``n_test``, and ``time_s``, the wall-clock
84
+ seconds to fit and predict.
85
+ """
86
+ if tables is None:
87
+ tables = _default_tables(pipeline)
88
+ elif isinstance(tables, str):
89
+ tables = [tables]
90
+ rows = []
91
+ for name in tables:
92
+ X, y, task = load_table(name, data_dir=data_dir)
93
+ folds = get_folds(name)
94
+ if len(X) != len(folds[0][0]) + len(folds[0][1]):
95
+ raise ValueError(f"{name}: {len(X)} rows, but its folds cover {len(folds[0][0]) + len(folds[0][1])}")
96
+ for fold, (train_idx, test_idx) in enumerate(folds):
97
+ model, X_test = clone(pipeline), X.iloc[test_idx]
98
+ t0 = time.perf_counter()
99
+ with warnings.catch_warnings():
100
+ warnings.filterwarnings("ignore", message="Found unknown categories")
101
+ model.fit(X.iloc[train_idx], y[train_idx])
102
+ if task == "regression":
103
+ out = dict(pred=model.predict(X_test))
104
+ else:
105
+ out = dict(proba=model.predict_proba(X_test), classes=model.classes_)
106
+ seconds = time.perf_counter() - t0
107
+ rows.append({"table": name, "task": task, "fold": fold,
108
+ "score": checked_score(task, y[train_idx], y[test_idx], **out),
109
+ "n_train": len(train_idx), "n_test": len(test_idx), "time_s": seconds})
110
+ return pd.DataFrame(rows)
strable/taxonomy.py ADDED
@@ -0,0 +1,156 @@
1
+ """The kind of strings each column of a table holds, with the STRABLE paper's taxonomy.
2
+
3
+ Six types: categorical, name, structured_code, free_text, identifier, datetime. Each string column
4
+ gets a few metrics, computed on its first 1,000 non-missing cells (uniqueness and the datetime share
5
+ use every non-missing cell), and fixed rules on these metrics give its type. The metrics and rules
6
+ are those of ``classify_column_heuristic`` in
7
+ scripts/natural_language_test_VSE_vs_STRABLE_vs_CARTE_vs_TTB.py of the STRABLE repository.
8
+
9
+ The word lists are NLTK's corpora, as in the paper: ``words`` (its English file ``en``, the Unix
10
+ "words" file) for the dictionary hit rate, and ``stopwords`` (English). The first call downloads
11
+ them with ``nltk.download`` when they are missing.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import re
17
+ from functools import cache
18
+ from typing import NamedTuple
19
+
20
+ import pandas as pd
21
+
22
+ TYPES = ("categorical", "name", "structured_code", "free_text", "identifier", "datetime")
23
+ METRICS = ("n_unique", "uniqueness", "avg_chars_per_cell", "avg_words_per_cell", "dict_hit_rate", "stopword_density",
24
+ "symbol_density", "prop_numeric_chars", "prop_multiword", "prop_has_pattern", "prop_is_datetime")
25
+ SAMPLE = 1000
26
+
27
+ # A cell is a date when it matches any of these: 2024-03-28, 2024-03-28T14:30, 28/03/2024,
28
+ # 14:30:00 or 2:30 PM, 28 March 2024, March 28, 2024.
29
+ DATETIME = re.compile("|".join([
30
+ r"\d{4}-\d{2}-\d{2}",
31
+ r"\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}",
32
+ r"\d{1,2}[/\-\.]\d{1,2}[/\-\.]\d{2,4}",
33
+ r"\d{2}:\d{2}(:\d{2})?(\s?[APap][Mm])?",
34
+ r"\d{1,2}\s+\w{3,9}\s+\d{4}",
35
+ r"\w{3,9}\s+\d{1,2},?\s+\d{4}",
36
+ ]))
37
+ # A cell holds a code when it contains an ISO date, a US zip code, an amount in dollars, a
38
+ # percentage, an ICD-style code (J45.5) or a letters-dash-digits code (NDC-12345).
39
+ CODE = re.compile(r"\b\d{4}-\d{2}-\d{2}\b|\b\d{5}(-\d{4})?\b|\$[\d,]+(\.\d+)?|\b\d+(\.\d+)?%"
40
+ r"|\b[A-Z]\d{2}(\.\d+)?\b|\b[A-Z]{2,}-\d+\b")
41
+ NOT_LETTERS = re.compile(r"[^a-zA-Z]+")
42
+ SYMBOLS = re.compile(r"[^a-zA-Z0-9\s]")
43
+ WHITESPACE = re.compile(r"\s+")
44
+
45
+
46
+ class Profile(NamedTuple):
47
+ """``columns``: one row per string column, its type and metrics. ``mix``: the share of each type."""
48
+
49
+ columns: pd.DataFrame
50
+ mix: pd.Series
51
+
52
+
53
+ def _nltk_corpus(name: str):
54
+ """NLTK's corpus ``name``, downloaded quietly the first time it is missing."""
55
+ import nltk # imported here: only profile() needs it
56
+
57
+ try:
58
+ nltk.data.find(f"corpora/{name}")
59
+ except LookupError:
60
+ if not nltk.download(name, quiet=True):
61
+ raise RuntimeError(
62
+ f"strable.profile needs NLTK's {name!r} corpus and could not download it (offline?). "
63
+ "Download it once while online with `python -m nltk.downloader words stopwords`, "
64
+ "or set NLTK_DATA to a folder that holds both corpora.") from None
65
+ return getattr(nltk.corpus, name)
66
+
67
+
68
+ @cache
69
+ def _english_words() -> frozenset:
70
+ return frozenset(_nltk_corpus("words").words("en"))
71
+
72
+
73
+ @cache
74
+ def _stopwords() -> frozenset:
75
+ return frozenset(_nltk_corpus("stopwords").words("english"))
76
+
77
+
78
+ def string_columns(df: pd.DataFrame) -> list[str]:
79
+ """The columns skrub's TableVectorizer keeps as text: not numbers, not parsed dates, not all missing."""
80
+ from skrub import TableVectorizer # imported here: skrub is slow to import
81
+
82
+ tv = TableVectorizer(cardinality_threshold=0, low_cardinality="passthrough", high_cardinality="passthrough",
83
+ numeric="passthrough", datetime="passthrough")
84
+ tv.fit(df)
85
+ return [col for col, kind in tv.column_to_kind_.items() if kind == "high_cardinality"]
86
+
87
+
88
+ def _share(tokens: list[str], words: frozenset) -> float:
89
+ return sum(t in words for t in tokens) / len(tokens) if tokens else 0.0
90
+
91
+
92
+ def _digit_share(text: str) -> float:
93
+ return sum(c.isdigit() for c in text) / len(text) if text else 0.0
94
+
95
+
96
+ def column_metrics(column: pd.Series) -> dict[str, float]:
97
+ """The metrics of one string column, as in the paper."""
98
+ cells = column.dropna().astype(str)
99
+ sample = cells.iloc[:SAMPLE]
100
+ text = " ".join(sample.tolist())
101
+ n_unique = cells.nunique()
102
+ return {
103
+ "n_unique": n_unique,
104
+ "uniqueness": n_unique / len(cells) if len(cells) else 0.0,
105
+ "avg_chars_per_cell": sample.str.len().mean(),
106
+ "avg_words_per_cell": sample.map(lambda s: len(WHITESPACE.split(s.strip()))).mean(),
107
+ # as in the paper: lowercase then split for the dictionary, split then lowercase for stopwords
108
+ "dict_hit_rate": _share([t for t in NOT_LETTERS.split(text.lower()) if t], _english_words()),
109
+ "stopword_density": _share([t.lower() for t in NOT_LETTERS.split(text) if t], _stopwords()),
110
+ "symbol_density": len(SYMBOLS.findall(text)) / len(text) if text else 0.0,
111
+ "prop_numeric_chars": _digit_share("".join(sample.tolist())),
112
+ "prop_multiword": sample.str.contains(r"\s", regex=True).mean(),
113
+ "prop_has_pattern": sample.map(lambda s: CODE.search(s) is not None).mean(),
114
+ "prop_is_datetime": cells.map(lambda s: DATETIME.search(s) is not None).mean() if len(cells) else 0.0,
115
+ }
116
+
117
+
118
+ def classify(m: dict[str, float]) -> str:
119
+ """The type of a column from its metrics. The rules run in order, most specific first."""
120
+ if m["prop_is_datetime"] >= 0.7:
121
+ return "datetime"
122
+ # Patterns, digits or symbols dominate; columns with very few distinct values stay categorical.
123
+ structured = (m["prop_has_pattern"] >= 0.2 or m["prop_numeric_chars"] >= 0.25 or m["symbol_density"] >= 0.15
124
+ or (m["symbol_density"] >= 0.1 and m["dict_hit_rate"] < 0.3))
125
+ if structured and m["uniqueness"] >= 0.02:
126
+ return "structured_code"
127
+ # Near-unique, short, not words.
128
+ if m["uniqueness"] >= 0.8 and m["dict_hit_rate"] < 0.3 and m["avg_words_per_cell"] < 3:
129
+ return "identifier"
130
+ # Several words per cell, real words and stopwords: prose rather than multi-word names.
131
+ if (m["avg_words_per_cell"] >= 4 and m["dict_hit_rate"] >= 0.4 and m["prop_multiword"] >= 0.8
132
+ and m["stopword_density"] >= 0.1):
133
+ return "free_text"
134
+ # About two real words per cell (a person or a place, even when repeated), or fairly unique short words.
135
+ if (m["dict_hit_rate"] >= 0.5 and 1.5 <= m["avg_words_per_cell"] <= 4 and m["prop_multiword"] >= 0.5
136
+ and m["prop_numeric_chars"] < 0.1):
137
+ return "name"
138
+ if m["uniqueness"] >= 0.3 and m["dict_hit_rate"] >= 0.3 and m["avg_words_per_cell"] < 4:
139
+ return "name"
140
+ return "categorical"
141
+
142
+
143
+ def profile(df: pd.DataFrame) -> Profile:
144
+ """The type and metrics of each string column of ``df``, and the table's mix of types.
145
+
146
+ String columns are those skrub's TableVectorizer keeps as text; columns it reads as numbers or
147
+ dates are left out. Returns ``Profile(columns, mix)``: ``columns`` has one row per string column
148
+ (index: the column name) with its ``type`` and metrics; ``mix`` is the share of each of the six
149
+ types among the string columns (all 0 when there is none).
150
+ """
151
+ names = string_columns(df)
152
+ metrics = [column_metrics(df[name]) for name in names]
153
+ columns = pd.DataFrame(metrics, index=pd.Index(names, name="column"), columns=list(METRICS))
154
+ columns.insert(0, "type", [classify(m) for m in metrics])
155
+ mix = columns["type"].value_counts(normalize=True).reindex(list(TYPES), fill_value=0.0).rename("share")
156
+ return Profile(columns, mix)