Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,6 @@ data/
*.pt
gpu.log
slurm/error
slurm/output
slurm/output
slurm/results
paper_results/
41 changes: 41 additions & 0 deletions tests/test_feature_selection.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
save_feature_selection_comparison,
)
from thesis_experiments.standard_feature_selection import (
build_downstream_classifier,
SELECTOR_FACTORIES,
build_feature_selectors,
evaluate_standard_feature_selector,
Expand All @@ -23,6 +24,16 @@
SEED = 42


class TestDownstreamClassifiers:
def test_registered_classifiers_build(self):
assert build_downstream_classifier("logistic_regression", SEED) is not None
assert build_downstream_classifier("random_forest", SEED) is not None

def test_unknown_classifier_raises(self):
with pytest.raises(ValueError, match="Unknown downstream classifier"):
build_downstream_classifier("not_a_classifier", SEED)


# ============================================================
# feature_recovery_metrics
# ============================================================
Expand Down Expand Up @@ -209,6 +220,7 @@ def test_smoke_run_creates_outputs(self, tmp_path: Path):
k=3,
seed=SEED,
results_dir=tmp_path,
dataset="tiny",
)
# All nine selectors present.
assert len(rows) == 9
Expand All @@ -227,12 +239,41 @@ def test_smoke_run_creates_outputs(self, tmp_path: Path):
for row in rows:
assert row["downstream_accuracy"] is not None
assert 0.0 <= row["f1"] <= 1.0
assert row["runtime_seconds"] >= 0.0
# Output files created.
assert (tmp_path / "standard_feature_selection_results.csv").exists()
assert (tmp_path / "standard_feature_selection_config.json").exists()
config = json.loads(
(tmp_path / "standard_feature_selection_config.json").read_text()
)
assert config["dataset"] == "tiny"
assert config["downstream_classifier"] == "logistic_regression"
assert "runtime_seconds" not in config
# CSV is parseable and has one row per selector.
df = pd.read_csv(tmp_path / "standard_feature_selection_results.csv")
assert len(df) == 9
assert "runtime_seconds" in df.columns
assert (df["runtime_seconds"] >= 0.0).all()

def test_random_forest_downstream_classifier(self, tmp_path: Path):
X, y, truth = _make_tiny_dataset()
rows = run_standard_feature_selection(
X_train=X[:140],
y_train=y[:140],
X_test=X[140:],
y_test=y[140:],
truth_features=truth,
k=3,
seed=SEED,
results_dir=tmp_path,
methods=("SelectKBest_f_classif",),
downstream_classifier="random_forest",
)
assert rows[0]["downstream_accuracy"] is not None
config = json.loads(
(tmp_path / "standard_feature_selection_config.json").read_text()
)
assert config["downstream_classifier"] == "random_forest"

def test_k_larger_than_n_features_raises(self, tmp_path: Path):
X, y, _ = _make_tiny_dataset(n_samples=50)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@
``standard_feature_selection_results.csv`` and
``standard_feature_selection_config.json`` (written by
``run_standard_feature_selection``; both carry a ``run_timestamp``
field) plus the recovery bar chart ``feature_selection_comparison.png``
field and the dataset name) plus the recovery bar chart
``feature_selection_comparison.png``
/ ``.pdf`` (written by ``plot_feature_selection_comparison`` -- same
chart as the small pipeline experiments produce, minus the LBBNN row).
The run directory also holds one aggregated
Expand Down Expand Up @@ -59,6 +60,7 @@
plot_feature_selection_comparison,
)
from thesis_experiments.standard_feature_selection import ( # noqa: E402
DEFAULT_DOWNSTREAM_CLASSIFIER,
run_standard_feature_selection,
)

Expand All @@ -82,6 +84,7 @@
"SelectFromModel_LogisticRegression",
"SelectFromModel_RandomForest",
)
DOWNSTREAM_CLASSIFIER = "random_forest" #DEFAULT_DOWNSTREAM_CLASSIFIER

