code: import numpy as np
  import pytest
  from scipy import sparse
  from scipy.sparse import random as sparse_random
  from sklearn.utils._testing import assert_array_almost_equal
  
  from numpy.testing import assert_allclose, assert_array_equal
  from scipy.interpolate import BSpline
  from sklearn.linear_model import LinearRegression
  from sklearn.pipeline import Pipeline
  from sklearn.preprocessing import (
      KBinsDiscretizer,
      PolynomialFeatures,
      SplineTransformer,
  )
  from sklearn.utils.fixes import linspace, sp_version, parse_version
  
  
  @pytest.mark.parametrize("est", (PolynomialFeatures, SplineTransformer))
  def test_polynomial_and_spline_array_order(est):
      """Test that output array has the given order."""
      X = np.arange(10).reshape(5, 2)
  
      def is_c_contiguous(a):
          return np.isfortran(a.T)
  
      assert is_c_contiguous(est().fit_transform(X))
      assert is_c_contiguous(est(order="C").fit_transform(X))
      assert np.isfortran(est(order="F").fit_transform(X))
  
  
  @pytest.mark.parametrize(
      "params, err_msg",
      [
          ({"degree": -1}, "degree must be a non-negative integer"),
          ({"degree": 2.5}, "degree must be a non-negative integer"),
          ({"degree": "string"}, "degree must be a non-negative integer"),
          ({"n_knots": 1}, "n_knots must be a positive integer >= 2."),
          ({"n_knots": 1}, "n_knots must be a positive integer >= 2."),
          ({"n_knots": 2.5}, "n_knots must be a positive integer >= 2."),
          ({"n_knots": "string"}, "n_knots must be a positive integer >= 2."),
          ({"knots": 1}, "Expected 2D array, got scalar array instead:"),
          ({"knots": [1, 2]}, "Expected 2D array, got 1D array instead:"),
          (
              {"knots": [[1]]},
              r"Number of knots, knots.shape\[0\], must be >= 2.",
          ),
          (
              {"knots": [[1, 5], [2, 6]]},
              r"knots.shape\[1\] == n_features is violated.",
          ),
          (
              {"knots": [[1], [1], [2]]},
              "knots must be sorted without duplicates.",
          ),
          ({"knots": [[2], [1]]}, "knots must be sorted without duplicates."),
          (
              {"extrapolation": None},
              "extrapolation must be one of 'error', 'constant', 'linear', "
              "'continue' or 'periodic'.",
          ),
          (
              {"extrapolation": 1},
              "extrapolation must be one of 'error', 'constant', 'linear', "
              "'continue' or 'periodic'.",
          ),
          (
              {"extrapolation": "string"},
              "extrapolation must be one of 'error', 'constant', 'linear', "
              "'continue' or 'periodic'.",
          ),
          ({"include_bias": None}, "include_bias must be bool."),
          ({"include_bias": 1}, "include_bias must be bool."),
          ({"include_bias": "string"}, "include_bias must be bool."),
          (
              {"extrapolation": "periodic", "n_knots": 3, "degree": 3},
              "Periodic splines require degree < n_knots. Got n_knots=3 and degree=3.",
          ),
          (
              {"extrapolation": "periodic", "knots": [[0], [1]], "degree": 2},
              "Periodic splines require degree < n_knots. Got n_knots=2 and degree=2.",
          ),
      ],
  )
  def test_spline_transformer_input_validation(params, err_msg):
      """Test that we raise errors for invalid input in SplineTransformer."""
      X = [[1], [2]]
  
      with pytest.raises(ValueError, match=err_msg):
          SplineTransformer(**params).fit(X)
  
  
  def test_spline_transformer_manual_knot_input():
      """
      Test that array-like knot positions in SplineTransformer are accepted.
      """
      X = np.arange(20).reshape(10, 2)
      knots = [[0.5, 1], [1.5, 2], [5, 10]]
      st1 = SplineTransformer(degree=3, knots=knots, n_knots=None).fit(X)
      knots = np.asarray(knots)
      st2 = SplineTransformer(degree=3, knots=knots, n_knots=None).fit(X)
      for i in range(X.shape[1]):
          assert_allclose(st1.bsplines_[i].t, st2.bsplines_[i].t)
  
  
  @pytest.mark.parametrize("extrapolation", ["continue", "periodic"])
  def test_spline_transformer_integer_knots(extrapolation):
      """Test that SplineTransformer accepts integer value knot positions."""
      X = np.arange(20).reshape(10, 2)
      knots = [[0, 1], [1, 2], [5, 5], [11, 10], [12, 11]]
      _ = SplineTransformer(
          degree=3, knots=knots, extrapolation=extrapolation
      ).fit_transform(X)
  
  
  def test_spline_transformer_feature_names():
      """Test that SplineTransformer generates correct features name."""
      X = np.arange(20).reshape(10, 2)
      splt = SplineTransformer(n_knots=3, degree=3, include_bias=True).fit(X)
      feature_names = splt.get_feature_names()
      assert_array_equal(
          feature_names,
          [
              "x0_sp_0",
              "x0_sp_1",
              "x0_sp_2",
              "x0_sp_3",
              "x0_sp_4",
              "x1_sp_0",
              "x1_sp_1",
              "x1_sp_2",
              "x1_sp_3",
              "x1_sp_4",
          ],
      )
  
      splt = SplineTransformer(n_knots=3, degree=3, include_bias=False).fit(X)
      feature_names = splt.get_feature_names(["a", "b"])
      assert_array_equal(
          feature_names,
          [
              "a_sp_0",
              "a_sp_1",
              "a_sp_2",
              "a_sp_3",
              "b_sp_0",
              "b_sp_1",
              "b_sp_2",
              "b_sp_3",
          ],
      )
  
  
  @pytest.mark.parametrize("degree", range(1, 5))
  @pytest.mark.parametrize("n_knots", range(3, 5))
  @pytest.mark.parametrize("knots", ["uniform", "quantile"])
  @pytest.mark.parametrize("extrapolation", ["constant", "periodic"])
  def test_spline_transformer_unity_decomposition(degree, n_knots, knots, extrapolation):
      """Test that B-splines are indeed a decomposition of unity.
  
      Splines basis functions must sum up to 1 per row, if we stay in between
      boundaries.
      """
      X = np.linspace(0, 1, 100)[:, None]
      # make the boundaries 0 and 1 part of X_train, for sure.
      X_train = np.r_[[[0]], X[::2, :], [[1]]]
      X_test = X[1::2, :]
  
      if extrapolation == "periodic":
          n_knots = n_knots + degree  # periodic splines require degree < n_knots
  
      splt = SplineTransformer(
          n_knots=n_knots,
          degree=degree,
          knots=knots,
          include_bias=True,
          extrapolation=extrapolation,
      )
      splt.fit(X_train)
      for X in [X_train, X_test]:
          assert_allclose(np.sum(splt.transform(X), axis=1), 1)
  
  
  @pytest.mark.parametrize(["bias", "intercept"], [(True, False), (False, True)])
  def test_spline_transformer_linear_regression(bias, intercept):
      """Test that B-splines fit a sinusodial curve pretty well."""
      X = np.linspace(0, 10, 100)[:, None]
      y = np.sin(X[:, 0]) + 2  # +2 to avoid the value 0 in assert_allclose
      pipe = Pipeline(
          steps=[
              (
                  "spline",
                  SplineTransformer(
                      n_knots=15,
                      degree=3,
                      include_bias=bias,
                      extrapolation="constant",
                  ),
              ),
              ("ols", LinearRegression(fit_intercept=intercept)),
          ]
      )
      pipe.fit(X, y)
      assert_allclose(pipe.predict(X), y, rtol=1e-3)
  
  
  @pytest.mark.parametrize(
      "knots, n_knots, degree",
      [
          ("uniform", 5, 3),
          ("uniform", 12, 8),
          (
              [[-1.0, 0.0], [0, 1.0], [0.1, 2.0], [0.2, 3.0], [0.3, 4.0], [1, 5.0]],
              None,
              3,
          ),
      ],
  )
  def test_spline_transformer_periodicity_of_extrapolation(knots, n_knots, degree):
      """Test that the SplineTransformer is periodic for multiple features."""
      X_1 = linspace((-1, 0), (1, 5), 10)
      X_2 = linspace((1, 5), (3, 10), 10)
  
      splt = SplineTransformer(
          knots=knots, n_knots=n_knots, degree=degree, extrapolation="periodic"
      )
      splt.fit(X_1)
  
      assert_allclose(splt.transform(X_1), splt.transform(X_2))
  
  
  @pytest.mark.parametrize(["bias", "intercept"], [(True, False), (False, True)])
  def test_spline_transformer_periodic_linear_regression(bias, intercept):
      """Test that B-splines fit a periodic curve pretty well."""
      # "+ 3" to avoid the value 0 in assert_allclose
      def f(x):
          return np.sin(2 * np.pi * x) - np.sin(8 * np.pi * x) + 3
  
      X = np.linspace(0, 1, 101)[:, None]
      pipe = Pipeline(
          steps=[
              (
                  "spline",
                  SplineTransformer(
                      n_knots=20,
                      degree=3,
                      include_bias=bias,
                      extrapolation="periodic",
                  ),
              ),
              ("ols", LinearRegression(fit_intercept=intercept)),
          ]
      )
      pipe.fit(X, f(X[:, 0]))
  
      # Generate larger array to check periodic extrapolation
      X_ = np.linspace(-1, 2, 301)[:, None]
      predictions = pipe.predict(X_)
      assert_allclose(predictions, f(X_[:, 0]), atol=0.01, rtol=0.01)
      assert_allclose(predictions[0:100], predictions[100:200], rtol=1e-3)
  
  
  @pytest.mark.skipif(
      sp_version < parse_version("1.0.0"),
      reason="Periodic extrapolation not yet implemented for BSpline.",
  )
  def test_spline_transformer_periodic_spline_backport():
      """Test that the backport of extrapolate="periodic" works correctly"""
      X = np.linspace(-2, 3.5, 10)[:, None]
      degree = 2
  
      # Use periodic extrapolation backport in SplineTransformer
      transformer = SplineTransformer(
          degree=degree, extrapolation="periodic", knots=[[-1.0], [0.0], [1.0]]
      )
      Xt = transformer.fit_transform(X)
  
      # Use periodic extrapolation in BSpline
      coef = np.array([[1.0, 0.0], [0.0, 1.0], [1.0, 0.0], [0.0, 1.0]])
      spl = BSpline(np.arange(-3, 4), coef, degree, "periodic")
      Xspl = spl(X[:, 0])
      assert_allclose(Xt, Xspl)
  
  
  def test_spline_transformer_periodic_splines_periodicity():
      """
      Test if shifted knots result in the same transformation up to permutation.
      """
      X = np.linspace(0, 10, 101)[:, None]
  
      transformer_1 = SplineTransformer(
          degree=3,
          extrapolation="periodic",
          knots=[[0.0], [1.0], [3.0], [4.0], [5.0], [8.0]],
      )
  
      transformer_2 = SplineTransformer(
          degree=3,
          extrapolation="periodic",
          knots=[[1.0], [3.0], [4.0], [5.0], [8.0], [9.0]],
      )
  
      Xt_1 = transformer_1.fit_transform(X)
      Xt_2 = transformer_2.fit_transform(X)
  
      assert_allclose(Xt_1, Xt_2[:, [4, 0, 1, 2, 3]])
  
  
  @pytest.mark.parametrize("degree", [3, 5])
  def test_spline_transformer_periodic_splines_smoothness(degree):
      """Test that spline transformation is smooth at first / last knot."""
      X = np.linspace(-2, 10, 10_000)[:, None]
  
      transformer = SplineTransformer(
          degree=degree,
          extrapolation="periodic",
          knots=[[0.0], [1.0], [3.0], [4.0], [5.0], [8.0]],
      )
      Xt = transformer.fit_transform(X)
  
      delta = (X.max() - X.min()) / len(X)
      tol = 10 * delta
  
      dXt = Xt
      # We expect splines of degree `degree` to be (`degree`-1) times
      # continuously differentiable. I.e. for d = 0, ..., `degree` - 1 the d-th
      # derivative should be continous. This is the case if the (d+1)-th
      # numerical derivative is reasonably small (smaller than `tol` in absolute
      # value). We thus compute d-th numeric derivatives for d = 1, ..., `degree`
      # and compare them to `tol`.
      #
      # Note that the 0-th derivative is the function itself, such that we are
      # also checking its continuity.
      for d in range(1, degree + 1):
          # Check continuity of the (d-1)-th derivative
          diff = np.diff(dXt, axis=0)
          assert np.abs(diff).max() < tol
          # Compute d-th numeric derivative
          dXt = diff / delta
  
      # As degree `degree` splines are not `degree` times continously
      # differentiable at the knots, the `degree + 1`-th numeric derivative
      # should have spikes at the knots.
      diff = np.diff(dXt, axis=0)
      assert np.abs(diff).max() > 1
  
  
  @pytest.mark.parametrize(["bias", "intercept"], [(True, False), (False, True)])
  @pytest.mark.parametrize("degree", [1, 2, 3, 4, 5])
  def test_spline_transformer_extrapolation(bias, intercept, degree):
      """Test that B-spline extrapolation works correctly."""
      # we use a straight line for that
      X = np.linspace(-1, 1, 100)[:, None]
      y = X.squeeze()
  
      # 'constant'
      pipe = Pipeline(
          [
              [
                  "spline",
                  SplineTransformer(
                      n_knots=4,
                      degree=degree,
                      include_bias=bias,
                      extrapolation="constant",
                  ),
              ],
              ["ols", LinearRegression(fit_intercept=intercept)],
          ]
      )
      pipe.fit(X, y)
      assert_allclose(pipe.predict([[-10], [5]]), [-1, 1])
  
      # 'linear'
      pipe = Pipeline(
          [
              [
                  "spline",
                  SplineTransformer(
                      n_knots=4,
                      degree=degree,
                      include_bias=bias,
                      extrapolation="linear",
                  ),
              ],
              ["ols", LinearRegression(fit_intercept=intercept)],
          ]
      )
      pipe.fit(X, y)
      assert_allclose(pipe.predict([[-10], [5]]), [-10, 5])
  
      # 'error'
      splt = SplineTransformer(
          n_knots=4, degree=degree, include_bias=bias, extrapolation="error"
      )
      splt.fit(X)
      with pytest.raises(ValueError):
          splt.transform([[-10]])
      with pytest.raises(ValueError):
          splt.transform([[5]])
  
  
  def test_spline_transformer_kbindiscretizer():
      """Test that a B-spline of degree=0 is equivalent to KBinsDiscretizer."""
      rng = np.random.RandomState(97531)
      X = rng.randn(200).reshape(200, 1)
      n_bins = 5
      n_knots = n_bins + 1
  
      splt = SplineTransformer(
          n_knots=n_knots, degree=0, knots="quantile", include_bias=True
      )
      splines = splt.fit_transform(X)
  
      kbd = KBinsDiscretizer(n_bins=n_bins, encode="onehot-dense", strategy="quantile")
      kbins = kbd.fit_transform(X)
  
      # Though they should be exactly equal, we test approximately with high
      # accuracy.
      assert_allclose(splines, kbins, rtol=1e-13)
  
  
  @pytest.mark.parametrize("n_knots", [5, 10])
  @pytest.mark.parametrize("include_bias", [True, False])
  @pytest.mark.parametrize("degree", [3, 5])
  def test_spline_transformer_n_features_out(n_knots, include_bias, degree):
      """Test that transform results in n_features_out_ features."""
      splt = SplineTransformer(n_knots=n_knots, degree=degree, include_bias=include_bias)
      X = np.linspace(0, 1, 10)[:, None]
      splt.fit(X)
  
      assert splt.transform(X).shape[1] == splt.n_features_out_
  
  
  @pytest.mark.parametrize(
      "params, err_msg",
      [
          ({"degree": -1}, "degree must be a non-negative integer"),
          ({"degree": 2.5}, "degree must be a non-negative int or tuple"),
          ({"degree": "12"}, r"degree=\(min_degree, max_degree\) must"),
          ({"degree": "string"}, "degree must be a non-negative int or tuple"),
          ({"degree": (-1, 2)}, r"degree=\(min_degree, max_degree\) must"),
          ({"degree": (0, 1.5)}, r"degree=\(min_degree, max_degree\) must"),
          ({"degree": (3, 2)}, r"degree=\(min_degree, max_degree\) must"),
      ],
  )
  def test_polynomial_features_input_validation(params, err_msg):
      """Test that we raise errors for invalid input in PolynomialFeatures."""
      X = [[1], [2]]
  
      with pytest.raises(ValueError, match=err_msg):
          PolynomialFeatures(**params).fit(X)
  
  
  @pytest.fixture()
  def single_feature_degree3():
      X = np.arange(6)[:, np.newaxis]
      P = np.hstack([np.ones_like(X), X, X ** 2, X ** 3])
      return X, P
  
  
  @pytest.mark.parametrize(
      "degree, include_bias, interaction_only, indices",
      [
          (3, True, False, slice(None, None)),
          (3, False, False, slice(1, None)),
          (3, True, True, [0, 1]),
          (3, False, True, [1]),
          ((2, 3), True, False, [0, 2, 3]),
          ((2, 3), False, False, [2, 3]),
          ((2, 3), True, True, [0]),
          ((2, 3), False, True, []),
      ],
  )
  @pytest.mark.parametrize(
      "sparse_X",
      [False, sparse.csr_matrix, sparse.csc_matrix],
  )
  def test_polynomial_features_one_feature(
      single_feature_degree3,
      degree,
      include_bias,
      interaction_only,
      indices,
      sparse_X,
  ):
      """Test PolynomialFeatures on single feature up to degree 3."""
      X, P = single_feature_degree3
      if sparse_X:
          X = sparse_X(X)
      tf = PolynomialFeatures(
          degree=degree, include_bias=include_bias, interaction_only=interaction_only
      ).fit(X)
      out = tf.transform(X)
      if sparse_X:
          out = out.toarray()
      assert_allclose(out, P[:, indices])
      if tf.n_output_features_ > 0:
          assert tf.powers_.shape == (tf.n_output_features_, tf.n_features_in_)
  
  
  @pytest.fixture()
  def two_features_degree3():
      X = np.arange(6).reshape((3, 2))
      x1 = X[:, :1]
      x2 = X[:, 1:]
      P = np.hstack(
          [
              x1 ** 0 * x2 ** 0,  # 0
              x1 ** 1 * x2 ** 0,  # 1
              x1 ** 0 * x2 ** 1,  # 2
              x1 ** 2 * x2 ** 0,  # 3
              x1 ** 1 * x2 ** 1,  # 4
              x1 ** 0 * x2 ** 2,  # 5
              x1 ** 3 * x2 ** 0,  # 6
              x1 ** 2 * x2 ** 1,  # 7
              x1 ** 1 * x2 ** 2,  # 8
              x1 ** 0 * x2 ** 3,  # 9
          ]
      )
      return X, P
  
  
  @pytest.mark.parametrize(
      "degree, include_bias, interaction_only, indices",
      [
          (2, True, False, slice(0, 6)),
          (2, False, False, slice(1, 6)),
          (2, True, True, [0, 1, 2, 4]),
          (2, False, True, [1, 2, 4]),
          ((2, 2), True, False, [0, 3, 4, 5]),
          ((2, 2), False, False, [3, 4, 5]),
          ((2, 2), True, True, [0, 4]),
          ((2, 2), False, True, [4]),
          (3, True, False, slice(None, None)),
          (3, False, False, slice(1, None)),
          (3, True, True, [0, 1, 2, 4]),
          (3, False, True, [1, 2, 4]),
          ((2, 3), True, False, [0, 3, 4, 5, 6, 7, 8, 9]),
          ((2, 3), False, False, slice(3, None)),
          ((2, 3), True, True, [0, 4]),
          ((2, 3), False, True, [4]),
          ((3, 3), True, False, [0, 6, 7, 8, 9]),
          ((3, 3), False, False, [6, 7, 8, 9]),
          ((3, 3), True, True, [0]),
          ((3, 3), False, True, []),  # would need 3 input features
      ],
  )
  @pytest.mark.parametrize(
      "sparse_X",
      [False, sparse.csr_matrix, sparse.csc_matrix],
  )
  def test_polynomial_features_two_features(
      two_features_degree3,
      degree,
      include_bias,
      interaction_only,
      indices,
      sparse_X,
  ):
      """Test PolynomialFeatures on 2 features up to degree 3."""
      X, P = two_features_degree3
      if sparse_X:
          X = sparse_X(X)
      tf = PolynomialFeatures(
          degree=degree, include_bias=include_bias, interaction_only=interaction_only
      ).fit(X)
      out = tf.transform(X)
      if sparse_X:
          out = out.toarray()
      assert_allclose(out, P[:, indices])
      if tf.n_output_features_ > 0:
          assert tf.powers_.shape == (tf.n_output_features_, tf.n_features_in_)
  
  
  def test_polynomial_feature_names():
      X = np.arange(30).reshape(10, 3)
      poly = PolynomialFeatures(degree=2, include_bias=True).fit(X)
      feature_names = poly.get_feature_names()
      assert_array_equal(
          ["1", "x0", "x1", "x2", "x0^2", "x0 x1", "x0 x2", "x1^2", "x1 x2", "x2^2"],
          feature_names,
      )
      assert len(feature_names) == poly.transform(X).shape[1]
  
      poly = PolynomialFeatures(degree=3, include_bias=False).fit(X)
      feature_names = poly.get_feature_names(["a", "b", "c"])
      assert_array_equal(
          [
              "a",
              "b",
              "c",
              "a^2",
              "a b",
              "a c",
              "b^2",
              "b c",
              "c^2",
              "a^3",
              "a^2 b",
              "a^2 c",
              "a b^2",
              "a b c",
              "a c^2",
              "b^3",
              "b^2 c",
              "b c^2",
              "c^3",
          ],
          feature_names,
      )
      assert len(feature_names) == poly.transform(X).shape[1]
  
      poly = PolynomialFeatures(degree=(2, 3), include_bias=False).fit(X)
      feature_names = poly.get_feature_names(["a", "b", "c"])
      assert_array_equal(
          [
              "a^2",
              "a b",
              "a c",
              "b^2",
              "b c",
              "c^2",
              "a^3",
              "a^2 b",
              "a^2 c",
              "a b^2",
              "a b c",
              "a c^2",
              "b^3",
              "b^2 c",
              "b c^2",
              "c^3",
          ],
          feature_names,
      )
      assert len(feature_names) == poly.transform(X).shape[1]
  
      poly = PolynomialFeatures(
          degree=(3, 3), include_bias=True, interaction_only=True
      ).fit(X)
      feature_names = poly.get_feature_names(["a", "b", "c"])
      assert_array_equal(["1", "a b c"], feature_names)
      assert len(feature_names) == poly.transform(X).shape[1]
  
      # test some unicode
      poly = PolynomialFeatures(degree=1, include_bias=True).fit(X)
      feature_names = poly.get_feature_names(["\u0001F40D", "\u262E", "\u05D0"])
      assert_array_equal(["1", "\u0001F40D", "\u262E", "\u05D0"], feature_names)
  
  
  @pytest.mark.parametrize(
      ["deg", "include_bias", "interaction_only", "dtype"],
      [
          (1, True, False, int),
          (2, True, False, int),
          (2, True, False, np.float32),
          (2, True, False, np.float64),
          (3, False, False, np.float64),
          (3, False, True, np.float64),
          (4, False, False, np.float64),
          (4, False, True, np.float64),
      ],
  )
  def test_polynomial_features_csc_X(deg, include_bias, interaction_only, dtype):
      rng = np.random.RandomState(0)
      X = rng.randint(0, 2, (100, 2))
      X_csc = sparse.csc_matrix(X)
  
      est = PolynomialFeatures(
          deg, include_bias=include_bias, interaction_only=interaction_only
      )
      Xt_csc = est.fit_transform(X_csc.astype(dtype))
      Xt_dense = est.fit_transform(X.astype(dtype))
  
      assert isinstance(Xt_csc, sparse.csc_matrix)
      assert Xt_csc.dtype == Xt_dense.dtype
      assert_array_almost_equal(Xt_csc.A, Xt_dense)
  
  
  @pytest.mark.parametrize(
      ["deg", "include_bias", "interaction_only", "dtype"],
      [
          (1, True, False, int),
          (2, True, False, int),
          (2, True, False, np.float32),
          (2, True, False, np.float64),
          (3, False, False, np.float64),
          (3, False, True, np.float64),
      ],
  )
  def test_polynomial_features_csr_X(deg, include_bias, interaction_only, dtype):
      rng = np.random.RandomState(0)
      X = rng.randint(0, 2, (100, 2))
      X_csr = sparse.csr_matrix(X)
  
      est = PolynomialFeatures(
          deg, include_bias=include_bias, interaction_only=interaction_only
      )
      Xt_csr = est.fit_transform(X_csr.astype(dtype))
      Xt_dense = est.fit_transform(X.astype(dtype, copy=False))
  
      assert isinstance(Xt_csr, sparse.csr_matrix)
      assert Xt_csr.dtype == Xt_dense.dtype
      assert_array_almost_equal(Xt_csr.A, Xt_dense)
  
  
  @pytest.mark.parametrize("n_features", [1, 4, 5])
  @pytest.mark.parametrize(
      "min_degree, max_degree", [(0, 1), (0, 2), (1, 3), (0, 4), (3, 4)]
  )
  @pytest.mark.parametrize("interaction_only", [True, False])
  @pytest.mark.parametrize("include_bias", [True, False])
  def test_num_combinations(
      n_features,
      min_degree,
      max_degree,
      interaction_only,
      include_bias,
  ):
      """
      Test that n_output_features_ is calculated correctly.
      """
      x = sparse.csr_matrix(([1], ([0], [n_features - 1])))
      est = PolynomialFeatures(
          degree=max_degree,
          interaction_only=interaction_only,
          include_bias=include_bias,
      )
      est.fit(x)
      num_combos = est.n_output_features_
  
      combos = PolynomialFeatures._combinations(
          n_features=n_features,
          min_degree=0,
          max_degree=max_degree,
          interaction_only=interaction_only,
          include_bias=include_bias,
      )
      assert num_combos == sum([1 for _ in combos])
  
  
  @pytest.mark.parametrize(
      ["deg", "include_bias", "interaction_only", "dtype"],
      [
          (2, True, False, np.float32),
          (2, True, False, np.float64),
          (3, False, False, np.float64),
          (3, False, True, np.float64),
      ],
  )
  def test_polynomial_features_csr_X_floats(deg, include_bias, interaction_only, dtype):
      X_csr = sparse_random(1000, 10, 0.5, random_state=0).tocsr()
      X = X_csr.toarray()
  
      est = PolynomialFeatures(
          deg, include_bias=include_bias, interaction_only=interaction_only
      )
      Xt_csr = est.fit_transform(X_csr.astype(dtype))
      Xt_dense = est.fit_transform(X.astype(dtype))
  
      assert isinstance(Xt_csr, sparse.csr_matrix)
      assert Xt_csr.dtype == Xt_dense.dtype
      assert_array_almost_equal(Xt_csr.A, Xt_dense)
  
  
  @pytest.mark.parametrize(
      ["zero_row_index", "deg", "interaction_only"],
      [
          (0, 2, True),
          (1, 2, True),
          (2, 2, True),
          (0, 3, True),
          (1, 3, True),
          (2, 3, True),
          (0, 2, False),
          (1, 2, False),
          (2, 2, False),
          (0, 3, False),
          (1, 3, False),
          (2, 3, False),
      ],
  )
  def test_polynomial_features_csr_X_zero_row(zero_row_index, deg, interaction_only):
      X_csr = sparse_random(3, 10, 1.0, random_state=0).tocsr()
      X_csr[zero_row_index, :] = 0.0
      X = X_csr.toarray()
  
      est = PolynomialFeatures(deg, include_bias=False, interaction_only=interaction_only)
      Xt_csr = est.fit_transform(X_csr)
      Xt_dense = est.fit_transform(X)
  
      assert isinstance(Xt_csr, sparse.csr_matrix)
      assert Xt_csr.dtype == Xt_dense.dtype
      assert_array_almost_equal(Xt_csr.A, Xt_dense)
  
  
  # This degree should always be one more than the highest degree supported by
  # _csr_expansion.
  @pytest.mark.parametrize(
      ["include_bias", "interaction_only"],
      [(True, True), (True, False), (False, True), (False, False)],
  )
  def test_polynomial_features_csr_X_degree_4(include_bias, interaction_only):
      X_csr = sparse_random(1000, 10, 0.5, random_state=0).tocsr()
      X = X_csr.toarray()
  
      est = PolynomialFeatures(
          4, include_bias=include_bias, interaction_only=interaction_only
      )
      Xt_csr = est.fit_transform(X_csr)
      Xt_dense = est.fit_transform(X)
  
      assert isinstance(Xt_csr, sparse.csr_matrix)
      assert Xt_csr.dtype == Xt_dense.dtype
      assert_array_almost_equal(Xt_csr.A, Xt_dense)
  
  
  @pytest.mark.parametrize(
      ["deg", "dim", "interaction_only"],
      [
          (2, 1, True),
          (2, 2, True),
          (3, 1, True),
          (3, 2, True),
          (3, 3, True),
          (2, 1, False),
          (2, 2, False),
          (3, 1, False),
          (3, 2, False),
          (3, 3, False),
      ],
  )
  def test_polynomial_features_csr_X_dim_edges(deg, dim, interaction_only):
      X_csr = sparse_random(1000, dim, 0.5, random_state=0).tocsr()
      X = X_csr.toarray()
  
      est = PolynomialFeatures(deg, interaction_only=interaction_only)
      Xt_csr = est.fit_transform(X_csr)
      Xt_dense = est.fit_transform(X)
  
      assert isinstance(Xt_csr, sparse.csr_matrix)
      assert Xt_csr.dtype == Xt_dense.dtype
      assert_array_almost_equal(Xt_csr.A, Xt_dense)
  
  
  def test_polynomial_features_deprecated_n_input_features():
      # check that we raise a deprecation warning when accessing
      # `n_input_features_`. FIXME: remove in 1.2
      depr_msg = (
          "The attribute `n_input_features_` was deprecated in version "
          "1.0 and will be removed in 1.2."
      )
      X = np.arange(10).reshape(5, 2)
  
      with pytest.warns(FutureWarning, match=depr_msg):
          PolynomialFeatures().fit(X).n_input_features_
   # Authors: Nicolas Tresegnie <nicolas.tresegnie@gmail.com>
  #          Sergey Feldman <sergeyfeldman@gmail.com>
  # License: BSD 3 clause
  
  import numbers
  import warnings
  from collections import Counter
  
  import numpy as np
  import numpy.ma as ma
  from scipy import sparse as sp
  from scipy import stats
  
  from ..base import BaseEstimator, TransformerMixin
  from ..utils.sparsefuncs import _get_median
  from ..utils.validation import check_is_fitted
  from ..utils.validation import FLOAT_DTYPES
  from ..utils._mask import _get_mask
  from ..utils import is_scalar_nan
  
  
  def _check_inputs_dtype(X, missing_values):
      if X.dtype.kind in ("f", "i", "u") and not isinstance(missing_values, numbers.Real):
          raise ValueError(
              "'X' and 'missing_values' types are expected to be"
              " both numerical. Got X.dtype={} and "
              " type(missing_values)={}.".format(X.dtype, type(missing_values))
          )
  
  
  def _most_frequent(array, extra_value, n_repeat):
      """Compute the most frequent value in a 1d array extended with
      [extra_value] * n_repeat, where extra_value is assumed to be not part
      of the array."""
      # Compute the most frequent value in array only
      if array.size > 0:
          if array.dtype == object:
              # scipy.stats.mode is slow with object dtype array.
              # Python Counter is more efficient
              counter = Counter(array)
              most_frequent_count = counter.most_common(1)[0][1]
              # tie breaking similarly to scipy.stats.mode
              most_frequent_value = min(
                  value
                  for value, count in counter.items()
                  if count == most_frequent_count
              )
          else:
              mode = stats.mode(array)
              most_frequent_value = mode[0][0]
              most_frequent_count = mode[1][0]
      else:
          most_frequent_value = 0
          most_frequent_count = 0
  
      # Compare to array + [extra_value] * n_repeat
      if most_frequent_count == 0 and n_repeat == 0:
          return np.nan
      elif most_frequent_count < n_repeat:
          return extra_value
      elif most_frequent_count > n_repeat:
          return most_frequent_value
      elif most_frequent_count == n_repeat:
          # tie breaking similarly to scipy.stats.mode
          return min(most_frequent_value, extra_value)
  
  
  class _BaseImputer(TransformerMixin, BaseEstimator):
      """Base class for all imputers.
  
      It adds automatically support for `add_indicator`.
      """
  
      def __init__(self, *, missing_values=np.nan, add_indicator=False):
          self.missing_values = missing_values
          self.add_indicator = add_indicator
  
      def _fit_indicator(self, X):
          """Fit a MissingIndicator."""
          if self.add_indicator:
              self.indicator_ = MissingIndicator(
                  missing_values=self.missing_values, error_on_new=False
              )
              self.indicator_._fit(X, precomputed=True)
          else:
              self.indicator_ = None
  
      def _transform_indicator(self, X):
          """Compute the indicator mask.'
  
          Note that X must be the original data as passed to the imputer before
          any imputation, since imputation may be done inplace in some cases.
          """
          if self.add_indicator:
              if not hasattr(self, "indicator_"):
                  raise ValueError(
                      "Make sure to call _fit_indicator before _transform_indicator"
                  )
              return self.indicator_.transform(X)
  
      def _concatenate_indicator(self, X_imputed, X_indicator):
          """Concatenate indicator mask with the imputed data."""
          if not self.add_indicator:
              return X_imputed
  
          hstack = sp.hstack if sp.issparse(X_imputed) else np.hstack
          if X_indicator is None:
              raise ValueError(
                  "Data from the missing indicator are not provided. Call "
                  "_fit_indicator and _transform_indicator in the imputer "
                  "implementation."
              )
  
          return hstack((X_imputed, X_indicator))
  
      def _more_tags(self):
          return {"allow_nan": is_scalar_nan(self.missing_values)}
  
  
  class SimpleImputer(_BaseImputer):
      """Imputation transformer for completing missing values.
  
      Read more in the :ref:`User Guide <impute>`.
  
      .. versionadded:: 0.20
         `SimpleImputer` replaces the previous `sklearn.preprocessing.Imputer`
         estimator which is now removed.
  
      Parameters
      ----------
      missing_values : int, float, str, np.nan or None, default=np.nan
          The placeholder for the missing values. All occurrences of
          `missing_values` will be imputed. For pandas' dataframes with
          nullable integer dtypes with missing values, `missing_values`
          should be set to `np.nan`, since `pd.NA` will be converted to `np.nan`.
  
      strategy : string, default='mean'
          The imputation strategy.
  
          - If "mean", then replace missing values using the mean along
            each column. Can only be used with numeric data.
          - If "median", then replace missing values using the median along
            each column. Can only be used with numeric data.
          - If "most_frequent", then replace missing using the most frequent
            value along each column. Can be used with strings or numeric data.
            If there is more than one such value, only the smallest is returned.
          - If "constant", then replace missing values with fill_value. Can be
            used with strings or numeric data.
  
          .. versionadded:: 0.20
             strategy="constant" for fixed value imputation.
  
      fill_value : string or numerical value, default=None
          When strategy == "constant", fill_value is used to replace all
          occurrences of missing_values.
          If left to the default, fill_value will be 0 when imputing numerical
          data and "missing_value" for strings or object data types.
  
      verbose : integer, default=0
          Controls the verbosity of the imputer.
  
      copy : boolean, default=True
          If True, a copy of X will be created. If False, imputation will
          be done in-place whenever possible. Note that, in the following cases,
          a new copy will always be made, even if `copy=False`:
  
          - If X is not an array of floating values;
          - If X is encoded as a CSR matrix;
          - If add_indicator=True.
  
      add_indicator : boolean, default=False
          If True, a :class:`MissingIndicator` transform will stack onto output
          of the imputer's transform. This allows a predictive estimator
          to account for missingness despite imputation. If a feature has no
          missing values at fit/train time, the feature won't appear on
          the missing indicator even if there are missing values at
          transform/test time.
  
      Attributes
      ----------
      statistics_ : array of shape (n_features,)
          The imputation fill value for each feature.
          Computing statistics can result in `np.nan` values.
          During :meth:`transform`, features corresponding to `np.nan`
          statistics will be discarded.
  
      indicator_ : :class:`~sklearn.impute.MissingIndicator`
          Indicator used to add binary indicators for missing values.
          ``None`` if add_indicator is False.
  
      n_features_in_ : int
          Number of features seen during :term:`fit`.
  
          .. versionadded:: 0.24
  
      See Also
      --------
      IterativeImputer : Multivariate imputation of missing values.
  
      Examples
      --------
      >>> import numpy as np
      >>> from sklearn.impute import SimpleImputer
      >>> imp_mean = SimpleImputer(missing_values=np.nan, strategy='mean')
      >>> imp_mean.fit([[7, 2, 3], [4, np.nan, 6], [10, 5, 9]])
      SimpleImputer()
      >>> X = [[np.nan, 2, 3], [4, np.nan, 6], [10, np.nan, 9]]
      >>> print(imp_mean.transform(X))
      [[ 7.   2.   3. ]
       [ 4.   3.5  6. ]
       [10.   3.5  9. ]]
  
      Notes
      -----
      Columns which only contained missing values at :meth:`fit` are discarded
      upon :meth:`transform` if strategy is not "constant".
  
      """
  
      def __init__(
          self,
          *,
          missing_values=np.nan,
          strategy="mean",
          fill_value=None,
          verbose=0,
          copy=True,
          add_indicator=False,
      ):
          super().__init__(missing_values=missing_values, add_indicator=add_indicator)
          self.strategy = strategy
          self.fill_value = fill_value
          self.verbose = verbose
          self.copy = copy
  
      def _validate_input(self, X, in_fit):
          allowed_strategies = ["mean", "median", "most_frequent", "constant"]
          if self.strategy not in allowed_strategies:
              raise ValueError(
                  "Can only use these strategies: {0}  got strategy={1}".format(
                      allowed_strategies, self.strategy
                  )
              )
  
          if self.strategy in ("most_frequent", "constant"):
              # If input is a list of strings, dtype = object.
              # Otherwise ValueError is raised in SimpleImputer
              # with strategy='most_frequent' or 'constant'
              # because the list is converted to Unicode numpy array
              if isinstance(X, list) and any(
                  isinstance(elem, str) for row in X for elem in row
              ):
                  dtype = object
              else:
                  dtype = None
          else:
              dtype = FLOAT_DTYPES
  
          if not is_scalar_nan(self.missing_values):
              force_all_finite = True
          else:
              force_all_finite = "allow-nan"
  
          try:
              X = self._validate_data(
                  X,
                  reset=in_fit,
                  accept_sparse="csc",
                  dtype=dtype,
                  force_all_finite=force_all_finite,
                  copy=self.copy,
              )
          except ValueError as ve:
              if "could not convert" in str(ve):
                  new_ve = ValueError(
                      "Cannot use {} strategy with non-numeric data:\n{}".format(
                          self.strategy, ve
                      )
                  )
                  raise new_ve from None
              else:
                  raise ve
  
          _check_inputs_dtype(X, self.missing_values)
          if X.dtype.kind not in ("i", "u", "f", "O"):
              raise ValueError(
                  "SimpleImputer does not support data with dtype "
                  "{0}. Please provide either a numeric array (with"
                  " a floating point or integer dtype) or "
                  "categorical data represented either as an array "
                  "with integer dtype or an array of string values "
                  "with an object dtype.".format(X.dtype)
              )
  
          return X
  
      def fit(self, X, y=None):
          """Fit the imputer on X.
  
          Parameters
          ----------
          X : {array-like, sparse matrix}, shape (n_samples, n_features)
              Input data, where ``n_samples`` is the number of samples and
              ``n_features`` is the number of features.
  
          Returns
          -------
          self : SimpleImputer
          """
          X = self._validate_input(X, in_fit=True)
  
          # default fill_value is 0 for numerical input and "missing_value"
          # otherwise
          if self.fill_value is None:
              if X.dtype.kind in ("i", "u", "f"):
                  fill_value = 0
              else:
                  fill_value = "missing_value"
          else:
              fill_value = self.fill_value
  
          # fill_value should be numerical in case of numerical input
          if (
              self.strategy == "constant"
              and X.dtype.kind in ("i", "u", "f")
              and not isinstance(fill_value, numbers.Real)
          ):
              raise ValueError(
                  "'fill_value'={0} is invalid. Expected a "
                  "numerical value when imputing numerical "
                  "data".format(fill_value)
              )
  
          if sp.issparse(X):
              # missing_values = 0 not allowed with sparse data as it would
              # force densification
              if self.missing_values == 0:
                  raise ValueError(
                      "Imputation not possible when missing_values "
                      "== 0 and input is sparse. Provide a dense "
                      "array instead."
                  )
              else:
                  self.statistics_ = self._sparse_fit(
                      X, self.strategy, self.missing_values, fill_value
                  )
  
          else:
              self.statistics_ = self._dense_fit(
                  X, self.strategy, self.missing_values, fill_value
              )
  
          return self
  
      def _sparse_fit(self, X, strategy, missing_values, fill_value):
          """Fit the transformer on sparse data."""
          missing_mask = _get_mask(X, missing_values)
          mask_data = missing_mask.data
          n_implicit_zeros = X.shape[0] - np.diff(X.indptr)
  
          statistics = np.empty(X.shape[1])
  
          if strategy == "constant":
              # for constant strategy, self.statistcs_ is used to store
              # fill_value in each column
              statistics.fill(fill_value)
          else:
              for i in range(X.shape[1]):
                  column = X.data[X.indptr[i] : X.indptr[i + 1]]
                  mask_column = mask_data[X.indptr[i] : X.indptr[i + 1]]
                  column = column[~mask_column]
  
                  # combine explicit and implicit zeros
                  mask_zeros = _get_mask(column, 0)
                  column = column[~mask_zeros]
                  n_explicit_zeros = mask_zeros.sum()
                  n_zeros = n_implicit_zeros[i] + n_explicit_zeros
  
                  if strategy == "mean":
                      s = column.size + n_zeros
                      statistics[i] = np.nan if s == 0 else column.sum() / s
  
                  elif strategy == "median":
                      statistics[i] = _get_median(column, n_zeros)
  
                  elif strategy == "most_frequent":
                      statistics[i] = _most_frequent(column, 0, n_zeros)
          super()._fit_indicator(missing_mask)
  
          return statistics
  
      def _dense_fit(self, X, strategy, missing_values, fill_value):
          """Fit the transformer on dense data."""
          missing_mask = _get_mask(X, missing_values)
          masked_X = ma.masked_array(X, mask=missing_mask)
  
          super()._fit_indicator(missing_mask)
  
          # Mean
          if strategy == "mean":
              mean_masked = np.ma.mean(masked_X, axis=0)
              # Avoid the warning "Warning: converting a masked element to nan."
              mean = np.ma.getdata(mean_masked)
              mean[np.ma.getmask(mean_masked)] = np.nan
  
              return mean
  
          # Median
          elif strategy == "median":
              median_masked = np.ma.median(masked_X, axis=0)
              # Avoid the warning "Warning: converting a masked element to nan."
              median = np.ma.getdata(median_masked)
              median[np.ma.getmaskarray(median_masked)] = np.nan
  
              return median
  
          # Most frequent
          elif strategy == "most_frequent":
              # Avoid use of scipy.stats.mstats.mode due to the required
              # additional overhead and slow benchmarking performance.
              # See Issue 14325 and PR 14399 for full discussion.
  
              # To be able access the elements by columns
              X = X.transpose()
              mask = missing_mask.transpose()
  
              if X.dtype.kind == "O":
                  most_frequent = np.empty(X.shape[0], dtype=object)
              else:
                  most_frequent = np.empty(X.shape[0])
  
              for i, (row, row_mask) in enumerate(zip(X[:], mask[:])):
                  row_mask = np.logical_not(row_mask).astype(bool)
                  row = row[row_mask]
                  most_frequent[i] = _most_frequent(row, np.nan, 0)
  
              return most_frequent
  
          # Constant
          elif strategy == "constant":
              # for constant strategy, self.statistcs_ is used to store
              # fill_value in each column
              return np.full(X.shape[1], fill_value, dtype=X.dtype)
  
      def transform(self, X):
          """Impute all missing values in X.
  
          Parameters
          ----------
          X : {array-like, sparse matrix}, shape (n_samples, n_features)
              The input data to complete.
  
          Returns
          -------
          X_imputed : {ndarray, sparse matrix} of shape \
                  (n_samples, n_features_out)
              `X` with imputed values.
          """
          check_is_fitted(self)
  
          X = self._validate_input(X, in_fit=False)
          statistics = self.statistics_
  
          if X.shape[1] != statistics.shape[0]:
              raise ValueError(
                  "X has %d features per sample, expected %d"
                  % (X.shape[1], self.statistics_.shape[0])
              )
  
          # compute mask before eliminating invalid features
          missing_mask = _get_mask(X, self.missing_values)
  
          # Delete the invalid columns if strategy is not constant
          if self.strategy == "constant":
              valid_statistics = statistics
              valid_statistics_indexes = None
          else:
              # same as np.isnan but also works for object dtypes
              invalid_mask = _get_mask(statistics, np.nan)
              valid_mask = np.logical_not(invalid_mask)
              valid_statistics = statistics[valid_mask]
              valid_statistics_indexes = np.flatnonzero(valid_mask)
  
              if invalid_mask.any():
                  missing = np.arange(X.shape[1])[invalid_mask]
                  if self.verbose:
                      warnings.warn(
                          "Deleting features without observed values: %s" % missing
                      )
                  X = X[:, valid_statistics_indexes]
  
          # Do actual imputation
          if sp.issparse(X):
              if self.missing_values == 0:
                  raise ValueError(
                      "Imputation not possible when missing_values "
                      "== 0 and input is sparse. Provide a dense "
                      "array instead."
                  )
              else:
                  # if no invalid statistics are found, use the mask computed
                  # before, else recompute mask
                  if valid_statistics_indexes is None:
                      mask = missing_mask.data
                  else:
                      mask = _get_mask(X.data, self.missing_values)
                  indexes = np.repeat(
                      np.arange(len(X.indptr) - 1, dtype=int), np.diff(X.indptr)
                  )[mask]
  
                  X.data[mask] = valid_statistics[indexes].astype(X.dtype, copy=False)
          else:
              # use mask computed before eliminating invalid mask
              if valid_statistics_indexes is None:
                  mask_valid_features = missing_mask
              else:
                  mask_valid_features = missing_mask[:, valid_statistics_indexes]
              n_missing = np.sum(mask_valid_features, axis=0)
              values = np.repeat(valid_statistics, n_missing)
              coordinates = np.where(mask_valid_features.transpose())[::-1]
  
              X[coordinates] = values
  
          X_indicator = super()._transform_indicator(missing_mask)
  
          return super()._concatenate_indicator(X, X_indicator)
  
      def inverse_transform(self, X):
          """Convert the data back to the original representation.
  
          Inverts the `transform` operation performed on an array.
          This operation can only be performed after :class:`SimpleImputer` is
          instantiated with `add_indicator=True`.
  
          Note that ``inverse_transform`` can only invert the transform in
          features that have binary indicators for missing values. If a feature
          has no missing values at ``fit`` time, the feature won't have a binary
          indicator, and the imputation done at ``transform`` time won't be
          inverted.
  
          .. versionadded:: 0.24
  
          Parameters
          ----------
          X : array-like of shape \
                  (n_samples, n_features + n_features_missing_indicator)
              The imputed data to be reverted to original data. It has to be
              an augmented array of imputed data and the missing indicator mask.
  
          Returns
          -------
          X_original : ndarray of shape (n_samples, n_features)
              The original X with missing values as it was prior
              to imputation.
          """
          check_is_fitted(self)
  
          if not self.add_indicator:
              raise ValueError(
                  "'inverse_transform' works only when "
                  "'SimpleImputer' is instantiated with "
                  "'add_indicator=True'. "
                  f"Got 'add_indicator={self.add_indicator}' "
                  "instead."
              )
  
          n_features_missing = len(self.indicator_.features_)
          non_empty_feature_count = X.shape[1] - n_features_missing
          array_imputed = X[:, :non_empty_feature_count].copy()
          missing_mask = X[:, non_empty_feature_count:].astype(bool)
  
          n_features_original = len(self.statistics_)
          shape_original = (X.shape[0], n_features_original)
          X_original = np.zeros(shape_original)
          X_original[:, self.indicator_.features_] = missing_mask
          full_mask = X_original.astype(bool)
  
          imputed_idx, original_idx = 0, 0
          while imputed_idx < len(array_imputed.T):
              if not np.all(X_original[:, original_idx]):
                  X_original[:, original_idx] = array_imputed.T[imputed_idx]
                  imputed_idx += 1
                  original_idx += 1
              else:
                  original_idx += 1
  
          X_original[full_mask] = self.missing_values
          return X_original
  
  
  class MissingIndicator(TransformerMixin, BaseEstimator):
      """Binary indicators for missing values.
  
      Note that this component typically should not be used in a vanilla
      :class:`Pipeline` consisting of transformers and a classifier, but rather
      could be added using a :class:`FeatureUnion` or :class:`ColumnTransformer`.
  
      Read more in the :ref:`User Guide <impute>`.
  
      .. versionadded:: 0.20
  
      Parameters
      ----------
      missing_values : int, float, string, np.nan or None, default=np.nan
          The placeholder for the missing values. All occurrences of
          `missing_values` will be imputed. For pandas' dataframes with
          nullable integer dtypes with missing values, `missing_values`
          should be set to `np.nan`, since `pd.NA` will be converted to `np.nan`.
  
      features : {'missing-only', 'all'}, default='missing-only'
          Whether the imputer mask should represent all or a subset of
          features.
  
          - If 'missing-only' (default), the imputer mask will only represent
            features containing missing values during fit time.
          - If 'all', the imputer mask will represent all features.
  
      sparse : bool or 'auto', default='auto'
          Whether the imputer mask format should be sparse or dense.
  
          - If 'auto' (default), the imputer mask will be of same type as
            input.
          - If True, the imputer mask will be a sparse matrix.
          - If False, the imputer mask will be a numpy array.
  
      error_on_new : bool, default=True
          If True, transform will raise an error when there are features with
          missing values in transform that have no missing values in fit. This is
          applicable only when `features='missing-only'`.
  
      Attributes
      ----------
      features_ : ndarray, shape (n_missing_features,) or (n_features,)
          The features indices which will be returned when calling ``transform``.
          They are computed during ``fit``. For ``features='all'``, it is
          to ``range(n_features)``.
  
      n_features_in_ : int
          Number of features seen during :term:`fit`.
  
          .. versionadded:: 0.24
  
      Examples
      --------
      >>> import numpy as np
      >>> from sklearn.impute import MissingIndicator
      >>> X1 = np.array([[np.nan, 1, 3],
      ...                [4, 0, np.nan],
      ...                [8, 1, 0]])
      >>> X2 = np.array([[5, 1, np.nan],
      ...                [np.nan, 2, 3],
      ...                [2, 4, 0]])
      >>> indicator = MissingIndicator()
      >>> indicator.fit(X1)
      MissingIndicator()
      >>> X2_tr = indicator.transform(X2)
      >>> X2_tr
      array([[False,  True],
             [ True, False],
             [False, False]])
  
      """
  
      def __init__(
          self,
          *,
          missing_values=np.nan,
          features="missing-only",
          sparse="auto",
          error_on_new=True,
      ):
          self.missing_values = missing_values
          self.features = features
          self.sparse = sparse
          self.error_on_new = error_on_new
  
      def _get_missing_features_info(self, X):
          """Compute the imputer mask and the indices of the features
          containing missing values.
  
          Parameters
          ----------
          X : {ndarray or sparse matrix}, shape (n_samples, n_features)
              The input data with missing values. Note that ``X`` has been
              checked in ``fit`` and ``transform`` before to call this function.
  
          Returns
          -------
          imputer_mask : {ndarray or sparse matrix}, shape \
          (n_samples, n_features)
              The imputer mask of the original data.
  
          features_with_missing : ndarray, shape (n_features_with_missing)
              The features containing missing values.
  
          """
          if not self._precomputed:
              imputer_mask = _get_mask(X, self.missing_values)
          else:
              imputer_mask = X
  
          if sp.issparse(X):
              imputer_mask.eliminate_zeros()
  
              if self.features == "missing-only":
                  n_missing = imputer_mask.getnnz(axis=0)
  
              if self.sparse is False:
                  imputer_mask = imputer_mask.toarray()
              elif imputer_mask.format == "csr":
                  imputer_mask = imputer_mask.tocsc()
          else:
              if not self._precomputed:
                  imputer_mask = _get_mask(X, self.missing_values)
              else:
                  imputer_mask = X
  
              if self.features == "missing-only":
                  n_missing = imputer_mask.sum(axis=0)
  
              if self.sparse is True:
                  imputer_mask = sp.csc_matrix(imputer_mask)
  
          if self.features == "all":
              features_indices = np.arange(X.shape[1])
          else:
              features_indices = np.flatnonzero(n_missing)
  
          return imputer_mask, features_indices
  
      def _validate_input(self, X, in_fit):
          if not is_scalar_nan(self.missing_values):
              force_all_finite = True
          else:
              force_all_finite = "allow-nan"
          X = self._validate_data(
              X,
              reset=in_fit,
              accept_sparse=("csc", "csr"),
              dtype=None,
              force_all_finite=force_all_finite,
          )
          _check_inputs_dtype(X, self.missing_values)
          if X.dtype.kind not in ("i", "u", "f", "O"):
              raise ValueError(
                  "MissingIndicator does not support data with "
                  "dtype {0}. Please provide either a numeric array"
                  " (with a floating point or integer dtype) or "
                  "categorical data represented either as an array "
                  "with integer dtype or an array of string values "
                  "with an object dtype.".format(X.dtype)
              )
  
          if sp.issparse(X) and self.missing_values == 0:
              # missing_values = 0 not allowed with sparse data as it would
              # force densification
              raise ValueError(
                  "Sparse input with missing_values=0 is "
                  "not supported. Provide a dense "
                  "array instead."
              )
  
          return X
  
      def _fit(self, X, y=None, precomputed=False):
          """Fit the transformer on X.
  
          Parameters
          ----------
          X : {array-like, sparse matrix}, shape (n_samples, n_features)
              Input data, where ``n_samples`` is the number of samples and
              ``n_features`` is the number of features.
              If `precomputed` is True, then `X` is a mask of the
              input data.
  
          precomputed : bool
              Whether the input data is a mask.
  
          Returns
          -------
          imputer_mask : {ndarray or sparse matrix}, shape (n_samples, \
          n_features)
              The imputer mask of the original data.
  
          """
          if precomputed:
              if not (hasattr(X, "dtype") and X.dtype.kind == "b"):
                  raise ValueError("precomputed is True but the input data is not a mask")
              self._precomputed = True
          else:
              self._precomputed = False
  
          # Need not validate X again as it would have already been validated
          # in the Imputer calling MissingIndicator
          if not self._precomputed:
              X = self._validate_input(X, in_fit=True)
  
          self._n_features = X.shape[1]
  
          if self.features not in ("missing-only", "all"):
              raise ValueError(
                  "'features' has to be either 'missing-only' or "
                  "'all'. Got {} instead.".format(self.features)
              )
  
          if not (
              (isinstance(self.sparse, str) and self.sparse == "auto")
              or isinstance(self.sparse, bool)
          ):
              raise ValueError(
                  "'sparse' has to be a boolean or 'auto'. Got {!r} instead.".format(
                      self.sparse
                  )
              )
  
          missing_features_info = self._get_missing_features_info(X)
          self.features_ = missing_features_info[1]
  
          return missing_features_info[0]
  
      def fit(self, X, y=None):
          """Fit the transformer on X.
  
          Parameters
          ----------
          X : {array-like, sparse matrix}, shape (n_samples, n_features)
              Input data, where ``n_samples`` is the number of samples and
              ``n_features`` is the number of features.
  
          Returns
          -------
          self : object
              Returns self.
          """
          self._fit(X, y)
  
          return self
  
      def transform(self, X):
          """Generate missing values indicator for X.
  
          Parameters
          ----------
          X : {array-like, sparse matrix}, shape (n_samples, n_features)
              The input data to complete.
  
          Returns
          -------
          Xt : {ndarray or sparse matrix}, shape (n_samples, n_features) \
          or (n_samples, n_features_with_missing)
              The missing indicator for input data. The data type of ``Xt``
              will be boolean.
  
          """
          check_is_fitted(self)
  
          # Need not validate X again as it would have already been validated
          # in the Imputer calling MissingIndicator
          if not self._precomputed:
              X = self._validate_input(X, in_fit=False)
          else:
              if not (hasattr(X, "dtype") and X.dtype.kind == "b"):
                  raise ValueError("precomputed is True but the input data is not a mask")
  
          imputer_mask, features = self._get_missing_features_info(X)
  
          if self.features == "missing-only":
              features_diff_fit_trans = np.setdiff1d(features, self.features_)
              if self.error_on_new and features_diff_fit_trans.size > 0:
                  raise ValueError(
                      "The features {} have missing values "
                      "in transform but have no missing values "
                      "in fit.".format(features_diff_fit_trans)
                  )
  
              if self.features_.size < self._n_features:
                  imputer_mask = imputer_mask[:, self.features_]
  
          return imputer_mask
  
      def fit_transform(self, X, y=None):
          """Generate missing values indicator for X.
  
          Parameters
          ----------
          X : {array-like, sparse matrix}, shape (n_samples, n_features)
              The input data to complete.
  
          Returns
          -------
          Xt : {ndarray or sparse matrix}, shape (n_samples, n_features) \
          or (n_samples, n_features_with_missing)
              The missing indicator for input data. The data type of ``Xt``
              will be boolean.
  
          """
          imputer_mask = self._fit(X, y)
  
          if self.features_.size < self._n_features:
              imputer_mask = imputer_mask[:, self.features_]
  
          return imputer_mask
  
      def _more_tags(self):
          return {
              "allow_nan": True,
              "X_types": ["2darray", "string"],
              "preserves_dtype": [],
          }
  
apis: numpy.diff numpy.ones_like numpy.asarray numpy.random.RandomState sklearn.utils.fixes.parse_version scipy.sparse.csc_matrix sklearn.linear_model.LinearRegression sklearn.preprocessing.PolynomialFeatures._combinations numpy.testing.assert_array_equal numpy.abs numpy.linspace sklearn.utils._testing.assert_array_almost_equal sklearn.preprocessing.KBinsDiscretizer numpy.arange numpy.hstack sklearn.utils.fixes.linspace scipy.sparse.random sklearn.preprocessing.SplineTransformer scipy.sparse.csr_matrix numpy.isfortran numpy.testing.assert_allclose numpy.array numpy.sin sklearn.preprocessing.PolynomialFeatures
apis: numpy.sum scipy.stats.mode numpy.diff numpy.ma.getmaskarray numpy.ma.masked_array scipy.sparse.csc_matrix numpy.logical_not numpy.flatnonzero numpy.ma.getdata numpy.ma.median numpy.ma.mean numpy.zeros numpy.ma.getmask numpy.setdiff1d numpy.repeat numpy.arange numpy.all numpy.empty scipy.sparse.issparse numpy.full