gasbench 1.0.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.
- gasbench/__init__.py +28 -0
- gasbench/__main__.py +85 -0
- gasbench/baselines.py +268 -0
- gasbench/data.py +455 -0
- gasbench/datafiles/CHECKSUMS.md5 +1 -0
- gasbench/datafiles/CHECKSUMS.sha256 +1 -0
- gasbench/datafiles/DATASHEET.md +506 -0
- gasbench/datafiles/MANIFEST.sha256 +37 -0
- gasbench/datafiles/model_table.csv +471 -0
- gasbench/datafiles/provenance/README.md +215 -0
- gasbench/datafiles/provenance/SOURCE_FILES.sha256 +3 -0
- gasbench/datafiles/provenance/carpenter2010_runs.csv +101 -0
- gasbench/datafiles/provenance/doi_registry.csv +44 -0
- gasbench/datafiles/provenance/experiment_sources.csv +471 -0
- gasbench/datafiles/provenance/input_corrections.csv +2444 -0
- gasbench/datafiles/provenance/msw_source_marks.csv +71 -0
- gasbench/datafiles/provenance/primary_paper_runs.csv +259 -0
- gasbench/datafiles/provenance/recheck_sample.csv +101 -0
- gasbench/datafiles/provenance/scoring_exclusions.csv +15 -0
- gasbench/datafiles/provenance/study_checks/README.md +14 -0
- gasbench/datafiles/provenance/study_checks/berrueco2014_paper.csv +9 -0
- gasbench/datafiles/provenance/study_checks/caballero2000_paper.csv +19 -0
- gasbench/datafiles/provenance/study_checks/campoy2008_paper.csv +10 -0
- gasbench/datafiles/provenance/study_checks/campoy2009_paper.csv +21 -0
- gasbench/datafiles/provenance/study_checks/campoy2010_paper.csv +13 -0
- gasbench/datafiles/provenance/study_checks/christodoulou2014a_paper.csv +5 -0
- gasbench/datafiles/provenance/study_checks/christodoulou2014b_paper.csv +13 -0
- gasbench/datafiles/provenance/study_checks/kurkela1992_paper.csv +12 -0
- gasbench/datafiles/provenance/study_checks/kurkela2016_paper.csv +5 -0
- gasbench/datafiles/provenance/study_checks/kwapinska2015_paper.csv +23 -0
- gasbench/datafiles/provenance/study_checks/li2004_paper.csv +16 -0
- gasbench/datafiles/provenance/study_checks/mansaray1999_paper.csv +10 -0
- gasbench/datafiles/provenance/study_checks/mayerhofer2012_paper.csv +14 -0
- gasbench/datafiles/provenance/study_checks/miccio2009_paper.csv +7 -0
- gasbench/datafiles/provenance/study_checks/nilsson2016_paper.csv +20 -0
- gasbench/datafiles/provenance/study_checks/sarker2015_paper.csv +16 -0
- gasbench/datafiles/provenance/study_checks/serrano2016_paper.csv +6 -0
- gasbench/datafiles/provenance/study_checks/serrano2017_paper.csv +5 -0
- gasbench/datafiles/provenance/study_checks/siedlecki2009_paper.csv +5 -0
- gasbench/datafiles/provenance/study_checks/siedlecki2011_paper.csv +9 -0
- gasbench/datafiles/provenance/study_checks/skoulou2008_bar_readings.csv +10 -0
- gasbench/datafiles/provenance/study_checks/soria2019_paper.csv +5 -0
- gasbench/datafiles/provenance/study_checks/virginie2012_paper.csv +10 -0
- gasbench/datafiles/provenance/study_checks/weerachanchai2009_paper.csv +8 -0
- gasbench/datafiles/provenance/study_checks/zhao2021_figure_readings.csv +21 -0
- gasbench/datafiles/provenance/study_checks/zheng2016_figure_readings.csv +7 -0
- gasbench/datafiles/provenance/target_corrections.csv +49 -0
- gasbench/datafiles/splits_v1.0.json +1641 -0
- gasbench/equilibrium.py +207 -0
- gasbench/evaluate.py +290 -0
- gasbench/grouping.py +14 -0
- gasbench/hybrid.py +173 -0
- gasbench/leaderboard.py +207 -0
- gasbench/metrics.py +145 -0
- gasbench/splits.py +125 -0
- gasbench/tuned.py +222 -0
- gasbench/uncertainty.py +218 -0
- gasbench-1.0.0.dist-info/METADATA +492 -0
- gasbench-1.0.0.dist-info/RECORD +63 -0
- gasbench-1.0.0.dist-info/WHEEL +5 -0
- gasbench-1.0.0.dist-info/entry_points.txt +2 -0
- gasbench-1.0.0.dist-info/licenses/LICENSE +21 -0
- gasbench-1.0.0.dist-info/top_level.txt +1 -0
gasbench/__init__.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""GasBench: a leave-one-study-out benchmark for gasification syngas prediction."""
|
|
2
|
+
__version__ = "1.0.0"
|
|
3
|
+
|
|
4
|
+
from .data import (
|
|
5
|
+
ALLOWED_FEATURES, FEATURE_SETS, TARGETS, Dataset, load, load_raw, verify,
|
|
6
|
+
)
|
|
7
|
+
from .evaluate import ScoreCard, evaluate
|
|
8
|
+
from .splits import load_splits
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"__version__", "ALLOWED_FEATURES", "FEATURE_SETS", "TARGETS", "Dataset", "ScoreCard",
|
|
12
|
+
"evaluate", "load", "load_raw", "load_splits", "verify", "silence_core_count_message",
|
|
13
|
+
]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def silence_core_count_message() -> None:
|
|
17
|
+
"""Stop joblib printing a warning and a traceback on recent Windows.
|
|
18
|
+
|
|
19
|
+
scikit-learn asks joblib for the number of physical cores. On Windows, older
|
|
20
|
+
joblib releases run the ``wmic`` tool for that, which Windows 11 no longer ships,
|
|
21
|
+
so every run prints "Could not find the number of physical cores" followed by a
|
|
22
|
+
traceback. Nothing is wrong, but it reads like an error. Giving joblib a core
|
|
23
|
+
count (one less than the logical cores) skips the question. Does nothing on other
|
|
24
|
+
systems or when LOKY_MAX_CPU_COUNT is already set.
|
|
25
|
+
"""
|
|
26
|
+
import os
|
|
27
|
+
if os.name == "nt" and "LOKY_MAX_CPU_COUNT" not in os.environ:
|
|
28
|
+
os.environ["LOKY_MAX_CPU_COUNT"] = str(max(1, (os.cpu_count() or 2) - 1))
|
gasbench/__main__.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
"""GasBench on the command line.
|
|
2
|
+
|
|
3
|
+
gasbench verify check every data file against this release
|
|
4
|
+
gasbench info the core track: runs and studies
|
|
5
|
+
gasbench baselines score the baselines on every split and write the leaderboard
|
|
6
|
+
gasbench leaderboard rebuild the leaderboard from saved score cards
|
|
7
|
+
gasbench check CARD check one saved score card
|
|
8
|
+
|
|
9
|
+
``python -m gasbench`` works the same way. ``--results`` is the folder that holds
|
|
10
|
+
``scorecards/`` and ``leaderboard.md`` (default: ``results`` in the current folder).
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import argparse
|
|
15
|
+
import json
|
|
16
|
+
import re
|
|
17
|
+
import sys
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
from . import __version__, silence_core_count_message
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _slug(text: str) -> str:
|
|
24
|
+
return re.sub(r"[^a-z0-9]+", "_", text.lower()).strip("_")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def main(argv=None) -> int:
|
|
28
|
+
parser = argparse.ArgumentParser(prog="gasbench", description=__doc__,
|
|
29
|
+
formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
30
|
+
parser.add_argument("command", choices=["verify", "info", "baselines", "leaderboard", "check"],
|
|
31
|
+
help="what to do")
|
|
32
|
+
parser.add_argument("card", nargs="?", type=Path, help="score card to check (for 'check')")
|
|
33
|
+
parser.add_argument("--results", type=Path, default=Path("results"),
|
|
34
|
+
help="folder with scorecards/ and leaderboard.md (default: ./results)")
|
|
35
|
+
parser.add_argument("--version", action="version", version=f"GasBench {__version__}")
|
|
36
|
+
args = parser.parse_args(argv)
|
|
37
|
+
silence_core_count_message()
|
|
38
|
+
cards_dir = args.results / "scorecards"
|
|
39
|
+
|
|
40
|
+
if args.command == "verify":
|
|
41
|
+
from .data import verify
|
|
42
|
+
try:
|
|
43
|
+
result = verify()
|
|
44
|
+
except RuntimeError as error:
|
|
45
|
+
print(error, file=sys.stderr)
|
|
46
|
+
return 1
|
|
47
|
+
print(f"GasBench {__version__}: all {result['files_checked']} data files verified "
|
|
48
|
+
f"(benchmark sha256 {result['benchmark_sha256'][:16]}...)")
|
|
49
|
+
elif args.command == "info":
|
|
50
|
+
from .data import load
|
|
51
|
+
ds = load("core")
|
|
52
|
+
print(f"GasBench {__version__} core track: {len(ds)} runs, "
|
|
53
|
+
f"{ds.meta['split_group'].nunique()} studies "
|
|
54
|
+
f"({ds.meta['split_group_strict'].nunique()} groups of papers that share an author, in loso_strict)")
|
|
55
|
+
print(ds.meta.groupby("split_group").size().sort_values(ascending=False).to_string())
|
|
56
|
+
elif args.command == "baselines":
|
|
57
|
+
from .baselines import run_baselines
|
|
58
|
+
from .leaderboard import read_cards, to_markdown
|
|
59
|
+
for card in run_baselines():
|
|
60
|
+
card.save(cards_dir / f"{card.split}__{_slug(card.name)}.json")
|
|
61
|
+
print(card, "\n")
|
|
62
|
+
(args.results / "leaderboard.md").write_text(to_markdown(read_cards(cards_dir)), encoding="utf-8")
|
|
63
|
+
print(f"Wrote {args.results / 'leaderboard.md'}")
|
|
64
|
+
elif args.command == "leaderboard":
|
|
65
|
+
from .leaderboard import read_cards, to_markdown
|
|
66
|
+
cards = read_cards(cards_dir) if cards_dir.exists() else []
|
|
67
|
+
if not cards:
|
|
68
|
+
print(f"No score cards in {cards_dir}. Run 'gasbench baselines' or save cards there first.")
|
|
69
|
+
return 1
|
|
70
|
+
(args.results / "leaderboard.md").write_text(to_markdown(cards), encoding="utf-8")
|
|
71
|
+
print(f"Wrote {args.results / 'leaderboard.md'} from {len(cards)} score cards")
|
|
72
|
+
elif args.command == "check":
|
|
73
|
+
from .leaderboard import check_card
|
|
74
|
+
if args.card is None:
|
|
75
|
+
parser.error("'check' needs the path of a score card")
|
|
76
|
+
reasons = check_card(json.loads(args.card.read_text(encoding="utf-8")))
|
|
77
|
+
if reasons:
|
|
78
|
+
print("Not accepted: " + "; ".join(reasons))
|
|
79
|
+
return 1
|
|
80
|
+
print("Accepted: official, made with this release, and its scores follow from its predictions")
|
|
81
|
+
return 0
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
if __name__ == "__main__":
|
|
85
|
+
raise SystemExit(main())
|
gasbench/baselines.py
ADDED
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
"""Reference models every submission is compared against.
|
|
2
|
+
|
|
3
|
+
The hyperparameters of the fixed baselines are the ones used in September 2026,
|
|
4
|
+
when the same frozen table was first modeled with leave-one-study-out splits. They
|
|
5
|
+
were not tuned on the folds reported here, but they were not chosen blind to these
|
|
6
|
+
data either; ``gasbench.tuned`` gives models that choose their own inside each
|
|
7
|
+
training fold.
|
|
8
|
+
|
|
9
|
+
Besides the fixed baselines there are simple references that use no physics and
|
|
10
|
+
almost no inputs (the training mean, the training median and the training mean of
|
|
11
|
+
runs with the same gasifying agent), and a ridge model fitted within studies, which
|
|
12
|
+
removes each training study's own offset before fitting.
|
|
13
|
+
|
|
14
|
+
Two further regressors and four models built on thermodynamics complete the set:
|
|
15
|
+
gradient boosting on histograms with categories handled natively, ridge regression on
|
|
16
|
+
log-ratios of the four species, and the models of ``gasbench.hybrid``. Their settings
|
|
17
|
+
were written down before they were scored and were not changed afterward.
|
|
18
|
+
"""
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import numpy as np
|
|
22
|
+
import pandas as pd
|
|
23
|
+
from sklearn.base import BaseEstimator, RegressorMixin
|
|
24
|
+
from sklearn.compose import ColumnTransformer
|
|
25
|
+
from sklearn.dummy import DummyRegressor
|
|
26
|
+
from sklearn.ensemble import GradientBoostingRegressor, HistGradientBoostingRegressor, RandomForestRegressor
|
|
27
|
+
from sklearn.impute import SimpleImputer
|
|
28
|
+
from sklearn.linear_model import Ridge
|
|
29
|
+
from sklearn.multioutput import MultiOutputRegressor
|
|
30
|
+
from sklearn.pipeline import Pipeline
|
|
31
|
+
from sklearn.preprocessing import OneHotEncoder, OrdinalEncoder, StandardScaler
|
|
32
|
+
from threadpoolctl import threadpool_limits
|
|
33
|
+
|
|
34
|
+
from .data import CATEGORICAL_FEATURES, FEATURE_SETS
|
|
35
|
+
from .equilibrium import COLUMNS as EQUILIBRIUM_COLUMNS
|
|
36
|
+
from .equilibrium import EquilibriumModel
|
|
37
|
+
from .evaluate import evaluate
|
|
38
|
+
from .metrics import FLOOR_FOR_LOG_RATIO, clr
|
|
39
|
+
from .splits import SEED
|
|
40
|
+
|
|
41
|
+
RIDGE_ALPHA = 10.0
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def preprocessor(features) -> ColumnTransformer:
|
|
45
|
+
"""Median-impute and scale numeric inputs; one-hot categoricals.
|
|
46
|
+
|
|
47
|
+
Fitted inside each training fold only. A missing category is its own level
|
|
48
|
+
("missing") rather than being replaced by the most frequent one.
|
|
49
|
+
"""
|
|
50
|
+
numeric = [f for f in features if f not in CATEGORICAL_FEATURES]
|
|
51
|
+
categorical = [f for f in features if f in CATEGORICAL_FEATURES]
|
|
52
|
+
steps = []
|
|
53
|
+
if numeric:
|
|
54
|
+
steps.append(("num", Pipeline([
|
|
55
|
+
("impute", SimpleImputer(strategy="median", keep_empty_features=True)),
|
|
56
|
+
("scale", StandardScaler()),
|
|
57
|
+
]), numeric))
|
|
58
|
+
if categorical:
|
|
59
|
+
steps.append(("cat", Pipeline([
|
|
60
|
+
("impute", SimpleImputer(strategy="constant", fill_value="missing", keep_empty_features=True)),
|
|
61
|
+
("onehot", OneHotEncoder(handle_unknown="ignore", sparse_output=False)),
|
|
62
|
+
]), categorical))
|
|
63
|
+
return ColumnTransformer(steps, remainder="drop", sparse_threshold=0)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _estimators() -> dict:
|
|
67
|
+
return {
|
|
68
|
+
"ridge": Ridge(alpha=RIDGE_ALPHA),
|
|
69
|
+
"random_forest": RandomForestRegressor(
|
|
70
|
+
n_estimators=150, max_depth=10, min_samples_leaf=3, max_features=0.8,
|
|
71
|
+
random_state=SEED, n_jobs=1,
|
|
72
|
+
),
|
|
73
|
+
"gradient_boosting": GradientBoostingRegressor(
|
|
74
|
+
n_estimators=150, learning_rate=0.03, max_depth=2, min_samples_leaf=5,
|
|
75
|
+
subsample=0.8, random_state=SEED,
|
|
76
|
+
),
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class AgentMean(BaseEstimator, RegressorMixin):
|
|
81
|
+
"""The mean of the training runs with the same gasifying agent (the overall mean if none)."""
|
|
82
|
+
|
|
83
|
+
def fit(self, X, Y):
|
|
84
|
+
Y = np.asarray(Y, dtype=float)
|
|
85
|
+
agent = X["agent"].fillna("missing").astype(str).to_numpy()
|
|
86
|
+
self.overall_ = Y.mean(axis=0)
|
|
87
|
+
self.by_agent_ = {a: Y[agent == a].mean(axis=0) for a in np.unique(agent)}
|
|
88
|
+
return self
|
|
89
|
+
|
|
90
|
+
def predict(self, X):
|
|
91
|
+
agent = X["agent"].fillna("missing").astype(str).to_numpy()
|
|
92
|
+
return np.array([self.by_agent_.get(a, self.overall_) for a in agent])
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class WithinStudyRidge(BaseEstimator, RegressorMixin):
|
|
96
|
+
"""Ridge regression fitted on deviations from each training study's own means.
|
|
97
|
+
|
|
98
|
+
Removing each study's mean before fitting keeps differences between studies (rig,
|
|
99
|
+
analysis, laboratory) out of the slopes. A new study is predicted with the slopes and
|
|
100
|
+
the average of the training studies' intercepts, each study weighted equally. Needs the
|
|
101
|
+
study of every training run, which ``gasbench.evaluate`` passes as ``groups``.
|
|
102
|
+
"""
|
|
103
|
+
|
|
104
|
+
def __init__(self, features=None, alpha=RIDGE_ALPHA):
|
|
105
|
+
self.features = features
|
|
106
|
+
self.alpha = alpha
|
|
107
|
+
|
|
108
|
+
def fit(self, X, Y, groups=None):
|
|
109
|
+
Y = np.asarray(Y, dtype=float)
|
|
110
|
+
if groups is None:
|
|
111
|
+
groups = np.zeros(len(Y))
|
|
112
|
+
self.prep_ = preprocessor(self.features if self.features is not None else list(X.columns)).fit(X)
|
|
113
|
+
Z = self.prep_.transform(X)
|
|
114
|
+
g = pd.Series(np.asarray(groups).astype(str))
|
|
115
|
+
z_mean = pd.DataFrame(Z).groupby(g.to_numpy()).transform("mean").to_numpy()
|
|
116
|
+
y_mean = pd.DataFrame(Y).groupby(g.to_numpy()).transform("mean").to_numpy()
|
|
117
|
+
self.ridge_ = Ridge(alpha=self.alpha, fit_intercept=False).fit(Z - z_mean, Y - y_mean)
|
|
118
|
+
study_z = pd.DataFrame(Z).groupby(g.to_numpy()).mean().to_numpy()
|
|
119
|
+
study_y = pd.DataFrame(Y).groupby(g.to_numpy()).mean().to_numpy()
|
|
120
|
+
self.intercept_ = (study_y - study_z @ self.ridge_.coef_.T).mean(axis=0)
|
|
121
|
+
return self
|
|
122
|
+
|
|
123
|
+
def predict(self, X):
|
|
124
|
+
return self.prep_.transform(X) @ self.ridge_.coef_.T + self.intercept_
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
class LogRatioRidge(BaseEstimator, RegressorMixin):
|
|
128
|
+
"""Ridge regression on the centred log-ratios of the four species.
|
|
129
|
+
|
|
130
|
+
The predictions are positive and sum to 100 by construction. Measured shares are
|
|
131
|
+
floored at the same value as in ``gasbench.metrics.clr`` before the logarithm.
|
|
132
|
+
"""
|
|
133
|
+
|
|
134
|
+
def __init__(self, features=None, alpha=RIDGE_ALPHA):
|
|
135
|
+
self.features = features
|
|
136
|
+
self.alpha = alpha
|
|
137
|
+
|
|
138
|
+
def fit(self, X, Y):
|
|
139
|
+
self.prep_ = preprocessor(self.features if self.features is not None else list(X.columns)).fit(X)
|
|
140
|
+
self.ridge_ = Ridge(alpha=self.alpha).fit(self.prep_.transform(X), clr(np.asarray(Y, dtype=float)))
|
|
141
|
+
return self
|
|
142
|
+
|
|
143
|
+
def predict(self, X):
|
|
144
|
+
z = np.exp(self.ridge_.predict(self.prep_.transform(X)))
|
|
145
|
+
return 100.0 * z / z.sum(axis=1, keepdims=True)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
class HistogramBoosting(BaseEstimator, RegressorMixin):
|
|
149
|
+
"""Histogram gradient boosting, one model per species, with the categories kept as categories.
|
|
150
|
+
|
|
151
|
+
Missing numbers and categories no training run used are handled by the trees themselves.
|
|
152
|
+
The fit runs on one thread, which is faster on a table of this size and makes the result
|
|
153
|
+
independent of the number of cores.
|
|
154
|
+
"""
|
|
155
|
+
|
|
156
|
+
def __init__(self, features=None):
|
|
157
|
+
self.features = features
|
|
158
|
+
|
|
159
|
+
def fit(self, X, Y):
|
|
160
|
+
features = self.features if self.features is not None else list(X.columns)
|
|
161
|
+
numeric = [f for f in features if f not in CATEGORICAL_FEATURES]
|
|
162
|
+
categorical = [f for f in features if f in CATEGORICAL_FEATURES]
|
|
163
|
+
prep = ColumnTransformer([
|
|
164
|
+
("cat", Pipeline([
|
|
165
|
+
("impute", SimpleImputer(strategy="constant", fill_value="missing", keep_empty_features=True)),
|
|
166
|
+
("code", OrdinalEncoder(handle_unknown="use_encoded_value", unknown_value=np.nan)),
|
|
167
|
+
]), categorical),
|
|
168
|
+
("num", "passthrough", numeric),
|
|
169
|
+
], remainder="drop", sparse_threshold=0)
|
|
170
|
+
head = HistGradientBoostingRegressor(
|
|
171
|
+
learning_rate=0.05, max_iter=200, max_leaf_nodes=8, min_samples_leaf=10, l2_regularization=1.0,
|
|
172
|
+
early_stopping=False, categorical_features=list(range(len(categorical))), random_state=SEED)
|
|
173
|
+
with threadpool_limits(limits=1):
|
|
174
|
+
self.pipeline_ = Pipeline([("prep", prep), ("model", MultiOutputRegressor(head))]).fit(X, Y)
|
|
175
|
+
return self
|
|
176
|
+
|
|
177
|
+
def predict(self, X):
|
|
178
|
+
with threadpool_limits(limits=1):
|
|
179
|
+
return self.pipeline_.predict(X)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def make_baseline(model: str, features):
|
|
183
|
+
"""An unfitted baseline predicting all four species."""
|
|
184
|
+
if model in PHYSICS_MODELS:
|
|
185
|
+
from . import hybrid
|
|
186
|
+
return {"equilibrium_recalibrated": lambda: hybrid.RecalibratedEquilibrium(),
|
|
187
|
+
"equilibrium_residual_ridge": lambda: hybrid.EquilibriumResidual(list(features), "ridge"),
|
|
188
|
+
"equilibrium_residual_forest": lambda: hybrid.EquilibriumResidual(list(features), "random_forest"),
|
|
189
|
+
"equilibrium_restricted": lambda: hybrid.QuasiEquilibrium()}[model]()
|
|
190
|
+
if model == "hist_gradient_boosting":
|
|
191
|
+
return HistogramBoosting(features=list(features))
|
|
192
|
+
if model == "ridge_log_ratio":
|
|
193
|
+
return LogRatioRidge(features=list(features))
|
|
194
|
+
if model == "mean":
|
|
195
|
+
return DummyRegressor(strategy="mean")
|
|
196
|
+
if model == "median":
|
|
197
|
+
return DummyRegressor(strategy="median")
|
|
198
|
+
if model == "agent_mean":
|
|
199
|
+
return AgentMean()
|
|
200
|
+
if model == "within_study_ridge":
|
|
201
|
+
return WithinStudyRidge(features=list(features))
|
|
202
|
+
return Pipeline([
|
|
203
|
+
("prep", preprocessor(features)),
|
|
204
|
+
("model", MultiOutputRegressor(_estimators()[model])),
|
|
205
|
+
])
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
REFERENCE_MODELS = {"mean": "training mean", "median": "training median",
|
|
209
|
+
"agent_mean": "training mean by gasifying agent"}
|
|
210
|
+
FITTED_MODELS = ["ridge", "random_forest", "gradient_boosting", "within_study_ridge"]
|
|
211
|
+
FURTHER_MODELS = ["hist_gradient_boosting", "ridge_log_ratio"]
|
|
212
|
+
PHYSICS_MODELS = {"equilibrium_recalibrated": "equilibrium, recalibrated",
|
|
213
|
+
"equilibrium_residual_ridge": "equilibrium + ridge on the residual",
|
|
214
|
+
"equilibrium_residual_forest": "equilibrium + random forest on the residual",
|
|
215
|
+
"equilibrium_restricted": "equilibrium, restricted (3 fitted constants)"}
|
|
216
|
+
BASELINE_MODELS = list(REFERENCE_MODELS) + FITTED_MODELS + FURTHER_MODELS + list(PHYSICS_MODELS)
|
|
217
|
+
EQUILIBRIUM_NAME = "equilibrium (no fitting)"
|
|
218
|
+
STANDARD_LEARNERS = ("ridge", "random_forest", "gradient_boosting", "neural_network")
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def baseline_name(model: str, feature_set: str) -> str:
|
|
222
|
+
return REFERENCE_MODELS.get(model) or PHYSICS_MODELS.get(model) or f"{model} [{feature_set}]"
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def family(name: str) -> str:
|
|
226
|
+
"""The group a score card's model belongs to, from its name.
|
|
227
|
+
|
|
228
|
+
"reference" (the training mean and the like), "equilibrium" (no fitting), "physics"
|
|
229
|
+
(the fitted models of ``gasbench.hybrid``), "standard" (ridge, random forest, gradient
|
|
230
|
+
boosting and the neural network, fixed or tuned, on either input set), "further" (the
|
|
231
|
+
other baselines shipped with GasBench) and "submission" (anything else).
|
|
232
|
+
"""
|
|
233
|
+
if name in REFERENCE_MODELS.values():
|
|
234
|
+
return "reference"
|
|
235
|
+
if name == EQUILIBRIUM_NAME:
|
|
236
|
+
return "equilibrium"
|
|
237
|
+
if name in PHYSICS_MODELS.values():
|
|
238
|
+
return "physics"
|
|
239
|
+
learner = name.split(" [")[0].removesuffix(" tuned")
|
|
240
|
+
if learner in STANDARD_LEARNERS and name.endswith("]"):
|
|
241
|
+
return "standard"
|
|
242
|
+
if learner in ("within_study_ridge", *FURTHER_MODELS) and name.endswith("]"):
|
|
243
|
+
return "further"
|
|
244
|
+
return "submission"
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def run_baselines(splits=("random_5fold", "loso", "loso_strict"), track: str = "core") -> list:
|
|
248
|
+
"""Score every baseline on every split and feature set."""
|
|
249
|
+
cards = []
|
|
250
|
+
for split in splits:
|
|
251
|
+
for model in REFERENCE_MODELS:
|
|
252
|
+
cards.append(evaluate(make_baseline(model, ["agent"]), split=split, track=track,
|
|
253
|
+
features=FEATURE_SETS["conditions"], name=baseline_name(model, "")))
|
|
254
|
+
for fs_name, features in FEATURE_SETS.items():
|
|
255
|
+
for model in FITTED_MODELS:
|
|
256
|
+
cards.append(evaluate(make_baseline(model, features), split=split, track=track,
|
|
257
|
+
features=features, name=baseline_name(model, fs_name)))
|
|
258
|
+
for model in FURTHER_MODELS:
|
|
259
|
+
cards.append(evaluate(make_baseline(model, features), split=split, track=track,
|
|
260
|
+
features=features, name=baseline_name(model, fs_name)))
|
|
261
|
+
cards.append(evaluate(EquilibriumModel, split=split, track=track,
|
|
262
|
+
features=EQUILIBRIUM_COLUMNS, name=EQUILIBRIUM_NAME))
|
|
263
|
+
everything = FEATURE_SETS["conditions+composition"]
|
|
264
|
+
for model in PHYSICS_MODELS:
|
|
265
|
+
features = everything if "residual" in model else EQUILIBRIUM_COLUMNS
|
|
266
|
+
cards.append(evaluate(make_baseline(model, features), split=split, track=track,
|
|
267
|
+
features=features, name=baseline_name(model, "")))
|
|
268
|
+
return cards
|