diff --git a/docs/representations/spline_expansions.md b/docs/representations/spline_expansions.md index 10028bc..f8d065c 100644 --- a/docs/representations/spline_expansions.md +++ b/docs/representations/spline_expansions.md @@ -95,7 +95,9 @@ These two share the B-spline machinery but target special shapes. M-spline : A non-negative spline basis (`include_bias=False`). Useful when the components themselves should be non-negative, for example as a density-like basis. Built by rescaling each B-spline -basis function so it integrates to one over its support, +basis function so it integrates to one over its support. The basis is non-negative inside the +fitted range; with an `"extrapolate"` or `"warn"` out-of-range policy it continues the scaled +B-spline boundary pieces, which can be negative beyond the range, $$ M_k(x) = \frac{p + 1}{\tau_{k+p+1} - \tau_k}\, B_k(x). diff --git a/pretab/expansion/spline/m_spline.py b/pretab/expansion/spline/m_spline.py index 101b019..4d5f1b5 100644 --- a/pretab/expansion/spline/m_spline.py +++ b/pretab/expansion/spline/m_spline.py @@ -21,7 +21,10 @@ class MSplineTransformer(BaseSplineTransformer): Transform numerical features using an M-spline basis expansion. M-splines are non-negative basis functions obtained by scaling each B-spline - by ``(degree + 1) / knot_span`` so that it integrates to one. Knot placement + by ``(degree + 1) / knot_span`` so that it integrates to one. Under an + ``out_of_range`` policy of ``"extrapolate"`` or ``"warn"``, a value beyond the + fitted range is evaluated on the extended boundary polynomial pieces, exactly + the scaled B-spline extrapolation, which can be negative there. Knot placement follows the same priority as the other spline transformers: explicit (``knot_locations``) > target-aware (``placement_strategy``) > automatic (``output_dim`` with ``placement_strategy``). @@ -81,6 +84,9 @@ def _mspline_basis(self, x: np.ndarray, knots: np.ndarray, basis_idx: int) -> np not depend on the units of the feature. Only a basis function whose support is degenerate relative to the knot range (zero width, possible only for a knot vector with a repeated knot) is returned as zeros. + Inside the knot range the values are non-negative; beyond it (reached only + under an ``"extrapolate"`` / ``"warn"`` policy) the boundary polynomial + pieces are continued without clipping, like the B-spline basis. """ n_coef = len(knots) - self.degree - 1 coef = np.zeros(n_coef) @@ -93,7 +99,11 @@ def _mspline_basis(self, x: np.ndarray, knots: np.ndarray, basis_idx: int) -> np knot_span = knots[basis_idx + self.degree + 1] - knots[basis_idx] if knot_span <= np.finfo(float).eps * (knots[-1] - knots[0]): return np.zeros(len(x)) - return np.maximum(values * (self.degree + 1) / knot_span, 0.0) + scaled = values * (self.degree + 1) / knot_span + # Clipping at zero only guards in-range round-off: outside the knot range it + # would cut the negative parts off the extended boundary polynomial pieces. + inside = (x >= knots[0]) & (x <= knots[-1]) + return np.where(inside, np.maximum(scaled, 0.0), scaled) def _design_matrix(self, x: np.ndarray, knots: np.ndarray) -> np.ndarray: n_coef = len(knots) - self.degree - 1 diff --git a/tests/core/test_policy.py b/tests/core/test_policy.py index 7d4abbe..3d1dbd9 100644 --- a/tests/core/test_policy.py +++ b/tests/core/test_policy.py @@ -180,6 +180,36 @@ def test_extrapolated_bspline_rows_are_not_zeroed(cls, reaction): np.testing.assert_array_equal(out[2], clipped[0]) # in-range rows are unchanged +@pytest.mark.parametrize("reaction", ["extrapolate", "warn"]) +@pytest.mark.parametrize("include_bias", [False, True]) +def test_extrapolated_mspline_rows_are_the_scaled_bspline_extension(reaction, include_bias): + """The M-spline values were clipped at zero everywhere, which cut the negative parts + off the extended boundary pieces and left a kink at the fitted range.""" + X = np.linspace(0, 1, 50).reshape(-1, 1) + probe = np.array([[-0.3], [-0.05], [0.5], [1.05], [1.3]]) + policy = RepresentationPolicy(out_of_range=reaction) + bspline = BSplineTransformer(output_dim=6, include_bias=include_bias, policy=policy).fit(X) + mspline = MSplineTransformer(output_dim=6, include_bias=include_bias, policy=policy).fit(X) + knots, degree = mspline.knots_[0], mspline.degree + n_basis = len(knots) - degree - 1 + scale = (degree + 1) / (knots[degree + 1 : degree + 1 + n_basis] - knots[:n_basis]) + if include_bias: + scale = np.concatenate([[1.0], scale]) + + with warnings.catch_warnings(): + warnings.simplefilter("ignore", DataWarning) + expected = bspline.transform(probe) * scale + actual = mspline.transform(probe) + just_outside, just_inside = mspline.transform([[-1e-6], [1e-6]]) + + np.testing.assert_allclose(actual, expected, rtol=1e-10, atol=1e-10) + assert (actual[[0, 1, 3, 4]] < 0).any() # the extension takes negative values beyond the range + np.testing.assert_array_equal( + actual[2], MSplineTransformer(output_dim=6, include_bias=include_bias).fit(X).transform([[0.5]])[0] + ) + np.testing.assert_allclose(just_outside, just_inside, atol=1e-3) # continuous across the boundary + + def test_extrapolated_mspline_and_tensor_rows_are_not_zeroed(): policy = RepresentationPolicy(out_of_range="extrapolate") X = np.linspace(0, 1, 50).reshape(-1, 1)