DATASETS_DIR = (
REPO_ROOT / "thesis_experiments/synthetic_data/generated_datasets/small_datasets"
Expand All @@ -102,14 +105,10 @@
# the easier control).
DATASETS: dict[str, tuple[str, str]] = {
"linear": ("linear_dataset_small", "linear_dataset_small_metadata"),
"interactions": (
"interaction_dataset_small",
"interaction_dataset_small_metadata",
),
"interactions_no_main_effects": (
"interaction_no_main_effects_dataset_small",
"interaction_no_main_effects_dataset_small_metadata",
),
"interactions_pure_effects": (
"interaction_pure_effects_dataset_small",
"interaction_pure_effects_dataset_small_metadata",
),
}


Expand Down Expand Up @@ -139,6 +138,8 @@ def run_dataset(dataset_name: str, csv_stem: str, metadata_stem: str) -> list[di
seed=SEED,
results_dir=results_dir,
methods=PAPER_METHODS,
dataset=dataset_name,
downstream_classifier=DOWNSTREAM_CLASSIFIER,
)
# Recovery bar chart (same chart as the small pipeline experiments,
# minus the LBBNN row). Row-driven, so it renders whatever methods
Expand Down
8 changes: 7 additions & 1 deletion thesis_experiments/pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,10 @@
save_training_outputs,
train_model,
)
from thesis_experiments.standard_feature_selection import run_standard_feature_selection
from thesis_experiments.standard_feature_selection import (
DEFAULT_DOWNSTREAM_CLASSIFIER,
run_standard_feature_selection,
)

# Bootstrap examples/_common.py (same pattern as the experiment scripts).
REPO_ROOT = Path(__file__).resolve().parents[1]
Expand Down Expand Up @@ -95,6 +98,7 @@ class ExperimentConfig:
standard_methods: tuple[str, ...] | None = None
# Ad-hoc selector additions (instances or (k, seed) -> selector).
extra_standard_selectors: dict[str, Any] | None = None
downstream_classifier: str = DEFAULT_DOWNSTREAM_CLASSIFIER

# Stage toggles (defaults preserve the current experiment behavior).
run_baselines: bool = True
Expand Down Expand Up @@ -155,6 +159,7 @@ def print_configuration(config: ExperimentConfig) -> None:
else ", ".join(config.standard_methods)
)
print(f" Standard FS methods: {methods}")
print(f" Downstream classifier: {config.downstream_classifier}")
print(f" Run baselines: {config.run_baselines}")
print(f" Run explanations: {config.run_explanations}")
print(f" Run path graphs: {config.run_path_graphs}")
Expand Down Expand Up @@ -270,6 +275,7 @@ def run_experiment(config: ExperimentConfig) -> ExperimentResult:
results_dir=config.results_dir,
methods=config.standard_methods,
extra_selectors=config.extra_standard_selectors,
downstream_classifier=config.downstream_classifier,
)
comparison_rows = save_feature_selection_comparison(
lbbnn_features=lbbnn_features,
Expand Down
75 changes: 63 additions & 12 deletions thesis_experiments/standard_feature_selection.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
from datetime import datetime
from functools import partial
from pathlib import Path
from time import perf_counter
from typing import Any, Callable, Sequence

import numpy as np
Expand All @@ -71,13 +72,16 @@
)

__all__ = [
"DOWNSTREAM_CLASSIFIER_FACTORIES",
"SELECTOR_FACTORIES",
"build_downstream_classifier",
"build_feature_selectors",
"evaluate_standard_feature_selector",
"run_standard_feature_selection",
]

_LOG_PREFIX = "[standard-fs]"
DEFAULT_DOWNSTREAM_CLASSIFIER = "logistic_regression"


# ============================================================
Expand All @@ -90,6 +94,42 @@ def _as_numpy_array(data: Any) -> np.ndarray:
return np.asarray(data)


def _scaled_logistic_regression(seed: int) -> Pipeline:
return Pipeline(
[
("scaler", StandardScaler()),
("classifier", LogisticRegression(max_iter=1000, random_state=seed)),
]
)


def _random_forest(seed: int) -> RandomForestClassifier:
return RandomForestClassifier(
n_estimators=300,
min_samples_leaf=2,
random_state=seed,
n_jobs=-1,
)


DOWNSTREAM_CLASSIFIER_FACTORIES: dict[str, Callable[[int], Any]] = {
"logistic_regression": _scaled_logistic_regression,
"random_forest": _random_forest,
}


def build_downstream_classifier(name: str, seed: int) -> Any:
"""Build a named, unfitted downstream classifier."""
try:
factory = DOWNSTREAM_CLASSIFIER_FACTORIES[name]
except KeyError as exc:
raise ValueError(
f"Unknown downstream classifier {name!r}. Valid options: "
f"{sorted(DOWNSTREAM_CLASSIFIER_FACTORIES)}"
) from exc
return factory(seed)


