diff --git a/deeptab/data/datamodule.py b/deeptab/data/datamodule.py index fbf9d860..2ea2c243 100644 --- a/deeptab/data/datamodule.py +++ b/deeptab/data/datamodule.py @@ -44,6 +44,40 @@ def _prepare_regression_labels(y, *, vector_targets: bool = False) -> torch.Tens return torch.as_tensor(y_arr, dtype=torch.float32) +def _preprocessing_target(y): + """Reduce vector regression targets to the scalar target preprocessing expects. + + Target-aware representations (PLE, the default, and target-aware spline + placement) grow their decision trees on a single target column, and PreTab + flattens whatever it receives. A target matrix of shape + ``(n_samples, n_targets)``, such as the component columns of a Dirichlet + family, would therefore be read as ``n_samples * n_targets`` scalar targets + and rejected as misaligned with the features. + + Placement only needs a scalar signal that varies with the target, so a + target matrix is projected onto its first principal axis: the direction + along which the targets vary most. For two components this is equivalent to + using either column, since they differ only by sign and offset. + + Parameters + ---------- + y : array-like of shape (n_samples,) or (n_samples, n_targets) + Training targets. + + Returns + ------- + array-like + ``y`` unchanged when it is one-dimensional or a single column, otherwise + a float64 array of shape ``(n_samples,)``. + """ + targets = np.asarray(y) + if targets.ndim != 2 or targets.shape[1] == 1: + return y + centered = targets.astype(np.float64) - targets.mean(axis=0, dtype=np.float64) + _, _, axes = np.linalg.svd(centered, full_matrices=False) + return centered @ axes[0] + + def _positional_columns(X): """Relabel non-string DataFrame columns by position before they reach PreTab. @@ -287,7 +321,12 @@ def preprocess_data( self.X_val = _positional_columns(self.X_val) if fit_preprocessing: - self.preprocessor = fit_preprocessor(self.preprocessor, self.X_train, self.y_train, self.embeddings_train) + # Classification labels are passed through untouched; only a + # regression target matrix needs reducing to a single column. + preprocessing_target = _preprocessing_target(self.y_train) if self.regression else self.y_train + self.preprocessor = fit_preprocessor( + self.preprocessor, self.X_train, preprocessing_target, self.embeddings_train + ) # Align explicit per-row sampling weights with the (possibly auto-split) train set. self._train_sample_weights = self._resolve_train_sample_weights( diff --git a/tests/data/test_datamodule.py b/tests/data/test_datamodule.py index 3dc40935..9a79bf27 100644 --- a/tests/data/test_datamodule.py +++ b/tests/data/test_datamodule.py @@ -822,3 +822,38 @@ def test_positional_columns_relabels_only_non_positional_integer_labels(columns, result = _positional_columns(frame) assert list(result.columns) == expected np.testing.assert_array_equal(result.to_numpy(), frame.to_numpy()) + + +@pytest.mark.parametrize("shape", [(12,), (12, 1)]) +def test_preprocessing_target_leaves_scalar_targets_unchanged(shape): + from deeptab.data.datamodule import _preprocessing_target + + targets = np.arange(12, dtype=np.float32).reshape(shape) + assert _preprocessing_target(targets) is targets + + +def test_preprocessing_target_projects_a_target_matrix_onto_one_aligned_column(): + from deeptab.data.datamodule import _preprocessing_target + + targets = np.random.default_rng(0).dirichlet([2, 3, 4], size=40) + reduced = _preprocessing_target(targets) + assert reduced.shape == (40,) + assert np.isfinite(reduced).all() + # The projection keeps the variance of the dominant target direction. + centered = targets - targets.mean(axis=0) + assert reduced.var() == pytest.approx(np.linalg.eigvalsh(np.cov(centered.T, bias=True))[-1]) + + +def test_preprocessing_target_matches_either_column_of_a_two_component_target(): + from deeptab.data.datamodule import _preprocessing_target + + share = np.random.default_rng(1).uniform(0.1, 0.9, size=30) + reduced = _preprocessing_target(np.column_stack([share, 1 - share])) + assert abs(np.corrcoef(reduced, share)[0, 1]) == pytest.approx(1.0) + + +def test_preprocessing_target_handles_constant_target_rows(): + from deeptab.data.datamodule import _preprocessing_target + + reduced = _preprocessing_target(np.tile([0.2, 0.3, 0.5], (8, 1))) + np.testing.assert_allclose(reduced, np.zeros(8), atol=1e-12) diff --git a/tests/integration/test_lss_base.py b/tests/integration/test_lss_base.py index d9a45eb1..beb5f288 100644 --- a/tests/integration/test_lss_base.py +++ b/tests/integration/test_lss_base.py @@ -413,6 +413,42 @@ def test_multivariate_families_build_and_fit_three_outputs(tmp_path, family): assert loaded.score(_X[:6], targets[:6]) == pytest.approx(model.score(_X[:6], targets[:6])) +@pytest.mark.parametrize( + "preprocessing", + [ + {"numerical_method": "ple"}, + {"numerical_method": "cubicspline", "target_aware": True, "placement_strategy": "cart"}, + ], + ids=["ple", "target-aware-spline"], +) +@pytest.mark.parametrize("explicit_validation", [False, True]) +def test_dirichlet_fits_with_target_aware_preprocessing(tmp_path, preprocessing, explicit_validation): + """A Dirichlet target matrix must not reach the preprocessor as flattened scalars.""" + from deeptab.configs import MLPConfig, PreprocessingConfig + + targets = np.random.default_rng(7).dirichlet([2, 3, 4], size=_N) + model = MLPLSS( + model_config=MLPConfig(d_model=16, dropout=0.0), + preprocessing_config=PreprocessingConfig(output_dim=7, **preprocessing), + trainer_config=TrainerConfig(max_epochs=1, batch_size=16), + random_state=42, + ) + validation = {"X_val": _X[64:], "y_val": targets[64:]} if explicit_validation else {} + model.fit( + _X[:64], + targets[:64], + family="dirichlet", + accelerator="cpu", + enable_progress_bar=False, + default_root_dir=str(tmp_path), + **validation, + ) + predictions = model.predict(_X[:6]) + assert predictions.shape == (6, 3) + assert (predictions > 0).all() + assert np.isfinite(model.score(_X[:6], targets[:6])) + + @pytest.mark.parametrize("model_name", ["TabM", "TabM-averaged", "Trompt"]) @pytest.mark.parametrize( "family,options",