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
52 changes: 49 additions & 3 deletions pretab/expansion/spline/multivariate/thin_plate.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
----------
Expand Down Expand Up @@ -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:
Expand All @@ -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

Expand Down Expand Up @@ -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_)
Expand Down
39 changes: 39 additions & 0 deletions tests/expansion/spline/test_thinplate_transformer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
24 changes: 24 additions & 0 deletions tests/integration/test_feature_groups.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]]
Expand Down
Loading