# ============================================================
# Selectors
# ============================================================
Expand Down Expand Up @@ -260,12 +300,13 @@ def evaluate_standard_feature_selector(
selector_name: str,
selector: Any,
truth_features: Sequence[int] | None,
downstream_classifier: str = DEFAULT_DOWNSTREAM_CLASSIFIER,
seed: int = 42,
) -> dict[str, Any]:
"""Fit one standard selector; evaluate recovery + downstream accuracy.

The downstream classifier is a ``Pipeline(StandardScaler,
LogisticRegression)`` trained on the selected features, mirroring the
protocol in ``experiments_noise_data/sklearn_feature_selection_experiment.py``.
The downstream classifier is selected from the named classifier registry
and trained on the selected features.

Args:
X_train: Training features, shape ``(n_train, n_features)``. Must
Expand All @@ -276,6 +317,8 @@ def evaluate_standard_feature_selector(
selector_name: Name used in the result row.
selector: Unfitted scikit-learn selector instance.
truth_features: Ground-truth feature indices, or ``None``.
downstream_classifier: Registered downstream classifier name.
seed: Random seed for stochastic downstream classifiers.

Returns:
Result row with the selected features, downstream classifier
Expand All @@ -286,19 +329,22 @@ def evaluate_standard_feature_selector(
X_test = _as_numpy_array(X_test)
y_test = _as_numpy_array(y_test).ravel()

selector_start = perf_counter()
selector.fit(X_train, y_train)
selected_features = np.where(selector.get_support())[0].tolist()
X_train_selected = selector.transform(X_train)
X_test_selected = selector.transform(X_test)
selector_runtime_seconds = perf_counter() - selector_start

row: dict[str, Any] = {
"method": selector_name,
"method_type": "standard",
"downstream_classifier": downstream_classifier,
"runtime_seconds": selector_runtime_seconds,
"n_selected": len(selected_features),
"selected_features": selected_features,
}

X_train_selected = selector.transform(X_train)
X_test_selected = selector.transform(X_test)

if X_train_selected.shape[1] == 0:
# Degenerate case: nothing selected -> no downstream classifier.
row.update(
Expand All @@ -308,12 +354,7 @@ def evaluate_standard_feature_selector(
downstream_f1=None,
)
else:
clf = Pipeline(
[
("scaler", StandardScaler()),
("classifier", LogisticRegression(max_iter=1000)),
]
)
clf = build_downstream_classifier(downstream_classifier, seed)
clf.fit(X_train_selected, y_train)
y_pred = clf.predict(X_test_selected)
row.update(
Expand Down Expand Up @@ -342,6 +383,8 @@ def run_standard_feature_selection(
rfe_step: int = 1,
methods: Sequence[str] | None = None,
extra_selectors: dict[str, Any] | None = None,
dataset: str | None = None,
downstream_classifier: str = DEFAULT_DOWNSTREAM_CLASSIFIER,
) -> list[dict[str, Any]]:
"""Run the standard selectors on the given split and save the results.

Expand All @@ -362,12 +405,16 @@ def run_standard_feature_selection(
extra_selectors: Ad-hoc additions for this run only -- either
unfitted selector instances or ``(k, seed) -> selector``
callables.
dataset: Optional dataset name to record in the saved config.
downstream_classifier: Registered classifier used for downstream
evaluation.

Returns:
List of result rows (one dict per selector).
"""
results_dir = Path(results_dir)
results_dir.mkdir(parents=True, exist_ok=True)
build_downstream_classifier(downstream_classifier, seed)

# Timestamp (local time, ISO format) recorded in every output file so
# runs on the same day can be distinguished even if files are moved.
Expand Down Expand Up @@ -404,6 +451,8 @@ def run_standard_feature_selection(
selector_name=name,
selector=selector,
truth_features=truth_features,
downstream_classifier=downstream_classifier,
seed=seed,
)
rows.append(row)

Expand All @@ -428,6 +477,7 @@ def run_standard_feature_selection(

config = {
"run_timestamp": run_timestamp,
"dataset": dataset,
"k_features_to_select": k,
"rfe_step": rfe_step,
"seed": seed,
Expand All @@ -437,6 +487,7 @@ def run_standard_feature_selection(
"n_features": int(n_features),
"truth_features_provided": truth_features is not None,
"n_truth_features": len(truth_features) if truth_features is not None else None,
"downstream_classifier": downstream_classifier,
}
save_json(config, results_dir / "standard_feature_selection_config.json")
print(
Expand Down
Loading