From 013a0a9988c021871f3b6b5e86c0519f99d7eead Mon Sep 17 00:00:00 2001 From: ChrisW09 <50968720+ChrisW09@users.noreply.github.com> Date: Sun, 29 Nov 2026 13:13:44 +0100 Subject: [PATCH] fix(splines): choose thin-plate landmarks from complete rows ThinPlateSplineTransformer declares allow_nan and its transform turns a missing coordinate into a NaN row, but fit passed rows with NaN to the landmark selection: k-means rejected them, and a subsampled NaN landmark made the SVD fail. A tprs feature group with missing_policy="propagate" could therefore not be fitted. fit now selects the landmarks from the rows without a missing value and counts only those rows towards the minimum sample size. Without missing values the landmarks and the basis are unchanged. Add the missing fit and transform docstrings. Fixes #151 --- .../spline/multivariate/thin_plate.py | 52 +++++++++++++++++-- .../spline/test_thinplate_transformer.py | 39 ++++++++++++++ tests/integration/test_feature_groups.py | 24 +++++++++ 3 files changed, 112 insertions(+), 3 deletions(-) diff --git a/pretab/expansion/spline/multivariate/thin_plate.py b/pretab/expansion/spline/multivariate/thin_plate.py index 333b3fc..43d36d4 100644 --- a/pretab/expansion/spline/multivariate/thin_plate.py +++ b/pretab/expansion/spline/multivariate/thin_plate.py @@ -85,6 +85,9 @@ class ThinPlateSplineTransformer(SplineBasisMixin, TransformerMixin, BaseEstimat ``d>=3``. - The construction follows the thin-plate spline theory of Wahba [1]_ and the low-rank thin-plate regression spline of Wood [2]_. + - Missing values (NaN) are allowed. ``fit`` chooses the landmarks from the + rows without a missing value, and ``transform`` returns an all-NaN row for + a row with a missing coordinate (a leading bias column stays ``1``). References ---------- @@ -146,6 +149,30 @@ def _select_landmarks(self, X, n_landmarks, rng): return X[idx] def fit(self, X, y=None): + """Choose the landmarks and build the reduced thin-plate basis. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Training data. Rows with a missing value (NaN) are skipped when the + landmarks are chosen. + y : Ignored + Not used, present for API consistency by convention. + + Returns + ------- + self : object + Fitted transformer. + + Raises + ------ + InvalidParamError + If ``n_components``, ``landmark_strategy`` or ``rank_strategy`` is + invalid. + InsufficientSamplesError + If fewer than ``n_components + n_features + 1`` rows have no missing + value. + """ X = self._validate_allow_nan(X, reset=True) if not isinstance(self.n_components, (int, np.integer)) or self.n_components < 1: @@ -159,14 +186,20 @@ def fit(self, X, y=None): n, d = X.shape n_landmarks = self.n_components + d + 1 - if n < n_landmarks: + # The landmarks define the whole basis, so they come from complete rows only: + # k-means rejects NaN, and a NaN landmark would make every output NaN. + complete = ~np.isnan(X).any(axis=1) + X_complete = X if complete.all() else X[complete] + n_complete = X_complete.shape[0] + if n_complete < n_landmarks: + detail = "" if n_complete == n else f" without a missing value ({n - n_complete} of {n} rows have one)" raise InsufficientSamplesError( f"ThinPlateSplineTransformer with n_components={self.n_components} on {d} feature(s) " - f"needs at least {n_landmarks} samples; got {n}." + f"needs at least {n_landmarks} samples{detail}; got {n_complete}." ) rng = check_random_state(self.random_state) - C = np.asarray(self._select_landmarks(X, n_landmarks, rng), dtype=float) + C = np.asarray(self._select_landmarks(X_complete, n_landmarks, rng), dtype=float) length = C.shape[0] self.landmarks_ = C @@ -200,6 +233,19 @@ def fit(self, X, y=None): return self def transform(self, X): + """Expand ``X`` into the fitted thin-plate basis. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Data to transform. + + Returns + ------- + X_tps : ndarray of shape (n_samples, total_output_dim_) + The basis values. A row with a missing coordinate is NaN in every + basis column; a leading bias column stays ``1``. + """ check_is_fitted(self, "components_") X = self._validate_allow_nan(X, reset=False) K_new = self._tps_kernel(cdist(X, self.landmarks_), self.d_) diff --git a/tests/expansion/spline/test_thinplate_transformer.py b/tests/expansion/spline/test_thinplate_transformer.py index 4b94b30..6e7640a 100644 --- a/tests/expansion/spline/test_thinplate_transformer.py +++ b/tests/expansion/spline/test_thinplate_transformer.py @@ -141,3 +141,42 @@ def test_tprs_expands_a_missing_value_to_a_nan_row(n_features): assert np.isnan(out[1]).all() np.testing.assert_allclose(out[[0, 2]], transformer.transform(X[[0, 2]]), rtol=1e-12, atol=1e-12) + + +@pytest.mark.parametrize("landmark_strategy", ["kmeans", "subsample"]) +@pytest.mark.parametrize("n_features", [1, 2, 3]) +def test_tprs_fits_on_rows_with_missing_values(landmark_strategy, n_features): + """The class allows NaN, so fit chooses its landmarks from the complete rows + instead of failing in k-means or producing a NaN landmark.""" + rng = np.random.default_rng(3) + X = rng.uniform(size=(80, n_features)) + missing = rng.random(80) < 0.3 + X[missing, 0] = np.nan + params = {"n_components": 5, "landmark_strategy": landmark_strategy, "random_state": 0} + + transformer = ThinPlateSplineTransformer(**params).fit(X) + reference = ThinPlateSplineTransformer(**params).fit(X[~missing]) + out = transformer.transform(X) + + assert np.isfinite(transformer.landmarks_).all() + np.testing.assert_array_equal(transformer.landmarks_, reference.landmarks_) + assert np.isnan(out[missing]).all() + np.testing.assert_allclose(out[~missing], reference.transform(X[~missing]), rtol=1e-12, atol=1e-12) + + +def test_tprs_missing_rows_keep_the_bias_column(): + rng = np.random.default_rng(4) + X = rng.uniform(size=(40, 2)) + X[0, 1] = np.nan + out = ThinPlateSplineTransformer(n_components=4, include_bias=True, random_state=0).fit_transform(X) + np.testing.assert_array_equal(out[:, 0], np.ones(40)) + assert np.isnan(out[0, 1:]).all() + assert np.isfinite(out[1:]).all() + + +def test_tprs_counts_only_complete_rows_towards_the_minimum_sample_size(): + X = np.random.default_rng(5).uniform(size=(10, 2)) + X[:3, 0] = np.nan + # n_components=5 on 2 features needs 8 landmarks; only 7 rows are complete. + with pytest.raises(InsufficientSamplesError, match=r"needs at least 8 samples without a missing value \(3 of 10"): + ThinPlateSplineTransformer(n_components=5).fit(X) diff --git a/tests/integration/test_feature_groups.py b/tests/integration/test_feature_groups.py index f495220..2649588 100644 --- a/tests/integration/test_feature_groups.py +++ b/tests/integration/test_feature_groups.py @@ -152,6 +152,30 @@ def test_grouped_layout_matches_independent_blocks(frame, typed, mixed, reverse, pd.testing.assert_frame_equal(data, before) +@pytest.mark.parametrize("method", ["tensorspline", "tprs"]) +def test_propagated_missing_value_gives_a_nan_group_row(frame, method): + data = frame[["east", "north"]].copy() + data.loc[[0, 5], "north"] = np.nan + options = _representation(method) + if method == "tprs": + options["landmark_strategy"] = "kmeans" # k-means rejected any NaN row before + group = FeatureGroup("location", ["north", "east"], RepresentationConfig.from_dict(options)) + processor = Preprocessor( + feature_groups=[group], + numerical_method="none", + target_aware=False, + placement_strategy="uniform", + missing_policy="propagate", + output_format="dense", + ).fit(data) + + out = np.asarray(processor.transform(data, return_array=True)) + + assert out.shape == (len(data), processor.total_output_dim_) + assert np.isnan(out[[0, 5]]).all() + assert np.isfinite(np.delete(out, [0, 5], axis=0)).all() + + @pytest.mark.parametrize("method", ["tensorspline", "tprs"]) def test_typed_group_spec_round_trip_preserves_fitted_contract(frame, method): data = frame[["east", "north"]]