facedyn 1.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.
facedyn/__init__.py ADDED
@@ -0,0 +1,186 @@
1
+ """Interpretable, leakage-aware classification of facial action unit (AU) time series.
2
+
3
+ The pipeline runs from frame-level AU intensities to a video-level
4
+ classifier: smoothing, normalisation, NMF or representative-AU reduction,
5
+ interpretable time-series features, Boruta selection with stability across
6
+ seeds, binary or multiclass classification, and evaluation. Splitting and
7
+ cross-validation keep the unit of independence intact -- the participant for
8
+ repeated-measures data, the pair for matched-pairs designs -- and
9
+ :func:`cross_validate_pipeline` refits every fitted step inside each fold.
10
+
11
+ facedyn began as the Python port of the R analysis in a deepfake-detection
12
+ study (Murphy, Cook & Cuve, in prep). References in the docs to "the
13
+ original R analysis" or "the deepfake study" mean that work. It is kept as
14
+ a validated reference, not as the package's scope.
15
+ """
16
+
17
+ __version__ = "1.1.0"
18
+
19
+ from facedyn.au_labels import humanise_au_label, humanise_au_labels, humanise_feature_label
20
+ from facedyn.classifiers import (
21
+ CLASSIFIER_NAMES,
22
+ fit_classifiers,
23
+ make_classifier,
24
+ make_classifiers,
25
+ )
26
+ from facedyn.crossval import CVPipelineResult, cross_validate_pipeline
27
+ from facedyn.effects import (
28
+ ale_grid,
29
+ feature_effect_ale,
30
+ feature_effect_ale_cv,
31
+ plot_feature_effect,
32
+ summarise_feature_effects,
33
+ )
34
+ from facedyn.evaluation import (
35
+ classification_metrics,
36
+ confusion_matrix_frame,
37
+ cross_validate_grouped,
38
+ delong_roc_test,
39
+ evaluate_models,
40
+ pairwise_contrasts,
41
+ plot_accuracy_comparison,
42
+ plot_confusion_matrix,
43
+ plot_decision_boundary,
44
+ plot_probability_distributions,
45
+ plot_roc_curves,
46
+ plot_roc_ovr,
47
+ roc_auc_delong_ci,
48
+ )
49
+ from facedyn.face_maps import plot_nmf_face_maps
50
+ from facedyn.feature_selection import (
51
+ BorutaRun,
52
+ BorutaSelector,
53
+ boruta_feature_stats,
54
+ correlated_feature_clusters,
55
+ gini_importance,
56
+ oob_permutation_importance,
57
+ plot_boruta_importance,
58
+ plot_boruta_stability,
59
+ plot_feature_clusters,
60
+ tentative_rough_fix,
61
+ )
62
+ from facedyn.features import (
63
+ CallableFeatureExtractor,
64
+ FeatureCleaner,
65
+ RFeatureExtractor,
66
+ TimeSeriesFeatureExtractor,
67
+ cmfts_r_features,
68
+ extract_timeseries_features,
69
+ feature_diagnostics,
70
+ pivot_features_wide,
71
+ reshape_to_wide,
72
+ )
73
+ from facedyn.nmf import (
74
+ NMFDecomposer,
75
+ nmf_cophenetic_correlation,
76
+ nmf_rank_cv_sweep,
77
+ nmf_rank_mse_sweep,
78
+ nmf_reconstruction_error,
79
+ nmf_reconstruction_r2_per_au,
80
+ plot_nmf_basis_heatmap,
81
+ plot_nmf_cophenetic_correlation,
82
+ plot_nmf_rank_cv,
83
+ plot_nmf_reconstruction,
84
+ plot_nmf_reconstruction_extremes,
85
+ plot_nmf_reconstruction_r2_bar,
86
+ )
87
+ from facedyn.normalisation import ZScoreShiftNormalizer
88
+ from facedyn.representative_aus import RepresentativeAUSelector, select_representative_aus
89
+ from facedyn.smoothing import RollingSmoother, plot_smoothing_comparison
90
+ from facedyn.splitting import (
91
+ RepeatedStratifiedGroupKFold,
92
+ group_report,
93
+ group_train_test_split,
94
+ groups_from_column,
95
+ pair_group_report,
96
+ pair_groups,
97
+ pair_groups_from_filenames,
98
+ paired_train_test_split,
99
+ )
100
+ from facedyn.tuning import (
101
+ ThresholdTuningResult,
102
+ plot_threshold_sweep,
103
+ threshold_grid,
104
+ threshold_sweep,
105
+ tune_selection_threshold,
106
+ )
107
+
108
+ __all__ = [
109
+ "CLASSIFIER_NAMES",
110
+ "BorutaRun",
111
+ "BorutaSelector",
112
+ "CVPipelineResult",
113
+ "CallableFeatureExtractor",
114
+ "FeatureCleaner",
115
+ "NMFDecomposer",
116
+ "RFeatureExtractor",
117
+ "RepeatedStratifiedGroupKFold",
118
+ "RepresentativeAUSelector",
119
+ "RollingSmoother",
120
+ "ThresholdTuningResult",
121
+ "TimeSeriesFeatureExtractor",
122
+ "ZScoreShiftNormalizer",
123
+ "ale_grid",
124
+ "boruta_feature_stats",
125
+ "classification_metrics",
126
+ "cmfts_r_features",
127
+ "confusion_matrix_frame",
128
+ "correlated_feature_clusters",
129
+ "cross_validate_grouped",
130
+ "cross_validate_pipeline",
131
+ "delong_roc_test",
132
+ "evaluate_models",
133
+ "extract_timeseries_features",
134
+ "feature_diagnostics",
135
+ "feature_effect_ale",
136
+ "feature_effect_ale_cv",
137
+ "fit_classifiers",
138
+ "gini_importance",
139
+ "group_report",
140
+ "group_train_test_split",
141
+ "groups_from_column",
142
+ "humanise_au_label",
143
+ "humanise_au_labels",
144
+ "humanise_feature_label",
145
+ "make_classifier",
146
+ "make_classifiers",
147
+ "nmf_cophenetic_correlation",
148
+ "nmf_rank_cv_sweep",
149
+ "nmf_rank_mse_sweep",
150
+ "nmf_reconstruction_error",
151
+ "nmf_reconstruction_r2_per_au",
152
+ "oob_permutation_importance",
153
+ "pair_group_report",
154
+ "pair_groups",
155
+ "pair_groups_from_filenames",
156
+ "paired_train_test_split",
157
+ "pairwise_contrasts",
158
+ "pivot_features_wide",
159
+ "plot_accuracy_comparison",
160
+ "plot_boruta_importance",
161
+ "plot_boruta_stability",
162
+ "plot_confusion_matrix",
163
+ "plot_decision_boundary",
164
+ "plot_feature_clusters",
165
+ "plot_feature_effect",
166
+ "plot_nmf_basis_heatmap",
167
+ "plot_nmf_cophenetic_correlation",
168
+ "plot_nmf_face_maps",
169
+ "plot_nmf_rank_cv",
170
+ "plot_nmf_reconstruction",
171
+ "plot_nmf_reconstruction_extremes",
172
+ "plot_nmf_reconstruction_r2_bar",
173
+ "plot_probability_distributions",
174
+ "plot_roc_curves",
175
+ "plot_roc_ovr",
176
+ "plot_smoothing_comparison",
177
+ "plot_threshold_sweep",
178
+ "reshape_to_wide",
179
+ "roc_auc_delong_ci",
180
+ "select_representative_aus",
181
+ "summarise_feature_effects",
182
+ "tentative_rough_fix",
183
+ "threshold_grid",
184
+ "threshold_sweep",
185
+ "tune_selection_threshold",
186
+ ]
facedyn/_plot_utils.py ADDED
@@ -0,0 +1,21 @@
1
+ """Shared helper for facedyn's matplotlib-based ``plot_*`` functions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+
8
+ def save_figure(fig, save_path: str | Path | None, output_dir: str | Path, dpi: int) -> None:
9
+ """Save `fig` to `output_dir / save_path`, if `save_path` is given.
10
+
11
+ Saving a finished figure doesn't depend on what was plotted, so every
12
+ ``plot_*`` function's ``save_path``/``output_dir``/``dpi`` parameters
13
+ share this one implementation rather than each re-deriving it. No-op
14
+ when ``save_path`` is None (the default for all of them), so a plot
15
+ call never saves unless a filename is explicitly given.
16
+ """
17
+ if save_path is None:
18
+ return
19
+ output_dir = Path(output_dir)
20
+ output_dir.mkdir(parents=True, exist_ok=True)
21
+ fig.savefig(output_dir / save_path, dpi=dpi, bbox_inches="tight")
facedyn/au_labels.py ADDED
@@ -0,0 +1,142 @@
1
+ """Human-readable names for OpenFace Action Unit (AU) intensity columns."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+
7
+ __all__ = [
8
+ "AU_DESCRIPTIONS",
9
+ "extract_au_code",
10
+ "humanise_au_label",
11
+ "humanise_au_labels",
12
+ "humanise_feature_label",
13
+ ]
14
+
15
+ #: FACS action names for OpenFace's 17 AU intensity ("_r") columns, keyed by
16
+ #: AU code. Taken from the original R analysis (``final_analysis.Rmd``,
17
+ #: ``au_names``), not re-derived, since the exact wording there is what the
18
+ #: published figures use.
19
+ AU_DESCRIPTIONS: dict[str, str] = {
20
+ "AU01": "Inner Brow Raiser",
21
+ "AU02": "Outer Brow Raiser",
22
+ "AU04": "Brow Lowerer",
23
+ "AU05": "Upper Lid Raiser",
24
+ "AU06": "Cheek Raiser",
25
+ "AU07": "Lid Tightener",
26
+ "AU09": "Nose Wrinkler",
27
+ "AU10": "Upper Lip Raiser",
28
+ "AU12": "Lip Corner Puller",
29
+ "AU14": "Dimpler",
30
+ "AU15": "Lip Corner Depressor",
31
+ "AU17": "Chin Raiser",
32
+ "AU20": "Lip Stretcher",
33
+ "AU23": "Lip Tightener",
34
+ "AU25": "Lips Part",
35
+ "AU26": "Jaw Drop",
36
+ "AU45": "Blink",
37
+ }
38
+
39
+ _AU_CODE_PATTERN = re.compile(r"AU\d{2}", re.IGNORECASE)
40
+
41
+
42
+ def extract_au_code(column: str) -> str | None:
43
+ """Extract the ``AU##`` code from a column name, or ``None`` if absent.
44
+
45
+ Works regardless of naming convention, such as ``AU01_r``,
46
+ ``smth_AU01_r`` or ``AU01_inner_brow_raiser``. Unlike
47
+ :func:`humanise_au_label`, the code is not checked against
48
+ :data:`AU_DESCRIPTIONS`, so unrecognised codes are returned rather than
49
+ swallowed.
50
+
51
+ Examples
52
+ --------
53
+ >>> extract_au_code("smth_AU01_r")
54
+ 'AU01'
55
+ >>> extract_au_code("video_filename")
56
+ """
57
+ match = _AU_CODE_PATTERN.search(column)
58
+ return match.group(0).upper() if match else None
59
+
60
+
61
+ def humanise_au_label(column: str) -> str:
62
+ """Convert an AU column name to a ``"AU## - Description"`` label.
63
+
64
+ Finds an ``AU##`` code anywhere in the name, so raw, smoothed and
65
+ already-readable columns all give the same label. Names with no
66
+ recognisable code, or a code outside OpenFace's 17 intensity columns,
67
+ are returned unchanged rather than raising.
68
+
69
+ Parameters
70
+ ----------
71
+ column : str
72
+ A column name to humanise.
73
+
74
+ Returns
75
+ -------
76
+ str
77
+ ``"AU## - Description"`` if an AU code was recognized, otherwise
78
+ ``column`` unchanged.
79
+
80
+ Examples
81
+ --------
82
+ >>> humanise_au_label("smth_AU01_r")
83
+ 'AU01 - Inner Brow Raiser'
84
+ >>> humanise_au_label("AU01_inner_brow_raiser")
85
+ 'AU01 - Inner Brow Raiser'
86
+ >>> humanise_au_label("video_filename")
87
+ 'video_filename'
88
+ """
89
+ code = extract_au_code(column)
90
+ if code is None:
91
+ return column
92
+ description = AU_DESCRIPTIONS.get(code)
93
+ if description is None:
94
+ return column
95
+ return f"{code} - {description}"
96
+
97
+
98
+ def humanise_au_labels(columns: list[str]) -> list[str]:
99
+ """Apply :func:`humanise_au_label` to each name in a list of columns."""
100
+ return [humanise_au_label(column) for column in columns]
101
+
102
+
103
+ def humanise_feature_label(column: str) -> str:
104
+ """Convert a time-series feature column to a readable label.
105
+
106
+ facedyn's video-level feature tables name columns
107
+ ``f"{feature}_{series}"`` (see
108
+ :func:`~facedyn.features.pivot_features_wide`), e.g.
109
+ ``kurtosis_smth_AU12_r``. This gives ``"AU12 - Lip Corner Puller —
110
+ kurtosis"``. Feature names come from
111
+ :data:`facedyn.features.timeseries.FEATURE_NAMES`, matched longest
112
+ first so ``acf10_sumsq`` is not read as ``acf1``. The reverse order
113
+ (``AU12_r__kurtosis``) is recognised too.
114
+
115
+ A series without a recognised AU code (e.g. an NMF activation
116
+ ``nmf1``) is kept as it is, and a name that matches no known feature
117
+ falls back to :func:`humanise_au_label`.
118
+
119
+ Examples
120
+ --------
121
+ >>> humanise_feature_label("kurtosis_smth_AU12_r")
122
+ 'AU12 - Lip Corner Puller — kurtosis'
123
+ >>> humanise_feature_label("acf10_sumsq_nmf2")
124
+ 'nmf2 — acf10_sumsq'
125
+ >>> humanise_feature_label("AU12_r__kurtosis")
126
+ 'AU12 - Lip Corner Puller — kurtosis'
127
+ """
128
+ # Imported here: facedyn.features imports this module.
129
+ from facedyn.features.timeseries import FEATURE_NAMES
130
+
131
+ names = sorted(FEATURE_NAMES, key=len, reverse=True)
132
+ feature = series = None
133
+ for name in names:
134
+ if column.startswith(name + "_") and len(column) > len(name) + 1:
135
+ feature, series = name, column[len(name) + 1 :]
136
+ break
137
+ if column.endswith("_" + name) and len(column) > len(name) + 1:
138
+ feature, series = name, column[: -len(name) - 1].rstrip("_")
139
+ break
140
+ if feature is None or series is None:
141
+ return humanise_au_label(column)
142
+ return f"{humanise_au_label(series)} — {feature}"
facedyn/classifiers.py ADDED
@@ -0,0 +1,277 @@
1
+ """Classifiers for the video-level decision.
2
+
3
+ Binary or multiclass: every model here accepts any number of classes.
4
+
5
+ Four models, matching the R analysis of the deepfake study (Murphy, Cook &
6
+ Cuve, in prep) that facedyn was first built for: random forest, a documented
7
+ C5.0 substitute, an RBF-kernel SVM, and unpenalised logistic regression.
8
+ Each is an ordinary :class:`sklearn.pipeline.Pipeline` -- nothing here
9
+ wraps or hides scikit-learn, so anything that works with an sklearn
10
+ estimator works with these.
11
+
12
+ Every pipeline standardises its features first, because the R code z-scored
13
+ the feature table with ``caret::preProcess(method=c("center","scale"))``
14
+ before fitting *any* model, trees included. Keeping the scaler inside the
15
+ pipeline also means it is refitted within each cross-validation fold rather
16
+ than leaking test-fold statistics into training.
17
+
18
+ When cross-validating these on repeated-measures or matched-pairs data,
19
+ pass ``groups`` (from :func:`facedyn.splitting.groups_from_column` for one
20
+ group per participant, or :func:`facedyn.splitting.pair_groups` for matched
21
+ pairs) and use :class:`facedyn.splitting.RepeatedStratifiedGroupKFold`.
22
+ Better still, start from frame-level data with
23
+ :func:`facedyn.crossval.cross_validate_pipeline`, which refits every step
24
+ inside each fold.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ from typing import Any
30
+
31
+ import numpy as np
32
+ import sklearn
33
+ from sklearn.base import BaseEstimator
34
+ from sklearn.calibration import CalibratedClassifierCV
35
+ from sklearn.ensemble import AdaBoostClassifier, RandomForestClassifier
36
+ from sklearn.linear_model import LogisticRegression
37
+ from sklearn.pipeline import Pipeline
38
+ from sklearn.preprocessing import StandardScaler
39
+ from sklearn.svm import SVC
40
+
41
+ __all__ = [
42
+ "CLASSIFIER_LABELS",
43
+ "CLASSIFIER_NAMES",
44
+ "PAPER1_PARAMS",
45
+ "PAPER1_PARAM_GRIDS",
46
+ "fit_classifiers",
47
+ "make_classifier",
48
+ "make_classifiers",
49
+ ]
50
+
51
+ CLASSIFIER_NAMES = (
52
+ "random_forest",
53
+ "c50_substitute",
54
+ "svm_rbf",
55
+ "logistic_regression",
56
+ )
57
+
58
+ #: Human-readable labels, used by the plotting helpers in
59
+ #: :mod:`facedyn.evaluation`.
60
+ CLASSIFIER_LABELS = {
61
+ "random_forest": "Random Forest",
62
+ "c50_substitute": "C5.0 substitute (AdaBoost)",
63
+ "svm_rbf": "SVM (RBF)",
64
+ "logistic_regression": "Logistic Regression",
65
+ }
66
+
67
+ #: Hyperparameters replicating the deepfake study's fixed-parameter R fits
68
+ #: (``caret::trainControl(method="none")``). See each entry's note in
69
+ #: :func:`make_classifier`.
70
+ PAPER1_PARAMS: dict[str, dict[str, Any]] = {
71
+ "random_forest": {"n_estimators": 500, "max_features": 4},
72
+ "c50_substitute": {"n_estimators": 20},
73
+ "svm_rbf": {"estimator__C": 0.25},
74
+ "logistic_regression": {},
75
+ }
76
+
77
+ #: Grids replicating R's ``repeatedcv`` tuning, keyed for
78
+ #: :class:`~sklearn.model_selection.GridSearchCV` on the pipelines this
79
+ #: module builds. R tuned with ``tuneLength=5`` on ROC; caret's own
80
+ #: ``svmRadial`` grid at that length is ``C = 2^(-2:2)`` with sigma fixed,
81
+ #: which is reproduced here. The SVM's ``C`` sits one level down
82
+ #: (``estimator__C``) because the SVC is wrapped for Platt scaling.
83
+ PAPER1_PARAM_GRIDS: dict[str, dict[str, list[Any]]] = {
84
+ "random_forest": {"classifier__max_features": [1, 2, 4, 6, 8]},
85
+ "c50_substitute": {"classifier__n_estimators": [1, 10, 20, 30, 40]},
86
+ "svm_rbf": {"classifier__estimator__C": [0.25, 0.5, 1.0, 2.0, 4.0]},
87
+ "logistic_regression": {},
88
+ }
89
+
90
+
91
+ def _unpenalised_logistic_params() -> dict:
92
+ """How to ask the installed scikit-learn for an unregularised fit.
93
+
94
+ R's ``glm(family = binomial)`` is plain maximum likelihood, whereas
95
+ scikit-learn regularises by default. ``penalty=None`` said that up to
96
+ scikit-learn 1.7 and is deprecated from 1.8 in favour of ``C=inf``, so
97
+ pick whichever the installed version wants rather than emitting a
98
+ `FutureWarning` on new versions or a `TypeError` on old ones.
99
+
100
+ On scikit-learn 1.8 the ``C=inf`` route still prints "Setting
101
+ penalty=None will ignore the C and l1_ratio parameters" when fitting.
102
+ That warning is spurious -- it comes from scikit-learn translating
103
+ ``C=inf`` into its own internal ``penalty=None`` and then warning as
104
+ though the caller had set it. The fit really is unregularised
105
+ (coefficients match ``penalty=None`` exactly, and are about twice the
106
+ norm of the regularised default).
107
+ """
108
+ version = tuple(int(part) for part in sklearn.__version__.split(".")[:2] if part.isdigit())
109
+ return {"C": np.inf} if version >= (1, 8) else {"penalty": None}
110
+
111
+
112
+ def _build_estimator(name: str, random_state, n_jobs) -> BaseEstimator:
113
+ if name == "random_forest":
114
+ return RandomForestClassifier(random_state=random_state, n_jobs=n_jobs)
115
+ if name == "c50_substitute":
116
+ # AdaBoost's default base learner (a depth-1 tree) is kept, having
117
+ # been measured as the closest stand-in for C5.0 -- see
118
+ # `make_classifier`.
119
+ return AdaBoostClassifier(random_state=random_state)
120
+ if name == "svm_rbf":
121
+ # SVC has no probability of its own; R's `caret` fits Platt scaling
122
+ # for `classProbs = TRUE`. scikit-learn deprecated doing this through
123
+ # `SVC(probability=True)` in 1.9 (removal in 1.11) in favour of this
124
+ # wrapper, which runs the same procedure: a sigmoid fitted to 5-fold
125
+ # cross-validated decision values, with the SVC itself refit on all
126
+ # the data. Used on every scikit-learn version so results do not
127
+ # depend on which one is installed. Deterministic: the folds are
128
+ # unshuffled, so `random_state` is not needed.
129
+ return CalibratedClassifierCV(SVC(kernel="rbf"), method="sigmoid", cv=5, ensemble=False)
130
+ if name == "logistic_regression":
131
+ # Unregularised, matching R's `glm(family = binomial)`; sklearn's
132
+ # default applies L2, which would not be the same model.
133
+ return LogisticRegression(max_iter=1000, **_unpenalised_logistic_params())
134
+ raise ValueError(f"Unknown classifier {name!r}. Choose from {CLASSIFIER_NAMES}.")
135
+
136
+
137
+ def make_classifier(
138
+ name: str,
139
+ preset: str = "paper1",
140
+ random_state: int | None = None,
141
+ n_jobs: int | None = None,
142
+ **overrides,
143
+ ) -> Pipeline:
144
+ """Build one classifier as a scaler + estimator pipeline.
145
+
146
+ Parameters
147
+ ----------
148
+ name : {"random_forest", "c50_substitute", "svm_rbf", "logistic_regression"}
149
+ Which model to build.
150
+
151
+ ``"c50_substitute"`` **is a substitution, not a port.** C5.0 has no
152
+ Python implementation, and bridging to R's would make R a runtime
153
+ dependency, which this package deliberately avoids (rpy2 is only
154
+ ever an optional extra). C5.0's boosting is adaptive reweighting of decision
155
+ trees, so :class:`~sklearn.ensemble.AdaBoostClassifier` is the
156
+ closest same-family stand-in, and R's ``trials = 20`` maps directly
157
+ onto ``n_estimators=20``.
158
+
159
+ Its base learner is AdaBoost's own default, a depth-1 tree, chosen
160
+ by measurement rather than assumption. Trained on the deepfake
161
+ study's 370 videos with its eight published features and scored on
162
+ the held-out 94, depth-1 reaches ROC-AUC **0.660** against R's real C5.0
163
+ (``model="tree", trials=20, winnow=FALSE``) at **0.651**; depth-2
164
+ reaches 0.697 and depth-3 falls to 0.582. Deeper trees are not a
165
+ better C5.0, they are a different model. That is one dataset's
166
+ worth of evidence, so treat it as a sensible default rather than a
167
+ settled equivalence -- and report these numbers as coming from an
168
+ AdaBoost substitute, not from C5.0.
169
+ preset : {"paper1", "default"}, default "paper1"
170
+ ``"paper1"`` applies :data:`PAPER1_PARAMS`, the fixed
171
+ hyperparameters the deepfake study's R analysis used with
172
+ ``trainControl(method="none")``: 500 trees at ``mtry=4`` for the
173
+ forest (a value chosen for its 8-feature table -- scikit-learn
174
+ clamps it if you have fewer), 20 boosting iterations, and
175
+ ``C=0.25``, which is the single row of `caret`'s own ``svmRadial``
176
+ grid at ``tuneLength=1``. ``"default"`` leaves scikit-learn's
177
+ defaults in place, which is the better starting point on any other
178
+ dataset. ``"paper1"`` stays the default only so that existing code
179
+ keeps reproducing the published numbers.
180
+ random_state : int, optional
181
+ Seeds the estimator. Logistic regression and the SVM are
182
+ deterministic and ignore it.
183
+ n_jobs : int, optional
184
+ Passed to the random forest; the other estimators are
185
+ single-threaded.
186
+ **overrides
187
+ Estimator parameters applied last, overriding the preset --
188
+ ``make_classifier("random_forest", n_estimators=100)``. For
189
+ ``"svm_rbf"``, the SVC's own parameters take an ``estimator__``
190
+ prefix (``estimator__C=1.0``), because the SVC is wrapped in
191
+ :class:`~sklearn.calibration.CalibratedClassifierCV`.
192
+
193
+ Returns
194
+ -------
195
+ sklearn.pipeline.Pipeline
196
+ Steps ``"scaler"`` (:class:`~sklearn.preprocessing.StandardScaler`)
197
+ and ``"classifier"``. Set parameters through the pipeline with the
198
+ ``classifier__`` prefix, as :data:`PAPER1_PARAM_GRIDS` does.
199
+
200
+ Notes
201
+ -----
202
+ ``"svm_rbf"`` is an RBF :class:`~sklearn.svm.SVC` inside
203
+ :class:`~sklearn.calibration.CalibratedClassifierCV` (sigmoid, 5-fold,
204
+ ``ensemble=False``): Platt scaling, as `caret` uses for class
205
+ probabilities. ``predict`` takes the most probable class, so it always
206
+ agrees with ``predict_proba`` (``SVC(probability=True)`` predicted from
207
+ the raw decision function and could disagree).
208
+
209
+ One deliberate difference from R for the SVM: `caret` takes the RBF
210
+ width from ``kernlab::sigest``, a data-driven heuristic with no
211
+ scikit-learn equivalent. These pipelines use ``gamma="scale"``, which
212
+ is also data-driven (``1 / (n_features * X.var())``) but not the same
213
+ estimator, so SVM numbers will differ from R's more than the other
214
+ three models do.
215
+ """
216
+ if preset not in ("paper1", "default"):
217
+ raise ValueError(f"preset must be 'paper1' or 'default', got {preset!r}")
218
+
219
+ estimator = _build_estimator(name, random_state, n_jobs)
220
+ if preset == "paper1":
221
+ estimator.set_params(**PAPER1_PARAMS[name])
222
+ if overrides:
223
+ estimator.set_params(**overrides)
224
+
225
+ return Pipeline([("scaler", StandardScaler()), ("classifier", estimator)])
226
+
227
+
228
+ def make_classifiers(
229
+ names: list[str] | None = None,
230
+ preset: str = "paper1",
231
+ random_state: int | None = None,
232
+ n_jobs: int | None = None,
233
+ ) -> dict[str, Pipeline]:
234
+ """Build several classifiers at once, keyed by name.
235
+
236
+ Parameters
237
+ ----------
238
+ names : list of str, optional
239
+ Defaults to all of :data:`CLASSIFIER_NAMES`.
240
+ preset, random_state, n_jobs
241
+ As :func:`make_classifier`.
242
+
243
+ Returns
244
+ -------
245
+ dict of str to Pipeline
246
+ Unfitted pipelines, in the order given.
247
+ """
248
+ names = list(CLASSIFIER_NAMES) if names is None else list(names)
249
+ return {
250
+ name: make_classifier(name, preset=preset, random_state=random_state, n_jobs=n_jobs)
251
+ for name in names
252
+ }
253
+
254
+
255
+ def fit_classifiers(models: dict[str, Pipeline], X, y) -> dict[str, Pipeline]:
256
+ """Fit each model on the same training data.
257
+
258
+ Parameters
259
+ ----------
260
+ models : dict of str to estimator
261
+ As returned by :func:`make_classifiers`.
262
+ X : pd.DataFrame or array-like
263
+ Training features -- the selected feature columns only, with no
264
+ metadata columns.
265
+ y : array-like
266
+ Training labels, two classes or more. Strings such as
267
+ ``"happy"``/``"sad"``/``"angry"`` are fine and are carried through to
268
+ :func:`facedyn.evaluation.evaluate_models`.
269
+
270
+ Returns
271
+ -------
272
+ dict of str to Pipeline
273
+ The same models, fitted in place and returned for chaining.
274
+ """
275
+ for model in models.values():
276
+ model.fit(X, y)
277
+ return models