diff --git "a/test/data.jsonl" "b/test/data.jsonl" --- "a/test/data.jsonl" +++ "b/test/data.jsonl" @@ -14,7 +14,7 @@ {"repo": "matplotlib/matplotlib", "instance_id": "matplotlib__matplotlib-25779", "html_url": "https://github.com/matplotlib/matplotlib/pull/25779", "feature_patch": "diff --git a/doc/users/next_whats_new/get_vertices_co_vertices.rst b/doc/users/next_whats_new/get_vertices_co_vertices.rst\nnew file mode 100644\nindex 000000000000..98254a82ce63\n--- /dev/null\n+++ b/doc/users/next_whats_new/get_vertices_co_vertices.rst\n@@ -0,0 +1,7 @@\n+``Ellipse.get_vertices()``, ``Ellipse.get_co_vertices()``\n+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n+These methods return the coordinates of ellipse vertices of\n+major and minor axis. Additionally, an example gallery demo is added which\n+shows how to add an arrow to an ellipse showing a clockwise or counter-clockwise\n+rotation of the ellipse. To place the arrow exactly on the ellipse,\n+the coordinates of the vertices are used.\ndiff --git a/galleries/examples/shapes_and_collections/ellipse_arrow.py b/galleries/examples/shapes_and_collections/ellipse_arrow.py\nnew file mode 100644\nindex 000000000000..4bcdc016faa6\n--- /dev/null\n+++ b/galleries/examples/shapes_and_collections/ellipse_arrow.py\n@@ -0,0 +1,53 @@\n+\"\"\"\n+===================================\n+Ellipse with orientation arrow demo\n+===================================\n+\n+This demo shows how to draw an ellipse with\n+an orientation arrow (clockwise or counterclockwise).\n+Compare this to the :doc:`Ellipse collection example\n+`.\n+\"\"\"\n+\n+import matplotlib.pyplot as plt\n+\n+from matplotlib.markers import MarkerStyle\n+from matplotlib.patches import Ellipse\n+from matplotlib.transforms import Affine2D\n+\n+# Create a figure and axis\n+fig, ax = plt.subplots(subplot_kw={\"aspect\": \"equal\"})\n+\n+ellipse = Ellipse(\n+ xy=(2, 4),\n+ width=30,\n+ height=20,\n+ angle=35,\n+ facecolor=\"none\",\n+ edgecolor=\"b\"\n+)\n+ax.add_patch(ellipse)\n+\n+# Plot an arrow marker at the end point of minor axis\n+vertices = ellipse.get_co_vertices()\n+t = Affine2D().rotate_deg(ellipse.angle)\n+ax.plot(\n+ vertices[0][0],\n+ vertices[0][1],\n+ color=\"b\",\n+ marker=MarkerStyle(\">\", \"full\", t),\n+ markersize=10\n+)\n+# Note: To reverse the orientation arrow, switch the marker type from > to <.\n+\n+plt.show()\n+\n+# %%\n+#\n+# .. admonition:: References\n+#\n+# The use of the following functions, methods, classes and modules is shown\n+# in this example:\n+#\n+# - `matplotlib.patches`\n+# - `matplotlib.patches.Ellipse`\ndiff --git a/lib/matplotlib/patches.py b/lib/matplotlib/patches.py\nindex 245bb7b777c8..ecf03ca4051b 100644\n--- a/lib/matplotlib/patches.py\n+++ b/lib/matplotlib/patches.py\n@@ -1654,6 +1654,37 @@ def get_corners(self):\n return self.get_patch_transform().transform(\n [(-1, -1), (1, -1), (1, 1), (-1, 1)])\n \n+ def _calculate_length_between_points(self, x0, y0, x1, y1):\n+ return np.sqrt((x1 - x0)**2 + (y1 - y0)**2)\n+\n+ def get_vertices(self):\n+ \"\"\"\n+ Return the vertices coordinates of the ellipse.\n+\n+ The definition can be found `here `_\n+\n+ .. versionadded:: 3.8\n+ \"\"\"\n+ if self.width < self.height:\n+ ret = self.get_patch_transform().transform([(0, 1), (0, -1)])\n+ else:\n+ ret = self.get_patch_transform().transform([(1, 0), (-1, 0)])\n+ return [tuple(x) for x in ret]\n+\n+ def get_co_vertices(self):\n+ \"\"\"\n+ Return the co-vertices coordinates of the ellipse.\n+\n+ The definition can be found `here `_\n+\n+ .. versionadded:: 3.8\n+ \"\"\"\n+ if self.width < self.height:\n+ ret = self.get_patch_transform().transform([(1, 0), (-1, 0)])\n+ else:\n+ ret = self.get_patch_transform().transform([(0, 1), (0, -1)])\n+ return [tuple(x) for x in ret]\n+\n \n class Annulus(Patch):\n \"\"\"\ndiff --git a/lib/matplotlib/patches.pyi b/lib/matplotlib/patches.pyi\nindex 1e70a1efc3be..e9302563083c 100644\n--- a/lib/matplotlib/patches.pyi\n+++ b/lib/matplotlib/patches.pyi\n@@ -259,6 +259,10 @@ class Ellipse(Patch):\n \n def get_corners(self) -> np.ndarray: ...\n \n+ def get_vertices(self) -> list[tuple[float, float]]: ...\n+ def get_co_vertices(self) -> list[tuple[float, float]]: ...\n+\n+\n class Annulus(Patch):\n a: float\n b: float\n", "test_patch": "diff --git a/lib/matplotlib/tests/test_patches.py b/lib/matplotlib/tests/test_patches.py\nindex b9e1db32d419..fd872bac98d4 100644\n--- a/lib/matplotlib/tests/test_patches.py\n+++ b/lib/matplotlib/tests/test_patches.py\n@@ -104,6 +104,57 @@ def test_corner_center():\n assert_almost_equal(ellipse.get_corners(), corners_rot)\n \n \n+def test_ellipse_vertices():\n+ # expect 0 for 0 ellipse width, height\n+ ellipse = Ellipse(xy=(0, 0), width=0, height=0, angle=0)\n+ assert_almost_equal(\n+ ellipse.get_vertices(),\n+ [(0.0, 0.0), (0.0, 0.0)],\n+ )\n+ assert_almost_equal(\n+ ellipse.get_co_vertices(),\n+ [(0.0, 0.0), (0.0, 0.0)],\n+ )\n+\n+ ellipse = Ellipse(xy=(0, 0), width=2, height=1, angle=30)\n+ assert_almost_equal(\n+ ellipse.get_vertices(),\n+ [\n+ (\n+ ellipse.center[0] + ellipse.width / 4 * np.sqrt(3),\n+ ellipse.center[1] + ellipse.width / 4,\n+ ),\n+ (\n+ ellipse.center[0] - ellipse.width / 4 * np.sqrt(3),\n+ ellipse.center[1] - ellipse.width / 4,\n+ ),\n+ ],\n+ )\n+ assert_almost_equal(\n+ ellipse.get_co_vertices(),\n+ [\n+ (\n+ ellipse.center[0] - ellipse.height / 4,\n+ ellipse.center[1] + ellipse.height / 4 * np.sqrt(3),\n+ ),\n+ (\n+ ellipse.center[0] + ellipse.height / 4,\n+ ellipse.center[1] - ellipse.height / 4 * np.sqrt(3),\n+ ),\n+ ],\n+ )\n+ v1, v2 = np.array(ellipse.get_vertices())\n+ np.testing.assert_almost_equal((v1 + v2) / 2, ellipse.center)\n+ v1, v2 = np.array(ellipse.get_co_vertices())\n+ np.testing.assert_almost_equal((v1 + v2) / 2, ellipse.center)\n+\n+ ellipse = Ellipse(xy=(2.252, -10.859), width=2.265, height=1.98, angle=68.78)\n+ v1, v2 = np.array(ellipse.get_vertices())\n+ np.testing.assert_almost_equal((v1 + v2) / 2, ellipse.center)\n+ v1, v2 = np.array(ellipse.get_co_vertices())\n+ np.testing.assert_almost_equal((v1 + v2) / 2, ellipse.center)\n+\n+\n def test_rotate_rect():\n loc = np.asarray([1.0, 2.0])\n width = 2\n", "doc_changes": [{"path": "doc/users/next_whats_new/get_vertices_co_vertices.rst", "old_path": "/dev/null", "new_path": "b/doc/users/next_whats_new/get_vertices_co_vertices.rst", "metadata": "diff --git a/doc/users/next_whats_new/get_vertices_co_vertices.rst b/doc/users/next_whats_new/get_vertices_co_vertices.rst\nnew file mode 100644\nindex 000000000000..98254a82ce63\n--- /dev/null\n+++ b/doc/users/next_whats_new/get_vertices_co_vertices.rst\n@@ -0,0 +1,7 @@\n+``Ellipse.get_vertices()``, ``Ellipse.get_co_vertices()``\n+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n+These methods return the coordinates of ellipse vertices of\n+major and minor axis. Additionally, an example gallery demo is added which\n+shows how to add an arrow to an ellipse showing a clockwise or counter-clockwise\n+rotation of the ellipse. To place the arrow exactly on the ellipse,\n+the coordinates of the vertices are used.\n"}], "version": "3.7", "base_commit": "06305a2f5dc589888697b3b909859103b8259153", "PASS2PASS": ["lib/matplotlib/tests/test_patches.py::test_patch_alpha_override[pdf]", "lib/matplotlib/tests/test_patches.py::test_clip_to_bbox[png]", "lib/matplotlib/tests/test_patches.py::test_contains_points", "lib/matplotlib/tests/test_patches.py::test_units_rectangle[png]", "lib/matplotlib/tests/test_patches.py::test_connection_patch[png]", "lib/matplotlib/tests/test_patches.py::test_wedge_range[png]", "lib/matplotlib/tests/test_patches.py::test_datetime_datetime_fails", "lib/matplotlib/tests/test_patches.py::test_fancyarrow_shape_error", "lib/matplotlib/tests/test_patches.py::test_datetime_rectangle", "lib/matplotlib/tests/test_patches.py::test_boxstyle_errors[Round,foo-Incorrect style argument: 'Round,foo']", "lib/matplotlib/tests/test_patches.py::test_negative_rect", "lib/matplotlib/tests/test_patches.py::test_multi_color_hatch[pdf]", "lib/matplotlib/tests/test_patches.py::test_connection_patch_fig[png]", "lib/matplotlib/tests/test_patches.py::test_autoscale_arc[svg]", "lib/matplotlib/tests/test_patches.py::test_patch_alpha_override[svg]", "lib/matplotlib/tests/test_patches.py::test_large_arc[svg]", "lib/matplotlib/tests/test_patches.py::test_patch_linestyle_accents", "lib/matplotlib/tests/test_patches.py::test_rotated_arcs[svg]", "lib/matplotlib/tests/test_patches.py::test_patch_custom_linestyle[pdf]", "lib/matplotlib/tests/test_patches.py::test_modifying_arc[svg]", "lib/matplotlib/tests/test_patches.py::test_Polygon_close", "lib/matplotlib/tests/test_patches.py::test_modifying_arc[png]", "lib/matplotlib/tests/test_patches.py::test_autoscale_arc[png]", "lib/matplotlib/tests/test_patches.py::test_patch_alpha_coloring[svg]", "lib/matplotlib/tests/test_patches.py::test_color_override_warning[edgecolor]", "lib/matplotlib/tests/test_patches.py::test_rotate_rect", "lib/matplotlib/tests/test_patches.py::test_patch_linestyle_none[png]", "lib/matplotlib/tests/test_patches.py::test_annulus_setters[png]", "lib/matplotlib/tests/test_patches.py::test_patch_str", "lib/matplotlib/tests/test_patches.py::test_multi_color_hatch[svg]", "lib/matplotlib/tests/test_patches.py::test_patch_custom_linestyle[svg]", "lib/matplotlib/tests/test_patches.py::test_dash_offset_patch_draw[png]", "lib/matplotlib/tests/test_patches.py::test_clip_to_bbox[svg]", "lib/matplotlib/tests/test_patches.py::test_multi_color_hatch[png]", "lib/matplotlib/tests/test_patches.py::test_fancyarrow_setdata", "lib/matplotlib/tests/test_patches.py::test_patch_alpha_coloring[png]", "lib/matplotlib/tests/test_patches.py::test_wedge_range[pdf]", "lib/matplotlib/tests/test_patches.py::test_wedge_range[svg]", "lib/matplotlib/tests/test_patches.py::test_corner_center", "lib/matplotlib/tests/test_patches.py::test_default_linestyle", "lib/matplotlib/tests/test_patches.py::test_empty_verts", "lib/matplotlib/tests/test_patches.py::test_patch_alpha_override[png]", "lib/matplotlib/tests/test_patches.py::test_default_capstyle", "lib/matplotlib/tests/test_patches.py::test_contains_point", "lib/matplotlib/tests/test_patches.py::test_modifying_arc[pdf]", "lib/matplotlib/tests/test_patches.py::test_color_override_warning[facecolor]", "lib/matplotlib/tests/test_patches.py::test_default_joinstyle", "lib/matplotlib/tests/test_patches.py::test_arc_in_collection[pdf]", "lib/matplotlib/tests/test_patches.py::test_wedge_movement", "lib/matplotlib/tests/test_patches.py::test_annulus[png]", "lib/matplotlib/tests/test_patches.py::test_clip_to_bbox[pdf]", "lib/matplotlib/tests/test_patches.py::test_arc_in_collection[svg]", "lib/matplotlib/tests/test_patches.py::test_degenerate_polygon", "lib/matplotlib/tests/test_patches.py::test_arc_in_collection[png]", "lib/matplotlib/tests/test_patches.py::test_shadow[png]", "lib/matplotlib/tests/test_patches.py::test_rotate_rect_draw[png]", "lib/matplotlib/tests/test_patches.py::test_patch_color_none", "lib/matplotlib/tests/test_patches.py::test_arc_in_collection[eps]", "lib/matplotlib/tests/test_patches.py::test_default_antialiased", "lib/matplotlib/tests/test_patches.py::test_annulus_setters2[png]", "lib/matplotlib/tests/test_patches.py::test_fancyarrow_units", "lib/matplotlib/tests/test_patches.py::test_patch_custom_linestyle[png]", "lib/matplotlib/tests/test_patches.py::test_patch_alpha_coloring[pdf]", "lib/matplotlib/tests/test_patches.py::test_boxstyle_errors[foo-Unknown style: 'foo']", "lib/matplotlib/tests/test_patches.py::test_modifying_arc[eps]"], "FAIL2PASS": ["lib/matplotlib/tests/test_patches.py::test_ellipse_vertices"], "mask_doc_diff": [{"path": "doc/users/next_whats_new/get_vertices_co_vertices.rst", "old_path": "/dev/null", "new_path": "b/doc/users/next_whats_new/get_vertices_co_vertices.rst", "metadata": "diff --git a/doc/users/next_whats_new/get_vertices_co_vertices.rst b/doc/users/next_whats_new/get_vertices_co_vertices.rst\nnew file mode 100644\nindex 0000000000..98254a82ce\n--- /dev/null\n+++ b/doc/users/next_whats_new/get_vertices_co_vertices.rst\n@@ -0,0 +1,7 @@\n+``Ellipse.get_vertices()``, ``Ellipse.get_co_vertices()``\n+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n+These methods return the coordinates of ellipse vertices of\n+major and minor axis. Additionally, an example gallery demo is added which\n+shows how to add an arrow to an ellipse showing a clockwise or counter-clockwise\n+rotation of the ellipse. To place the arrow exactly on the ellipse,\n+the coordinates of the vertices are used.\n"}], "augmentations": {"header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [{"type": "file", "name": "galleries/examples/shapes_and_collections/ellipse_arrow.py"}]}, "problem_statement": "diff --git a/doc/users/next_whats_new/get_vertices_co_vertices.rst b/doc/users/next_whats_new/get_vertices_co_vertices.rst\nnew file mode 100644\nindex 0000000000..98254a82ce\n--- /dev/null\n+++ b/doc/users/next_whats_new/get_vertices_co_vertices.rst\n@@ -0,0 +1,7 @@\n+``Ellipse.get_vertices()``, ``Ellipse.get_co_vertices()``\n+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n+These methods return the coordinates of ellipse vertices of\n+major and minor axis. Additionally, an example gallery demo is added which\n+shows how to add an arrow to an ellipse showing a clockwise or counter-clockwise\n+rotation of the ellipse. To place the arrow exactly on the ellipse,\n+the coordinates of the vertices are used.\n\nIf completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:\n[{'type': 'file', 'name': 'galleries/examples/shapes_and_collections/ellipse_arrow.py'}]\n"} {"repo": "matplotlib/matplotlib", "instance_id": "matplotlib__matplotlib-25542", "html_url": "https://github.com/matplotlib/matplotlib/pull/25542", "feature_patch": "diff --git a/doc/users/next_whats_new/multiplelocator_offset.rst b/doc/users/next_whats_new/multiplelocator_offset.rst\nnew file mode 100644\nindex 000000000000..863fdb3c4d7e\n--- /dev/null\n+++ b/doc/users/next_whats_new/multiplelocator_offset.rst\n@@ -0,0 +1,17 @@\n+``offset`` parameter for MultipleLocator\n+----------------------------------------\n+\n+An *offset* may now be specified to shift all the ticks by the given value.\n+\n+.. plot::\n+ :include-source: true\n+\n+ import matplotlib.pyplot as plt\n+ import matplotlib.ticker as mticker\n+\n+ _, ax = plt.subplots()\n+ ax.plot(range(10))\n+ locator = mticker.MultipleLocator(base=3, offset=0.3)\n+ ax.xaxis.set_major_locator(locator)\n+\n+ plt.show()\ndiff --git a/galleries/examples/ticks/tick-locators.py b/galleries/examples/ticks/tick-locators.py\nindex e634e022173c..6cf4afaf22d7 100644\n--- a/galleries/examples/ticks/tick-locators.py\n+++ b/galleries/examples/ticks/tick-locators.py\n@@ -37,8 +37,8 @@ def setup(ax, title):\n axs[0].xaxis.set_minor_locator(ticker.NullLocator())\n \n # Multiple Locator\n-setup(axs[1], title=\"MultipleLocator(0.5)\")\n-axs[1].xaxis.set_major_locator(ticker.MultipleLocator(0.5))\n+setup(axs[1], title=\"MultipleLocator(0.5, offset=0.2)\")\n+axs[1].xaxis.set_major_locator(ticker.MultipleLocator(0.5, offset=0.2))\n axs[1].xaxis.set_minor_locator(ticker.MultipleLocator(0.1))\n \n # Fixed Locator\n@@ -53,7 +53,7 @@ def setup(ax, title):\n \n # Index Locator\n setup(axs[4], title=\"IndexLocator(base=0.5, offset=0.25)\")\n-axs[4].plot(range(0, 5), [0]*5, color='white')\n+axs[4].plot([0]*5, color='white')\n axs[4].xaxis.set_major_locator(ticker.IndexLocator(base=0.5, offset=0.25))\n \n # Auto Locator\ndiff --git a/lib/matplotlib/ticker.py b/lib/matplotlib/ticker.py\nindex bf059567f5fe..0877e58c5fe7 100644\n--- a/lib/matplotlib/ticker.py\n+++ b/lib/matplotlib/ticker.py\n@@ -1831,17 +1831,41 @@ def view_limits(self, vmin, vmax):\n \n class MultipleLocator(Locator):\n \"\"\"\n- Set a tick on each integer multiple of the *base* within the view\n- interval.\n+ Set a tick on each integer multiple of the *base* plus an *offset* within\n+ the view interval.\n \"\"\"\n \n- def __init__(self, base=1.0):\n+ def __init__(self, base=1.0, offset=0.0):\n+ \"\"\"\n+ Parameters\n+ ----------\n+ base : float > 0\n+ Interval between ticks.\n+ offset : float\n+ Value added to each multiple of *base*.\n+\n+ .. versionadded:: 3.8\n+ \"\"\"\n self._edge = _Edge_integer(base, 0)\n+ self._offset = offset\n \n- def set_params(self, base):\n- \"\"\"Set parameters within this locator.\"\"\"\n+ def set_params(self, base=None, offset=None):\n+ \"\"\"\n+ Set parameters within this locator.\n+\n+ Parameters\n+ ----------\n+ base : float > 0\n+ Interval between ticks.\n+ offset : float\n+ Value added to each multiple of *base*.\n+\n+ .. versionadded:: 3.8\n+ \"\"\"\n if base is not None:\n self._edge = _Edge_integer(base, 0)\n+ if offset is not None:\n+ self._offset = offset\n \n def __call__(self):\n \"\"\"Return the locations of the ticks.\"\"\"\n@@ -1852,19 +1876,20 @@ def tick_values(self, vmin, vmax):\n if vmax < vmin:\n vmin, vmax = vmax, vmin\n step = self._edge.step\n+ vmin -= self._offset\n+ vmax -= self._offset\n vmin = self._edge.ge(vmin) * step\n n = (vmax - vmin + 0.001 * step) // step\n- locs = vmin - step + np.arange(n + 3) * step\n+ locs = vmin - step + np.arange(n + 3) * step + self._offset\n return self.raise_if_exceeds(locs)\n \n def view_limits(self, dmin, dmax):\n \"\"\"\n- Set the view limits to the nearest multiples of *base* that\n- contain the data.\n+ Set the view limits to the nearest tick values that contain the data.\n \"\"\"\n if mpl.rcParams['axes.autolimit_mode'] == 'round_numbers':\n- vmin = self._edge.le(dmin) * self._edge.step\n- vmax = self._edge.ge(dmax) * self._edge.step\n+ vmin = self._edge.le(dmin - self._offset) * self._edge.step + self._offset\n+ vmax = self._edge.ge(dmax - self._offset) * self._edge.step + self._offset\n if vmin == vmax:\n vmin -= 1\n vmax += 1\ndiff --git a/lib/matplotlib/ticker.pyi b/lib/matplotlib/ticker.pyi\nindex e53a665432e2..1f4239ef2718 100644\n--- a/lib/matplotlib/ticker.pyi\n+++ b/lib/matplotlib/ticker.pyi\n@@ -212,9 +212,8 @@ class LinearLocator(Locator):\n ) -> None: ...\n \n class MultipleLocator(Locator):\n- def __init__(self, base: float = ...) -> None: ...\n- # Makes set_params `base` argument mandatory\n- def set_params(self, base: float | None) -> None: ... # type: ignore[override]\n+ def __init__(self, base: float = ..., offset: float = ...) -> None: ...\n+ def set_params(self, base: float | None = ..., offset: float | None = ...) -> None: ...\n def view_limits(self, dmin: float, dmax: float) -> tuple[float, float]: ...\n \n class _Edge_integer:\n", "test_patch": "diff --git a/lib/matplotlib/tests/test_ticker.py b/lib/matplotlib/tests/test_ticker.py\nindex 3d38df575f09..53224d373f80 100644\n--- a/lib/matplotlib/tests/test_ticker.py\n+++ b/lib/matplotlib/tests/test_ticker.py\n@@ -63,6 +63,12 @@ def test_basic(self):\n 9.441, 12.588])\n assert_almost_equal(loc.tick_values(-7, 10), test_value)\n \n+ def test_basic_with_offset(self):\n+ loc = mticker.MultipleLocator(base=3.147, offset=1.2)\n+ test_value = np.array([-8.241, -5.094, -1.947, 1.2, 4.347, 7.494,\n+ 10.641])\n+ assert_almost_equal(loc.tick_values(-7, 10), test_value)\n+\n def test_view_limits(self):\n \"\"\"\n Test basic behavior of view limits.\n@@ -80,6 +86,15 @@ def test_view_limits_round_numbers(self):\n loc = mticker.MultipleLocator(base=3.147)\n assert_almost_equal(loc.view_limits(-4, 4), (-6.294, 6.294))\n \n+ def test_view_limits_round_numbers_with_offset(self):\n+ \"\"\"\n+ Test that everything works properly with 'round_numbers' for auto\n+ limit.\n+ \"\"\"\n+ with mpl.rc_context({'axes.autolimit_mode': 'round_numbers'}):\n+ loc = mticker.MultipleLocator(base=3.147, offset=1.3)\n+ assert_almost_equal(loc.view_limits(-4, 4), (-4.994, 4.447))\n+\n def test_set_params(self):\n \"\"\"\n Create multiple locator with 0.7 base, and change it to something else.\n@@ -88,6 +103,8 @@ def test_set_params(self):\n mult = mticker.MultipleLocator(base=0.7)\n mult.set_params(base=1.7)\n assert mult._edge.step == 1.7\n+ mult.set_params(offset=3)\n+ assert mult._offset == 3\n \n \n class TestAutoMinorLocator:\n", "doc_changes": [{"path": "doc/users/next_whats_new/multiplelocator_offset.rst", "old_path": "/dev/null", "new_path": "b/doc/users/next_whats_new/multiplelocator_offset.rst", "metadata": "diff --git a/doc/users/next_whats_new/multiplelocator_offset.rst b/doc/users/next_whats_new/multiplelocator_offset.rst\nnew file mode 100644\nindex 000000000000..863fdb3c4d7e\n--- /dev/null\n+++ b/doc/users/next_whats_new/multiplelocator_offset.rst\n@@ -0,0 +1,17 @@\n+``offset`` parameter for MultipleLocator\n+----------------------------------------\n+\n+An *offset* may now be specified to shift all the ticks by the given value.\n+\n+.. plot::\n+ :include-source: true\n+\n+ import matplotlib.pyplot as plt\n+ import matplotlib.ticker as mticker\n+\n+ _, ax = plt.subplots()\n+ ax.plot(range(10))\n+ locator = mticker.MultipleLocator(base=3, offset=0.3)\n+ ax.xaxis.set_major_locator(locator)\n+\n+ plt.show()\n"}], "version": "3.7", "base_commit": "7b821ce6b4a4474b1013435954c05c63574e3814", "PASS2PASS": ["lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[1000-100-1000]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_offset_value[-0.492-0.492-0]", "lib/matplotlib/tests/test_ticker.py::TestPercentFormatter::test_basic[autodecimal, x<100%, display_range=8.4 (autodecimal test 2)]", "lib/matplotlib/tests/test_ticker.py::TestMultipleLocator::test_view_limits_round_numbers", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[0.001-0.015-0.001]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_cursor_dummy_axis[0.0123-0.012]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_invalid[-0.1]", "lib/matplotlib/tests/test_ticker.py::TestEngFormatter::test_params[True-1001-expected21]", "lib/matplotlib/tests/test_ticker.py::TestAsinhLocator::test_linear_values", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_minor[lims6-expected_low_ticks6]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_format_data[0.1-1e-1]", "lib/matplotlib/tests/test_ticker.py::TestFormatStrFormatter::test_basic", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_format_data_short[253]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_nonsingular_ok[lims0]", "lib/matplotlib/tests/test_ticker.py::TestLogLocator::test_tick_values_not_empty", "lib/matplotlib/tests/test_ticker.py::TestLogFormatterMathtext::test_min_exponent[3-1000.0-$\\\\mathdefault{10^{3}}$]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[0.003141592654-100-0]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_variablelength[0.02005753653785041]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[0.003141592654-0.001-3.142e-3]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[0.1-0.001-1e-1]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[1000-0.015-1000]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_basic[0.001]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[0.01-0.001-1e-2]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_nonsingular_ok[lims8]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_invalid[-1]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatterMathtext::test_min_exponent[0-1-$\\\\mathdefault{10^{0}}$]", "lib/matplotlib/tests/test_ticker.py::TestEngFormatter::test_params[False--1234.56789-expected0]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatterExponent::test_basic[2.718281828459045-False-50-locs2-positions2-expected2]", "lib/matplotlib/tests/test_ticker.py::TestEngFormatter::test_params[True--999.9999-expected19]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[0.3141592654-0.015-0.314]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_variablelength[0.9956983447069072]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_minor_vs_major[False-lims3-cases3]", "lib/matplotlib/tests/test_ticker.py::TestPercentFormatter::test_latex[True-True-50\\\\{t}%]", "lib/matplotlib/tests/test_ticker.py::TestMaxNLocator::test_basic[0.001-0.0001-expected1]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[1000-0.001-1000]", "lib/matplotlib/tests/test_ticker.py::test_small_range_loglocator[9]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatterExponent::test_basic[5.0-False-50-locs2-positions2-expected2]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatterExponent::test_basic[5.0-False-10-locs1-positions1-expected1]", "lib/matplotlib/tests/test_ticker.py::TestPercentFormatter::test_basic[decimals=0, x>100%]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[0.3141592654-100-0.3]", "lib/matplotlib/tests/test_ticker.py::TestPercentFormatter::test_basic[autodecimal, x<-100%, display_range=1e-6 (tiny display range)]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatterMathtext::test_min_exponent[3-100.0-$\\\\mathdefault{100}$]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[1-0.015-1]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatterSciNotation::test_basic[10-500000-$\\\\mathdefault{5\\\\times10^{5}}$]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_format_data[0.11-1.1e-1]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatterExponent::test_basic[3.141592653589793-False-10-locs1-positions1-expected1]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_basic[0.1]", "lib/matplotlib/tests/test_ticker.py::TestFixedLocator::test_set_params", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_nonsingular_ok[lims3]", "lib/matplotlib/tests/test_ticker.py::TestPercentFormatter::test_basic[autodecimal, x>100%, display_range=6 (custom xmax test)]", "lib/matplotlib/tests/test_ticker.py::TestAsinhLocator::test_symmetrizing", "lib/matplotlib/tests/test_ticker.py::TestSymmetricalLogLocator::test_set_params", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_cursor_dummy_axis[0.0-0.000]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_nonsingular_ok[lims11]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_nonsingular_ok[lims26]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[100-100-100]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_unicode_minus[False--1]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatterExponent::test_basic[3.141592653589793-True-4-locs0-positions0-expected0]", "lib/matplotlib/tests/test_ticker.py::TestLogLocator::test_switch_to_autolocator", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_basic_major[lims1-expected_low_ticks1]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_logit_deformater[STUFF0.41OTHERSTUFF-0.41]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_basic[1e-07]", "lib/matplotlib/tests/test_ticker.py::TestEngFormatter::test_params[True--0.00123456789-expected7]", "lib/matplotlib/tests/test_ticker.py::TestPercentFormatter::test_basic[autodecimal, x<100%, display_range=1]", "lib/matplotlib/tests/test_ticker.py::TestAutoMinorLocator::test_basic", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[0.1-0.015-0.1]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_offset_value[3789.12-3783.1-3780]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[0.03141592654-0.5-0.031]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_basic[0.999999999]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatterMathtext::test_min_exponent[0-100.0-$\\\\mathdefault{10^{2}}$]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[3.141592654-1000000.0-3.1]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[100-1000000.0-100]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_sublabel", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[0.01-5-0.01]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[0.0003141592654-0.015-0]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[0.0001-1000000.0-1e-4]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_scilimits[True-scilimits8-lim8-6-False]", "lib/matplotlib/tests/test_ticker.py::TestLogLocator::test_tick_values_correct", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_scilimits[True-scilimits2-lim2-0-False]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_LogFormatter_call[1000]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[0.0003141592654-5-0]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatterSciNotation::test_basic[10-100000-$\\\\mathdefault{10^{5}}$]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[0.0001-100-0]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_variablelength[0.0009110511944006454]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_empty_locs", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_basic_major[lims5-expected_low_ticks5]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[314159.2654-0.5-314159.265]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_scilimits[True-scilimits4-lim4-2-False]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_offset_value[0.99-1.01-1]", "lib/matplotlib/tests/test_ticker.py::TestAutoMinorLocator::test_number_of_minor_ticks_int[10-lim2-ref2-False]", "lib/matplotlib/tests/test_ticker.py::TestPercentFormatter::test_basic[Custom percent symbol]", "lib/matplotlib/tests/test_ticker.py::TestAutoMinorLocator::test_number_of_minor_ticks_int[2-lim0-ref0-True]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_logit_deformater[STUFF-None]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[31.41592654-0.001-3.142e1]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[31.41592654-0.5-31.416]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_logit_deformater[STUFF1-0.41OTHERSTUFF-0.5900000000000001]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[0.3141592654-0.5-0.314]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_offset_value[-0.452-0.492-0]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_use_locale", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_nonsingular_ok[lims5]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_nonsingular_ok[lims18]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_nonsingular_ok[lims20]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_variablelength[0.08839967720705845]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[314159.2654-5-314159.27]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[0.003141592654-0.5-0.003]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_basic_major[lims2-expected_low_ticks2]", "lib/matplotlib/tests/test_ticker.py::TestPercentFormatter::test_basic[decimals=1, x=100%]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_variablelength[0.6852009766653157]", "lib/matplotlib/tests/test_ticker.py::TestPercentFormatter::test_latex[True-False-50\\\\{t}%]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_maxn_major[lims2]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_basic[0.9999]", "lib/matplotlib/tests/test_ticker.py::TestEngFormatter::test_params[True-1.23456789-expected15]", "lib/matplotlib/tests/test_ticker.py::TestAsinhLocator::test_base_rounding", "lib/matplotlib/tests/test_ticker.py::TestAutoMinorLocator::test_first_and_last_minorticks", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_nbins_major[lims3]", "lib/matplotlib/tests/test_ticker.py::TestEngFormatter::test_params[True-0.123456789-expected12]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[3.141592654e-05-0.5-0]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatterExponent::test_basic[10.0-False-10-locs1-positions1-expected1]", "lib/matplotlib/tests/test_ticker.py::test_set_offset_string[formatter0]", "lib/matplotlib/tests/test_ticker.py::test_minorticks_rc", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_use_offset[True]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[10-1000000.0-10]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_offset_value[123-189-0]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[0.03141592654-5-0.03]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_minor_vs_major[True-lims2-cases2]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_variablelength[0.3147990233346844]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatterExponent::test_basic[2.718281828459045-False-10-locs1-positions1-expected1]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[0.0003141592654-0.001-3.142e-4]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[1e-05-5-0]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_LogFormatter_call_tiny[1e-323]", "lib/matplotlib/tests/test_ticker.py::TestAsinhLocator::test_near_zero", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[100-0.015-100]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatterExponent::test_basic[2.0-False-10-locs1-positions1-expected1]", "lib/matplotlib/tests/test_ticker.py::TestPercentFormatter::test_latex[False-False-50\\\\{t}%]", "lib/matplotlib/tests/test_ticker.py::TestAutoMinorLocator::test_number_of_minor_ticks_auto[lim1-ref1-False]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_variablelength[0.0043016552930929]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[0.001-0.001-1e-3]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_basic[0.9]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[10-0.001-10]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_nonsingular_ok[lims29]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[0.0001-0.015-0]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatterSciNotation::test_basic[10-1e-05-$\\\\mathdefault{10^{-5}}$]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[10000-5-10000]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatterExponent::test_blank", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[10000-1000000.0-1e4]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[31.41592654-100-31.4]", "lib/matplotlib/tests/test_ticker.py::TestEngFormatter::test_params[False--1.23456789-expected2]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_basic[1e-09]", "lib/matplotlib/tests/test_ticker.py::TestAutoMinorLocator::test_low_number_of_majorticks[0-0]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[314.1592654-0.015-314.159]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_basic_major[lims4-expected_low_ticks4]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_minor_vs_major[True-lims1-cases1]", "lib/matplotlib/tests/test_ticker.py::TestPercentFormatter::test_basic[autodecimal, x<100%, display_range=8.5 (autodecimal test 1)]", "lib/matplotlib/tests/test_ticker.py::TestAutoMinorLocator::test_additional[lim6-ref6]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_minor[lims4-expected_low_ticks4]", "lib/matplotlib/tests/test_ticker.py::TestMaxNLocator::test_integer[1-55-steps2-expected2]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[0.001-1000000.0-1e-3]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatterSciNotation::test_basic[10-5e-05-$\\\\mathdefault{5\\\\times10^{-5}}$]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_nonsingular_ok[lims10]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_basic[0.99999]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[100-5-100]", "lib/matplotlib/tests/test_ticker.py::TestEngFormatter::test_params[True-1.23e+33-expected24]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_format_data[110000000.0-1.1e8]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatterSciNotation::test_basic[2-0.0375-$\\\\mathdefault{1.2\\\\times2^{-5}}$]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_variablelength[0.9116003227929417]", "lib/matplotlib/tests/test_ticker.py::test_majformatter_type", "lib/matplotlib/tests/test_ticker.py::TestEngFormatter::test_params[True--1234.56789-expected1]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_scilimits[False-scilimits0-lim0-0-False]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[10000-100-10000]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_variablelength[0.9990889488055994]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatterSciNotation::test_basic[10-2e-05-$\\\\mathdefault{2\\\\times10^{-5}}$]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatterExponent::test_basic[5.0-True-4-locs0-positions0-expected0]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_nonsingular_nok[0.84]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_nonsingular_ok[lims16]", "lib/matplotlib/tests/test_ticker.py::TestPercentFormatter::test_basic[decimals=0, x=100%]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_nonsingular_ok[lims21]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[0.1-100-0.1]", "lib/matplotlib/tests/test_ticker.py::TestEngFormatter::test_params[True-1000-expected20]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[0.03141592654-0.001-3.142e-2]", "lib/matplotlib/tests/test_ticker.py::TestAutoMinorLocator::test_number_of_minor_ticks_auto[lim1-ref1-True]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_nonsingular_ok[lims15]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_basic[0.5]", "lib/matplotlib/tests/test_ticker.py::TestEngFormatter::test_params[True-1.23456789e-06-expected11]", "lib/matplotlib/tests/test_ticker.py::TestAutoMinorLocator::test_using_all_default_major_steps", "lib/matplotlib/tests/test_ticker.py::TestPercentFormatter::test_basic[decimals=1, x<100%]", "lib/matplotlib/tests/test_ticker.py::TestMultipleLocator::test_basic", "lib/matplotlib/tests/test_ticker.py::TestLogFormatterExponent::test_basic[3.141592653589793-False-50-locs2-positions2-expected2]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_nonsingular_ok[lims27]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[0.01-0.015-0.01]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[0.003141592654-5-0]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_offset_value[12341-12349-12340]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_nbins_major[lims0]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatterSciNotation::test_basic[10-5-$\\\\mathdefault{5\\\\times10^{0}}$]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_basic[1e-05]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[31.41592654-1000000.0-3.1e1]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_offset_value[1900.0-1200.0-0]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_nonsingular_ok[lims23]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatterSciNotation::test_basic[10--1-$\\\\mathdefault{-10^{0}}$]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[0.01-100-0]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_useMathText[False]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_invalid[2]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_minor_vs_major[True-lims0-cases0]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_offset_value[0.4538-0.4578-0.45]", "lib/matplotlib/tests/test_ticker.py::TestAutoMinorLocator::test_number_of_minor_ticks[10-5]", "lib/matplotlib/tests/test_ticker.py::TestEngFormatter::test_params[True-100001-expected22]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_nonsingular_ok[lims6]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[314159.2654-1000000.0-3.1e5]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[314159.2654-0.001-3.142e5]", "lib/matplotlib/tests/test_ticker.py::TestAsinhLocator::test_fallback", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_nonsingular_ok[lims12]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatterMathtext::test_min_exponent[3-1-$\\\\mathdefault{1}$]", "lib/matplotlib/tests/test_ticker.py::TestEngFormatter::test_params[True-0-expected10]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_basic[0.99999999]", "lib/matplotlib/tests/test_ticker.py::test_minformatter_type", "lib/matplotlib/tests/test_ticker.py::TestMaxNLocator::test_basic[20-100-expected0]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_use_offset[False]", "lib/matplotlib/tests/test_ticker.py::TestEngFormatter::test_params[False--0.00123456789-expected6]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_cursor_precision[0.0-0.000]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_basic_major[lims0-expected_low_ticks0]", "lib/matplotlib/tests/test_ticker.py::TestEngFormatter::test_params[True-0-expected9]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_offset_value[123-123-0]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatterMathtext::test_min_exponent[3-0.01-$\\\\mathdefault{0.01}$]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_offset_value[-189--123-0]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_nbins_major[lims1]", "lib/matplotlib/tests/test_ticker.py::TestAutoMinorLocator::test_additional[lim0-ref0]", "lib/matplotlib/tests/test_ticker.py::TestPercentFormatter::test_basic[decimals=1, x<0%]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[10-0.5-10]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_cursor_precision[0.0123-0.012]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_useMathText[True]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_basic[1e-08]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[31415.92654-0.5-31415.927]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_invalid[1.5]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_format_data_short[754]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[1e-05-0.5-0]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[0.1-1000000.0-1e-1]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_cursor_precision[12.3-12.300]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[10-100-10]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_nonsingular_nok[0.9359999999999999]", "lib/matplotlib/tests/test_ticker.py::TestAsinhLocator::test_wide_values", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_scilimits[True-scilimits1-lim1-0-False]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_nbins_major[lims4]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_basic_major[lims3-expected_low_ticks3]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatterSciNotation::test_basic[10-200000-$\\\\mathdefault{2\\\\times10^{5}}$]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_nonsingular_ok[lims17]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[314.1592654-1000000.0-3.1e2]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[0.0001-5-0]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_offset_value[99990.5-100000.5-100000]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[1-5-1]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_unicode_minus[True-\\u22121]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[314.1592654-5-314.16]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[100-0.001-100]", "lib/matplotlib/tests/test_ticker.py::TestEngFormatter::test_params[True-1-expected14]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[0.03141592654-1000000.0-3.1e-2]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[10000-0.001-1e4]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_minor[lims7-expected_low_ticks7]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_offset_value[-100010.5--99999.5--100000]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_minor[lims3-expected_low_ticks3]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_logit_deformater[STUFF12.4e-3OTHERSTUFF-None]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_nbins_major[lims10]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[0.01-1000000.0-1e-2]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[1000-5-1000]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_nonsingular_ok[lims13]", "lib/matplotlib/tests/test_ticker.py::test_remove_overlap[False-9]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatterMathtext::test_min_exponent[0-0.01-$\\\\mathdefault{10^{-2}}$]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_nonsingular_ok[lims25]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_cmr10_substitutions", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[10000-0.5-10000]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[0.001-100-0]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatterExponent::test_basic[2.0-False-50-locs2-positions2-expected2]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[3141.592654-0.015-3141.593]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[3.141592654-0.015-3.142]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_LogFormatter_call[100]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_offset_value[-12335.3-12335.3-0]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[1-100-1]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[1e-05-0.015-0]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatterMathtext::test_min_exponent[3-0.001-$\\\\mathdefault{10^{-3}}$]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[31.41592654-5-31.42]", "lib/matplotlib/tests/test_ticker.py::TestMaxNLocator::test_basic[-8.5e-51-0-expected4]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_nonsingular_ok[lims28]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_nbins_major[lims6]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[3.141592654e-05-1000000.0-3.1e-5]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[100-0.5-100]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[3.141592654e-05-5-0]", "lib/matplotlib/tests/test_ticker.py::TestMultipleLocator::test_view_limits", "lib/matplotlib/tests/test_ticker.py::test_remove_overlap[None-6]", "lib/matplotlib/tests/test_ticker.py::TestStrMethodFormatter::test_basic[{x:05d}-input0-00002]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_basic[0.01]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_cursor_precision[0.123-0.123]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_nonsingular_ok[lims19]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[0.0003141592654-100-0]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[1000-1000000.0-1000]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatterSciNotation::test_basic[2-0.03125-$\\\\mathdefault{2^{-5}}$]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[3.141592654e-05-0.001-3.142e-5]", "lib/matplotlib/tests/test_ticker.py::test_small_range_loglocator[1]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_nonsingular_ok[lims4]", "lib/matplotlib/tests/test_ticker.py::TestAsinhLocator::test_init", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[314159.2654-100-314159.3]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[314159.2654-0.015-314159.265]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[10000-0.015-10000]", "lib/matplotlib/tests/test_ticker.py::TestAutoMinorLocator::test_number_of_minor_ticks[1-5]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[10-5-10]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_format_data[100000000.0-1e8]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[10-0.015-10]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_invalid[-0.5]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatterSciNotation::test_basic[2-32-$\\\\mathdefault{2^{5}}$]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[3141.592654-100-3141.6]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatterSciNotation::test_basic[2-1.2-$\\\\mathdefault{1.2\\\\times2^{0}}$]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_set_use_offset_float", "lib/matplotlib/tests/test_ticker.py::TestLogFormatterExponent::test_basic[2.718281828459045-True-4-locs0-positions0-expected0]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatterSciNotation::test_basic[10-1-$\\\\mathdefault{10^{0}}$]", "lib/matplotlib/tests/test_ticker.py::test_bad_locator_subs[sub1]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_use_overline", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[100000-100-100000]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_logit_deformater[STUFF1-1.41\\\\cdot10^{-2}OTHERSTUFF-0.9859]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[31415.92654-1000000.0-3.1e4]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[100000-0.001-1e5]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[31415.92654-5-31415.93]", "lib/matplotlib/tests/test_ticker.py::TestAutoMinorLocator::test_number_of_minor_ticks_int[2-lim0-ref0-False]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_maxn_major[lims0]", "lib/matplotlib/tests/test_ticker.py::TestAutoMinorLocator::test_number_of_minor_ticks_int[4-lim1-ref1-False]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_LogFormatter_call[10]", "lib/matplotlib/tests/test_ticker.py::TestAutoMinorLocator::test_additional[lim4-ref4]", "lib/matplotlib/tests/test_ticker.py::TestAsinhLocator::test_set_params", "lib/matplotlib/tests/test_ticker.py::TestPercentFormatter::test_basic[decimals=0, x<100%]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_minor[lims5-expected_low_ticks5]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[31.41592654-0.015-31.416]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_offset_value[900.0-1200.0-0]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[1-0.001-1]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[3141.592654-0.5-3141.593]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatterExponent::test_basic[2.0-True-4-locs0-positions0-expected0]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[100000-0.5-100000]", "lib/matplotlib/tests/test_ticker.py::test_locale_comma", "lib/matplotlib/tests/test_ticker.py::TestEngFormatter::test_params[True--0.123456789-expected5]", "lib/matplotlib/tests/test_ticker.py::TestMaxNLocator::test_integer[-0.1-1.1-None-expected0]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_offset_value[1233999-1234001-1234000]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[3.141592654e-05-0.015-0]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_offset_value[15.99-16.01-16]", "lib/matplotlib/tests/test_ticker.py::test_set_offset_string[formatter1]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[1-1000000.0-1]", "lib/matplotlib/tests/test_ticker.py::test_NullFormatter", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_nonsingular_nok[0.064]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_nbins_major[lims8]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_basic[0.99]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[3141.592654-1000000.0-3.1e3]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_scilimits[True-scilimits6-lim6-9-True]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatterSciNotation::test_basic[10-2-$\\\\mathdefault{2\\\\times10^{0}}$]", "lib/matplotlib/tests/test_ticker.py::TestEngFormatter::test_params[True-999.9999-expected17]", "lib/matplotlib/tests/test_ticker.py::test_engformatter_usetex_useMathText", "lib/matplotlib/tests/test_ticker.py::test_small_range_loglocator[2]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_scilimits[True-scilimits5-lim5--3-False]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_minor_number", "lib/matplotlib/tests/test_ticker.py::TestAutoMinorLocator::test_number_of_minor_ticks_int[4-lim1-ref1-True]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[1-0.5-1]", "lib/matplotlib/tests/test_ticker.py::TestNullLocator::test_set_params", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[0.3141592654-5-0.31]", "lib/matplotlib/tests/test_ticker.py::TestLogLocator::test_set_params", "lib/matplotlib/tests/test_ticker.py::TestPercentFormatter::test_basic[decimals=0, x<0%]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_format_data_short[100]", "lib/matplotlib/tests/test_ticker.py::TestEngFormatter::test_params[False--999.9999-expected18]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[0.0003141592654-1000000.0-3.1e-4]", "lib/matplotlib/tests/test_ticker.py::TestMaxNLocator::test_basic[0-8.5e-51-expected3]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[3141.592654-0.001-3.142e3]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[0.3141592654-0.001-3.142e-1]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_nonsingular_ok[lims2]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_one_half", "lib/matplotlib/tests/test_ticker.py::TestLogFormatterExponent::test_basic[10.0-False-50-locs2-positions2-expected2]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[3.141592654-0.001-3.142]", "lib/matplotlib/tests/test_ticker.py::test_small_range_loglocator[3]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_basic_major[lims7-expected_low_ticks7]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_logit_deformater[STUFF1.41\\\\cdot10^{-2}OTHERSTUFF-0.0141]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_basic[0.999]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[0.001-5-0]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_offset_value[9.99-10.01-10]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[0.0001-0.5-0]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_offset_value[12331.4-12350.5-12300]", "lib/matplotlib/tests/test_ticker.py::TestEngFormatter::test_params[False--0.123456789-expected4]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[3141.592654-5-3141.59]", "lib/matplotlib/tests/test_ticker.py::TestAutoMinorLocator::test_additional[lim3-ref3]", "lib/matplotlib/tests/test_ticker.py::TestPercentFormatter::test_basic[Empty percent symbol]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[0.0003141592654-0.5-0]", "lib/matplotlib/tests/test_ticker.py::test_majlocator_type", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[0.1-0.5-0.1]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_minor[lims2-expected_low_ticks2]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_nbins_major[lims5]", "lib/matplotlib/tests/test_ticker.py::test_bad_locator_subs[sub0]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_nbins_major[lims9]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[0.1-5-0.1]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_nbins_major[lims2]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[0.0001-0.001-1e-4]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[0.3141592654-1000000.0-3.1e-1]", "lib/matplotlib/tests/test_ticker.py::TestPercentFormatter::test_basic[None as percent symbol]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[1000-0.5-1000]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_minor[lims1-expected_low_ticks1]", "lib/matplotlib/tests/test_ticker.py::TestPercentFormatter::test_basic[decimals=1, x>100%]", "lib/matplotlib/tests/test_ticker.py::test_minlocator_type", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_offset_value[45124.3-45831.75-45000]", "lib/matplotlib/tests/test_ticker.py::TestLogLocator::test_multiple_shared_axes", "lib/matplotlib/tests/test_ticker.py::TestAutoMinorLocator::test_additional[lim7-ref7]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[314.1592654-0.001-3.142e2]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[3.141592654-5-3.14]", "lib/matplotlib/tests/test_ticker.py::TestEngFormatter::test_params[True-0.1-expected13]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_offset_value[-100000.5--99990.5--100000]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_cursor_dummy_axis[12.3-12.300]", "lib/matplotlib/tests/test_ticker.py::TestAutoMinorLocator::test_number_of_minor_ticks[2.5-5]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_maxn_major[lims1]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[1e-05-0.001-1e-5]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_nonsingular_nok[0.6000000000000001]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_cursor_dummy_axis[1.23-1.230]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_offset_value[99.99-100.01-100]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_basic[0.999999]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[0.03141592654-0.015-0.031]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_nonsingular_ok[lims7]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_scilimits[True-scilimits7-lim7-5-False]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_nonsingular_ok[lims14]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_nonsingular_ok[lims1]", "lib/matplotlib/tests/test_ticker.py::TestAutoMinorLocator::test_additional[lim2-ref2]", "lib/matplotlib/tests/test_ticker.py::TestAutoMinorLocator::test_number_of_minor_ticks_auto[lim0-ref0-True]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_nonsingular_nok[0.39999999999999997]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_cursor_precision[1.23-1.230]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[3.141592654-100-3.1]", "lib/matplotlib/tests/test_ticker.py::TestMaxNLocator::test_basic[-1000000000000000.0-1000000000000000.0-expected2]", "lib/matplotlib/tests/test_ticker.py::TestAutoMinorLocator::test_additional[lim5-ref5]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_nonsingular_nok[0.16]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_offset_value[12592.82-12591.43-12590]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_basic[0.9999999]", "lib/matplotlib/tests/test_ticker.py::test_remove_overlap[True-6]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_offset_value[9.0-12.0-0]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_offset_value[1-1-1]", "lib/matplotlib/tests/test_ticker.py::TestLogLocator::test_polar_axes", "lib/matplotlib/tests/test_ticker.py::TestLogLocator::test_basic", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[31415.92654-0.001-3.142e4]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[1e-05-1000000.0-1e-5]", "lib/matplotlib/tests/test_ticker.py::TestLinearLocator::test_set_params", "lib/matplotlib/tests/test_ticker.py::TestAutoMinorLocator::test_number_of_minor_ticks[2-4]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatterSciNotation::test_basic[2-38.4-$\\\\mathdefault{1.2\\\\times2^{5}}$]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[3.141592654e-05-100-0]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_scilimits[True-scilimits3-lim3-2-False]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_offset_value[-12349--12341--12340]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_nonsingular_ok[lims24]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_offset_value[99999.5-100010.5-100000]", "lib/matplotlib/tests/test_ticker.py::TestEngFormatter::test_params[True--0.0-expected8]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[3.141592654-0.5-3.142]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[0.001-0.5-0.001]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatterExponent::test_basic[10.0-True-4-locs0-positions0-expected0]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_LogFormatter_call[1]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[0.03141592654-100-0]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_basic_major[lims6-expected_low_ticks6]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_nonsingular_ok[lims22]", "lib/matplotlib/tests/test_ticker.py::TestMaxNLocator::test_integer[-0.1-0.95-None-expected1]", "lib/matplotlib/tests/test_ticker.py::TestIndexLocator::test_set_params", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_nbins_major[lims7]", "lib/matplotlib/tests/test_ticker.py::TestAutoMinorLocator::test_number_of_minor_ticks_int[10-lim2-ref2-True]", "lib/matplotlib/tests/test_ticker.py::TestAutoMinorLocator::test_low_number_of_majorticks[1-0]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_minor_attr", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[100000-1000000.0-1e5]", "lib/matplotlib/tests/test_ticker.py::TestAutoMinorLocator::test_number_of_minor_ticks[5-5]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[1e-05-100-0]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_variablelength[0.9799424634621495]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[0.003141592654-0.015-0.003]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[31415.92654-100-31415.9]", "lib/matplotlib/tests/test_ticker.py::TestEngFormatter::test_params[True-999.9-expected16]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_LogFormatter_call_tiny[2e-323]", "lib/matplotlib/tests/test_ticker.py::TestEngFormatter::test_params[True--1.23456789-expected3]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_nonsingular_ok[lims9]", "lib/matplotlib/tests/test_ticker.py::TestLogitLocator::test_minor[lims0-expected_low_ticks0]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[314.1592654-0.5-314.159]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_LogFormatter_call_tiny[1.1e-322]", "lib/matplotlib/tests/test_ticker.py::TestAutoMinorLocator::test_additional[lim1-ref1]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_offset_value[0.000721-0.0007243-0.00072]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_cursor_dummy_axis[0.123-0.123]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_basic[1e-06]", "lib/matplotlib/tests/test_ticker.py::TestPercentFormatter::test_latex[False-True-50\\\\\\\\\\\\{t\\\\}\\\\%]", "lib/matplotlib/tests/test_ticker.py::TestAutoMinorLocator::test_number_of_minor_ticks_auto[lim0-ref0-False]", "lib/matplotlib/tests/test_ticker.py::TestStrMethodFormatter::test_basic[{x:03d}-{pos:02d}-input1-002-01]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[0.003141592654-1000000.0-3.1e-3]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_LogFormatter_call_tiny[1e-322]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[31415.92654-0.015-31415.927]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_invalid[1.1]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[314.1592654-100-314.2]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatterSciNotation::test_basic[2-1-$\\\\mathdefault{2^{0}}$]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[0.01-0.5-0.01]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[100000-5-100000]", "lib/matplotlib/tests/test_ticker.py::TestLogitFormatter::test_basic[0.0001]", "lib/matplotlib/tests/test_ticker.py::TestLinearLocator::test_basic", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_offset_value[-1234001--1233999--1234000]", "lib/matplotlib/tests/test_ticker.py::TestEngFormatter::test_params[True-987654.321-expected23]", "lib/matplotlib/tests/test_ticker.py::TestScalarFormatter::test_offset_value[5.99-6.01-6]", "lib/matplotlib/tests/test_ticker.py::TestLogFormatter::test_pprint[100000-0.015-100000]"], "FAIL2PASS": ["lib/matplotlib/tests/test_ticker.py::TestMultipleLocator::test_set_params", "lib/matplotlib/tests/test_ticker.py::TestMultipleLocator::test_basic_with_offset", "lib/matplotlib/tests/test_ticker.py::TestMultipleLocator::test_view_limits_round_numbers_with_offset"], "mask_doc_diff": [{"path": "doc/users/next_whats_new/multiplelocator_offset.rst", "old_path": "/dev/null", "new_path": "b/doc/users/next_whats_new/multiplelocator_offset.rst", "metadata": "diff --git a/doc/users/next_whats_new/multiplelocator_offset.rst b/doc/users/next_whats_new/multiplelocator_offset.rst\nnew file mode 100644\nindex 0000000000..863fdb3c4d\n--- /dev/null\n+++ b/doc/users/next_whats_new/multiplelocator_offset.rst\n@@ -0,0 +1,17 @@\n+``offset`` parameter for MultipleLocator\n+----------------------------------------\n+\n+An *offset* may now be specified to shift all the ticks by the given value.\n+\n+.. plot::\n+ :include-source: true\n+\n+ import matplotlib.pyplot as plt\n+ import matplotlib.ticker as mticker\n+\n+ _, ax = plt.subplots()\n+ ax.plot(range(10))\n+ locator = mticker.MultipleLocator(base=3, offset=0.3)\n+ ax.xaxis.set_major_locator(locator)\n+\n+ plt.show()\n"}], "augmentations": {"header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": []}, "problem_statement": "diff --git a/doc/users/next_whats_new/multiplelocator_offset.rst b/doc/users/next_whats_new/multiplelocator_offset.rst\nnew file mode 100644\nindex 0000000000..863fdb3c4d\n--- /dev/null\n+++ b/doc/users/next_whats_new/multiplelocator_offset.rst\n@@ -0,0 +1,17 @@\n+``offset`` parameter for MultipleLocator\n+----------------------------------------\n+\n+An *offset* may now be specified to shift all the ticks by the given value.\n+\n+.. plot::\n+ :include-source: true\n+\n+ import matplotlib.pyplot as plt\n+ import matplotlib.ticker as mticker\n+\n+ _, ax = plt.subplots()\n+ ax.plot(range(10))\n+ locator = mticker.MultipleLocator(base=3, offset=0.3)\n+ ax.xaxis.set_major_locator(locator)\n+\n+ plt.show()\n\n"} {"repo": "matplotlib/matplotlib", "instance_id": "matplotlib__matplotlib-24257", "html_url": "https://github.com/matplotlib/matplotlib/pull/24257", "feature_patch": "diff --git a/doc/api/next_api_changes/development/24257-AL.rst b/doc/api/next_api_changes/development/24257-AL.rst\nnew file mode 100644\nindex 000000000000..584420df8fd7\n--- /dev/null\n+++ b/doc/api/next_api_changes/development/24257-AL.rst\n@@ -0,0 +1,2 @@\n+importlib_resources>=2.3.0 is now required on Python<3.10\n+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\ndiff --git a/doc/devel/dependencies.rst b/doc/devel/dependencies.rst\nindex fb76857898a4..365c062364e2 100644\n--- a/doc/devel/dependencies.rst\n+++ b/doc/devel/dependencies.rst\n@@ -26,6 +26,9 @@ reference.\n * `Pillow `_ (>= 6.2)\n * `pyparsing `_ (>= 2.3.1)\n * `setuptools `_\n+* `pyparsing `_ (>= 2.3.1)\n+* `importlib-resources `_\n+ (>= 3.2.0; only required on Python < 3.10)\n \n \n .. _optional_dependencies:\ndiff --git a/doc/users/next_whats_new/styles_from_packages.rst b/doc/users/next_whats_new/styles_from_packages.rst\nnew file mode 100644\nindex 000000000000..d129bb356fa7\n--- /dev/null\n+++ b/doc/users/next_whats_new/styles_from_packages.rst\n@@ -0,0 +1,11 @@\n+Style files can be imported from third-party packages\n+-----------------------------------------------------\n+\n+Third-party packages can now distribute style files that are globally available\n+as follows. Assume that a package is importable as ``import mypackage``, with\n+a ``mypackage/__init__.py`` module. Then a ``mypackage/presentation.mplstyle``\n+style sheet can be used as ``plt.style.use(\"mypackage.presentation\")``.\n+\n+The implementation does not actually import ``mypackage``, making this process\n+safe against possible import-time side effects. Subpackages (e.g.\n+``dotted.package.name``) are also supported.\ndiff --git a/environment.yml b/environment.yml\nindex 28ff3a1b2c34..c9b7aa610720 100644\n--- a/environment.yml\n+++ b/environment.yml\n@@ -12,6 +12,7 @@ dependencies:\n - contourpy>=1.0.1\n - cycler>=0.10.0\n - fonttools>=4.22.0\n+ - importlib-resources>=3.2.0\n - kiwisolver>=1.0.1\n - numpy>=1.19\n - pillow>=6.2\ndiff --git a/lib/matplotlib/style/core.py b/lib/matplotlib/style/core.py\nindex 646b39dcc5df..ed5cd4f63bc5 100644\n--- a/lib/matplotlib/style/core.py\n+++ b/lib/matplotlib/style/core.py\n@@ -15,10 +15,18 @@\n import logging\n import os\n from pathlib import Path\n+import sys\n import warnings\n \n+if sys.version_info >= (3, 10):\n+ import importlib.resources as importlib_resources\n+else:\n+ # Even though Py3.9 has importlib.resources, it doesn't properly handle\n+ # modules added in sys.path.\n+ import importlib_resources\n+\n import matplotlib as mpl\n-from matplotlib import _api, _docstring, rc_params_from_file, rcParamsDefault\n+from matplotlib import _api, _docstring, _rc_params_in_file, rcParamsDefault\n \n _log = logging.getLogger(__name__)\n \n@@ -64,23 +72,6 @@\n \"directly use the seaborn API instead.\")\n \n \n-def _remove_blacklisted_style_params(d, warn=True):\n- o = {}\n- for key in d: # prevent triggering RcParams.__getitem__('backend')\n- if key in STYLE_BLACKLIST:\n- if warn:\n- _api.warn_external(\n- f\"Style includes a parameter, {key!r}, that is not \"\n- \"related to style. Ignoring this parameter.\")\n- else:\n- o[key] = d[key]\n- return o\n-\n-\n-def _apply_style(d, warn=True):\n- mpl.rcParams.update(_remove_blacklisted_style_params(d, warn=warn))\n-\n-\n @_docstring.Substitution(\n \"\\n\".join(map(\"- {}\".format, sorted(STYLE_BLACKLIST, key=str.lower)))\n )\n@@ -99,20 +90,28 @@ def use(style):\n Parameters\n ----------\n style : str, dict, Path or list\n- A style specification. Valid options are:\n \n- +------+-------------------------------------------------------------+\n- | str | The name of a style or a path/URL to a style file. For a |\n- | | list of available style names, see `.style.available`. |\n- +------+-------------------------------------------------------------+\n- | dict | Dictionary with valid key/value pairs for |\n- | | `matplotlib.rcParams`. |\n- +------+-------------------------------------------------------------+\n- | Path | A path-like object which is a path to a style file. |\n- +------+-------------------------------------------------------------+\n- | list | A list of style specifiers (str, Path or dict) applied from |\n- | | first to last in the list. |\n- +------+-------------------------------------------------------------+\n+ A style specification.\n+\n+ - If a str, this can be one of the style names in `.style.available`\n+ (a builtin style or a style installed in the user library path).\n+\n+ This can also be a dotted name of the form \"package.style_name\"; in\n+ that case, \"package\" should be an importable Python package name,\n+ e.g. at ``/path/to/package/__init__.py``; the loaded style file is\n+ ``/path/to/package/style_name.mplstyle``. (Style files in\n+ subpackages are likewise supported.)\n+\n+ This can also be the path or URL to a style file, which gets loaded\n+ by `.rc_params_from_file`.\n+\n+ - If a dict, this is a mapping of key/value pairs for `.rcParams`.\n+\n+ - If a Path, this is the path to a style file, which gets loaded by\n+ `.rc_params_from_file`.\n+\n+ - If a list, this is a list of style specifiers (str, Path or dict),\n+ which get applied from first to last in the list.\n \n Notes\n -----\n@@ -129,33 +128,52 @@ def use(style):\n \n style_alias = {'mpl20': 'default', 'mpl15': 'classic'}\n \n- def fix_style(s):\n- if isinstance(s, str):\n- s = style_alias.get(s, s)\n- if s in _DEPRECATED_SEABORN_STYLES:\n+ for style in styles:\n+ if isinstance(style, str):\n+ style = style_alias.get(style, style)\n+ if style in _DEPRECATED_SEABORN_STYLES:\n _api.warn_deprecated(\"3.6\", message=_DEPRECATED_SEABORN_MSG)\n- s = _DEPRECATED_SEABORN_STYLES[s]\n- return s\n-\n- for style in map(fix_style, styles):\n- if not isinstance(style, (str, Path)):\n- _apply_style(style)\n- elif style == 'default':\n- # Deprecation warnings were already handled when creating\n- # rcParamsDefault, no need to reemit them here.\n- with _api.suppress_matplotlib_deprecation_warning():\n- _apply_style(rcParamsDefault, warn=False)\n- elif style in library:\n- _apply_style(library[style])\n- else:\n+ style = _DEPRECATED_SEABORN_STYLES[style]\n+ if style == \"default\":\n+ # Deprecation warnings were already handled when creating\n+ # rcParamsDefault, no need to reemit them here.\n+ with _api.suppress_matplotlib_deprecation_warning():\n+ # don't trigger RcParams.__getitem__('backend')\n+ style = {k: rcParamsDefault[k] for k in rcParamsDefault\n+ if k not in STYLE_BLACKLIST}\n+ elif style in library:\n+ style = library[style]\n+ elif \".\" in style:\n+ pkg, _, name = style.rpartition(\".\")\n+ try:\n+ path = (importlib_resources.files(pkg)\n+ / f\"{name}.{STYLE_EXTENSION}\")\n+ style = _rc_params_in_file(path)\n+ except (ModuleNotFoundError, IOError) as exc:\n+ # There is an ambiguity whether a dotted name refers to a\n+ # package.style_name or to a dotted file path. Currently,\n+ # we silently try the first form and then the second one;\n+ # in the future, we may consider forcing file paths to\n+ # either use Path objects or be prepended with \"./\" and use\n+ # the slash as marker for file paths.\n+ pass\n+ if isinstance(style, (str, Path)):\n try:\n- rc = rc_params_from_file(style, use_default_template=False)\n- _apply_style(rc)\n+ style = _rc_params_in_file(style)\n except IOError as err:\n raise IOError(\n- \"{!r} not found in the style library and input is not a \"\n- \"valid URL or path; see `style.available` for list of \"\n- \"available styles\".format(style)) from err\n+ f\"{style!r} is not a valid package style, path of style \"\n+ f\"file, URL of style file, or library style name (library \"\n+ f\"styles are listed in `style.available`)\") from err\n+ filtered = {}\n+ for k in style: # don't trigger RcParams.__getitem__('backend')\n+ if k in STYLE_BLACKLIST:\n+ _api.warn_external(\n+ f\"Style includes a parameter, {k!r}, that is not \"\n+ f\"related to style. Ignoring this parameter.\")\n+ else:\n+ filtered[k] = style[k]\n+ mpl.rcParams.update(filtered)\n \n \n @contextlib.contextmanager\n@@ -205,8 +223,7 @@ def read_style_directory(style_dir):\n styles = dict()\n for path in Path(style_dir).glob(f\"*.{STYLE_EXTENSION}\"):\n with warnings.catch_warnings(record=True) as warns:\n- styles[path.stem] = rc_params_from_file(\n- path, use_default_template=False)\n+ styles[path.stem] = _rc_params_in_file(path)\n for w in warns:\n _log.warning('In %s: %s', path, w.message)\n return styles\ndiff --git a/setup.py b/setup.py\nindex 365de0c0b5a2..2f1fb84f8cc6 100644\n--- a/setup.py\n+++ b/setup.py\n@@ -334,6 +334,11 @@ def make_release_tree(self, base_dir, files):\n os.environ.get(\"CIBUILDWHEEL\", \"0\") != \"1\"\n ) else []\n ),\n+ extras_require={\n+ ':python_version<\"3.10\"': [\n+ \"importlib-resources>=3.2.0\",\n+ ],\n+ },\n use_scm_version={\n \"version_scheme\": \"release-branch-semver\",\n \"local_scheme\": \"node-and-date\",\ndiff --git a/tutorials/introductory/customizing.py b/tutorials/introductory/customizing.py\nindex ea6b501e99ea..10fc21d2187b 100644\n--- a/tutorials/introductory/customizing.py\n+++ b/tutorials/introductory/customizing.py\n@@ -9,9 +9,9 @@\n \n There are three ways to customize Matplotlib:\n \n- 1. :ref:`Setting rcParams at runtime`.\n- 2. :ref:`Using style sheets`.\n- 3. :ref:`Changing your matplotlibrc file`.\n+1. :ref:`Setting rcParams at runtime`.\n+2. :ref:`Using style sheets`.\n+3. :ref:`Changing your matplotlibrc file`.\n \n Setting rcParams at runtime takes precedence over style sheets, style\n sheets take precedence over :file:`matplotlibrc` files.\n@@ -137,6 +137,17 @@ def plotting_function():\n # >>> import matplotlib.pyplot as plt\n # >>> plt.style.use('./images/presentation.mplstyle')\n #\n+#\n+# Distributing styles\n+# -------------------\n+#\n+# You can include style sheets into standard importable Python packages (which\n+# can be e.g. distributed on PyPI). If your package is importable as\n+# ``import mypackage``, with a ``mypackage/__init__.py`` module, and you add\n+# a ``mypackage/presentation.mplstyle`` style sheet, then it can be used as\n+# ``plt.style.use(\"mypackage.presentation\")``. Subpackages (e.g.\n+# ``dotted.package.name``) are also supported.\n+#\n # Alternatively, you can make your style known to Matplotlib by placing\n # your ``.mplstyle`` file into ``mpl_configdir/stylelib``. You\n # can then load your custom style sheet with a call to\n", "test_patch": "diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml\nindex 020f09df4010..eddb14be0bc6 100644\n--- a/.github/workflows/tests.yml\n+++ b/.github/workflows/tests.yml\n@@ -162,8 +162,8 @@ jobs:\n \n # Install dependencies from PyPI.\n python -m pip install --upgrade $PRE \\\n- 'contourpy>=1.0.1' cycler fonttools kiwisolver numpy packaging \\\n- pillow pyparsing python-dateutil setuptools-scm \\\n+ 'contourpy>=1.0.1' cycler fonttools kiwisolver importlib_resources \\\n+ numpy packaging pillow pyparsing python-dateutil setuptools-scm \\\n -r requirements/testing/all.txt \\\n ${{ matrix.extra-requirements }}\n \ndiff --git a/lib/matplotlib/tests/test_style.py b/lib/matplotlib/tests/test_style.py\nindex c788c45920ae..7d1ed94ea236 100644\n--- a/lib/matplotlib/tests/test_style.py\n+++ b/lib/matplotlib/tests/test_style.py\n@@ -190,3 +190,18 @@ def test_deprecated_seaborn_styles():\n \n def test_up_to_date_blacklist():\n assert mpl.style.core.STYLE_BLACKLIST <= {*mpl.rcsetup._validators}\n+\n+\n+def test_style_from_module(tmp_path, monkeypatch):\n+ monkeypatch.syspath_prepend(tmp_path)\n+ monkeypatch.chdir(tmp_path)\n+ pkg_path = tmp_path / \"mpl_test_style_pkg\"\n+ pkg_path.mkdir()\n+ (pkg_path / \"test_style.mplstyle\").write_text(\n+ \"lines.linewidth: 42\", encoding=\"utf-8\")\n+ pkg_path.with_suffix(\".mplstyle\").write_text(\n+ \"lines.linewidth: 84\", encoding=\"utf-8\")\n+ mpl.style.use(\"mpl_test_style_pkg.test_style\")\n+ assert mpl.rcParams[\"lines.linewidth\"] == 42\n+ mpl.style.use(\"mpl_test_style_pkg.mplstyle\")\n+ assert mpl.rcParams[\"lines.linewidth\"] == 84\ndiff --git a/requirements/testing/minver.txt b/requirements/testing/minver.txt\nindex d932b0aa34e7..82301e900f52 100644\n--- a/requirements/testing/minver.txt\n+++ b/requirements/testing/minver.txt\n@@ -3,6 +3,7 @@\n contourpy==1.0.1\n cycler==0.10\n kiwisolver==1.0.1\n+importlib-resources==3.2.0\n numpy==1.19.0\n packaging==20.0\n pillow==6.2.1\n", "doc_changes": [{"path": "doc/api/next_api_changes/development/24257-AL.rst", "old_path": "/dev/null", "new_path": "b/doc/api/next_api_changes/development/24257-AL.rst", "metadata": "diff --git a/doc/api/next_api_changes/development/24257-AL.rst b/doc/api/next_api_changes/development/24257-AL.rst\nnew file mode 100644\nindex 000000000000..584420df8fd7\n--- /dev/null\n+++ b/doc/api/next_api_changes/development/24257-AL.rst\n@@ -0,0 +1,2 @@\n+importlib_resources>=2.3.0 is now required on Python<3.10\n+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"}, {"path": "doc/devel/dependencies.rst", "old_path": "a/doc/devel/dependencies.rst", "new_path": "b/doc/devel/dependencies.rst", "metadata": "diff --git a/doc/devel/dependencies.rst b/doc/devel/dependencies.rst\nindex fb76857898a4..365c062364e2 100644\n--- a/doc/devel/dependencies.rst\n+++ b/doc/devel/dependencies.rst\n@@ -26,6 +26,9 @@ reference.\n * `Pillow `_ (>= 6.2)\n * `pyparsing `_ (>= 2.3.1)\n * `setuptools `_\n+* `pyparsing `_ (>= 2.3.1)\n+* `importlib-resources `_\n+ (>= 3.2.0; only required on Python < 3.10)\n \n \n .. _optional_dependencies:\n"}, {"path": "doc/users/next_whats_new/styles_from_packages.rst", "old_path": "/dev/null", "new_path": "b/doc/users/next_whats_new/styles_from_packages.rst", "metadata": "diff --git a/doc/users/next_whats_new/styles_from_packages.rst b/doc/users/next_whats_new/styles_from_packages.rst\nnew file mode 100644\nindex 000000000000..d129bb356fa7\n--- /dev/null\n+++ b/doc/users/next_whats_new/styles_from_packages.rst\n@@ -0,0 +1,11 @@\n+Style files can be imported from third-party packages\n+-----------------------------------------------------\n+\n+Third-party packages can now distribute style files that are globally available\n+as follows. Assume that a package is importable as ``import mypackage``, with\n+a ``mypackage/__init__.py`` module. Then a ``mypackage/presentation.mplstyle``\n+style sheet can be used as ``plt.style.use(\"mypackage.presentation\")``.\n+\n+The implementation does not actually import ``mypackage``, making this process\n+safe against possible import-time side effects. Subpackages (e.g.\n+``dotted.package.name``) are also supported.\n"}], "version": "3.5", "base_commit": "aca6e9d5e98811ca37c442217914b15e78127c89", "PASS2PASS": ["lib/matplotlib/tests/test_style.py::test_use", "lib/matplotlib/tests/test_style.py::test_available", "lib/matplotlib/tests/test_style.py::test_invalid_rc_warning_includes_filename", "lib/matplotlib/tests/test_style.py::test_context_with_union_of_dict_and_namedstyle", "lib/matplotlib/tests/test_style.py::test_context_with_dict_after_namedstyle", "lib/matplotlib/tests/test_style.py::test_xkcd_cm", "lib/matplotlib/tests/test_style.py::test_alias[mpl20]", "lib/matplotlib/tests/test_style.py::test_alias[mpl15]", "lib/matplotlib/tests/test_style.py::test_single_path", "lib/matplotlib/tests/test_style.py::test_context", "lib/matplotlib/tests/test_style.py::test_context_with_dict", "lib/matplotlib/tests/test_style.py::test_use_url", "lib/matplotlib/tests/test_style.py::test_deprecated_seaborn_styles", "lib/matplotlib/tests/test_style.py::test_context_with_dict_before_namedstyle", "lib/matplotlib/tests/test_style.py::test_up_to_date_blacklist", "lib/matplotlib/tests/test_style.py::test_context_with_badparam", "lib/matplotlib/tests/test_style.py::test_xkcd_no_cm"], "FAIL2PASS": ["lib/matplotlib/tests/test_style.py::test_style_from_module"], "mask_doc_diff": [{"path": "doc/api/next_api_changes/development/#####-AL.rst", "old_path": "/dev/null", "new_path": "b/doc/api/next_api_changes/development/#####-AL.rst", "metadata": "diff --git a/doc/api/next_api_changes/development/#####-AL.rst b/doc/api/next_api_changes/development/#####-AL.rst\nnew file mode 100644\nindex 0000000000..584420df8f\n--- /dev/null\n+++ b/doc/api/next_api_changes/development/#####-AL.rst\n@@ -0,0 +1,2 @@\n+importlib_resources>=2.3.0 is now required on Python<3.10\n+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"}, {"path": "doc/devel/dependencies.rst", "old_path": "a/doc/devel/dependencies.rst", "new_path": "b/doc/devel/dependencies.rst", "metadata": "diff --git a/doc/devel/dependencies.rst b/doc/devel/dependencies.rst\nindex fb76857898..365c062364 100644\n--- a/doc/devel/dependencies.rst\n+++ b/doc/devel/dependencies.rst\n@@ -26,6 +26,9 @@ reference.\n * `Pillow `_ (>= 6.2)\n * `pyparsing `_ (>= 2.3.1)\n * `setuptools `_\n+* `pyparsing `_ (>= 2.3.1)\n+* `importlib-resources `_\n+ (>= 3.2.0; only required on Python < 3.10)\n \n \n .. _optional_dependencies:\n"}, {"path": "doc/users/next_whats_new/styles_from_packages.rst", "old_path": "/dev/null", "new_path": "b/doc/users/next_whats_new/styles_from_packages.rst", "metadata": "diff --git a/doc/users/next_whats_new/styles_from_packages.rst b/doc/users/next_whats_new/styles_from_packages.rst\nnew file mode 100644\nindex 0000000000..d129bb356f\n--- /dev/null\n+++ b/doc/users/next_whats_new/styles_from_packages.rst\n@@ -0,0 +1,11 @@\n+Style files can be imported from third-party packages\n+-----------------------------------------------------\n+\n+Third-party packages can now distribute style files that are globally available\n+as follows. Assume that a package is importable as ``import mypackage``, with\n+a ``mypackage/__init__.py`` module. Then a ``mypackage/presentation.mplstyle``\n+style sheet can be used as ``plt.style.use(\"mypackage.presentation\")``.\n+\n+The implementation does not actually import ``mypackage``, making this process\n+safe against possible import-time side effects. Subpackages (e.g.\n+``dotted.package.name``) are also supported.\n"}], "augmentations": {"header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": []}, "problem_statement": "diff --git a/doc/api/next_api_changes/development/#####-AL.rst b/doc/api/next_api_changes/development/#####-AL.rst\nnew file mode 100644\nindex 0000000000..584420df8f\n--- /dev/null\n+++ b/doc/api/next_api_changes/development/#####-AL.rst\n@@ -0,0 +1,2 @@\n+importlib_resources>=2.3.0 is now required on Python<3.10\n+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\ndiff --git a/doc/devel/dependencies.rst b/doc/devel/dependencies.rst\nindex fb76857898..365c062364 100644\n--- a/doc/devel/dependencies.rst\n+++ b/doc/devel/dependencies.rst\n@@ -26,6 +26,9 @@ reference.\n * `Pillow `_ (>= 6.2)\n * `pyparsing `_ (>= 2.3.1)\n * `setuptools `_\n+* `pyparsing `_ (>= 2.3.1)\n+* `importlib-resources `_\n+ (>= 3.2.0; only required on Python < 3.10)\n \n \n .. _optional_dependencies:\n\ndiff --git a/doc/users/next_whats_new/styles_from_packages.rst b/doc/users/next_whats_new/styles_from_packages.rst\nnew file mode 100644\nindex 0000000000..d129bb356f\n--- /dev/null\n+++ b/doc/users/next_whats_new/styles_from_packages.rst\n@@ -0,0 +1,11 @@\n+Style files can be imported from third-party packages\n+-----------------------------------------------------\n+\n+Third-party packages can now distribute style files that are globally available\n+as follows. Assume that a package is importable as ``import mypackage``, with\n+a ``mypackage/__init__.py`` module. Then a ``mypackage/presentation.mplstyle``\n+style sheet can be used as ``plt.style.use(\"mypackage.presentation\")``.\n+\n+The implementation does not actually import ``mypackage``, making this process\n+safe against possible import-time side effects. Subpackages (e.g.\n+``dotted.package.name``) are also supported.\n\n"} -{"repo": "matplotlib/matplotlib", "instance_id": "matplotlib__matplotlib-26278", "html_url": "https://github.com/matplotlib/matplotlib/pull/26278", "feature_patch": "diff --git a/doc/users/next_whats_new/contour_clip_path.rst b/doc/users/next_whats_new/contour_clip_path.rst\nnew file mode 100644\nindex 000000000000..db4039a4fd70\n--- /dev/null\n+++ b/doc/users/next_whats_new/contour_clip_path.rst\n@@ -0,0 +1,24 @@\n+Clipping for contour plots\n+--------------------------\n+\n+`~.Axes.contour` and `~.Axes.contourf` now accept the *clip_path* parameter.\n+\n+.. plot::\n+ :include-source: true\n+\n+ import numpy as np\n+ import matplotlib.pyplot as plt\n+ import matplotlib.patches as mpatches\n+\n+ x = y = np.arange(-3.0, 3.01, 0.025)\n+ X, Y = np.meshgrid(x, y)\n+ Z1 = np.exp(-X**2 - Y**2)\n+ Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)\n+ Z = (Z1 - Z2) * 2\n+\n+ fig, ax = plt.subplots()\n+ patch = mpatches.RegularPolygon((0, 0), 5, radius=2,\n+ transform=ax.transData)\n+ ax.contourf(X, Y, Z, clip_path=patch)\n+\n+ plt.show()\ndiff --git a/lib/matplotlib/contour.py b/lib/matplotlib/contour.py\nindex 625c3524bfcb..6f97c5646ab0 100644\n--- a/lib/matplotlib/contour.py\n+++ b/lib/matplotlib/contour.py\n@@ -751,7 +751,7 @@ def __init__(self, ax, *args,\n hatches=(None,), alpha=None, origin=None, extent=None,\n cmap=None, colors=None, norm=None, vmin=None, vmax=None,\n extend='neither', antialiased=None, nchunk=0, locator=None,\n- transform=None, negative_linestyles=None,\n+ transform=None, negative_linestyles=None, clip_path=None,\n **kwargs):\n \"\"\"\n Draw contour lines or filled regions, depending on\n@@ -805,6 +805,7 @@ def __init__(self, ax, *args,\n super().__init__(\n antialiaseds=antialiased,\n alpha=alpha,\n+ clip_path=clip_path,\n transform=transform,\n )\n self.axes = ax\n@@ -1870,6 +1871,11 @@ def _initialize_x_y(self, z):\n \n The default is taken from :rc:`contour.algorithm`.\n \n+clip_path : `~matplotlib.patches.Patch` or `.Path` or `.TransformedPath`\n+ Set the clip path. See `~matplotlib.artist.Artist.set_clip_path`.\n+\n+ .. versionadded:: 3.8\n+\n data : indexable object, optional\n DATA_PARAMETER_PLACEHOLDER\n \ndiff --git a/lib/matplotlib/contour.pyi b/lib/matplotlib/contour.pyi\nindex c2190577169d..c7179637a1e1 100644\n--- a/lib/matplotlib/contour.pyi\n+++ b/lib/matplotlib/contour.pyi\n@@ -4,8 +4,10 @@ from matplotlib.axes import Axes\n from matplotlib.collections import Collection, PathCollection\n from matplotlib.colors import Colormap, Normalize\n from matplotlib.font_manager import FontProperties\n+from matplotlib.path import Path\n+from matplotlib.patches import Patch\n from matplotlib.text import Text\n-from matplotlib.transforms import Transform\n+from matplotlib.transforms import Transform, TransformedPatchPath, TransformedPath\n from matplotlib.ticker import Locator, Formatter\n \n from numpy.typing import ArrayLike\n@@ -99,6 +101,7 @@ class ContourSet(ContourLabeler, Collection):\n negative_linestyles: None | Literal[\n \"solid\", \"dashed\", \"dashdot\", \"dotted\"\n ] | Iterable[Literal[\"solid\", \"dashed\", \"dashdot\", \"dotted\"]]\n+ clip_path: Patch | Path | TransformedPath | TransformedPatchPath | None\n labelTexts: list[Text]\n labelCValues: list[ColorType]\n allkinds: list[np.ndarray]\n@@ -145,6 +148,7 @@ class ContourSet(ContourLabeler, Collection):\n negative_linestyles: Literal[\"solid\", \"dashed\", \"dashdot\", \"dotted\"]\n | Iterable[Literal[\"solid\", \"dashed\", \"dashdot\", \"dotted\"]]\n | None = ...,\n+ clip_path: Patch | Path | TransformedPath | TransformedPatchPath | None = ...,\n **kwargs\n ) -> None: ...\n def legend_elements(\n", "test_patch": "diff --git a/lib/matplotlib/tests/test_contour.py b/lib/matplotlib/tests/test_contour.py\nindex c730c8ea332d..7a4c4570580c 100644\n--- a/lib/matplotlib/tests/test_contour.py\n+++ b/lib/matplotlib/tests/test_contour.py\n@@ -9,6 +9,7 @@\n import matplotlib as mpl\n from matplotlib import pyplot as plt, rc_context, ticker\n from matplotlib.colors import LogNorm, same_color\n+import matplotlib.patches as mpatches\n from matplotlib.testing.decorators import image_comparison\n import pytest\n \n@@ -752,6 +753,14 @@ def test_contour_no_args():\n ax.contour(Z=data)\n \n \n+def test_contour_clip_path():\n+ fig, ax = plt.subplots()\n+ data = [[0, 1], [1, 0]]\n+ circle = mpatches.Circle([0.5, 0.5], 0.5, transform=ax.transAxes)\n+ cs = ax.contour(data, clip_path=circle)\n+ assert cs.get_clip_path() is not None\n+\n+\n def test_bool_autolevel():\n x, y = np.random.rand(2, 9)\n z = (np.arange(9) % 2).reshape((3, 3)).astype(bool)\n", "doc_changes": [{"path": "doc/users/next_whats_new/contour_clip_path.rst", "old_path": "/dev/null", "new_path": "b/doc/users/next_whats_new/contour_clip_path.rst", "metadata": "diff --git a/doc/users/next_whats_new/contour_clip_path.rst b/doc/users/next_whats_new/contour_clip_path.rst\nnew file mode 100644\nindex 000000000000..db4039a4fd70\n--- /dev/null\n+++ b/doc/users/next_whats_new/contour_clip_path.rst\n@@ -0,0 +1,24 @@\n+Clipping for contour plots\n+--------------------------\n+\n+`~.Axes.contour` and `~.Axes.contourf` now accept the *clip_path* parameter.\n+\n+.. plot::\n+ :include-source: true\n+\n+ import numpy as np\n+ import matplotlib.pyplot as plt\n+ import matplotlib.patches as mpatches\n+\n+ x = y = np.arange(-3.0, 3.01, 0.025)\n+ X, Y = np.meshgrid(x, y)\n+ Z1 = np.exp(-X**2 - Y**2)\n+ Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)\n+ Z = (Z1 - Z2) * 2\n+\n+ fig, ax = plt.subplots()\n+ patch = mpatches.RegularPolygon((0, 0), 5, radius=2,\n+ transform=ax.transData)\n+ ax.contourf(X, Y, Z, clip_path=patch)\n+\n+ plt.show()\n"}], "version": "3.7", "base_commit": "02d2e137251ebcbd698b6f1ff8c455a1e52082af", "PASS2PASS": ["lib/matplotlib/tests/test_contour.py::test_contour_shape_error[args9-Input z must be at least a (2, 2) shaped array, but has shape (1, 1)]", "lib/matplotlib/tests/test_contour.py::test_contour_shape_2d_valid", "lib/matplotlib/tests/test_contour.py::test_contour_manual_labels[svg-False]", "lib/matplotlib/tests/test_contour.py::test_contour_shape_error[args5-Shapes of y (9, 9) and z (9, 10) do not match]", "lib/matplotlib/tests/test_contour.py::test_contourf_log_extension[png-True]", "lib/matplotlib/tests/test_contour.py::test_negative_linestyles[dashdot]", "lib/matplotlib/tests/test_contour.py::test_contourf_decreasing_levels", "lib/matplotlib/tests/test_contour.py::test_algorithm_supports_corner_mask[serial]", "lib/matplotlib/tests/test_contour.py::test_contour_shape_error[args1-Length of y (10) must match number of rows in z (9)]", "lib/matplotlib/tests/test_contour.py::test_all_nan", "lib/matplotlib/tests/test_contour.py::test_corner_mask[png-False]", "lib/matplotlib/tests/test_contour.py::test_contourf_legend_elements", "lib/matplotlib/tests/test_contour.py::test_algorithm_name[serial-SerialContourGenerator]", "lib/matplotlib/tests/test_contour.py::test_contour_shape_error[args6-Inputs x and y must be 1D or 2D, not 3D]", "lib/matplotlib/tests/test_contour.py::test_contour_datetime_axis[png-True]", "lib/matplotlib/tests/test_contour.py::test_contour_datetime_axis[png-False]", "lib/matplotlib/tests/test_contour.py::test_algorithm_name[invalid-None]", "lib/matplotlib/tests/test_contour.py::test_contour_manual_labels[svg-True]", "lib/matplotlib/tests/test_contour.py::test_algorithm_supports_corner_mask[mpl2005]", "lib/matplotlib/tests/test_contour.py::test_bool_autolevel", "lib/matplotlib/tests/test_contour.py::test_quadcontourset_reuse", "lib/matplotlib/tests/test_contour.py::test_contour_shape_error[args4-Shapes of x (9, 9) and z (9, 10) do not match]", "lib/matplotlib/tests/test_contour.py::test_contour_Nlevels", "lib/matplotlib/tests/test_contour.py::test_contour_addlines[png-True]", "lib/matplotlib/tests/test_contour.py::test_algorithm_name[mpl2005-Mpl2005ContourGenerator]", "lib/matplotlib/tests/test_contour.py::test_circular_contour_warning", "lib/matplotlib/tests/test_contour.py::test_labels[png-True]", "lib/matplotlib/tests/test_contour.py::test_contour_manual_labels[png-True]", "lib/matplotlib/tests/test_contour.py::test_find_nearest_contour", "lib/matplotlib/tests/test_contour.py::test_contour_shape_error[args2-Number of dimensions of x (2) and y (1) do not match]", "lib/matplotlib/tests/test_contour.py::test_contour_manual[png-True]", "lib/matplotlib/tests/test_contour.py::test_contour_autolabel_beyond_powerlimits", "lib/matplotlib/tests/test_contour.py::test_algorithm_name[mpl2014-Mpl2014ContourGenerator]", "lib/matplotlib/tests/test_contour.py::test_contour_uneven[png-True]", "lib/matplotlib/tests/test_contour.py::test_contour_shape_error[args3-Number of dimensions of x (1) and y (2) do not match]", "lib/matplotlib/tests/test_contour.py::test_contourf_log_extension[png-False]", "lib/matplotlib/tests/test_contour.py::test_contour_line_start_on_corner_edge[png-True]", "lib/matplotlib/tests/test_contour.py::test_contour_manual[png-False]", "lib/matplotlib/tests/test_contour.py::test_contour_shape_1d_valid", "lib/matplotlib/tests/test_contour.py::test_contour_shape_error[args8-Input z must be at least a (2, 2) shaped array, but has shape (1, 1)]", "lib/matplotlib/tests/test_contour.py::test_contourf_symmetric_locator", "lib/matplotlib/tests/test_contour.py::test_clabel_zorder[False-123-None]", "lib/matplotlib/tests/test_contour.py::test_contour_linewidth[1.23-4.24-None-4.24]", "lib/matplotlib/tests/test_contour.py::test_log_locator_levels[svg-False]", "lib/matplotlib/tests/test_contour.py::test_corner_mask[png-True]", "lib/matplotlib/tests/test_contour.py::test_find_nearest_contour_no_filled", "lib/matplotlib/tests/test_contour.py::test_subfigure_clabel", "lib/matplotlib/tests/test_contour.py::test_all_algorithms[png-False]", "lib/matplotlib/tests/test_contour.py::test_contour_closed_line_loop[png-True]", "lib/matplotlib/tests/test_contour.py::test_labels[png-False]", "lib/matplotlib/tests/test_contour.py::test_linestyles[dotted]", "lib/matplotlib/tests/test_contour.py::test_contour_line_start_on_corner_edge[png-False]", "lib/matplotlib/tests/test_contour.py::test_algorithm_name[threaded-ThreadedContourGenerator]", "lib/matplotlib/tests/test_contour.py::test_contour_manual_labels[pdf-False]", "lib/matplotlib/tests/test_contour.py::test_negative_linestyles[dotted]", "lib/matplotlib/tests/test_contour.py::test_contour_remove", "lib/matplotlib/tests/test_contour.py::test_contour_manual_labels[png-False]", "lib/matplotlib/tests/test_contour.py::test_negative_linestyles[solid]", "lib/matplotlib/tests/test_contour.py::test_contour_legend_elements", "lib/matplotlib/tests/test_contour.py::test_contour_linewidth[1.23-None-None-1.23]", "lib/matplotlib/tests/test_contour.py::test_linestyles[solid]", "lib/matplotlib/tests/test_contour.py::test_contour_no_args", "lib/matplotlib/tests/test_contour.py::test_clabel_zorder[False-123-1234]", "lib/matplotlib/tests/test_contour.py::test_algorithm_supports_corner_mask[mpl2014]", "lib/matplotlib/tests/test_contour.py::test_contour_manual_labels[pdf-True]", "lib/matplotlib/tests/test_contour.py::test_given_colors_levels_and_extends[png-False]", "lib/matplotlib/tests/test_contour.py::test_contour_closed_line_loop[png-False]", "lib/matplotlib/tests/test_contour.py::test_linestyles[dashed]", "lib/matplotlib/tests/test_contour.py::test_contour_uneven[png-False]", "lib/matplotlib/tests/test_contour.py::test_clabel_zorder[True-123-None]", "lib/matplotlib/tests/test_contour.py::test_algorithm_supports_corner_mask[threaded]", "lib/matplotlib/tests/test_contour.py::test_given_colors_levels_and_extends[png-True]", "lib/matplotlib/tests/test_contour.py::test_contour_shape_error[args0-Length of x (9) must match number of columns in z (10)]", "lib/matplotlib/tests/test_contour.py::test_linestyles[dashdot]", "lib/matplotlib/tests/test_contour.py::test_all_algorithms[png-True]", "lib/matplotlib/tests/test_contour.py::test_log_locator_levels[svg-True]", "lib/matplotlib/tests/test_contour.py::test_negative_linestyles[dashed]", "lib/matplotlib/tests/test_contour.py::test_contour_addlines[png-False]", "lib/matplotlib/tests/test_contour.py::test_clabel_zorder[True-123-1234]", "lib/matplotlib/tests/test_contour.py::test_contour_shape_error[args7-Input z must be 2D, not 3D]", "lib/matplotlib/tests/test_contour.py::test_contour_no_valid_levels", "lib/matplotlib/tests/test_contour.py::test_label_nonagg", "lib/matplotlib/tests/test_contour.py::test_contour_linewidth[1.23-4.24-5.02-5.02]"], "FAIL2PASS": ["lib/matplotlib/tests/test_contour.py::test_contour_clip_path"], "mask_doc_diff": [{"path": "doc/users/next_whats_new/contour_clip_path.rst", "old_path": "/dev/null", "new_path": "b/doc/users/next_whats_new/contour_clip_path.rst", "metadata": "diff --git a/doc/users/next_whats_new/contour_clip_path.rst b/doc/users/next_whats_new/contour_clip_path.rst\nnew file mode 100644\nindex 0000000000..db4039a4fd\n--- /dev/null\n+++ b/doc/users/next_whats_new/contour_clip_path.rst\n@@ -0,0 +1,24 @@\n+Clipping for contour plots\n+--------------------------\n+\n+`~.Axes.contour` and `~.Axes.contourf` now accept the *clip_path* parameter.\n+\n+.. plot::\n+ :include-source: true\n+\n+ import numpy as np\n+ import matplotlib.pyplot as plt\n+ import matplotlib.patches as mpatches\n+\n+ x = y = np.arange(-3.0, 3.01, 0.025)\n+ X, Y = np.meshgrid(x, y)\n+ Z1 = np.exp(-X**2 - Y**2)\n+ Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)\n+ Z = (Z1 - Z2) * 2\n+\n+ fig, ax = plt.subplots()\n+ patch = mpatches.RegularPolygon((0, 0), 5, radius=2,\n+ transform=ax.transData)\n+ ax.contourf(X, Y, Z, clip_path=patch)\n+\n+ plt.show()\n"}], "augmentations": {"header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": []}, "problem_statement": "diff --git a/doc/users/next_whats_new/contour_clip_path.rst b/doc/users/next_whats_new/contour_clip_path.rst\nnew file mode 100644\nindex 0000000000..db4039a4fd\n--- /dev/null\n+++ b/doc/users/next_whats_new/contour_clip_path.rst\n@@ -0,0 +1,24 @@\n+Clipping for contour plots\n+--------------------------\n+\n+`~.Axes.contour` and `~.Axes.contourf` now accept the *clip_path* parameter.\n+\n+.. plot::\n+ :include-source: true\n+\n+ import numpy as np\n+ import matplotlib.pyplot as plt\n+ import matplotlib.patches as mpatches\n+\n+ x = y = np.arange(-3.0, 3.01, 0.025)\n+ X, Y = np.meshgrid(x, y)\n+ Z1 = np.exp(-X**2 - Y**2)\n+ Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)\n+ Z = (Z1 - Z2) * 2\n+\n+ fig, ax = plt.subplots()\n+ patch = mpatches.RegularPolygon((0, 0), 5, radius=2,\n+ transform=ax.transData)\n+ ax.contourf(X, Y, Z, clip_path=patch)\n+\n+ plt.show()\n\n"} +{"repo": "matplotlib/matplotlib", "instance_id": "matplotlib__matplotlib-26278", "html_url": "https://github.com/matplotlib/matplotlib/pull/26278", "feature_patch": "diff --git a/doc/users/next_whats_new/contour_clip_path.rst b/doc/users/next_whats_new/contour_clip_path.rst\nnew file mode 100644\nindex 000000000000..db4039a4fd70\n--- /dev/null\n+++ b/doc/users/next_whats_new/contour_clip_path.rst\n@@ -0,0 +1,24 @@\n+Clipping for contour plots\n+--------------------------\n+\n+`~.Axes.contour` and `~.Axes.contourf` now accept the *clip_path* parameter.\n+\n+.. plot::\n+ :include-source: true\n+\n+ import numpy as np\n+ import matplotlib.pyplot as plt\n+ import matplotlib.patches as mpatches\n+\n+ x = y = np.arange(-3.0, 3.01, 0.025)\n+ X, Y = np.meshgrid(x, y)\n+ Z1 = np.exp(-X**2 - Y**2)\n+ Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)\n+ Z = (Z1 - Z2) * 2\n+\n+ fig, ax = plt.subplots()\n+ patch = mpatches.RegularPolygon((0, 0), 5, radius=2,\n+ transform=ax.transData)\n+ ax.contourf(X, Y, Z, clip_path=patch)\n+\n+ plt.show()\ndiff --git a/lib/matplotlib/contour.py b/lib/matplotlib/contour.py\nindex 625c3524bfcb..6f97c5646ab0 100644\n--- a/lib/matplotlib/contour.py\n+++ b/lib/matplotlib/contour.py\n@@ -751,7 +751,7 @@ def __init__(self, ax, *args,\n hatches=(None,), alpha=None, origin=None, extent=None,\n cmap=None, colors=None, norm=None, vmin=None, vmax=None,\n extend='neither', antialiased=None, nchunk=0, locator=None,\n- transform=None, negative_linestyles=None,\n+ transform=None, negative_linestyles=None, clip_path=None,\n **kwargs):\n \"\"\"\n Draw contour lines or filled regions, depending on\n@@ -805,6 +805,7 @@ def __init__(self, ax, *args,\n super().__init__(\n antialiaseds=antialiased,\n alpha=alpha,\n+ clip_path=clip_path,\n transform=transform,\n )\n self.axes = ax\n@@ -1870,6 +1871,11 @@ def _initialize_x_y(self, z):\n \n The default is taken from :rc:`contour.algorithm`.\n \n+clip_path : `~matplotlib.patches.Patch` or `.Path` or `.TransformedPath`\n+ Set the clip path. See `~matplotlib.artist.Artist.set_clip_path`.\n+\n+ .. versionadded:: 3.8\n+\n data : indexable object, optional\n DATA_PARAMETER_PLACEHOLDER\n \ndiff --git a/lib/matplotlib/contour.pyi b/lib/matplotlib/contour.pyi\nindex c2190577169d..c7179637a1e1 100644\n--- a/lib/matplotlib/contour.pyi\n+++ b/lib/matplotlib/contour.pyi\n@@ -4,8 +4,10 @@ from matplotlib.axes import Axes\n from matplotlib.collections import Collection, PathCollection\n from matplotlib.colors import Colormap, Normalize\n from matplotlib.font_manager import FontProperties\n+from matplotlib.path import Path\n+from matplotlib.patches import Patch\n from matplotlib.text import Text\n-from matplotlib.transforms import Transform\n+from matplotlib.transforms import Transform, TransformedPatchPath, TransformedPath\n from matplotlib.ticker import Locator, Formatter\n \n from numpy.typing import ArrayLike\n@@ -99,6 +101,7 @@ class ContourSet(ContourLabeler, Collection):\n negative_linestyles: None | Literal[\n \"solid\", \"dashed\", \"dashdot\", \"dotted\"\n ] | Iterable[Literal[\"solid\", \"dashed\", \"dashdot\", \"dotted\"]]\n+ clip_path: Patch | Path | TransformedPath | TransformedPatchPath | None\n labelTexts: list[Text]\n labelCValues: list[ColorType]\n allkinds: list[np.ndarray]\n@@ -145,6 +148,7 @@ class ContourSet(ContourLabeler, Collection):\n negative_linestyles: Literal[\"solid\", \"dashed\", \"dashdot\", \"dotted\"]\n | Iterable[Literal[\"solid\", \"dashed\", \"dashdot\", \"dotted\"]]\n | None = ...,\n+ clip_path: Patch | Path | TransformedPath | TransformedPatchPath | None = ...,\n **kwargs\n ) -> None: ...\n def legend_elements(\n", "test_patch": "diff --git a/lib/matplotlib/tests/test_contour.py b/lib/matplotlib/tests/test_contour.py\nindex c730c8ea332d..7a4c4570580c 100644\n--- a/lib/matplotlib/tests/test_contour.py\n+++ b/lib/matplotlib/tests/test_contour.py\n@@ -9,6 +9,7 @@\n import matplotlib as mpl\n from matplotlib import pyplot as plt, rc_context, ticker\n from matplotlib.colors import LogNorm, same_color\n+import matplotlib.patches as mpatches\n from matplotlib.testing.decorators import image_comparison\n import pytest\n \n@@ -752,6 +753,14 @@ def test_contour_no_args():\n ax.contour(Z=data)\n \n \n+def test_contour_clip_path():\n+ fig, ax = plt.subplots()\n+ data = [[0, 1], [1, 0]]\n+ circle = mpatches.Circle([0.5, 0.5], 0.5, transform=ax.transAxes)\n+ cs = ax.contour(data, clip_path=circle)\n+ assert cs.get_clip_path() is not None\n+\n+\n def test_bool_autolevel():\n x, y = np.random.rand(2, 9)\n z = (np.arange(9) % 2).reshape((3, 3)).astype(bool)\n", "doc_changes": [{"path": "doc/users/next_whats_new/contour_clip_path.rst", "old_path": "/dev/null", "new_path": "b/doc/users/next_whats_new/contour_clip_path.rst", "metadata": "diff --git a/doc/users/next_whats_new/contour_clip_path.rst b/doc/users/next_whats_new/contour_clip_path.rst\nnew file mode 100644\nindex 000000000000..db4039a4fd70\n--- /dev/null\n+++ b/doc/users/next_whats_new/contour_clip_path.rst\n@@ -0,0 +1,24 @@\n+Clipping for contour plots\n+--------------------------\n+\n+`~.Axes.contour` and `~.Axes.contourf` now accept the *clip_path* parameter.\n+\n+.. plot::\n+ :include-source: true\n+\n+ import numpy as np\n+ import matplotlib.pyplot as plt\n+ import matplotlib.patches as mpatches\n+\n+ x = y = np.arange(-3.0, 3.01, 0.025)\n+ X, Y = np.meshgrid(x, y)\n+ Z1 = np.exp(-X**2 - Y**2)\n+ Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)\n+ Z = (Z1 - Z2) * 2\n+\n+ fig, ax = plt.subplots()\n+ patch = mpatches.RegularPolygon((0, 0), 5, radius=2,\n+ transform=ax.transData)\n+ ax.contourf(X, Y, Z, clip_path=patch)\n+\n+ plt.show()\n"}], "version": "3.7", "base_commit": "02d2e137251ebcbd698b6f1ff8c455a1e52082af", "PASS2PASS": ["lib/matplotlib/tests/test_contour.py::test_contour_shape_error[args9-Input z must be at least a (2, 2) shaped array, but has shape (1, 1)]", "lib/matplotlib/tests/test_contour.py::test_contour_shape_2d_valid", "lib/matplotlib/tests/test_contour.py::test_contour_manual_labels[svg-False]", "lib/matplotlib/tests/test_contour.py::test_contour_shape_error[args5-Shapes of y (9, 9) and z (9, 10) do not match]", "lib/matplotlib/tests/test_contour.py::test_contourf_log_extension[png-True]", "lib/matplotlib/tests/test_contour.py::test_negative_linestyles[dashdot]", "lib/matplotlib/tests/test_contour.py::test_contourf_decreasing_levels", "lib/matplotlib/tests/test_contour.py::test_algorithm_supports_corner_mask[serial]", "lib/matplotlib/tests/test_contour.py::test_contour_shape_error[args1-Length of y (10) must match number of rows in z (9)]", "lib/matplotlib/tests/test_contour.py::test_all_nan", "lib/matplotlib/tests/test_contour.py::test_corner_mask[png-False]", "lib/matplotlib/tests/test_contour.py::test_contourf_legend_elements", "lib/matplotlib/tests/test_contour.py::test_algorithm_name[serial-SerialContourGenerator]", "lib/matplotlib/tests/test_contour.py::test_contour_shape_error[args6-Inputs x and y must be 1D or 2D, not 3D]", "lib/matplotlib/tests/test_contour.py::test_contour_datetime_axis[png-True]", "lib/matplotlib/tests/test_contour.py::test_contour_datetime_axis[png-False]", "lib/matplotlib/tests/test_contour.py::test_algorithm_name[invalid-None]", "lib/matplotlib/tests/test_contour.py::test_contour_manual_labels[svg-True]", "lib/matplotlib/tests/test_contour.py::test_algorithm_supports_corner_mask[mpl2005]", "lib/matplotlib/tests/test_contour.py::test_bool_autolevel", "lib/matplotlib/tests/test_contour.py::test_quadcontourset_reuse", "lib/matplotlib/tests/test_contour.py::test_contour_shape_error[args4-Shapes of x (9, 9) and z (9, 10) do not match]", "lib/matplotlib/tests/test_contour.py::test_contour_Nlevels", "lib/matplotlib/tests/test_contour.py::test_contour_addlines[png-True]", "lib/matplotlib/tests/test_contour.py::test_algorithm_name[mpl2005-Mpl2005ContourGenerator]", "lib/matplotlib/tests/test_contour.py::test_circular_contour_warning", "lib/matplotlib/tests/test_contour.py::test_labels[png-True]", "lib/matplotlib/tests/test_contour.py::test_contour_manual_labels[png-True]", "lib/matplotlib/tests/test_contour.py::test_find_nearest_contour", "lib/matplotlib/tests/test_contour.py::test_contour_shape_error[args2-Number of dimensions of x (2) and y (1) do not match]", "lib/matplotlib/tests/test_contour.py::test_contour_manual[png-True]", "lib/matplotlib/tests/test_contour.py::test_contour_autolabel_beyond_powerlimits", "lib/matplotlib/tests/test_contour.py::test_algorithm_name[mpl2014-Mpl2014ContourGenerator]", "lib/matplotlib/tests/test_contour.py::test_contour_uneven[png-True]", "lib/matplotlib/tests/test_contour.py::test_contour_shape_error[args3-Number of dimensions of x (1) and y (2) do not match]", "lib/matplotlib/tests/test_contour.py::test_contourf_log_extension[png-False]", "lib/matplotlib/tests/test_contour.py::test_contour_line_start_on_corner_edge[png-True]", "lib/matplotlib/tests/test_contour.py::test_contour_manual[png-False]", "lib/matplotlib/tests/test_contour.py::test_contour_shape_1d_valid", "lib/matplotlib/tests/test_contour.py::test_contour_shape_error[args8-Input z must be at least a (2, 2) shaped array, but has shape (1, 1)]", "lib/matplotlib/tests/test_contour.py::test_contourf_symmetric_locator", "lib/matplotlib/tests/test_contour.py::test_clabel_zorder[False-123-None]", "lib/matplotlib/tests/test_contour.py::test_contour_linewidth[1.23-4.24-None-4.24]", "lib/matplotlib/tests/test_contour.py::test_log_locator_levels[svg-False]", "lib/matplotlib/tests/test_contour.py::test_corner_mask[png-True]", "lib/matplotlib/tests/test_contour.py::test_find_nearest_contour_no_filled", "lib/matplotlib/tests/test_contour.py::test_subfigure_clabel", "lib/matplotlib/tests/test_contour.py::test_all_algorithms[png-False]", "lib/matplotlib/tests/test_contour.py::test_contour_closed_line_loop[png-True]", "lib/matplotlib/tests/test_contour.py::test_labels[png-False]", "lib/matplotlib/tests/test_contour.py::test_linestyles[dotted]", "lib/matplotlib/tests/test_contour.py::test_contour_line_start_on_corner_edge[png-False]", "lib/matplotlib/tests/test_contour.py::test_algorithm_name[threaded-ThreadedContourGenerator]", "lib/matplotlib/tests/test_contour.py::test_contour_manual_labels[pdf-False]", "lib/matplotlib/tests/test_contour.py::test_negative_linestyles[dotted]", "lib/matplotlib/tests/test_contour.py::test_contour_remove", "lib/matplotlib/tests/test_contour.py::test_contour_manual_labels[png-False]", "lib/matplotlib/tests/test_contour.py::test_negative_linestyles[solid]", "lib/matplotlib/tests/test_contour.py::test_contour_legend_elements", "lib/matplotlib/tests/test_contour.py::test_contour_linewidth[1.23-None-None-1.23]", "lib/matplotlib/tests/test_contour.py::test_linestyles[solid]", "lib/matplotlib/tests/test_contour.py::test_contour_no_args", "lib/matplotlib/tests/test_contour.py::test_clabel_zorder[False-123-1234]", "lib/matplotlib/tests/test_contour.py::test_algorithm_supports_corner_mask[mpl2014]", "lib/matplotlib/tests/test_contour.py::test_given_colors_levels_and_extends[png-False]", "lib/matplotlib/tests/test_contour.py::test_contour_closed_line_loop[png-False]", "lib/matplotlib/tests/test_contour.py::test_linestyles[dashed]", "lib/matplotlib/tests/test_contour.py::test_contour_uneven[png-False]", "lib/matplotlib/tests/test_contour.py::test_clabel_zorder[True-123-None]", "lib/matplotlib/tests/test_contour.py::test_algorithm_supports_corner_mask[threaded]", "lib/matplotlib/tests/test_contour.py::test_given_colors_levels_and_extends[png-True]", "lib/matplotlib/tests/test_contour.py::test_contour_shape_error[args0-Length of x (9) must match number of columns in z (10)]", "lib/matplotlib/tests/test_contour.py::test_linestyles[dashdot]", "lib/matplotlib/tests/test_contour.py::test_all_algorithms[png-True]", "lib/matplotlib/tests/test_contour.py::test_log_locator_levels[svg-True]", "lib/matplotlib/tests/test_contour.py::test_negative_linestyles[dashed]", "lib/matplotlib/tests/test_contour.py::test_contour_addlines[png-False]", "lib/matplotlib/tests/test_contour.py::test_clabel_zorder[True-123-1234]", "lib/matplotlib/tests/test_contour.py::test_contour_shape_error[args7-Input z must be 2D, not 3D]", "lib/matplotlib/tests/test_contour.py::test_contour_no_valid_levels", "lib/matplotlib/tests/test_contour.py::test_label_nonagg", "lib/matplotlib/tests/test_contour.py::test_contour_linewidth[1.23-4.24-5.02-5.02]"], "FAIL2PASS": ["lib/matplotlib/tests/test_contour.py::test_contour_clip_path"], "mask_doc_diff": [{"path": "doc/users/next_whats_new/contour_clip_path.rst", "old_path": "/dev/null", "new_path": "b/doc/users/next_whats_new/contour_clip_path.rst", "metadata": "diff --git a/doc/users/next_whats_new/contour_clip_path.rst b/doc/users/next_whats_new/contour_clip_path.rst\nnew file mode 100644\nindex 0000000000..db4039a4fd\n--- /dev/null\n+++ b/doc/users/next_whats_new/contour_clip_path.rst\n@@ -0,0 +1,24 @@\n+Clipping for contour plots\n+--------------------------\n+\n+`~.Axes.contour` and `~.Axes.contourf` now accept the *clip_path* parameter.\n+\n+.. plot::\n+ :include-source: true\n+\n+ import numpy as np\n+ import matplotlib.pyplot as plt\n+ import matplotlib.patches as mpatches\n+\n+ x = y = np.arange(-3.0, 3.01, 0.025)\n+ X, Y = np.meshgrid(x, y)\n+ Z1 = np.exp(-X**2 - Y**2)\n+ Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)\n+ Z = (Z1 - Z2) * 2\n+\n+ fig, ax = plt.subplots()\n+ patch = mpatches.RegularPolygon((0, 0), 5, radius=2,\n+ transform=ax.transData)\n+ ax.contourf(X, Y, Z, clip_path=patch)\n+\n+ plt.show()\n"}], "augmentations": {"header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": []}, "problem_statement": "diff --git a/doc/users/next_whats_new/contour_clip_path.rst b/doc/users/next_whats_new/contour_clip_path.rst\nnew file mode 100644\nindex 0000000000..db4039a4fd\n--- /dev/null\n+++ b/doc/users/next_whats_new/contour_clip_path.rst\n@@ -0,0 +1,24 @@\n+Clipping for contour plots\n+--------------------------\n+\n+`~.Axes.contour` and `~.Axes.contourf` now accept the *clip_path* parameter.\n+\n+.. plot::\n+ :include-source: true\n+\n+ import numpy as np\n+ import matplotlib.pyplot as plt\n+ import matplotlib.patches as mpatches\n+\n+ x = y = np.arange(-3.0, 3.01, 0.025)\n+ X, Y = np.meshgrid(x, y)\n+ Z1 = np.exp(-X**2 - Y**2)\n+ Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)\n+ Z = (Z1 - Z2) * 2\n+\n+ fig, ax = plt.subplots()\n+ patch = mpatches.RegularPolygon((0, 0), 5, radius=2,\n+ transform=ax.transData)\n+ ax.contourf(X, Y, Z, clip_path=patch)\n+\n+ plt.show()\n\n"} {"repo": "matplotlib/matplotlib", "instance_id": "matplotlib__matplotlib-25904", "html_url": "https://github.com/matplotlib/matplotlib/pull/25904", "feature_patch": "diff --git a/doc/users/next_whats_new/spinesproxyset.rst b/doc/users/next_whats_new/spinesproxyset.rst\nnew file mode 100644\nindex 000000000000..cfd8d2908ec7\n--- /dev/null\n+++ b/doc/users/next_whats_new/spinesproxyset.rst\n@@ -0,0 +1,3 @@\n+``SpinesProxy`` now supports calling the ``set()`` method\n+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n+One can now call e.g. ``ax.spines[:].set(visible=False)``.\ndiff --git a/lib/matplotlib/spines.py b/lib/matplotlib/spines.py\nindex 8560f7b6e4e2..eacb3e7e9d5c 100644\n--- a/lib/matplotlib/spines.py\n+++ b/lib/matplotlib/spines.py\n@@ -479,7 +479,7 @@ def set_color(self, c):\n \n class SpinesProxy:\n \"\"\"\n- A proxy to broadcast ``set_*`` method calls to all contained `.Spines`.\n+ A proxy to broadcast ``set_*()`` and ``set()`` method calls to contained `.Spines`.\n \n The proxy cannot be used for any other operations on its members.\n \n@@ -493,7 +493,7 @@ def __init__(self, spine_dict):\n def __getattr__(self, name):\n broadcast_targets = [spine for spine in self._spine_dict.values()\n if hasattr(spine, name)]\n- if not name.startswith('set_') or not broadcast_targets:\n+ if (name != 'set' and not name.startswith('set_')) or not broadcast_targets:\n raise AttributeError(\n f\"'SpinesProxy' object has no attribute '{name}'\")\n \n@@ -531,8 +531,8 @@ class Spines(MutableMapping):\n \n spines[:].set_visible(False)\n \n- The latter two indexing methods will return a `SpinesProxy` that broadcasts\n- all ``set_*`` calls to its members, but cannot be used for any other\n+ The latter two indexing methods will return a `SpinesProxy` that broadcasts all\n+ ``set_*()`` and ``set()`` calls to its members, but cannot be used for any other\n operation.\n \"\"\"\n def __init__(self, **kwargs):\n", "test_patch": "diff --git a/lib/matplotlib/tests/test_spines.py b/lib/matplotlib/tests/test_spines.py\nindex 89bc0c872de5..9ce16fb39227 100644\n--- a/lib/matplotlib/tests/test_spines.py\n+++ b/lib/matplotlib/tests/test_spines.py\n@@ -12,6 +12,9 @@ class SpineMock:\n def __init__(self):\n self.val = None\n \n+ def set(self, **kwargs):\n+ vars(self).update(kwargs)\n+\n def set_val(self, val):\n self.val = val\n \n@@ -35,6 +38,9 @@ def set_val(self, val):\n spines[:].set_val('y')\n assert all(spine.val == 'y' for spine in spines.values())\n \n+ spines[:].set(foo='bar')\n+ assert all(spine.foo == 'bar' for spine in spines.values())\n+\n with pytest.raises(AttributeError, match='foo'):\n spines.foo\n with pytest.raises(KeyError, match='foo'):\n", "doc_changes": [{"path": "doc/users/next_whats_new/spinesproxyset.rst", "old_path": "/dev/null", "new_path": "b/doc/users/next_whats_new/spinesproxyset.rst", "metadata": "diff --git a/doc/users/next_whats_new/spinesproxyset.rst b/doc/users/next_whats_new/spinesproxyset.rst\nnew file mode 100644\nindex 000000000000..cfd8d2908ec7\n--- /dev/null\n+++ b/doc/users/next_whats_new/spinesproxyset.rst\n@@ -0,0 +1,3 @@\n+``SpinesProxy`` now supports calling the ``set()`` method\n+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n+One can now call e.g. ``ax.spines[:].set(visible=False)``.\n"}], "version": "3.7", "base_commit": "2466ccb77a92fe57e045ac0c0b56d61ce563abf9", "PASS2PASS": ["lib/matplotlib/tests/test_spines.py::test_spines_black_axes[svg]", "lib/matplotlib/tests/test_spines.py::test_spines_axes_positions[svg]", "lib/matplotlib/tests/test_spines.py::test_spine_nonlinear_data_positions[png]", "lib/matplotlib/tests/test_spines.py::test_spines_data_positions[png]", "lib/matplotlib/tests/test_spines.py::test_spines_capstyle[png]", "lib/matplotlib/tests/test_spines.py::test_spines_axes_positions[png]", "lib/matplotlib/tests/test_spines.py::test_spines_capstyle[svg]", "lib/matplotlib/tests/test_spines.py::test_spines_axes_positions[pdf]", "lib/matplotlib/tests/test_spines.py::test_spines_data_positions[svg]", "lib/matplotlib/tests/test_spines.py::test_spines_data_positions[pdf]", "lib/matplotlib/tests/test_spines.py::test_spines_black_axes[pdf]", "lib/matplotlib/tests/test_spines.py::test_spines_black_axes[png]", "lib/matplotlib/tests/test_spines.py::test_spines_capstyle[pdf]", "lib/matplotlib/tests/test_spines.py::test_label_without_ticks"], "FAIL2PASS": ["lib/matplotlib/tests/test_spines.py::test_spine_class"], "mask_doc_diff": [{"path": "doc/users/next_whats_new/spinesproxyset.rst", "old_path": "/dev/null", "new_path": "b/doc/users/next_whats_new/spinesproxyset.rst", "metadata": "diff --git a/doc/users/next_whats_new/spinesproxyset.rst b/doc/users/next_whats_new/spinesproxyset.rst\nnew file mode 100644\nindex 0000000000..cfd8d2908e\n--- /dev/null\n+++ b/doc/users/next_whats_new/spinesproxyset.rst\n@@ -0,0 +1,3 @@\n+``SpinesProxy`` now supports calling the ``set()`` method\n+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n+One can now call e.g. ``ax.spines[:].set(visible=False)``.\n"}], "augmentations": {"header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": []}, "problem_statement": "diff --git a/doc/users/next_whats_new/spinesproxyset.rst b/doc/users/next_whats_new/spinesproxyset.rst\nnew file mode 100644\nindex 0000000000..cfd8d2908e\n--- /dev/null\n+++ b/doc/users/next_whats_new/spinesproxyset.rst\n@@ -0,0 +1,3 @@\n+``SpinesProxy`` now supports calling the ``set()`` method\n+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n+One can now call e.g. ``ax.spines[:].set(visible=False)``.\n\n"} {"repo": "pydata/xarray", "instance_id": "pydata__xarray-3475", "html_url": "https://github.com/pydata/xarray/pull/3475", "feature_patch": "diff --git a/doc/data-structures.rst b/doc/data-structures.rst\nindex d5567f4863e..93cdc7e9765 100644\n--- a/doc/data-structures.rst\n+++ b/doc/data-structures.rst\n@@ -393,14 +393,14 @@ methods (like pandas) for transforming datasets into new objects.\n \n For removing variables, you can select and drop an explicit list of\n variables by indexing with a list of names or using the\n-:py:meth:`~xarray.Dataset.drop` methods to return a new ``Dataset``. These\n+:py:meth:`~xarray.Dataset.drop_vars` methods to return a new ``Dataset``. These\n operations keep around coordinates:\n \n .. ipython:: python\n \n ds[['temperature']]\n ds[['temperature', 'temperature_double']]\n- ds.drop('temperature')\n+ ds.drop_vars('temperature')\n \n To remove a dimension, you can use :py:meth:`~xarray.Dataset.drop_dims` method.\n Any variables using that dimension are dropped:\ndiff --git a/doc/indexing.rst b/doc/indexing.rst\nindex 9ee8f1dddf8..ace960689a8 100644\n--- a/doc/indexing.rst\n+++ b/doc/indexing.rst\n@@ -232,14 +232,14 @@ Using indexing to *assign* values to a subset of dataset (e.g.,\n Dropping labels and dimensions\n ------------------------------\n \n-The :py:meth:`~xarray.Dataset.drop` method returns a new object with the listed\n+The :py:meth:`~xarray.Dataset.drop_sel` method returns a new object with the listed\n index labels along a dimension dropped:\n \n .. ipython:: python\n \n- ds.drop(space=['IN', 'IL'])\n+ ds.drop_sel(space=['IN', 'IL'])\n \n-``drop`` is both a ``Dataset`` and ``DataArray`` method.\n+``drop_sel`` is both a ``Dataset`` and ``DataArray`` method.\n \n Use :py:meth:`~xarray.Dataset.drop_dims` to drop a full dimension from a Dataset.\n Any variables with these dimensions are also dropped:\ndiff --git a/doc/whats-new.rst b/doc/whats-new.rst\nindex dcaab011e67..0906058469d 100644\n--- a/doc/whats-new.rst\n+++ b/doc/whats-new.rst\n@@ -38,6 +38,12 @@ Breaking changes\n \n New Features\n ~~~~~~~~~~~~\n+- :py:meth:`Dataset.drop_sel` & :py:meth:`DataArray.drop_sel` have been added for dropping labels.\n+ :py:meth:`Dataset.drop_vars` & :py:meth:`DataArray.drop_vars` have been added for \n+ dropping variables (including coordinates). The existing ``drop`` methods remain as a backward compatible \n+ option for dropping either lables or variables, but using the more specific methods is encouraged.\n+ (:pull:`3475`)\n+ By `Maximilian Roos `_\n - :py:meth:`Dataset.transpose` and :py:meth:`DataArray.transpose` now support an ellipsis (`...`)\n to represent all 'other' dimensions. For example, to move one dimension to the front,\n use `.transpose('x', ...)`. (:pull:`3421`)\n@@ -3752,6 +3758,7 @@ Enhancements\n explicitly listed variables or index labels:\n \n .. ipython:: python\n+ :okwarning:\n \n # drop variables\n ds = xray.Dataset({'x': 0, 'y': 1})\ndiff --git a/xarray/core/concat.py b/xarray/core/concat.py\nindex c26153eb0d8..5b4fc078236 100644\n--- a/xarray/core/concat.py\n+++ b/xarray/core/concat.py\n@@ -388,7 +388,7 @@ def ensure_common_dims(vars):\n result = result.set_coords(coord_names)\n result.encoding = result_encoding\n \n- result = result.drop(unlabeled_dims, errors=\"ignore\")\n+ result = result.drop_vars(unlabeled_dims, errors=\"ignore\")\n \n if coord is not None:\n # add concat dimension last to ensure that its in the final Dataset\ndiff --git a/xarray/core/dataarray.py b/xarray/core/dataarray.py\nindex 35ee90fb5c8..d2d37871ee9 100644\n--- a/xarray/core/dataarray.py\n+++ b/xarray/core/dataarray.py\n@@ -16,7 +16,6 @@\n TypeVar,\n Union,\n cast,\n- overload,\n )\n \n import numpy as np\n@@ -53,7 +52,7 @@\n from .formatting import format_item\n from .indexes import Indexes, default_indexes\n from .options import OPTIONS\n-from .utils import Default, ReprObject, _default, _check_inplace, either_dict_or_kwargs\n+from .utils import Default, ReprObject, _check_inplace, _default, either_dict_or_kwargs\n from .variable import (\n IndexVariable,\n Variable,\n@@ -249,7 +248,7 @@ class DataArray(AbstractArray, DataWithCoords):\n Dictionary for holding arbitrary metadata.\n \"\"\"\n \n- _accessors: Optional[Dict[str, Any]]\n+ _accessors: Optional[Dict[str, Any]] # noqa\n _coords: Dict[Any, Variable]\n _indexes: Optional[Dict[Hashable, pd.Index]]\n _name: Optional[Hashable]\n@@ -1890,41 +1889,72 @@ def transpose(self, *dims: Hashable, transpose_coords: bool = None) -> \"DataArra\n def T(self) -> \"DataArray\":\n return self.transpose()\n \n- # Drop coords\n- @overload\n- def drop(\n- self, labels: Union[Hashable, Iterable[Hashable]], *, errors: str = \"raise\"\n+ def drop_vars(\n+ self, names: Union[Hashable, Iterable[Hashable]], *, errors: str = \"raise\"\n ) -> \"DataArray\":\n- ...\n+ \"\"\"Drop variables from this DataArray.\n+\n+ Parameters\n+ ----------\n+ names : hashable or iterable of hashables\n+ Name(s) of variables to drop.\n+ errors: {'raise', 'ignore'}, optional\n+ If 'raise' (default), raises a ValueError error if any of the variable\n+ passed are not in the dataset. If 'ignore', any given names that are in the\n+ DataArray are dropped and no error is raised.\n+\n+ Returns\n+ -------\n+ dropped : Dataset\n+\n+ \"\"\"\n+ ds = self._to_temp_dataset().drop_vars(names, errors=errors)\n+ return self._from_temp_dataset(ds)\n \n- # Drop index labels along dimension\n- @overload # noqa: F811\n def drop(\n- self, labels: Any, dim: Hashable, *, errors: str = \"raise\" # array-like\n+ self,\n+ labels: Mapping = None,\n+ dim: Hashable = None,\n+ *,\n+ errors: str = \"raise\",\n+ **labels_kwargs,\n ) -> \"DataArray\":\n- ...\n+ \"\"\"Backward compatible method based on `drop_vars` and `drop_sel`\n \n- def drop(self, labels, dim=None, *, errors=\"raise\"): # noqa: F811\n- \"\"\"Drop coordinates or index labels from this DataArray.\n+ Using either `drop_vars` or `drop_sel` is encouraged\n+ \"\"\"\n+ ds = self._to_temp_dataset().drop(labels, dim, errors=errors)\n+ return self._from_temp_dataset(ds)\n+\n+ def drop_sel(\n+ self,\n+ labels: Mapping[Hashable, Any] = None,\n+ *,\n+ errors: str = \"raise\",\n+ **labels_kwargs,\n+ ) -> \"DataArray\":\n+ \"\"\"Drop index labels from this DataArray.\n \n Parameters\n ----------\n- labels : hashable or sequence of hashables\n- Name(s) of coordinates or index labels to drop.\n- If dim is not None, labels can be any array-like.\n- dim : hashable, optional\n- Dimension along which to drop index labels. By default (if\n- ``dim is None``), drops coordinates rather than index labels.\n+ labels : Mapping[Hashable, Any]\n+ Index labels to drop\n errors: {'raise', 'ignore'}, optional\n If 'raise' (default), raises a ValueError error if\n- any of the coordinates or index labels passed are not\n- in the array. If 'ignore', any given labels that are in the\n- array are dropped and no error is raised.\n+ any of the index labels passed are not\n+ in the dataset. If 'ignore', any given labels that are in the\n+ dataset are dropped and no error is raised.\n+ **labels_kwargs : {dim: label, ...}, optional\n+ The keyword arguments form of ``dim`` and ``labels``\n+\n Returns\n -------\n dropped : DataArray\n \"\"\"\n- ds = self._to_temp_dataset().drop(labels, dim, errors=errors)\n+ if labels_kwargs or isinstance(labels, dict):\n+ labels = either_dict_or_kwargs(labels, labels_kwargs, \"drop\")\n+\n+ ds = self._to_temp_dataset().drop_sel(labels, errors=errors)\n return self._from_temp_dataset(ds)\n \n def dropna(\ndiff --git a/xarray/core/dataset.py b/xarray/core/dataset.py\nindex 978242e5f6b..2cadc90334c 100644\n--- a/xarray/core/dataset.py\n+++ b/xarray/core/dataset.py\n@@ -25,7 +25,6 @@\n TypeVar,\n Union,\n cast,\n- overload,\n )\n \n import numpy as np\n@@ -80,6 +79,7 @@\n hashable,\n is_dict_like,\n is_list_like,\n+ is_scalar,\n maybe_wrap_array,\n )\n from .variable import IndexVariable, Variable, as_variable, broadcast_variables\n@@ -3519,39 +3519,98 @@ def _assert_all_in_dataset(\n \"cannot be found in this dataset\"\n )\n \n- # Drop variables\n- @overload # noqa: F811\n- def drop(\n- self, labels: Union[Hashable, Iterable[Hashable]], *, errors: str = \"raise\"\n+ def drop_vars(\n+ self, names: Union[Hashable, Iterable[Hashable]], *, errors: str = \"raise\"\n ) -> \"Dataset\":\n- ...\n+ \"\"\"Drop variables from this dataset.\n \n- # Drop index labels along dimension\n- @overload # noqa: F811\n- def drop(\n- self, labels: Any, dim: Hashable, *, errors: str = \"raise\" # array-like\n- ) -> \"Dataset\":\n- ...\n+ Parameters\n+ ----------\n+ names : hashable or iterable of hashables\n+ Name(s) of variables to drop.\n+ errors: {'raise', 'ignore'}, optional\n+ If 'raise' (default), raises a ValueError error if any of the variable\n+ passed are not in the dataset. If 'ignore', any given names that are in the\n+ dataset are dropped and no error is raised.\n \n- def drop( # noqa: F811\n- self, labels=None, dim=None, *, errors=\"raise\", **labels_kwargs\n- ):\n- \"\"\"Drop variables or index labels from this dataset.\n+ Returns\n+ -------\n+ dropped : Dataset\n+\n+ \"\"\"\n+ # the Iterable check is required for mypy\n+ if is_scalar(names) or not isinstance(names, Iterable):\n+ names = {names}\n+ else:\n+ names = set(names)\n+ if errors == \"raise\":\n+ self._assert_all_in_dataset(names)\n+\n+ variables = {k: v for k, v in self._variables.items() if k not in names}\n+ coord_names = {k for k in self._coord_names if k in variables}\n+ indexes = {k: v for k, v in self.indexes.items() if k not in names}\n+ return self._replace_with_new_dims(\n+ variables, coord_names=coord_names, indexes=indexes\n+ )\n+\n+ def drop(self, labels=None, dim=None, *, errors=\"raise\", **labels_kwargs):\n+ \"\"\"Backward compatible method based on `drop_vars` and `drop_sel`\n+\n+ Using either `drop_vars` or `drop_sel` is encouraged\n+ \"\"\"\n+ if errors not in [\"raise\", \"ignore\"]:\n+ raise ValueError('errors must be either \"raise\" or \"ignore\"')\n+\n+ if is_dict_like(labels) and not isinstance(labels, dict):\n+ warnings.warn(\n+ \"dropping coordinates using `drop` is be deprecated; use drop_vars.\",\n+ FutureWarning,\n+ stacklevel=2,\n+ )\n+ return self.drop_vars(labels, errors=errors)\n+\n+ if labels_kwargs or isinstance(labels, dict):\n+ if dim is not None:\n+ raise ValueError(\"cannot specify dim and dict-like arguments.\")\n+ labels = either_dict_or_kwargs(labels, labels_kwargs, \"drop\")\n+\n+ if dim is None and (is_list_like(labels) or is_scalar(labels)):\n+ warnings.warn(\n+ \"dropping variables using `drop` will be deprecated; using drop_vars is encouraged.\",\n+ PendingDeprecationWarning,\n+ stacklevel=2,\n+ )\n+ return self.drop_vars(labels, errors=errors)\n+ if dim is not None:\n+ warnings.warn(\n+ \"dropping labels using list-like labels is deprecated; using \"\n+ \"dict-like arguments with `drop_sel`, e.g. `ds.drop_sel(dim=[labels]).\",\n+ DeprecationWarning,\n+ stacklevel=2,\n+ )\n+ return self.drop_sel({dim: labels}, errors=errors, **labels_kwargs)\n+\n+ warnings.warn(\n+ \"dropping labels using `drop` will be deprecated; using drop_sel is encouraged.\",\n+ PendingDeprecationWarning,\n+ stacklevel=2,\n+ )\n+ return self.drop_sel(labels, errors=errors)\n+\n+ def drop_sel(self, labels=None, *, errors=\"raise\", **labels_kwargs):\n+ \"\"\"Drop index labels from this dataset.\n \n Parameters\n ----------\n- labels : hashable or iterable of hashables\n- Name(s) of variables or index labels to drop.\n- dim : None or hashable, optional\n- Dimension along which to drop index labels. By default (if\n- ``dim is None``), drops variables rather than index labels.\n+ labels : Mapping[Hashable, Any]\n+ Index labels to drop\n errors: {'raise', 'ignore'}, optional\n If 'raise' (default), raises a ValueError error if\n- any of the variable or index labels passed are not\n+ any of the index labels passed are not\n in the dataset. If 'ignore', any given labels that are in the\n dataset are dropped and no error is raised.\n **labels_kwargs : {dim: label, ...}, optional\n- The keyword arguments form of ``dim`` and ``labels``.\n+ The keyword arguments form of ``dim`` and ``labels`\n \n Returns\n -------\n@@ -3562,7 +3621,7 @@ def drop( # noqa: F811\n >>> data = np.random.randn(2, 3)\n >>> labels = ['a', 'b', 'c']\n >>> ds = xr.Dataset({'A': (['x', 'y'], data), 'y': labels})\n- >>> ds.drop(y=['a', 'c'])\n+ >>> ds.drop_sel(y=['a', 'c'])\n \n Dimensions: (x: 2, y: 1)\n Coordinates:\n@@ -3570,7 +3629,7 @@ def drop( # noqa: F811\n Dimensions without coordinates: x\n Data variables:\n A (x, y) float64 -0.3454 0.1734\n- >>> ds.drop(y='b')\n+ >>> ds.drop_sel(y='b')\n \n Dimensions: (x: 2, y: 2)\n Coordinates:\n@@ -3582,61 +3641,22 @@ def drop( # noqa: F811\n if errors not in [\"raise\", \"ignore\"]:\n raise ValueError('errors must be either \"raise\" or \"ignore\"')\n \n- if is_dict_like(labels) and not isinstance(labels, dict):\n- warnings.warn(\n- \"dropping coordinates using key values of dict-like labels is \"\n- \"deprecated; use drop_vars or a list of coordinates.\",\n- FutureWarning,\n- stacklevel=2,\n- )\n- if dim is not None and is_list_like(labels):\n- warnings.warn(\n- \"dropping dimensions using list-like labels is deprecated; use \"\n- \"dict-like arguments.\",\n- DeprecationWarning,\n- stacklevel=2,\n- )\n+ labels = either_dict_or_kwargs(labels, labels_kwargs, \"drop\")\n \n- if labels_kwargs or isinstance(labels, dict):\n- labels_kwargs = either_dict_or_kwargs(labels, labels_kwargs, \"drop\")\n- if dim is not None:\n- raise ValueError(\"cannot specify dim and dict-like arguments.\")\n- ds = self\n- for dim, labels in labels_kwargs.items():\n- ds = ds._drop_labels(labels, dim, errors=errors)\n- return ds\n- elif dim is None:\n- if isinstance(labels, str) or not isinstance(labels, Iterable):\n- labels = {labels}\n- else:\n- labels = set(labels)\n- return self._drop_vars(labels, errors=errors)\n- else:\n- return self._drop_labels(labels, dim, errors=errors)\n-\n- def _drop_labels(self, labels=None, dim=None, errors=\"raise\"):\n- # Don't cast to set, as it would harm performance when labels\n- # is a large numpy array\n- if utils.is_scalar(labels):\n- labels = [labels]\n- labels = np.asarray(labels)\n- try:\n- index = self.indexes[dim]\n- except KeyError:\n- raise ValueError(\"dimension %r does not have coordinate labels\" % dim)\n- new_index = index.drop(labels, errors=errors)\n- return self.loc[{dim: new_index}]\n-\n- def _drop_vars(self, names: set, errors: str = \"raise\") -> \"Dataset\":\n- if errors == \"raise\":\n- self._assert_all_in_dataset(names)\n-\n- variables = {k: v for k, v in self._variables.items() if k not in names}\n- coord_names = {k for k in self._coord_names if k in variables}\n- indexes = {k: v for k, v in self.indexes.items() if k not in names}\n- return self._replace_with_new_dims(\n- variables, coord_names=coord_names, indexes=indexes\n- )\n+ ds = self\n+ for dim, labels_for_dim in labels.items():\n+ # Don't cast to set, as it would harm performance when labels\n+ # is a large numpy array\n+ if utils.is_scalar(labels_for_dim):\n+ labels_for_dim = [labels_for_dim]\n+ labels_for_dim = np.asarray(labels_for_dim)\n+ try:\n+ index = self.indexes[dim]\n+ except KeyError:\n+ raise ValueError(\"dimension %r does not have coordinate labels\" % dim)\n+ new_index = index.drop(labels_for_dim, errors=errors)\n+ ds = ds.loc[{dim: new_index}]\n+ return ds\n \n def drop_dims(\n self, drop_dims: Union[Hashable, Iterable[Hashable]], *, errors: str = \"raise\"\n@@ -3679,7 +3699,7 @@ def drop_dims(\n )\n \n drop_vars = {k for k, v in self._variables.items() if set(v.dims) & drop_dims}\n- return self._drop_vars(drop_vars)\n+ return self.drop_vars(drop_vars)\n \n def transpose(self, *dims: Hashable) -> \"Dataset\":\n \"\"\"Return a new Dataset object with all array dimensions transposed.\ndiff --git a/xarray/core/groupby.py b/xarray/core/groupby.py\nindex 209ac14184b..c8906e34737 100644\n--- a/xarray/core/groupby.py\n+++ b/xarray/core/groupby.py\n@@ -775,7 +775,7 @@ def quantile(self, q, dim=None, interpolation=\"linear\", keep_attrs=None):\n )\n \n if np.asarray(q, dtype=np.float64).ndim == 0:\n- out = out.drop(\"quantile\")\n+ out = out.drop_vars(\"quantile\")\n return out\n \n def reduce(\ndiff --git a/xarray/core/merge.py b/xarray/core/merge.py\nindex daf0c3b059f..10c7804d718 100644\n--- a/xarray/core/merge.py\n+++ b/xarray/core/merge.py\n@@ -859,6 +859,6 @@ def dataset_update_method(\n if c not in value.dims and c in dataset.coords\n ]\n if coord_names:\n- other[key] = value.drop(coord_names)\n+ other[key] = value.drop_vars(coord_names)\n \n return merge_core([dataset, other], priority_arg=1, indexes=dataset.indexes)\ndiff --git a/xarray/core/resample.py b/xarray/core/resample.py\nindex 998964273be..2cb1bd55e19 100644\n--- a/xarray/core/resample.py\n+++ b/xarray/core/resample.py\n@@ -47,7 +47,7 @@ def _upsample(self, method, *args, **kwargs):\n if k == self._dim:\n continue\n if self._dim in v.dims:\n- self._obj = self._obj.drop(k)\n+ self._obj = self._obj.drop_vars(k)\n \n if method == \"asfreq\":\n return self.mean(self._dim)\n@@ -146,7 +146,7 @@ def _interpolate(self, kind=\"linear\"):\n dummy = self._obj.copy()\n for k, v in self._obj.coords.items():\n if k != self._dim and self._dim in v.dims:\n- dummy = dummy.drop(k)\n+ dummy = dummy.drop_vars(k)\n return dummy.interp(\n assume_sorted=True,\n method=kind,\n@@ -218,7 +218,7 @@ def apply(self, func, shortcut=False, args=(), **kwargs):\n # dimension, then we need to do so before we can rename the proxy\n # dimension we used.\n if self._dim in combined.coords:\n- combined = combined.drop(self._dim)\n+ combined = combined.drop_vars(self._dim)\n \n if self._resample_dim in combined.dims:\n combined = combined.rename({self._resample_dim: self._dim})\n", "test_patch": "diff --git a/xarray/tests/test_backends.py b/xarray/tests/test_backends.py\nindex 9b000b82b03..de3a7eadab0 100644\n--- a/xarray/tests/test_backends.py\n+++ b/xarray/tests/test_backends.py\n@@ -800,7 +800,7 @@ def equals_latlon(obj):\n assert \"coordinates\" not in ds[\"lat\"].attrs\n assert \"coordinates\" not in ds[\"lon\"].attrs\n \n- modified = original.drop([\"temp\", \"precip\"])\n+ modified = original.drop_vars([\"temp\", \"precip\"])\n with self.roundtrip(modified) as actual:\n assert_identical(actual, modified)\n with create_tmp_file() as tmp_file:\n@@ -2177,7 +2177,7 @@ def test_cross_engine_read_write_netcdf4(self):\n # Drop dim3, because its labels include strings. These appear to be\n # not properly read with python-netCDF4, which converts them into\n # unicode instead of leaving them as bytes.\n- data = create_test_data().drop(\"dim3\")\n+ data = create_test_data().drop_vars(\"dim3\")\n data.attrs[\"foo\"] = \"bar\"\n valid_engines = [\"netcdf4\", \"h5netcdf\"]\n for write_engine in valid_engines:\n@@ -2344,7 +2344,7 @@ def test_open_twice(self):\n \n def test_open_fileobj(self):\n # open in-memory datasets instead of local file paths\n- expected = create_test_data().drop(\"dim3\")\n+ expected = create_test_data().drop_vars(\"dim3\")\n expected.attrs[\"foo\"] = \"bar\"\n with create_tmp_file() as tmp_file:\n expected.to_netcdf(tmp_file, engine=\"h5netcdf\")\n@@ -4190,7 +4190,7 @@ def test_open_dataarray_options(self):\n with create_tmp_file() as tmp:\n data.to_netcdf(tmp)\n \n- expected = data.drop(\"y\")\n+ expected = data.drop_vars(\"y\")\n with open_dataarray(tmp, drop_variables=[\"y\"]) as loaded:\n assert_identical(expected, loaded)\n \ndiff --git a/xarray/tests/test_dask.py b/xarray/tests/test_dask.py\nindex 34115b29b23..fa8ae9991d7 100644\n--- a/xarray/tests/test_dask.py\n+++ b/xarray/tests/test_dask.py\n@@ -1129,11 +1129,11 @@ def test_map_blocks_to_array(map_ds):\n [\n lambda x: x,\n lambda x: x.to_dataset(),\n- lambda x: x.drop(\"x\"),\n+ lambda x: x.drop_vars(\"x\"),\n lambda x: x.expand_dims(k=[1, 2, 3]),\n lambda x: x.assign_coords(new_coord=(\"y\", x.y * 2)),\n lambda x: x.astype(np.int32),\n- # TODO: [lambda x: x.isel(x=1).drop(\"x\"), map_da],\n+ # TODO: [lambda x: x.isel(x=1).drop_vars(\"x\"), map_da],\n ],\n )\n def test_map_blocks_da_transformations(func, map_da):\n@@ -1147,9 +1147,9 @@ def test_map_blocks_da_transformations(func, map_da):\n \"func\",\n [\n lambda x: x,\n- lambda x: x.drop(\"cxy\"),\n- lambda x: x.drop(\"a\"),\n- lambda x: x.drop(\"x\"),\n+ lambda x: x.drop_vars(\"cxy\"),\n+ lambda x: x.drop_vars(\"a\"),\n+ lambda x: x.drop_vars(\"x\"),\n lambda x: x.expand_dims(k=[1, 2, 3]),\n lambda x: x.rename({\"a\": \"new1\", \"b\": \"new2\"}),\n # TODO: [lambda x: x.isel(x=1)],\ndiff --git a/xarray/tests/test_dataarray.py b/xarray/tests/test_dataarray.py\nindex 2c823b0c20a..acfe684d220 100644\n--- a/xarray/tests/test_dataarray.py\n+++ b/xarray/tests/test_dataarray.py\n@@ -906,7 +906,7 @@ def test_sel_dataarray(self):\n assert_array_equal(actual, da.isel(x=[0, 1, 2]))\n assert \"new_dim\" in actual.dims\n assert \"new_dim\" in actual.coords\n- assert_equal(actual[\"new_dim\"].drop(\"x\"), ind[\"new_dim\"])\n+ assert_equal(actual[\"new_dim\"].drop_vars(\"x\"), ind[\"new_dim\"])\n \n def test_sel_invalid_slice(self):\n array = DataArray(np.arange(10), [(\"x\", np.arange(10))])\n@@ -1660,7 +1660,7 @@ def test_expand_dims_with_greater_dim_size(self):\n coords=expected_coords,\n dims=list(expected_coords.keys()),\n attrs={\"key\": \"entry\"},\n- ).drop([\"y\", \"dim_0\"])\n+ ).drop_vars([\"y\", \"dim_0\"])\n assert_identical(expected, actual)\n \n # Test with kwargs instead of passing dict to dim arg.\n@@ -1677,7 +1677,7 @@ def test_expand_dims_with_greater_dim_size(self):\n },\n dims=[\"dim_1\", \"x\", \"dim_0\"],\n attrs={\"key\": \"entry\"},\n- ).drop(\"dim_0\")\n+ ).drop_vars(\"dim_0\")\n assert_identical(other_way_expected, other_way)\n \n def test_set_index(self):\n@@ -1993,7 +1993,7 @@ def test_stack_unstack(self):\n )\n pd.util.testing.assert_index_equal(a, b)\n \n- actual = orig.stack(z=[\"x\", \"y\"]).unstack(\"z\").drop([\"x\", \"y\"])\n+ actual = orig.stack(z=[\"x\", \"y\"]).unstack(\"z\").drop_vars([\"x\", \"y\"])\n assert_identical(orig, actual)\n \n dims = [\"a\", \"b\", \"c\", \"d\", \"e\"]\n@@ -2001,11 +2001,11 @@ def test_stack_unstack(self):\n stacked = orig.stack(ab=[\"a\", \"b\"], cd=[\"c\", \"d\"])\n \n unstacked = stacked.unstack([\"ab\", \"cd\"])\n- roundtripped = unstacked.drop([\"a\", \"b\", \"c\", \"d\"]).transpose(*dims)\n+ roundtripped = unstacked.drop_vars([\"a\", \"b\", \"c\", \"d\"]).transpose(*dims)\n assert_identical(orig, roundtripped)\n \n unstacked = stacked.unstack()\n- roundtripped = unstacked.drop([\"a\", \"b\", \"c\", \"d\"]).transpose(*dims)\n+ roundtripped = unstacked.drop_vars([\"a\", \"b\", \"c\", \"d\"]).transpose(*dims)\n assert_identical(orig, roundtripped)\n \n def test_stack_unstack_decreasing_coordinate(self):\n@@ -2109,40 +2109,43 @@ def test_drop_coordinates(self):\n expected = DataArray(np.random.randn(2, 3), dims=[\"x\", \"y\"])\n arr = expected.copy()\n arr.coords[\"z\"] = 2\n- actual = arr.drop(\"z\")\n+ actual = arr.drop_vars(\"z\")\n assert_identical(expected, actual)\n \n with pytest.raises(ValueError):\n- arr.drop(\"not found\")\n+ arr.drop_vars(\"not found\")\n \n- actual = expected.drop(\"not found\", errors=\"ignore\")\n+ actual = expected.drop_vars(\"not found\", errors=\"ignore\")\n assert_identical(actual, expected)\n \n with raises_regex(ValueError, \"cannot be found\"):\n- arr.drop(\"w\")\n+ arr.drop_vars(\"w\")\n \n- actual = expected.drop(\"w\", errors=\"ignore\")\n+ actual = expected.drop_vars(\"w\", errors=\"ignore\")\n assert_identical(actual, expected)\n \n renamed = arr.rename(\"foo\")\n with raises_regex(ValueError, \"cannot be found\"):\n- renamed.drop(\"foo\")\n+ renamed.drop_vars(\"foo\")\n \n- actual = renamed.drop(\"foo\", errors=\"ignore\")\n+ actual = renamed.drop_vars(\"foo\", errors=\"ignore\")\n assert_identical(actual, renamed)\n \n def test_drop_index_labels(self):\n arr = DataArray(np.random.randn(2, 3), coords={\"y\": [0, 1, 2]}, dims=[\"x\", \"y\"])\n- actual = arr.drop([0, 1], dim=\"y\")\n+ actual = arr.drop_sel(y=[0, 1])\n expected = arr[:, 2:]\n assert_identical(actual, expected)\n \n with raises_regex((KeyError, ValueError), \"not .* in axis\"):\n- actual = arr.drop([0, 1, 3], dim=\"y\")\n+ actual = arr.drop_sel(y=[0, 1, 3])\n \n- actual = arr.drop([0, 1, 3], dim=\"y\", errors=\"ignore\")\n+ actual = arr.drop_sel(y=[0, 1, 3], errors=\"ignore\")\n assert_identical(actual, expected)\n \n+ with pytest.warns(DeprecationWarning):\n+ arr.drop([0, 1, 3], dim=\"y\", errors=\"ignore\")\n+\n def test_dropna(self):\n x = np.random.randn(4, 4)\n x[::2, 0] = np.nan\n@@ -3360,7 +3363,7 @@ def test_to_pandas(self):\n da = DataArray(np.random.randn(*shape), dims=dims)\n with warnings.catch_warnings():\n warnings.filterwarnings(\"ignore\", r\"\\W*Panel is deprecated\")\n- roundtripped = DataArray(da.to_pandas()).drop(dims)\n+ roundtripped = DataArray(da.to_pandas()).drop_vars(dims)\n assert_identical(da, roundtripped)\n \n with raises_regex(ValueError, \"cannot convert\"):\n@@ -3411,11 +3414,13 @@ def test_to_and_from_series(self):\n assert_array_equal(expected.index.values, actual.index.values)\n assert \"foo\" == actual.name\n # test roundtrip\n- assert_identical(self.dv, DataArray.from_series(actual).drop([\"x\", \"y\"]))\n+ assert_identical(self.dv, DataArray.from_series(actual).drop_vars([\"x\", \"y\"]))\n # test name is None\n actual.name = None\n expected_da = self.dv.rename(None)\n- assert_identical(expected_da, DataArray.from_series(actual).drop([\"x\", \"y\"]))\n+ assert_identical(\n+ expected_da, DataArray.from_series(actual).drop_vars([\"x\", \"y\"])\n+ )\n \n @requires_sparse\n def test_from_series_sparse(self):\n@@ -3478,7 +3483,7 @@ def test_to_and_from_dict(self):\n \n # and the most bare bones representation still roundtrips\n d = {\"name\": \"foo\", \"dims\": (\"x\", \"y\"), \"data\": array.values}\n- assert_identical(array.drop(\"x\"), DataArray.from_dict(d))\n+ assert_identical(array.drop_vars(\"x\"), DataArray.from_dict(d))\n \n # missing a dims in the coords\n d = {\ndiff --git a/xarray/tests/test_dataset.py b/xarray/tests/test_dataset.py\nindex b9fa20fab26..50e78c9f685 100644\n--- a/xarray/tests/test_dataset.py\n+++ b/xarray/tests/test_dataset.py\n@@ -322,7 +322,7 @@ def __repr__(self):\n \n def test_info(self):\n ds = create_test_data(seed=123)\n- ds = ds.drop(\"dim3\") # string type prints differently in PY2 vs PY3\n+ ds = ds.drop_vars(\"dim3\") # string type prints differently in PY2 vs PY3\n ds.attrs[\"unicode_attr\"] = \"ba\u00ae\"\n ds.attrs[\"string_attr\"] = \"bar\"\n \n@@ -509,7 +509,9 @@ def test_constructor_compat(self):\n {\"c\": ((\"x\", \"y\"), np.zeros((2, 3))), \"x\": [0, 1]},\n )\n \n- actual = Dataset({\"a\": original[\"a\"][:, 0], \"b\": original[\"a\"][0].drop(\"x\")})\n+ actual = Dataset(\n+ {\"a\": original[\"a\"][:, 0], \"b\": original[\"a\"][0].drop_vars(\"x\")}\n+ )\n assert_identical(expected, actual)\n \n data = {\"x\": DataArray(0, coords={\"y\": 3}), \"y\": (\"z\", [1, 1, 1])}\n@@ -775,9 +777,9 @@ def test_coords_set(self):\n one_coord.reset_coords(\"x\")\n \n actual = all_coords.reset_coords(\"zzz\", drop=True)\n- expected = all_coords.drop(\"zzz\")\n+ expected = all_coords.drop_vars(\"zzz\")\n assert_identical(expected, actual)\n- expected = two_coords.drop(\"zzz\")\n+ expected = two_coords.drop_vars(\"zzz\")\n assert_identical(expected, actual)\n \n def test_coords_to_dataset(self):\n@@ -954,7 +956,7 @@ def test_dask_is_lazy(self):\n ds.fillna(0)\n ds.rename({\"dim1\": \"foobar\"})\n ds.set_coords(\"var1\")\n- ds.drop(\"var1\")\n+ ds.drop_vars(\"var1\")\n \n def test_isel(self):\n data = create_test_data()\n@@ -1097,7 +1099,7 @@ def test_isel_fancy(self):\n actual = data.isel(dim1=stations[\"dim1s\"], dim2=stations[\"dim2s\"])\n assert \"station\" in actual.coords\n assert \"station\" in actual.dims\n- assert_identical(actual[\"station\"].drop([\"dim2\"]), stations[\"station\"])\n+ assert_identical(actual[\"station\"].drop_vars([\"dim2\"]), stations[\"station\"])\n \n with raises_regex(ValueError, \"conflicting values for \"):\n data.isel(\n@@ -1123,7 +1125,7 @@ def test_isel_fancy(self):\n assert \"dim2\" in actual.coords\n assert \"a\" in actual[\"dim2\"].dims\n \n- assert_identical(actual[\"a\"].drop([\"dim2\"]), stations[\"a\"])\n+ assert_identical(actual[\"a\"].drop_vars([\"dim2\"]), stations[\"a\"])\n assert_identical(actual[\"b\"], stations[\"b\"])\n expected_var1 = data[\"var1\"].variable[\n stations[\"dim1s\"].variable, stations[\"dim2s\"].variable\n@@ -1132,7 +1134,7 @@ def test_isel_fancy(self):\n stations[\"dim1s\"].variable, stations[\"dim2s\"].variable\n ]\n expected_var3 = data[\"var3\"].variable[slice(None), stations[\"dim1s\"].variable]\n- assert_equal(actual[\"a\"].drop(\"dim2\"), stations[\"a\"])\n+ assert_equal(actual[\"a\"].drop_vars(\"dim2\"), stations[\"a\"])\n assert_array_equal(actual[\"var1\"], expected_var1)\n assert_array_equal(actual[\"var2\"], expected_var2)\n assert_array_equal(actual[\"var3\"], expected_var3)\n@@ -1200,7 +1202,7 @@ def test_isel_dataarray(self):\n indexing_da = indexing_da < 3\n actual = data.isel(dim2=indexing_da)\n assert_identical(\n- actual[\"dim2\"].drop(\"non_dim\").drop(\"non_dim2\"), data[\"dim2\"][:2]\n+ actual[\"dim2\"].drop_vars(\"non_dim\").drop_vars(\"non_dim2\"), data[\"dim2\"][:2]\n )\n assert_identical(actual[\"non_dim\"], indexing_da[\"non_dim\"][:2])\n assert_identical(actual[\"non_dim2\"], indexing_da[\"non_dim2\"])\n@@ -1286,8 +1288,10 @@ def test_sel_dataarray(self):\n expected = data.isel(dim2=[0, 1, 2]).rename({\"dim2\": \"new_dim\"})\n assert \"new_dim\" in actual.dims\n assert \"new_dim\" in actual.coords\n- assert_equal(actual.drop(\"new_dim\").drop(\"dim2\"), expected.drop(\"new_dim\"))\n- assert_equal(actual[\"new_dim\"].drop(\"dim2\"), ind[\"new_dim\"])\n+ assert_equal(\n+ actual.drop_vars(\"new_dim\").drop_vars(\"dim2\"), expected.drop_vars(\"new_dim\")\n+ )\n+ assert_equal(actual[\"new_dim\"].drop_vars(\"dim2\"), ind[\"new_dim\"])\n \n # with conflicted coordinate (silently ignored)\n ind = DataArray(\n@@ -1304,10 +1308,12 @@ def test_sel_dataarray(self):\n coords={\"new_dim\": [\"a\", \"b\", \"c\"], \"dim2\": 3},\n )\n actual = data.sel(dim2=ind)\n- assert_equal(actual[\"new_dim\"].drop(\"dim2\"), ind[\"new_dim\"].drop(\"dim2\"))\n+ assert_equal(\n+ actual[\"new_dim\"].drop_vars(\"dim2\"), ind[\"new_dim\"].drop_vars(\"dim2\")\n+ )\n expected = data.isel(dim2=[0, 1, 2])\n expected[\"dim2\"] = ((\"new_dim\"), expected[\"dim2\"].values)\n- assert_equal(actual[\"dim2\"].drop(\"new_dim\"), expected[\"dim2\"])\n+ assert_equal(actual[\"dim2\"].drop_vars(\"new_dim\"), expected[\"dim2\"])\n assert actual[\"var1\"].dims == (\"dim1\", \"new_dim\")\n \n # with non-dimensional coordinate\n@@ -1322,7 +1328,7 @@ def test_sel_dataarray(self):\n )\n actual = data.sel(dim2=ind)\n expected = data.isel(dim2=[0, 1, 2])\n- assert_equal(actual.drop(\"new_dim\"), expected)\n+ assert_equal(actual.drop_vars(\"new_dim\"), expected)\n assert np.allclose(actual[\"new_dim\"].values, ind[\"new_dim\"].values)\n \n def test_sel_dataarray_mindex(self):\n@@ -1554,8 +1560,8 @@ def test_sel_fancy(self):\n expected_ary = data[\"foo\"][[0, 1, 2], [0, 2, 1]]\n actual = data.sel(x=idx_x, y=idx_y)\n assert_array_equal(expected_ary, actual[\"foo\"])\n- assert_identical(actual[\"a\"].drop(\"x\"), idx_x[\"a\"])\n- assert_identical(actual[\"b\"].drop(\"y\"), idx_y[\"b\"])\n+ assert_identical(actual[\"a\"].drop_vars(\"x\"), idx_x[\"a\"])\n+ assert_identical(actual[\"b\"].drop_vars(\"y\"), idx_y[\"b\"])\n \n with pytest.raises(KeyError):\n data.sel(x=[2.5], y=[2.0], method=\"pad\", tolerance=1e-3)\n@@ -2094,36 +2100,50 @@ def test_variable_indexing(self):\n def test_drop_variables(self):\n data = create_test_data()\n \n- assert_identical(data, data.drop([]))\n+ assert_identical(data, data.drop_vars([]))\n \n expected = Dataset({k: data[k] for k in data.variables if k != \"time\"})\n- actual = data.drop(\"time\")\n+ actual = data.drop_vars(\"time\")\n assert_identical(expected, actual)\n- actual = data.drop([\"time\"])\n+ actual = data.drop_vars([\"time\"])\n assert_identical(expected, actual)\n \n with raises_regex(ValueError, \"cannot be found\"):\n- data.drop(\"not_found_here\")\n+ data.drop_vars(\"not_found_here\")\n+\n+ actual = data.drop_vars(\"not_found_here\", errors=\"ignore\")\n+ assert_identical(data, actual)\n+\n+ actual = data.drop_vars([\"not_found_here\"], errors=\"ignore\")\n+ assert_identical(data, actual)\n+\n+ actual = data.drop_vars([\"time\", \"not_found_here\"], errors=\"ignore\")\n+ assert_identical(expected, actual)\n+\n+ # deprecated approach with `drop` works (straight copy paste from above)\n \n- actual = data.drop(\"not_found_here\", errors=\"ignore\")\n+ with pytest.warns(PendingDeprecationWarning):\n+ actual = data.drop(\"not_found_here\", errors=\"ignore\")\n assert_identical(data, actual)\n \n- actual = data.drop([\"not_found_here\"], errors=\"ignore\")\n+ with pytest.warns(PendingDeprecationWarning):\n+ actual = data.drop([\"not_found_here\"], errors=\"ignore\")\n assert_identical(data, actual)\n \n- actual = data.drop([\"time\", \"not_found_here\"], errors=\"ignore\")\n+ with pytest.warns(PendingDeprecationWarning):\n+ actual = data.drop([\"time\", \"not_found_here\"], errors=\"ignore\")\n assert_identical(expected, actual)\n \n def test_drop_index_labels(self):\n data = Dataset({\"A\": ([\"x\", \"y\"], np.random.randn(2, 3)), \"x\": [\"a\", \"b\"]})\n \n with pytest.warns(DeprecationWarning):\n- actual = data.drop([\"a\"], \"x\")\n+ actual = data.drop([\"a\"], dim=\"x\")\n expected = data.isel(x=[1])\n assert_identical(expected, actual)\n \n with pytest.warns(DeprecationWarning):\n- actual = data.drop([\"a\", \"b\"], \"x\")\n+ actual = data.drop([\"a\", \"b\"], dim=\"x\")\n expected = data.isel(x=slice(0, 0))\n assert_identical(expected, actual)\n \n@@ -2147,30 +2167,30 @@ def test_drop_index_labels(self):\n \n # DataArrays as labels are a nasty corner case as they are not\n # Iterable[Hashable] - DataArray.__iter__ yields scalar DataArrays.\n- actual = data.drop(DataArray([\"a\", \"b\", \"c\"]), \"x\", errors=\"ignore\")\n+ actual = data.drop_sel(x=DataArray([\"a\", \"b\", \"c\"]), errors=\"ignore\")\n expected = data.isel(x=slice(0, 0))\n assert_identical(expected, actual)\n+ with pytest.warns(DeprecationWarning):\n+ data.drop(DataArray([\"a\", \"b\", \"c\"]), dim=\"x\", errors=\"ignore\")\n+ assert_identical(expected, actual)\n \n with raises_regex(ValueError, \"does not have coordinate labels\"):\n- data.drop(1, \"y\")\n+ data.drop_sel(y=1)\n \n def test_drop_labels_by_keyword(self):\n- # Tests for #2910: Support for a additional `drop()` API.\n data = Dataset(\n {\"A\": ([\"x\", \"y\"], np.random.randn(2, 6)), \"x\": [\"a\", \"b\"], \"y\": range(6)}\n )\n # Basic functionality.\n assert len(data.coords[\"x\"]) == 2\n \n- # In the future, this will break.\n with pytest.warns(DeprecationWarning):\n ds1 = data.drop([\"a\"], dim=\"x\")\n- ds2 = data.drop(x=\"a\")\n- ds3 = data.drop(x=[\"a\"])\n- ds4 = data.drop(x=[\"a\", \"b\"])\n- ds5 = data.drop(x=[\"a\", \"b\"], y=range(0, 6, 2))\n+ ds2 = data.drop_sel(x=\"a\")\n+ ds3 = data.drop_sel(x=[\"a\"])\n+ ds4 = data.drop_sel(x=[\"a\", \"b\"])\n+ ds5 = data.drop_sel(x=[\"a\", \"b\"], y=range(0, 6, 2))\n \n- # In the future, this will result in different behavior.\n arr = DataArray(range(3), dims=[\"c\"])\n with pytest.warns(FutureWarning):\n data.drop(arr.coords)\n@@ -2187,10 +2207,11 @@ def test_drop_labels_by_keyword(self):\n # Error handling if user tries both approaches.\n with pytest.raises(ValueError):\n data.drop(labels=[\"a\"], x=\"a\")\n- with pytest.raises(ValueError):\n- data.drop(dim=\"x\", x=\"a\")\n with pytest.raises(ValueError):\n data.drop(labels=[\"a\"], dim=\"x\", x=\"a\")\n+ warnings.filterwarnings(\"ignore\", r\"\\W*drop\")\n+ with pytest.raises(ValueError):\n+ data.drop(dim=\"x\", x=\"a\")\n \n def test_drop_dims(self):\n data = xr.Dataset(\n@@ -2203,15 +2224,15 @@ def test_drop_dims(self):\n )\n \n actual = data.drop_dims(\"x\")\n- expected = data.drop([\"A\", \"B\", \"x\"])\n+ expected = data.drop_vars([\"A\", \"B\", \"x\"])\n assert_identical(expected, actual)\n \n actual = data.drop_dims(\"y\")\n- expected = data.drop(\"A\")\n+ expected = data.drop_vars(\"A\")\n assert_identical(expected, actual)\n \n actual = data.drop_dims([\"x\", \"y\"])\n- expected = data.drop([\"A\", \"B\", \"x\"])\n+ expected = data.drop_vars([\"A\", \"B\", \"x\"])\n assert_identical(expected, actual)\n \n with pytest.raises((ValueError, KeyError)):\n@@ -2230,7 +2251,7 @@ def test_drop_dims(self):\n actual = data.drop_dims(\"z\", errors=\"wrong_value\")\n \n actual = data.drop_dims([\"x\", \"y\", \"z\"], errors=\"ignore\")\n- expected = data.drop([\"A\", \"B\", \"x\"])\n+ expected = data.drop_vars([\"A\", \"B\", \"x\"])\n assert_identical(expected, actual)\n \n def test_copy(self):\n@@ -2571,7 +2592,7 @@ def test_expand_dims_mixed_int_and_coords(self):\n original[\"x\"].values * np.ones([4, 3, 3]),\n coords=dict(d=range(4), e=[\"l\", \"m\", \"n\"], a=np.linspace(0, 1, 3)),\n dims=[\"d\", \"e\", \"a\"],\n- ).drop(\"d\"),\n+ ).drop_vars(\"d\"),\n \"y\": xr.DataArray(\n original[\"y\"].values * np.ones([4, 3, 4, 3]),\n coords=dict(\n@@ -2581,7 +2602,7 @@ def test_expand_dims_mixed_int_and_coords(self):\n a=np.linspace(0, 1, 3),\n ),\n dims=[\"d\", \"e\", \"b\", \"a\"],\n- ).drop(\"d\"),\n+ ).drop_vars(\"d\"),\n },\n coords={\"c\": np.linspace(0, 1, 5)},\n )\n@@ -3059,7 +3080,7 @@ def test_setitem_with_coords(self):\n np.arange(10), dims=\"dim3\", coords={\"numbers\": (\"dim3\", np.arange(10))}\n )\n expected = ds.copy()\n- expected[\"var3\"] = other.drop(\"numbers\")\n+ expected[\"var3\"] = other.drop_vars(\"numbers\")\n actual = ds.copy()\n actual[\"var3\"] = other\n assert_identical(expected, actual)\n@@ -4504,7 +4525,9 @@ def test_apply(self):\n actual = data.apply(lambda x: x.mean(keep_attrs=True), keep_attrs=True)\n assert_identical(expected, actual)\n \n- assert_identical(data.apply(lambda x: x, keep_attrs=True), data.drop(\"time\"))\n+ assert_identical(\n+ data.apply(lambda x: x, keep_attrs=True), data.drop_vars(\"time\")\n+ )\n \n def scale(x, multiple=1):\n return multiple * x\n@@ -4514,7 +4537,7 @@ def scale(x, multiple=1):\n assert_identical(actual[\"numbers\"], data[\"numbers\"])\n \n actual = data.apply(np.asarray)\n- expected = data.drop(\"time\") # time is not used on a data var\n+ expected = data.drop_vars(\"time\") # time is not used on a data var\n assert_equal(expected, actual)\n \n def make_example_math_dataset(self):\n@@ -4616,7 +4639,7 @@ def test_dataset_math_auto_align(self):\n assert_identical(expected, actual)\n \n actual = ds.isel(y=slice(1)) + ds.isel(y=slice(1, None))\n- expected = 2 * ds.drop(ds.y, dim=\"y\")\n+ expected = 2 * ds.drop_sel(y=ds.y)\n assert_equal(actual, expected)\n \n actual = ds + ds[[\"bar\"]]\ndiff --git a/xarray/tests/test_duck_array_ops.py b/xarray/tests/test_duck_array_ops.py\nindex 9df2f167cf2..f678af2fec5 100644\n--- a/xarray/tests/test_duck_array_ops.py\n+++ b/xarray/tests/test_duck_array_ops.py\n@@ -441,7 +441,8 @@ def test_argmin_max(dim_num, dtype, contains_nan, dask, func, skipna, aggdim):\n )\n expected = getattr(da, func)(dim=aggdim, skipna=skipna)\n assert_allclose(\n- actual.drop(list(actual.coords)), expected.drop(list(expected.coords))\n+ actual.drop_vars(list(actual.coords)),\n+ expected.drop_vars(list(expected.coords)),\n )\n \n \ndiff --git a/xarray/tests/test_interp.py b/xarray/tests/test_interp.py\nindex b9dc9a71acc..b93325d7eab 100644\n--- a/xarray/tests/test_interp.py\n+++ b/xarray/tests/test_interp.py\n@@ -553,7 +553,7 @@ def test_datetime_single_string():\n actual = da.interp(time=\"2000-01-01T12:00\")\n expected = xr.DataArray(0.5)\n \n- assert_allclose(actual.drop(\"time\"), expected)\n+ assert_allclose(actual.drop_vars(\"time\"), expected)\n \n \n @requires_cftime\ndiff --git a/xarray/tests/test_plot.py b/xarray/tests/test_plot.py\nindex 7deabd46eae..6e283ea01da 100644\n--- a/xarray/tests/test_plot.py\n+++ b/xarray/tests/test_plot.py\n@@ -1837,7 +1837,11 @@ def test_default_labels(self):\n assert substring_in_axes(self.darray.name, ax)\n \n def test_test_empty_cell(self):\n- g = self.darray.isel(row=1).drop(\"row\").plot(col=\"col\", hue=\"hue\", col_wrap=2)\n+ g = (\n+ self.darray.isel(row=1)\n+ .drop_vars(\"row\")\n+ .plot(col=\"col\", hue=\"hue\", col_wrap=2)\n+ )\n bottomright = g.axes[-1, -1]\n assert not bottomright.has_data()\n assert not bottomright.get_visible()\ndiff --git a/xarray/tests/test_units.py b/xarray/tests/test_units.py\nindex 9d14104bb50..80063f8b4bc 100644\n--- a/xarray/tests/test_units.py\n+++ b/xarray/tests/test_units.py\n@@ -1093,7 +1093,7 @@ def test_content_manipulation(self, func, dtype):\n \"func\",\n (\n pytest.param(\n- method(\"drop\", labels=np.array([1, 5]), dim=\"x\"),\n+ method(\"drop_sel\", labels=dict(x=np.array([1, 5]))),\n marks=pytest.mark.xfail(\n reason=\"selecting using incompatible units does not raise\"\n ),\n@@ -1128,9 +1128,9 @@ def test_content_manipulation_with_units(self, func, unit, error, dtype):\n \n expected = attach_units(\n func(strip_units(data_array), **stripped_kwargs),\n- {\"data\": quantity.units if func.name == \"drop\" else unit, \"x\": x.units},\n+ {\"data\": quantity.units if func.name == \"drop_sel\" else unit, \"x\": x.units},\n )\n- if error is not None and func.name == \"drop\":\n+ if error is not None and func.name == \"drop_sel\":\n with pytest.raises(error):\n func(data_array, **kwargs)\n else:\n", "doc_changes": [{"path": "doc/data-structures.rst", "old_path": "a/doc/data-structures.rst", "new_path": "b/doc/data-structures.rst", "metadata": "diff --git a/doc/data-structures.rst b/doc/data-structures.rst\nindex d5567f4863e..93cdc7e9765 100644\n--- a/doc/data-structures.rst\n+++ b/doc/data-structures.rst\n@@ -393,14 +393,14 @@ methods (like pandas) for transforming datasets into new objects.\n \n For removing variables, you can select and drop an explicit list of\n variables by indexing with a list of names or using the\n-:py:meth:`~xarray.Dataset.drop` methods to return a new ``Dataset``. These\n+:py:meth:`~xarray.Dataset.drop_vars` methods to return a new ``Dataset``. These\n operations keep around coordinates:\n \n .. ipython:: python\n \n ds[['temperature']]\n ds[['temperature', 'temperature_double']]\n- ds.drop('temperature')\n+ ds.drop_vars('temperature')\n \n To remove a dimension, you can use :py:meth:`~xarray.Dataset.drop_dims` method.\n Any variables using that dimension are dropped:\n"}, {"path": "doc/indexing.rst", "old_path": "a/doc/indexing.rst", "new_path": "b/doc/indexing.rst", "metadata": "diff --git a/doc/indexing.rst b/doc/indexing.rst\nindex 9ee8f1dddf8..ace960689a8 100644\n--- a/doc/indexing.rst\n+++ b/doc/indexing.rst\n@@ -232,14 +232,14 @@ Using indexing to *assign* values to a subset of dataset (e.g.,\n Dropping labels and dimensions\n ------------------------------\n \n-The :py:meth:`~xarray.Dataset.drop` method returns a new object with the listed\n+The :py:meth:`~xarray.Dataset.drop_sel` method returns a new object with the listed\n index labels along a dimension dropped:\n \n .. ipython:: python\n \n- ds.drop(space=['IN', 'IL'])\n+ ds.drop_sel(space=['IN', 'IL'])\n \n-``drop`` is both a ``Dataset`` and ``DataArray`` method.\n+``drop_sel`` is both a ``Dataset`` and ``DataArray`` method.\n \n Use :py:meth:`~xarray.Dataset.drop_dims` to drop a full dimension from a Dataset.\n Any variables with these dimensions are also dropped:\n"}, {"path": "doc/whats-new.rst", "old_path": "a/doc/whats-new.rst", "new_path": "b/doc/whats-new.rst", "metadata": "diff --git a/doc/whats-new.rst b/doc/whats-new.rst\nindex dcaab011e67..0906058469d 100644\n--- a/doc/whats-new.rst\n+++ b/doc/whats-new.rst\n@@ -38,6 +38,12 @@ Breaking changes\n \n New Features\n ~~~~~~~~~~~~\n+- :py:meth:`Dataset.drop_sel` & :py:meth:`DataArray.drop_sel` have been added for dropping labels.\n+ :py:meth:`Dataset.drop_vars` & :py:meth:`DataArray.drop_vars` have been added for \n+ dropping variables (including coordinates). The existing ``drop`` methods remain as a backward compatible \n+ option for dropping either lables or variables, but using the more specific methods is encouraged.\n+ (:pull:`3475`)\n+ By `Maximilian Roos `_\n - :py:meth:`Dataset.transpose` and :py:meth:`DataArray.transpose` now support an ellipsis (`...`)\n to represent all 'other' dimensions. For example, to move one dimension to the front,\n use `.transpose('x', ...)`. (:pull:`3421`)\n@@ -3752,6 +3758,7 @@ Enhancements\n explicitly listed variables or index labels:\n \n .. ipython:: python\n+ :okwarning:\n \n # drop variables\n ds = xray.Dataset({'x': 0, 'y': 1})\n"}], "version": "0014", "base_commit": "4dce93f134e8296ea730104b46ce3372b90304ac", "PASS2PASS": ["xarray/tests/test_dataset.py::test_rolling_reduce[max-1-None-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-3-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-4-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-3-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-True-std]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-3-3-False-1]", "xarray/tests/test_duck_array_ops.py::TestArrayNotNullEquiv::test_equal[arr12-arr22]", "xarray/tests/test_dataarray.py::TestDataArray::test_dataarray_diff_n1", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-None-median]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-1-1-False]", "xarray/tests/test_dataset.py::TestDataset::test_stack", "xarray/tests/test_dataset.py::test_rolling_reduce[var-1-3-True-2]", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords1-unaligned_coords5]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-3-1-True-2]", "xarray/tests/test_dataset.py::test_dir_non_string[None]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-2-1-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-1-3-True]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-3-1-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-3-2-True]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-True-median]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-4-None-False-1]", "xarray/tests/test_dataset.py::TestDataset::test_reindex_like_fill_value[2]", "xarray/tests/test_dataset.py::TestDataset::test_sel", "xarray/tests/test_dataarray.py::TestDataArray::test_align_mixed_indexes", "xarray/tests/test_dataset.py::test_rolling_reduce[var-2-None-True-1]", "xarray/tests/test_dataset.py::test_differentiate_datetime[True]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-3-3-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-4-1-True]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-False-max]", "xarray/tests/test_duck_array_ops.py::test_min_count[None-prod-False-bool_-2]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-True-max-False-float-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-4-3-False-2]", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[4-1-True]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-3-2-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-4-3-False]", "xarray/tests/test_dataset.py::TestDataset::test_align_fill_value[2.0]", "xarray/tests/test_dataset.py::TestDataset::test_coords_properties", "xarray/tests/test_dataset.py::test_rolling_reduce[min-1-3-True-1]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-False-sum-False-float32-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-3-2-False-2]", "xarray/tests/test_dataset.py::TestDataset::test_to_stacked_array_dtype_dims", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-None-None-mean]", "xarray/tests/test_dataset.py::TestDataset::test_to_and_from_dict_with_time_dim", "xarray/tests/test_duck_array_ops.py::test_reduce[None-False-min-False-bool_-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_attr_sources_multiindex", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-1-None-max]", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[3-3-True]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-4-None-False-1]", "xarray/tests/test_dataset.py::TestDataset::test_to_stacked_array_name", "xarray/tests/test_dataset.py::TestDataset::test_constructor_pandas_sequence", "xarray/tests/test_dataset.py::test_rolling_reduce[median-1-1-True-1]", "xarray/tests/test_dataset.py::TestDataset::test_roll_coords_none", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-3-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[4-1-True]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-3-None-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_resample_first", "xarray/tests/test_dataset.py::TestDataset::test_reindex_method", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-None-None-max]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-3-2-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-4-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[1-1-True]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-3-None-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-3-2-False-1]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-False-max-False-int-2]", "xarray/tests/test_duck_array_ops.py::test_min_count[None-sum-False-bool_-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-4-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-1-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-1-2-True-2]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-False-var-False-int-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-4-1-True]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-3-None-False-1]", "xarray/tests/test_dataset.py::test_coarsen[1-trim-left-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-4-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-4-2-False-1]", "xarray/tests/test_dataset.py::TestDataset::test_assign_multiindex_level", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-1-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-4-3-True-2]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-True-sum-False-bool_-2]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[2-None-True]", "xarray/tests/test_dataset.py::TestDataset::test_variable", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-3-1-False-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_where", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-1-2-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-1-2-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-3-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-2-1-False-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_dropna", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-1-1-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-3-2-True-2]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-True-var-False-int-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-2-2-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-2-None-True-1]", "xarray/tests/test_duck_array_ops.py::test_min_count[x-prod-False-float-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-1-2-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-3-1-True]", "xarray/tests/test_dataset.py::test_rolling_construct[3-True]", "xarray/tests/test_dataarray.py::TestDataArray::test_struct_array_dims", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords0-unaligned_coords8]", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-None-None-std]", "xarray/tests/test_dataarray.py::TestDataArray::test_resample_bad_resample_dim", "xarray/tests/test_dataset.py::TestDataset::test_coords_merge", "xarray/tests/test_dataset.py::test_rolling_reduce[min-1-3-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-4-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-4-1-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-1-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-None-mean]", "xarray/tests/test_duck_array_ops.py::test_multiple_dims[sum-False-float32]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-4-None-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_math_with_coords", "xarray/tests/test_dataset.py::TestDataset::test_groupby_nan", "xarray/tests/test_dataset.py::test_rolling_reduce[var-3-2-False-2]", "xarray/tests/test_duck_array_ops.py::test_isnull[array1]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-True-var-False-int-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_loc", "xarray/tests/test_dataset.py::test_rolling_reduce[var-3-1-False-2]", "xarray/tests/test_dataset.py::TestDataset::test_groupby_math_virtual", "xarray/tests/test_dataarray.py::TestDataArray::test_groupby_apply_changes_metadata", "xarray/tests/test_duck_array_ops.py::test_reduce[x-True-max-False-float32-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-3-None-False-2]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-True-sum-False-float-2]", "xarray/tests/test_dataset.py::TestDataset::test_where_other", "xarray/tests/test_dataset.py::test_rolling_reduce[std-4-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-1-1-False-2]", "xarray/tests/test_dataset.py::TestDataset::test_rename_old_name", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-4-3-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_constructor_from_0d", "xarray/tests/test_dataset.py::test_rolling_reduce[var-4-2-True-2]", "xarray/tests/test_duck_array_ops.py::test_multiple_dims[prod-False-float]", "xarray/tests/test_dataset.py::TestDataset::test_quantile", "xarray/tests/test_dataset.py::test_rolling_reduce[std-2-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-3-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-4-None-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-3-3-False-1]", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-None-False-mean]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-1-2-True-1]", "xarray/tests/test_dataset.py::TestDataset::test_reindex_warning", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[3-1-False]", "xarray/tests/test_dataarray.py::test_rolling_construct[4-True]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-2-1-True]", "xarray/tests/test_dataarray.py::TestDataArray::test_align_without_indexes_exclude", "xarray/tests/test_dataset.py::TestDataset::test_constructor", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-1-None-False-1]", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[3-3-False]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-4-2-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-2-3-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_getitem_dict", "xarray/tests/test_dataset.py::test_rolling_reduce[median-1-2-True-2]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-True-max-False-int-2]", "xarray/tests/test_dataset.py::TestDataset::test_reduce_bad_dim", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-None-True-std]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-2-2-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-4-None-True]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-3-2-True-1]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-True-max-False-float-2]", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[1-1-False]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[3-1-True]", "xarray/tests/test_dataset.py::TestDataset::test_coords_setitem_multiindex", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-1-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-1-3-True-1]", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-1-False-sum]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-3-None-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-1-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-1-None-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-1-3-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_da_resample_func_args", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-4-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-True-max]", "xarray/tests/test_dataarray.py::TestDataArray::test_getitem_empty_index", "xarray/tests/test_dataset.py::test_rolling_reduce[max-3-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-4-2-True-1]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-True-mean-False-float32-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_sel", "xarray/tests/test_duck_array_ops.py::test_reduce[None-False-max-False-int-1]", "xarray/tests/test_dataset.py::TestDataset::test_resample_loffset", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-3-None-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-1-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-1-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-2-3-False-2]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-False-min-False-int-2]", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[3-1-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-3-1-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-4-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-3-None-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-2-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-2-3-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-2-3-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-2-3-False-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_groupby_apply_ndarray", "xarray/tests/test_duck_array_ops.py::test_min_count[None-prod-False-bool_-1]", "xarray/tests/test_dataarray.py::test_isin[repeating_ints]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-False-sum-False-float32-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-2-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-3-1-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-1-None-False]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-3-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-True-median]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-4-3-False-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_series_categorical_index", "xarray/tests/test_duck_array_ops.py::test_reduce[x-True-mean-False-float32-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_copy_with_data", "xarray/tests/test_dataset.py::TestDataset::test_shift[fill_value0]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-True-min-False-int-2]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-True-sum-False-float-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_getitem_coords", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-True-median]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-2-2-True-1]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-False-mean-False-int-2]", "xarray/tests/test_duck_array_ops.py::test_cumsum_2d", "xarray/tests/test_dataset.py::TestDataset::test_virtual_variable_same_name", "xarray/tests/test_dataset.py::test_trapz_datetime[np-True]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-4-2-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-2-1-True]", "xarray/tests/test_dataset.py::TestDataset::test_resample_old_api", "xarray/tests/test_dataset.py::test_rolling_reduce[max-3-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-4-None-False-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_equals_and_identical", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-1-1-False-1]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-True-mean-False-int-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-2-None-True-1]", "xarray/tests/test_dataset.py::TestDataset::test_selection_multiindex", "xarray/tests/test_duck_array_ops.py::test_min_count[None-prod-False-int-1]", "xarray/tests/test_backends.py::test_invalid_netcdf_raises[scipy]", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords1-unaligned_coords1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-1-2-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-1-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-4-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-1-2-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-2-1-True-2]", "xarray/tests/test_duck_array_ops.py::test_multiple_dims[prod-False-int]", "xarray/tests/test_dataarray.py::TestDataArray::test_reduce_keep_attrs", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-None-sum]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-3-None-True-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_groupby_sum_default", "xarray/tests/test_dataset.py::TestDataset::test_to_array", "xarray/tests/test_dataset.py::test_rolling_reduce[std-4-3-False-1]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-False-min-False-float32-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-3-3-True]", "xarray/tests/test_duck_array_ops.py::test_min_count[None-prod-False-float32-2]", "xarray/tests/test_dataset.py::TestDataset::test_ds_resample_apply_func_args", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-2-1-False-2]", "xarray/tests/test_dataset.py::TestDataset::test_align_nocopy", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-True-min]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-None-var]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[3-2-True]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-4-None-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-4-1-False-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_getitem_dataarray", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[1-2-True]", "xarray/tests/test_dataset.py::TestDataset::test_resample_min_count", "xarray/tests/test_backends.py::TestEncodingInvalid::test_extract_h5nc_encoding", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-1-None-False-1]", "xarray/tests/test_dataset.py::TestDataset::test_constructor_invalid_dims", "xarray/tests/test_dataset.py::test_rolling_reduce[var-2-2-False-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_to_dataset_whole", "xarray/tests/test_dataset.py::TestDataset::test_resample_by_mean_with_keep_attrs", "xarray/tests/test_dataset.py::TestDataset::test_expand_dims_coords", "xarray/tests/test_dataset.py::test_rolling_reduce[min-3-1-False-2]", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords0-unaligned_coords7]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-2-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-None-std]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-True-var-False-float-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_sel_drop", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[1-2-False]", "xarray/tests/test_dataset.py::TestDataset::test_ipython_key_completion", "xarray/tests/test_dataset.py::test_rolling_reduce[max-4-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_construct[2-False]", "xarray/tests/test_dataset.py::TestDataset::test_setitem_pandas", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-False-min]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-False-mean-False-float32-2]", "xarray/tests/test_backends.py::test_invalid_netcdf_raises[netcdf4]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-3-3-True-2]", "xarray/tests/test_duck_array_ops.py::test_min_count[x-sum-False-bool_-2]", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-1-True-mean]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-1-1-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_dataset_math", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-2-3-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-3-None-False-1]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-False-var-False-float32-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_virtual_default_coords", "xarray/tests/test_dataarray.py::TestDataArray::test_dot", "xarray/tests/test_dataset.py::test_rolling_reduce[std-3-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-3-None-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-2-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-4-None-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_loc_assign_dataarray", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-2-None-False-1]", "xarray/tests/test_dataset.py::TestDataset::test_constructor_pandas_single", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-3-None-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-2-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-4-3-False-2]", "xarray/tests/test_dataset.py::test_coarsen_coords[1-True]", "xarray/tests/test_dataarray.py::TestDataArray::test_set_coords_update_index", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-4-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-2-2-True-2]", "xarray/tests/test_dataset.py::TestDataset::test_unicode_data", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-1-False-max]", "xarray/tests/test_dataset.py::TestDataset::test_time_season", "xarray/tests/test_dataarray.py::TestDataArray::test_empty_dataarrays_return_empty_result", "xarray/tests/test_dataarray.py::TestDataArray::test_align_copy", "xarray/tests/test_dataarray.py::TestDataArray::test_inplace_math_basics", "xarray/tests/test_duck_array_ops.py::test_cumsum_1d", "xarray/tests/test_duck_array_ops.py::test_reduce[x-True-max-False-float32-1]", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords0-unaligned_coords0]", "xarray/tests/test_dataarray.py::TestDataArray::test_expand_dims_with_scalar_coordinate", "xarray/tests/test_dataarray.py::TestDataArray::test_reduce_keepdims_bottleneck", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-3-1-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-2-None-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-1-3-False-1]", "xarray/tests/test_dataarray.py::test_rolling_construct[1-True]", "xarray/tests/test_dataset.py::TestDataset::test_convert_dataframe_with_many_types_and_multiindex", "xarray/tests/test_dataset.py::test_rolling_reduce[max-3-3-False-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_resample", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-2-None-False-1]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-False-mean-False-float-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-4-None-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-1-1-True]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-True-mean-False-float32-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-2-3-False]", "xarray/tests/test_dataarray.py::TestDataArray::test_tail", "xarray/tests/test_dataset.py::TestDataset::test_groupby_reduce", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-2-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-2-1-True-2]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-False-sum-False-float-2]", "xarray/tests/test_dataarray.py::test_rolling_construct[1-False]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[4-1-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-1-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-4-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-4-2-False-2]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-False-mean-False-int-2]", "xarray/tests/test_dataset.py::test_integrate[True]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-4-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-4-None-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-4-None-True]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-4-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-4-1-False-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_rename", "xarray/tests/test_dataset.py::TestDataset::test_broadcast_nocopy", "xarray/tests/test_dataarray.py::TestDataArray::test__title_for_slice_truncate", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-2-1-False-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_setitem_dataarray", "xarray/tests/test_duck_array_ops.py::test_reduce[None-True-min-False-bool_-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-2-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-3-None-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-1-2-True]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-2-None-True-2]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-True-sum-False-float-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-3-3-True-2]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-False-var-False-float-1]", "xarray/tests/test_dataset.py::TestDataset::test_setitem_original_non_unique_index", "xarray/tests/test_dataarray.py::TestDataArray::test_resample_skipna", "xarray/tests/test_dataarray.py::TestDataArray::test__title_for_slice", "xarray/tests/test_dataset.py::TestDataset::test_reindex_variables_copied", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-4-3-True]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-3-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-4-3-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-3-2-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-4-1-True-1]", "xarray/tests/test_duck_array_ops.py::TestOps::test_first", "xarray/tests/test_dataset.py::TestDataset::test_to_dict_with_numpy_attrs", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-4-1-False-1]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-True-var-False-float-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_expand_dims", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords0-unaligned_coords9]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-2-2-True-2]", "xarray/tests/test_duck_array_ops.py::test_multiple_dims[prod-False-float32]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-4-2-False-2]", "xarray/tests/test_dataarray.py::test_name_in_masking", "xarray/tests/test_duck_array_ops.py::test_reduce[None-False-max-False-bool_-1]", "xarray/tests/test_dataset.py::TestDataset::test_properties", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-1-True-std]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[4-None-False]", "xarray/tests/test_dataset.py::TestDataset::test_reduce_keepdims", "xarray/tests/test_dataset.py::test_rolling_reduce[min-4-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-3-2-False-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_reindex_like", "xarray/tests/test_duck_array_ops.py::test_reduce[x-True-mean-False-float-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-1-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-False-max]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-4-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-3-3-False-1]", "xarray/tests/test_duck_array_ops.py::TestOps::test_concatenate_type_promotion", "xarray/tests/test_dataset.py::test_rolling_reduce[var-1-1-True-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_shift[fill_value1-float-1]", "xarray/tests/test_dataset.py::TestDataset::test_align_non_unique", "xarray/tests/test_dataset.py::test_rolling_reduce[min-3-1-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-4-1-False-1]", "xarray/tests/test_duck_array_ops.py::test_isnull[array2]", "xarray/tests/test_dataset.py::TestDataset::test_virtual_variables_time", "xarray/tests/test_duck_array_ops.py::test_reduce[None-False-min-False-float-1]", "xarray/tests/test_duck_array_ops.py::test_multiple_dims[sum-False-int]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-3-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-3-1-True-2]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-False-mean-False-float-2]", "xarray/tests/test_dataset.py::test_dir_unicode[None]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[3-3-False]", "xarray/tests/test_dataset.py::TestDataset::test_resample_and_first", "xarray/tests/test_dataarray.py::TestDataArray::test_to_and_from_dict_with_time_dim", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-False-std]", "xarray/tests/test_dataset.py::TestDataset::test_coords_to_dataset", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-4-2-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-4-3-True-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_broadcast_coordinates", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-2-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-None-var]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-2-3-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-2-1-False-1]", "xarray/tests/test_dataset.py::TestDataset::test_variable_indexing", "xarray/tests/test_dataset.py::TestDataset::test_where_drop_empty", "xarray/tests/test_dataarray.py::TestDataArray::test_groupby_bins_multidim", "xarray/tests/test_dataset.py::test_rolling_reduce[max-2-2-False-2]", "xarray/tests/test_dataset.py::TestDataset::test_update_auto_align", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-False-mean]", "xarray/tests/test_dataarray.py::TestDataArray::test_coords_non_string", "xarray/tests/test_dataarray.py::TestDataArray::test_fillna", "xarray/tests/test_duck_array_ops.py::test_reduce[x-False-min-False-bool_-1]", "xarray/tests/test_duck_array_ops.py::test_min_count_dataset[prod]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-1-2-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-4-None-False-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_groupby_restore_dim_order", "xarray/tests/test_dataset.py::test_rolling_reduce[median-2-None-True-1]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-True-sum-False-int-1]", "xarray/tests/test_duck_array_ops.py::test_min_count[x-prod-False-float32-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-3-1-True-2]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-False-max-False-float32-2]", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-None-False-std]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-False-var-False-float32-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_selection_multiindex", "xarray/tests/test_dataset.py::test_rolling_reduce[std-4-2-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-3-2-False-2]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-False-max-False-float32-2]", "xarray/tests/test_dataset.py::TestDataset::test_reorder_levels", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-4-3-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-2-None-False-1]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-True-mean]", "xarray/tests/test_dataset.py::TestDataset::test_reindex_fill_value[2]", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[4-3-False]", "xarray/tests/test_dataset.py::TestDataset::test_getitem_hashable", "xarray/tests/test_duck_array_ops.py::test_reduce[x-True-max-False-bool_-1]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-None-median]", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-None-False-min]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-1-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-4-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-True-var]", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords1-unaligned_coords6]", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords0-unaligned_coords6]", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-1-True-sum]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-4-None-True-2]", "xarray/tests/test_dataset.py::TestDataset::test_sel_method", "xarray/tests/test_dataarray.py::TestDataArray::test_set_index", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-None-median]", "xarray/tests/test_dataarray.py::TestDataArray::test_groupby_math", "xarray/tests/test_dataset.py::test_rolling_reduce[min-3-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-4-2-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-2-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-3-1-True-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_assign_coords", "xarray/tests/test_dataarray.py::TestDataArray::test_index_math", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-3-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-3-3-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_constructor", "xarray/tests/test_dataset.py::TestDataset::test_constructor_1d", "xarray/tests/test_dataset.py::test_rolling_reduce[min-2-1-False-2]", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-1-True-median]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-1-None-False-2]", "xarray/tests/test_duck_array_ops.py::test_isnull[array4]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-False-var-False-bool_-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-4-None-False-1]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-True-sum-False-int-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-2-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-2-2-False-1]", "xarray/tests/test_dataset.py::TestDataset::test_constructor_0d", "xarray/tests/test_dataarray.py::TestDataArray::test_reduce_dtype", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-True-var]", "xarray/tests/test_dataset.py::test_isin[test_elements2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-3-1-True-2]", "xarray/tests/test_dataset.py::TestDataset::test_reduce_argmin", "xarray/tests/test_dataset.py::test_rolling_reduce[var-4-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-3-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-3-2-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-3-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-4-3-False-1]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-False-min-False-int-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-2-2-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-1-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-False-max]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[3-None-True]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[4-3-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-2-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-2-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-4-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-None-var]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-3-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-1-None-True-1]", "xarray/tests/test_dataset.py::TestDataset::test_loc", "xarray/tests/test_duck_array_ops.py::test_reduce[x-False-min-False-float32-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_array_interface", "xarray/tests/test_duck_array_ops.py::test_reduce[x-False-var-False-float-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-4-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-4-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-None-min]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-True-max-False-int-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_sel_dataarray_datetime", "xarray/tests/test_dataset.py::TestDataset::test_unstack_errors", "xarray/tests/test_duck_array_ops.py::test_reduce[None-True-min-False-float32-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_repr_multiindex", "xarray/tests/test_dataset.py::TestDataset::test_lazy_load", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[4-2-False]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-True-sum-False-float32-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_roll_coords_none", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-1-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-False-sum]", "xarray/tests/test_dataset.py::TestDataset::test_virtual_variables_default_coords", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-1-2-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_to_pandas_name_matches_coordinate", "xarray/tests/test_dataset.py::TestDataset::test_dataset_diff_n2", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-4-1-True-1]", "xarray/tests/test_dataset.py::TestDataset::test_shift[2.0]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-4-1-False-2]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-False-max-False-bool_-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-4-3-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_to_unstacked_dataset_raises_value_error", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-3-1-True-2]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-False-min-False-bool_-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-1-1-False-2]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-True-min-False-bool_-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-4-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-2-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-3-3-True-2]", "xarray/tests/test_dataset.py::TestDataset::test_from_dataframe_non_unique_columns", "xarray/tests/test_duck_array_ops.py::test_reduce[None-True-sum-False-bool_-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-4-2-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_coords_alignment", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-2-3-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-2-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-1-3-True-2]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[4-2-False]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-False-max-False-float32-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_groupby_multidim", "xarray/tests/test_dataarray.py::TestDataArray::test_dataset_getitem", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[3-2-True]", "xarray/tests/test_dataset.py::TestDataset::test_full_like", "xarray/tests/test_dataset.py::test_rolling_reduce[var-1-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-4-None-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-1-None-True-1]", "xarray/tests/test_dataset.py::TestDataset::test_align", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-3-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-False-sum]", "xarray/tests/test_duck_array_ops.py::test_min_count[x-sum-False-float32-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-3-1-False-1]", "xarray/tests/test_dataset.py::TestDataset::test_constructor_auto_align", "xarray/tests/test_dataset.py::TestDataset::test_align_exclude", "xarray/tests/test_dataset.py::test_differentiate[2-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-1-None-False-2]", "xarray/tests/test_duck_array_ops.py::test_min_count[None-sum-False-float32-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-2-3-False-2]", "xarray/tests/test_dataset.py::TestDataset::test_setitem_multiindex_level", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-1-2-True]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-3-2-True-1]", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords1-unaligned_coords9]", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords1-unaligned_coords3]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-2-3-True-2]", "xarray/tests/test_dataset.py::TestDataset::test_align_indexes", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-4-3-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-1-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-None-std]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-2-None-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-4-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-1-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-4-3-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-1-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-1-1-True-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_math", "xarray/tests/test_dataarray.py::TestDataArray::test_groupby_apply_identity", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-2-1-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-2-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-3-1-False-2]", "xarray/tests/test_dataset.py::TestDataset::test_repr_nep18", "xarray/tests/test_dataset.py::test_rolling_reduce[var-1-3-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-2-3-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-1-3-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-2-3-True-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_groupby_bins_empty", "xarray/tests/test_dataarray.py::TestDataArray::test_data_property", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-3-None-True]", "xarray/tests/test_dataarray.py::TestDataArray::test_cumops", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-False-std]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-4-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-2-1-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-4-None-False-1]", "xarray/tests/test_dataset.py::test_differentiate_datetime[False]", "xarray/tests/test_dataset.py::TestDataset::test_reindex_fill_value[fill_value0]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-False-min-False-int-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-2-3-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-3-1-False-1]", "xarray/tests/test_dataset.py::TestDataset::test_update_overwrite_coords", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-3-1-False-1]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-False-min-False-int-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-2-2-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-1-3-False-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_reindex_fill_value[fill_value0]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-1-2-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-3-3-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_non_overlapping_dataarrays_return_empty_result", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-2-2-True-1]", "xarray/tests/test_duck_array_ops.py::test_min_count[None-prod-False-float-2]", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[2-3-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-2-2-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-2-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-3-1-False-2]", "xarray/tests/test_dataset.py::TestDataset::test_attribute_access", "xarray/tests/test_dataset.py::TestDataset::test_dataset_array_math", "xarray/tests/test_dataset.py::TestDataset::test_unstack", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-1-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-4-3-True-1]", "xarray/tests/test_dataset.py::test_isin[test_elements1]", "xarray/tests/test_dataset.py::TestDataset::test_setattr_raises", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-2-2-False-2]", "xarray/tests/test_dataset.py::TestDataset::test_rename_same_name", "xarray/tests/test_dataset.py::test_rolling_reduce[var-4-2-True-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_loc_single_boolean", "xarray/tests/test_dataarray.py::TestDataArray::test_groupby_properties", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-3-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-3-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-4-3-False-2]", "xarray/tests/test_dataset.py::TestDataset::test_update_index", "xarray/tests/test_duck_array_ops.py::test_reduce[None-False-max-False-int-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-1-3-False-1]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-True-var-False-int-2]", "xarray/tests/test_dataset.py::TestDataset::test_rename", "xarray/tests/test_dataarray.py::TestDataArray::test_shift[fill_value1-float-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-4-1-False-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_coordinate_diff", "xarray/tests/test_dataset.py::TestDataset::test_stack_unstack_slow", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-False-mean]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-3-1-True-1]", "xarray/tests/test_duck_array_ops.py::TestArrayNotNullEquiv::test_some_not_equal", "xarray/tests/test_dataset.py::test_rolling_reduce[min-4-3-False-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_align_indexes", "xarray/tests/test_dataset.py::TestDataset::test_rename_vars", "xarray/tests/test_dataset.py::test_rolling_reduce[max-2-1-False-2]", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords0-unaligned_coords5]", "xarray/tests/test_dataarray.py::TestDataArray::test_coords_to_index", "xarray/tests/test_dataarray.py::TestDataArray::test_full_like", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-4-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-4-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-None-min]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-4-2-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-3-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-4-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-3-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-4-None-True-1]", "xarray/tests/test_dataarray.py::test_subclass_slots", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-1-True-min]", "xarray/tests/test_dataset.py::TestDataset::test_groupby_errors", "xarray/tests/test_dataarray.py::test_rolling_construct[3-False]", "xarray/tests/test_dataarray.py::TestDataArray::test_binary_op_join_setting", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[1-3-False]", "xarray/tests/test_dataset.py::TestDataset::test_broadcast_exclude", "xarray/tests/test_duck_array_ops.py::TestArrayNotNullEquiv::test_wrong_shape", "xarray/tests/test_dataarray.py::TestDataArray::test_groupby_restore_coord_dims", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[1-3-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-3-1-False-1]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-False-mean-False-int-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-4-1-True-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_resample_keep_attrs", "xarray/tests/test_duck_array_ops.py::test_reduce[None-True-max-False-float32-1]", "xarray/tests/test_dataarray.py::test_rolling_doc[1]", "xarray/tests/test_dataset.py::TestDataset::test_align_fill_value[fill_value0]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-True-min-False-bool_-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-False-mean]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-3-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-False-min]", "xarray/tests/test_dataset.py::TestDataset::test_constructor_deprecated", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-1-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-4-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-False-min]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-1-1-False-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_quantile", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords1-unaligned_coords4]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-None-max]", "xarray/tests/test_dataset.py::TestDataset::test_align_override", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[4-None-True]", "xarray/tests/test_dataset.py::TestDataset::test_setitem_align_new_indexes", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-1-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-2-2-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_thin", "xarray/tests/test_duck_array_ops.py::test_reduce[None-True-max-False-float-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_groupby_iter", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-1-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-2-None-True-1]", "xarray/tests/test_duck_array_ops.py::test_min_count[x-sum-False-int-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-2-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-1-None-False-1]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-True-min-False-float-2]", "xarray/tests/test_dataset.py::TestDataset::test_reduce_cumsum", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-True-max]", "xarray/tests/test_dataarray.py::test_rolling_properties[1]", "xarray/tests/test_dataset.py::TestDataset::test_squeeze", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-1-None-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-3-1-True]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-3-None-True-2]", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords0-unaligned_coords1]", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords1-unaligned_coords2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-3-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-None-var]", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[4-None-False]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-3-3-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-3-1-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-4-None-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-2-2-True]", "xarray/tests/test_dataarray.py::TestDataArray::test_upsample_tolerance", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-None-None-median]", "xarray/tests/test_dataset.py::test_weakref", "xarray/tests/test_dataset.py::TestDataset::test_setitem", "xarray/tests/test_dataset.py::TestDataset::test_dataset_diff_n1", "xarray/tests/test_dataarray.py::TestDataArray::test_isel_drop", "xarray/tests/test_dataset.py::TestDataset::test_data_vars_properties", "xarray/tests/test_dataset.py::TestDataset::test_reindex_like_fill_value[2.0]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-2-2-True-1]", "xarray/tests/test_duck_array_ops.py::test_cumprod_2d", "xarray/tests/test_dataset.py::test_rolling_reduce[min-2-None-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-3-2-False]", "xarray/tests/test_duck_array_ops.py::TestArrayNotNullEquiv::test_types[val10-val20-val30-null0]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[4-3-True]", "xarray/tests/test_dataarray.py::TestDataArray::test_roll_coords", "xarray/tests/test_dataset.py::test_differentiate[1-True]", "xarray/tests/test_dataarray.py::TestDataArray::test_reduce_keepdims", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords0-unaligned_coords2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-True-min]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-3-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-3-3-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_isel", "xarray/tests/test_dataset.py::test_rolling_reduce[median-3-None-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-2-None-False-1]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-False-sum-False-int-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_sel_no_index", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-3-1-False-1]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-False-max-False-bool_-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-1-None-False-1]", "xarray/tests/test_dataset.py::TestDataset::test_broadcast_equals", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-1-2-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-4-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-False-mean]", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-None-None-sum]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-3-3-True]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-2-1-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-2-3-True]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-4-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-2-3-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-4-None-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-3-2-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-2-2-False]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[1-2-False]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[2-2-True]", "xarray/tests/test_dataset.py::TestDataset::test_squeeze_drop", "xarray/tests/test_dataarray.py::TestDataArray::test_shift[2-int--5]", "xarray/tests/test_dataarray.py::TestDataArray::test_contains", "xarray/tests/test_duck_array_ops.py::test_reduce[x-True-var-False-float32-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-2-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-4-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-4-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-True-mean]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-4-None-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-1-None-False-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_math_name", "xarray/tests/test_backends.py::TestEncodingInvalid::test_extract_nc4_variable_encoding", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[1-3-True]", "xarray/tests/test_dataset.py::TestDataset::test_binary_op_join_setting", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-3-2-True]", "xarray/tests/test_dataset.py::TestDataset::test_broadcast_misaligned", "xarray/tests/test_duck_array_ops.py::test_isnull[array0]", "xarray/tests/test_dataset.py::TestDataset::test_to_and_from_dataframe", "xarray/tests/test_dataarray.py::TestDataArray::test_pickle", "xarray/tests/test_dataset.py::test_rolling_reduce[min-3-3-True-2]", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[1-1-True]", "xarray/tests/test_dataset.py::TestDataset::test_rename_inplace", "xarray/tests/test_duck_array_ops.py::test_min_count[x-sum-False-float-1]", "xarray/tests/test_dataset.py::TestDataset::test_groupby_order", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-2-None-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-1-1-False-1]", "xarray/tests/test_dataset.py::test_coarsen[1-pad-right-True]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-4-1-True-1]", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-1-False-mean]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-4-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-2-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-3-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-3-None-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-1-1-False]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[2-3-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-2-None-True-2]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-False-sum-False-int-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-2-3-True-1]", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[2-2-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-1-3-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_reindex_like_no_index", "xarray/tests/test_duck_array_ops.py::test_reduce[None-False-var-False-float32-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-3-None-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-2-1-True-2]", "xarray/tests/test_duck_array_ops.py::test_multiple_dims[sum-False-float]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-4-None-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-4-3-True-1]", "xarray/tests/test_dataset.py::TestDataset::test_count", "xarray/tests/test_dataset.py::test_rolling_reduce[std-4-None-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-1-3-True-1]", "xarray/tests/test_dataset.py::TestDataset::test_repr", "xarray/tests/test_dataset.py::TestDataset::test_dataset_retains_period_index_on_transpose", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-1-2-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-4-2-True]", "xarray/tests/test_dataset.py::TestDataset::test_copy_with_data_errors", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-1-3-True-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_sel_float", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-2-1-True-2]", "xarray/tests/test_dataset.py::TestDataset::test_coords_merge_mismatched_shape", "xarray/tests/test_duck_array_ops.py::test_reduce[None-False-max-False-float32-1]", "xarray/tests/test_dataset.py::TestDataset::test_broadcast_like", "xarray/tests/test_dataset.py::test_rolling_construct[4-True]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-3-3-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_align_dtype", "xarray/tests/test_dataset.py::test_rolling_reduce[median-4-None-True-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_constructor_from_self_described", "xarray/tests/test_dataset.py::TestDataset::test_to_and_from_empty_dataframe", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-None-True-min]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-1-3-True-1]", "xarray/tests/test_duck_array_ops.py::TestArrayNotNullEquiv::test_types[foo-bar-baz-nan]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-3-2-False-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_groupby_first_and_last", "xarray/tests/test_dataset.py::TestDataset::test_dataset_diff_exception_n_neg", "xarray/tests/test_dataset.py::TestDataset::test_to_stacked_array_to_unstacked_dataset", "xarray/tests/test_dataarray.py::TestDataArray::test_coords_replacement_alignment", "xarray/tests/test_dataset.py::test_rolling_reduce[max-2-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-False-std]", "xarray/tests/test_dataset.py::TestDataset::test_stack_unstack_fast", "xarray/tests/test_dataarray.py::TestDataArray::test_groupby_bins_sort", "xarray/tests/test_dataset.py::test_rolling_reduce[median-1-None-True-1]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-True-max-False-int-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-3-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-4-None-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-1-1-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-3-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-2-2-False-2]", "xarray/tests/test_dataarray.py::test_rolling_iter[1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-4-1-False-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_get_index", "xarray/tests/test_dataarray.py::TestDataArray::test_to_dataset_split", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-1-3-True-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_name", "xarray/tests/test_dataarray.py::TestDataArray::test_align_exclude", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-3-1-False]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[3-2-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-4-None-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-4-3-False-2]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-True-min-False-float-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-4-3-True]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-1-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[3-None-False]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-1-None-False-2]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-True-var-False-bool_-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-1-1-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-2-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-4-2-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-4-1-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-3-2-True-1]", "xarray/tests/test_dataset.py::TestDataset::test_dropna", "xarray/tests/test_dataset.py::test_isin[test_elements0]", "xarray/tests/test_dataarray.py::TestDataArray::test_math_automatic_alignment", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-1-None-True-2]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-False-var-False-float-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-2-None-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-3-3-True-1]", "xarray/tests/test_dataset.py::TestDataset::test_reindex", "xarray/tests/test_duck_array_ops.py::test_reduce[x-False-mean-False-float-1]", "xarray/tests/test_duck_array_ops.py::test_min_count[x-prod-False-float-1]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-None-min]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-3-None-True-2]", "xarray/tests/test_duck_array_ops.py::test_docs", "xarray/tests/test_dataset.py::test_rolling_reduce[median-2-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-2-None-True-2]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-False-sum-False-float-2]", "xarray/tests/test_dataset.py::TestDataset::test_setitem_dimension_override", "xarray/tests/test_dataset.py::test_rolling_reduce[max-4-None-False-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_sel_method", "xarray/tests/test_duck_array_ops.py::test_min_count[None-prod-False-int-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-2-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-2-None-False-2]", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[2-3-True]", "xarray/tests/test_dataarray.py::TestDataArray::test_unstack_pandas_consistency", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-4-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-True-var]", "xarray/tests/test_dataset.py::TestDataset::test_set_index", "xarray/tests/test_dataarray.py::TestDataArray::test_roll_no_coords", "xarray/tests/test_dataset.py::TestDataset::test_constructor_with_coords", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-1-False-std]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-4-None-True-1]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-False-max-False-float-2]", "xarray/tests/test_dataset.py::TestDataset::test_reindex_fill_value[2.0]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-3-3-False-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_selection_multiindex_remove_unused", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-4-3-True-2]", "xarray/tests/test_dataset.py::TestDataset::test_repr_multiindex", "xarray/tests/test_duck_array_ops.py::test_reduce[x-False-max-False-int-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_shift[2-int-0]", "xarray/tests/test_dataarray.py::TestDataArray::test_align_override_error[darrays0]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-3-None-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-1-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-1-2-True-1]", "xarray/tests/test_duck_array_ops.py::TestOps::test_all_nan_arrays", "xarray/tests/test_duck_array_ops.py::test_reduce[None-True-sum-False-int-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-4-2-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-3-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-False-max]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-False-sum-False-bool_-2]", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[2-None-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-1-None-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-3-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-3-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-1-2-False-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_is_null", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-None-False-median]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-3-None-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-1-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-1-2-True-1]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-False-min-False-bool_-2]", "xarray/tests/test_duck_array_ops.py::test_argmin_max_error", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[2-2-True]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-True-sum-False-bool_-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_indexes", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-True-min]", "xarray/tests/test_dataarray.py::test_rolling_construct[3-True]", "xarray/tests/test_dataset.py::test_rolling_construct[2-True]", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-None-True-mean]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-1-2-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-3-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-4-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-4-2-False-1]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-False-mean-False-float32-2]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-True-sum-False-bool_-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_shift[2-int-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-1-2-False-2]", "xarray/tests/test_dataset.py::TestDataset::test_equals_and_identical", "xarray/tests/test_dataset.py::test_rolling_reduce[var-3-None-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_reindex_fill_value[2.0]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-4-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-2-2-True-2]", "xarray/tests/test_dataset.py::TestDataset::test_combine_first", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-1-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-3-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-2-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-2-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-3-None-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-1-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-False-median]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-4-1-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-1-3-True-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-False-sum]", "xarray/tests/test_dataset.py::test_rolling_construct[1-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-3-None-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-3-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-None-mean]", "xarray/tests/test_dataset.py::TestDataset::test_expand_dims_int", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-2-1-False-1]", "xarray/tests/test_dataset.py::test_trapz_datetime[np-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-4-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-4-2-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-4-1-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-2-2-False-1]", "xarray/tests/test_dataset.py::TestDataset::test_sel_drop", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-1-None-False-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_properties", "xarray/tests/test_dataset.py::TestDataset::test_rename_dims", "xarray/tests/test_dataset.py::test_rolling_reduce[max-2-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-3-1-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_align_override", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-3-None-False-2]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-True-min-False-bool_-2]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[3-3-True]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-3-3-True-2]", "xarray/tests/test_duck_array_ops.py::test_multiple_dims[sum-False-bool_]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-4-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-1-None-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_broadcast_arrays", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-4-2-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-2-None-True-2]", "xarray/tests/test_dataset.py::TestDataset::test_isel", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-2-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-False-var]", "xarray/tests/test_dataset.py::TestDataset::test_reduce_strings", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-True-sum]", "xarray/tests/test_dataarray.py::TestDataArray::test_setitem_fancy", "xarray/tests/test_dataset.py::test_rolling_reduce[max-2-2-True-1]", "xarray/tests/test_dataset.py::TestDataset::test_reindex_like_fill_value[fill_value0]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-2-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-4-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-2-1-True-1]", "xarray/tests/test_dataset.py::TestDataset::test_roll_coords", "xarray/tests/test_dataset.py::test_rolling_reduce[var-3-None-False-2]", "xarray/tests/test_dataset.py::TestDataset::test_fillna", "xarray/tests/test_dataset.py::test_rolling_reduce[min-2-3-True-2]", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-None-False-max]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-3-2-False-1]", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[3-1-True]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-1-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-2-None-True-2]", "xarray/tests/test_dataset.py::test_raise_no_warning_for_nan_in_binary_ops", "xarray/tests/test_dataarray.py::test_rolling_construct[4-False]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-1-1-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-2-2-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-2-3-False-1]", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[2-None-True]", "xarray/tests/test_dataset.py::test_coarsen[1-trim-left-True]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-4-2-False-1]", "xarray/tests/test_dataset.py::TestDataset::test_where_drop_no_indexes", "xarray/tests/test_dataset.py::TestDataset::test_dataset_ellipsis_transpose_different_ordered_vars", "xarray/tests/test_dataset.py::TestDataset::test_copy", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-2-3-True-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_shift[2-int-1]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-False-sum-False-bool_-2]", "xarray/tests/test_duck_array_ops.py::test_min_count[None-sum-False-bool_-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-4-3-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-3-None-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-2-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-False-median]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-None-sum]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-2-None-True-1]", "xarray/tests/test_duck_array_ops.py::test_min_count[None-sum-False-float32-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-2-None-False-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_to_dataframe", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-None-False-sum]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-1-1-True-2]", "xarray/tests/test_dataset.py::TestDataset::test_reduce_cumsum_test_dims", "xarray/tests/test_dataset.py::test_rolling_reduce[max-4-1-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-1-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-3-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-1-None-True-1]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-False-var-False-int-2]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-False-min-False-float-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-3-2-False-1]", "xarray/tests/test_dataarray.py::test_weakref", "xarray/tests/test_dataset.py::TestDataset::test_reduce", "xarray/tests/test_dataarray.py::TestDataArray::test_broadcast_arrays_misaligned", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-None-max]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-3-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-2-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-4-None-False-1]", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[4-2-True]", "xarray/tests/test_dataarray.py::TestDataArray::test_groupby_math_not_aligned", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-2-1-False]", "xarray/tests/test_dataarray.py::TestDataArray::test_reindex_regressions", "xarray/tests/test_duck_array_ops.py::test_reduce[x-False-max-False-bool_-2]", "xarray/tests/test_dataset.py::TestDataset::test_sortby", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[1-None-False]", "xarray/tests/test_duck_array_ops.py::test_min_count[x-sum-False-float-2]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-False-var-False-float-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-4-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-3-3-False-1]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-True-min-False-float-1]", "xarray/tests/test_dataset.py::test_differentiate[2-True]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-3-2-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-2-2-True-1]", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[2-1-False]", "xarray/tests/test_duck_array_ops.py::TestOps::test_where_type_promotion", "xarray/tests/test_duck_array_ops.py::test_reduce[None-True-max-False-float32-2]", "xarray/tests/test_dataset.py::TestDataset::test_reduce_dtypes", "xarray/tests/test_dataarray.py::TestDataArray::test_repr_multiindex_long", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[1-2-True]", "xarray/tests/test_dataset.py::TestDataset::test_dataset_number_math", "xarray/tests/test_dataset.py::test_rolling_reduce[var-1-3-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-2-1-False-2]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-False-sum-False-float-1]", "xarray/tests/test_dataset.py::TestDataset::test_virtual_variable_multiindex", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-3-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-1-2-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-1-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-1-2-False-1]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-True-min-False-int-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_groupby_multidim_apply", "xarray/tests/test_dataset.py::TestDataset::test_broadcast", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-1-2-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-2-1-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-1-None-True]", "xarray/tests/test_duck_array_ops.py::test_min_count[None-sum-False-int-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-4-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-4-3-True-2]", "xarray/tests/test_dataset.py::TestDataset::test_sel_dataarray_mindex", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[1-1-False]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-3-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-4-2-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-2-1-True-1]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-True-max-False-int-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_shift[fill_value1-float--5]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-2-3-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-3-3-False-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_assign_attrs", "xarray/tests/test_dataset.py::test_rolling_reduce[min-1-1-False-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_reduce", "xarray/tests/test_dataset.py::test_rolling_reduce[std-2-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-1-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[4-2-True]", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-None-True-sum]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-True-mean-False-int-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-3-2-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-4-None-True-2]", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[2-1-True]", "xarray/tests/test_dataarray.py::TestDataArray::test_reset_index", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-None-max]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-4-3-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-4-None-False-2]", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-None-True-max]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-4-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-4-2-False-1]", "xarray/tests/test_duck_array_ops.py::test_min_count[None-prod-False-float-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_upsample", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-3-None-True-1]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-False-mean-False-float32-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-2-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-3-2-True-2]", "xarray/tests/test_dataset.py::TestDataset::test_assign", "xarray/tests/test_dataarray.py::TestDataArray::test_reduce_out", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-2-3-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_equals_failures", "xarray/tests/test_dataset.py::TestDataset::test_expand_dims_error", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-4-2-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-4-3-True-1]", "xarray/tests/test_dataset.py::TestDataset::test_setitem_auto_align", "xarray/tests/test_duck_array_ops.py::test_min_count[x-prod-False-float32-1]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-True-max]", "xarray/tests/test_duck_array_ops.py::TestOps::test_last", "xarray/tests/test_dataset.py::TestDataset::test_dataset_diff_exception_label_str", "xarray/tests/test_duck_array_ops.py::test_reduce[None-False-sum-False-bool_-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-3-None-True]", "xarray/tests/test_dataset.py::test_no_dict", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-4-1-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-2-None-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-3-3-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-4-3-True-2]", "xarray/tests/test_duck_array_ops.py::test_min_count[x-prod-False-int-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-4-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[1-None-True]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-True-max-False-float-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-1-1-False-1]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-True-var-False-float32-1]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-True-sum-False-int-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-4-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-None-mean]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-True-min-False-float32-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_reorder_levels", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-2-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[4-None-True]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-1-1-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-1-3-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-3-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-False-var]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-True-var-False-bool_-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_sel_invalid_slice", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-4-3-True-2]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-True-max-False-bool_-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-4-None-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-2-3-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-3-1-True-1]", "xarray/tests/test_dataset.py::TestDataset::test_get_index", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-4-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-3-2-True-2]", "xarray/tests/test_dataset.py::TestDataset::test_dataset_dataset_math", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-False-median]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-3-3-True-2]", "xarray/tests/test_dataset.py::TestDataset::test_roll_no_coords", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-2-1-False-1]", "xarray/tests/test_dataset.py::test_constructor_raises_with_invalid_coords[unaligned_coords0]", "xarray/tests/test_dataarray.py::test_rolling_iter[2]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-2-None-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-4-None-False-2]", "xarray/tests/test_dataset.py::TestDataset::test_align_exact", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-2-3-False-1]", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-1-True-max]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-3-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-2-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-3-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-4-1-False-2]", "xarray/tests/test_dataset.py::TestDataset::test_to_stacked_array_to_unstacked_dataset_different_dimension", "xarray/tests/test_dataset.py::TestDataset::test_equals_failures", "xarray/tests/test_dataarray.py::TestDataArray::test_matmul", "xarray/tests/test_duck_array_ops.py::test_reduce[None-False-max-False-float-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_combine_first", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-2-2-False-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_init_value", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-1-None-std]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-True-std]", "xarray/tests/test_dataarray.py::test_raise_no_warning_for_nan_in_binary_ops", "xarray/tests/test_dataset.py::TestDataset::test_resample_ds_da_are_the_same", "xarray/tests/test_dataset.py::test_rolling_reduce[min-1-1-False-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_isel_fancy", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-2-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-3-3-False-1]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-True-min-False-float32-2]", "xarray/tests/test_dataset.py::TestDataset::test_copy_with_data", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-1-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-True-std]", "xarray/tests/test_dataset.py::TestDataset::test_reduce_no_axis", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-2-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-4-1-False-2]", "xarray/tests/test_dataset.py::TestDataset::test_getitem", "xarray/tests/test_duck_array_ops.py::test_reduce[None-True-sum-False-float32-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-3-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-3-2-True-2]", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-1-False-median]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-3-2-False-1]", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-None-True-median]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-1-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-4-None-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-4-3-False-2]", "xarray/tests/test_dataset.py::TestDataset::test_groupby", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-2-None-True-1]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-True-var-False-bool_-2]", "xarray/tests/test_dataset.py::TestDataset::test_binary_op_propagate_indexes", "xarray/tests/test_duck_array_ops.py::test_min_count[x-sum-False-bool_-1]", "xarray/tests/test_dataset.py::test_rolling_construct[1-True]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-3-None-False-2]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-False-sum-False-int-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-1-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-3-None-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-4-2-False]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-1-3-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-1-None-False-2]", "xarray/tests/test_duck_array_ops.py::test_min_count[None-sum-False-float-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-2-1-False-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_coords", "xarray/tests/test_dataarray.py::TestDataArray::test_squeeze_drop", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-4-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-4-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-False-median]", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[4-3-True]", "xarray/tests/test_dataarray.py::TestDataArray::test_stack_unstack_decreasing_coordinate", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-False-min]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-True-sum]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-2-2-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-2-2-False-2]", "xarray/tests/test_dataset.py::TestDataset::test_groupby_returns_new_type", "xarray/tests/test_dataarray.py::TestDataArray::test_align", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-True-mean]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-False-std]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-False-sum-False-float32-1]", "xarray/tests/test_dataset.py::TestDataset::test_to_and_from_dict", "xarray/tests/test_dataarray.py::TestDataArray::test_groupby_bins", "xarray/tests/test_dataset.py::test_rolling_reduce[min-4-2-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-1-None-False-2]", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-1-False-min]", "xarray/tests/test_dataset.py::TestDataset::test_reduce_coords", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-1-None-True]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-2-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-True-sum]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-3-2-False-2]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-True-var-False-float-2]", "xarray/tests/test_dataset.py::TestDataset::test_reduce_scalars", "xarray/tests/test_dataset.py::test_rolling_reduce[median-2-1-True-2]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-True-sum-False-float32-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-3-2-False-1]", "xarray/tests/test_dataset.py::TestDataset::test_slice_virtual_variable", "xarray/tests/test_dataset.py::test_rolling_reduce[std-2-3-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-2-None-True-2]", "xarray/tests/test_dataset.py::TestDataset::test_where", "xarray/tests/test_dataset.py::test_integrate[False]", "xarray/tests/test_dataarray.py::TestDataArray::test_encoding", "xarray/tests/test_dataset.py::test_rolling_reduce[min-2-None-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-4-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-3-None-True-1]", "xarray/tests/test_dataset.py::TestDataset::test_to_and_from_dict_with_nan_nat", "xarray/tests/test_duck_array_ops.py::test_isnull[array3]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-3-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-True-min]", "xarray/tests/test_duck_array_ops.py::TestOps::test_count", "xarray/tests/test_dataset.py::test_rolling_construct[4-False]", "xarray/tests/test_duck_array_ops.py::test_min_count[x-sum-False-float32-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-2-2-True-1]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-True-mean-False-float-1]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-False-mean-False-float-2]", "xarray/tests/test_dataset.py::TestDataset::test_mean_uint_dtype", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-4-None-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-4-None-False]", "xarray/tests/test_duck_array_ops.py::test_min_count[x-sum-False-int-1]", "xarray/tests/test_dataset.py::TestDataset::test_real_and_imag", "xarray/tests/test_duck_array_ops.py::TestArrayNotNullEquiv::test_equal[arr10-arr20]", "xarray/tests/test_dataarray.py::TestDataArray::test_align_override_error[darrays1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-4-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-2-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-2-1-False-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_where_string", "xarray/tests/test_dataset.py::test_dir_expected_attrs[None]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-4-None-True-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_to_and_from_empty_series", "xarray/tests/test_duck_array_ops.py::test_reduce[None-False-mean-False-int-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-1-1-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_dims", "xarray/tests/test_dataset.py::TestDataset::test_reindex_like", "xarray/tests/test_dataset.py::TestDataset::test_assign_coords", "xarray/tests/test_duck_array_ops.py::test_reduce[x-False-sum-False-bool_-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-4-1-False-2]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-False-min-False-float-1]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-False-max-False-float-2]", "xarray/tests/test_duck_array_ops.py::test_datetime_to_numeric_datetime64", "xarray/tests/test_duck_array_ops.py::test_min_count[x-prod-False-bool_-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-1-None-False]", "xarray/tests/test_dataset.py::TestDataset::test_coords_setitem_with_new_dimension", "xarray/tests/test_dataarray.py::TestDataArray::test_broadcast_equals", "xarray/tests/test_duck_array_ops.py::test_reduce[None-False-var-False-bool_-2]", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[3-2-False]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-True-max]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-1-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-1-None-True-2]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-True-min-False-float-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-3-3-False-2]", "xarray/tests/test_duck_array_ops.py::TestArrayNotNullEquiv::test_equal[arr11-arr21]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-3-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-2-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-2-1-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-3-None-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-1-3-True]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-1-2-False-1]", "xarray/tests/test_dataset.py::TestDataset::test_thin", "xarray/tests/test_dataset.py::test_rolling_reduce[min-2-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-True-median]", "xarray/tests/test_dataset.py::test_subclass_slots", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-1-None-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-4-3-False-2]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-False-var-False-int-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_get_index_size_zero", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-True-var]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-True-sum-False-float32-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-2-None-False-2]", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-1-None-sum]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-1-3-False-1]", "xarray/tests/test_duck_array_ops.py::TestOps::test_stack_type_promotion", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[1-None-True]", "xarray/tests/test_dataarray.py::test_no_dict", "xarray/tests/test_dataset.py::TestDataset::test_attr_access", "xarray/tests/test_duck_array_ops.py::test_reduce[None-True-var-False-float32-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-1-2-False-2]", "xarray/tests/test_dataset.py::TestDataset::test_rank", "xarray/tests/test_dataset.py::test_rolling_reduce[min-2-3-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-3-3-False]", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-1-None-median]", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[3-None-False]", "xarray/tests/test_dataset.py::TestDataset::test_align_fill_value[2]", "xarray/tests/test_dataset.py::test_rolling_construct[3-False]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-2-2-False]", "xarray/tests/test_dataset.py::test_coarsen_coords[1-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-2-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-1-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-1-2-True-1]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-True-min-False-int-1]", "xarray/tests/test_dataset.py::TestDataset::test_unary_ops", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-2-None-True-1]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-False-mean-False-float32-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-3-1-False-2]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-True-sum-False-float-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-4-1-True-2]", "xarray/tests/test_dataset.py::TestDataset::test_resample_by_mean_discarding_attrs", "xarray/tests/test_dataset.py::test_rolling_reduce[max-4-3-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_sortby", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-1-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-None-std]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-2-2-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-4-2-True]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-3-3-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-2-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-None-median]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-False-var-False-int-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-3-None-True-1]", "xarray/tests/test_duck_array_ops.py::TestArrayNotNullEquiv::test_types[1.0-2.0-3.0-nan]", "xarray/tests/test_dataarray.py::TestDataArray::test_stack_nonunique_consistency", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-4-1-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-1-2-False]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-4-1-False]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-True-var-False-float-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-1-1-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-2-2-True-2]", "xarray/tests/test_dataset.py::TestDataset::test_pickle", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-4-None-True-2]", "xarray/tests/test_dataset.py::TestDataset::test_setitem_both_non_unique_index", "xarray/tests/test_dataset.py::test_rolling_reduce[var-2-1-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-2-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-4-1-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-3-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-1-3-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-4-3-False-1]", "xarray/tests/test_dataset.py::TestDataset::test_dataset_math_errors", "xarray/tests/test_dataset.py::test_differentiate[1-False]", "xarray/tests/test_dataset.py::TestDataset::test_filter_by_attrs", "xarray/tests/test_dataset.py::TestDataset::test_to_stacked_array_invalid_sample_dims", "xarray/tests/test_dataset.py::TestDataset::test_reduce_keep_attrs", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords0-unaligned_coords3]", "xarray/tests/test_dataset.py::TestDataset::test_delitem", "xarray/tests/test_duck_array_ops.py::test_min_count[None-prod-False-float32-1]", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords0-unaligned_coords4]", "xarray/tests/test_dataarray.py::TestDataArray::test_setattr_raises", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[2-None-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-1-3-True-2]", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[1-None-False]", "xarray/tests/test_duck_array_ops.py::TestArrayNotNullEquiv::test_types[foo-bar-baz-None]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[2-1-False]", "xarray/tests/test_dataarray.py::TestDataArray::test_reindex_method", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-3-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-None-std]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-3-2-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-2-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-4-2-False-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_groupby_sum", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-False-var]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-2-3-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-1-3-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-1-1-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-4-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-3-1-True-1]", "xarray/tests/test_dataset.py::TestDataset::test_update", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-False-sum]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-4-2-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-2-None-True]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-1-2-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-2-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-4-1-False-1]", "xarray/tests/test_dataset.py::TestDataset::test_where_drop", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-1-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-4-1-False-1]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-True-mean-False-int-1]", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-None-None-min]", "xarray/tests/test_dataarray.py::TestDataArray::test_constructor_invalid", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-2-3-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-1-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-1-1-False-2]", "xarray/tests/test_dataarray.py::test_rolling_count_correct", "xarray/tests/test_dataset.py::TestDataset::test_expand_dims_kwargs_python36plus", "xarray/tests/test_duck_array_ops.py::test_min_count[x-prod-False-bool_-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-3-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-3-2-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-1-1-True]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-1-None-True-2]", "xarray/tests/test_dataset.py::TestDataset::test_groupby_iter", "xarray/tests/test_dataset.py::test_rolling_reduce[min-1-1-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-3-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-None-min]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-4-1-True-2]", "xarray/tests/test_dataset.py::TestDataset::test_dataset_diff_n1_label", "xarray/tests/test_dataarray.py::TestDataArray::test_sizes", "xarray/tests/test_dataset.py::test_isin_dataset", "xarray/tests/test_dataset.py::test_rolling_reduce[median-4-3-False-1]", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords1-unaligned_coords7]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[2-2-False]", "xarray/tests/test_dataarray.py::TestDataArray::test_broadcast_like", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-4-2-False-2]", "xarray/tests/test_dataset.py::TestDataset::test_roll_multidim", "xarray/tests/test_dataarray.py::TestDataArray::test_real_and_imag", "xarray/tests/test_dataset.py::test_rolling_reduce[max-2-1-False-1]", "xarray/tests/test_dataset.py::TestDataset::test_tail", "xarray/tests/test_dataset.py::test_rolling_reduce[median-2-1-False-1]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-True-min-False-int-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-1-None-True-2]", "xarray/tests/test_dataarray.py::test_rolling_construct[2-False]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-1-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-3-1-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-2-3-True]", "xarray/tests/test_dataarray.py::TestDataArray::test_rank", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-True-sum]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-False-var-False-float32-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-1-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-1-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-1-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-4-3-False-1]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-False-min-False-float32-2]", "xarray/tests/test_dataset.py::TestDataset::test_isel_drop", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-3-None-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-3-2-False-2]", "xarray/tests/test_dataset.py::test_error_message_on_set_supplied", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-None-max]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-1-None-False-1]", "xarray/tests/test_duck_array_ops.py::test_min_count_dataset[sum]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-1-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-4-2-False-1]", "xarray/tests/test_duck_array_ops.py::test_min_count[None-sum-False-float-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-2-1-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_to_dataset_retains_keys", "xarray/tests/test_dataset.py::test_rolling_reduce[var-4-3-True-2]", "xarray/tests/test_dataset.py::TestDataset::test_reset_index", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-3-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-1-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-2-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[2-1-True]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-3-3-False-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_broadcast_arrays_exclude", "xarray/tests/test_duck_array_ops.py::test_reduce[x-True-mean-False-int-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-4-1-True-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_setitem", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-1-2-False-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_repr", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-2-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-None-sum]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-3-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-3-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-2-None-False-2]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-True-mean-False-float-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-1-2-False-2]", "xarray/tests/test_dataarray.py::test_rolling_construct[2-True]", "xarray/tests/test_dataarray.py::TestDataArray::test_binary_op_propagate_indexes", "xarray/tests/test_duck_array_ops.py::test_reduce[None-True-mean-False-float-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_virtual_time_components", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-1-3-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_to_and_from_dict_with_nan_nat", "xarray/tests/test_dataset.py::test_rolling_reduce[max-1-2-False-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_squeeze", "xarray/tests/test_dataset.py::TestDataset::test_reduce_only_one_axis", "xarray/tests/test_duck_array_ops.py::test_reduce[None-True-max-False-bool_-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-3-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[1-3-True]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-3-None-True-1]", "xarray/tests/test_dataset.py::TestDataset::test_modify_inplace", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-1-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-1-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-2-2-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-2-None-True-1]", "xarray/tests/test_dataset.py::TestDataset::test_attrs", "xarray/tests/test_dataarray.py::TestDataArray::test_groupby_count", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-4-2-False]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-4-None-True-1]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-True-max-False-bool_-1]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-False-max-False-float-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-2-3-False-2]", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[3-None-True]", "xarray/tests/test_dataarray.py::TestDataArray::test_head", "xarray/tests/test_duck_array_ops.py::test_reduce[x-False-var-False-bool_-2]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-False-sum-False-float32-1]", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-1-None-mean]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-1-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-2-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-2-2-True-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_shift[fill_value1-float-0]", "xarray/tests/test_dataarray.py::TestDataArray::test_isel_types", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[2-3-True]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-2-None-True]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-2-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-2-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-False-var]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-True-mean-False-float32-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-1-1-True-2]", "xarray/tests/test_dataset.py::TestDataset::test_isel_expand_dims_roundtrip", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-2-None-False]", "xarray/tests/test_dataset.py::TestDataset::test_reduce_non_numeric", "xarray/tests/test_dataset.py::TestDataset::test_repr_period_index", "xarray/tests/test_dataarray.py::TestDataArray::test_to_masked_array", "xarray/tests/test_dataset.py::test_rolling_reduce[std-3-1-True-1]", "xarray/tests/test_dataset.py::TestDataset::test_swap_dims", "xarray/tests/test_duck_array_ops.py::test_reduce[x-True-min-False-float32-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-1-3-False-1]", "xarray/tests/test_dataset.py::TestDataset::test_dataset_diff_n1_simple", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-3-3-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-3-None-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_reindex_fill_value[2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-1-None-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-4-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-2-None-False-1]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-True-var-False-bool_-2]", "xarray/tests/test_dataset.py::TestDataset::test_expand_dims_existing_scalar_coord", "xarray/tests/test_dataset.py::test_rolling_reduce[median-2-None-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-3-1-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-1-3-True-2]", "xarray/tests/test_duck_array_ops.py::test_min_count[None-sum-False-int-1]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-True-var-False-float32-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_coord_coords", "xarray/tests/test_dataset.py::TestDataset::test_merge_multiindex_level", "xarray/tests/test_dataset.py::test_rolling_reduce[max-4-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-2-3-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-3-None-False-1]", "xarray/tests/test_dataset.py::TestDataset::test_shift[2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-1-1-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-4-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-3-1-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_upsample_nd", "xarray/tests/test_dataset.py::test_rolling_reduce[max-2-3-True-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_getitem", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-1-None-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-1-3-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-2-None-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-4-3-False]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-3-3-False]", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords1-unaligned_coords0]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-3-None-False-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_transpose", "xarray/tests/test_dataset.py::TestDataset::test_head", "xarray/tests/test_dataset.py::test_rolling_reduce[median-4-2-True-1]", "xarray/tests/test_duck_array_ops.py::test_multiple_dims[prod-False-bool_]", "xarray/tests/test_dataset.py::test_rolling_properties[1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-3-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-1-2-True-2]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-True-var-False-int-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_to_dict_with_numpy_attrs", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-3-1-False-1]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-False-min-False-float-2]", "xarray/tests/test_dataset.py::TestDataset::test_assign_attrs", "xarray/tests/test_duck_array_ops.py::test_min_count[x-prod-False-int-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-2-2-True]", "xarray/tests/test_dataset.py::TestDataset::test_coords_modify", "xarray/tests/test_dataset.py::TestDataset::test_resample_by_last_discarding_attrs", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-None-mean]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-1-1-True-1]", "xarray/tests/test_dataset.py::TestDataset::test_asarray", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-3-3-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-3-2-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-1-None-False-1]", "xarray/tests/test_dataset.py::TestDataset::test_dataset_transpose", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-4-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-2-3-True-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_reset_coords", "xarray/tests/test_dataarray.py::TestDataArray::test_groupby_apply_center", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-4-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-3-1-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-2-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-3-None-False-1]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-False-min-False-float32-1]", "xarray/tests/test_dataset.py::TestDataset::test_groupby_math", "xarray/tests/test_dataset.py::test_rolling_reduce[var-2-2-False-2]", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[4-1-False]", "xarray/tests/test_duck_array_ops.py::test_reduce[None-False-sum-False-float-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_broadcast_arrays_nocopy", "xarray/tests/test_dataarray.py::TestDataArray::test_inplace_math_automatic_alignment", "xarray/tests/test_backends.py::TestCommon::test_robust_getitem", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords1-unaligned_coords8]", "xarray/tests/test_dataarray.py::TestDataArray::test_swap_dims", "xarray/tests/test_dataarray.py::TestDataArray::test_loc_assign", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-1-3-False]", "xarray/tests/test_dataarray.py::TestDataArray::test_expand_dims_error", "xarray/tests/test_duck_array_ops.py::test_reduce[x-False-sum-False-int-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-2-None-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-3-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-1-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-1-1-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_align_without_indexes_errors", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-1-None-min]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-2-1-False]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-2-1-False-2]", "xarray/tests/test_dataset.py::test_coarsen[1-pad-right-False]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-True-mean]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-None-sum]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-2-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-2-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-4-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-True-std]", "xarray/tests/test_duck_array_ops.py::test_reduce[x-False-var-False-bool_-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-3-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-1-None-True-1]"], "FAIL2PASS": ["xarray/tests/test_dataarray.py::TestDataArray::test_sel_dataarray", "xarray/tests/test_duck_array_ops.py::test_argmin_max[x-True-max-False-False-str-1]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[x-True-max-False-False-int-1]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[x-False-min-False-False-float32-2]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[x-True-min-False-False-float32-1]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[x-True-min-False-True-bool_-2]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[y-True-max-False-False-str-2]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[y-True-min-False-True-bool_-2]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[y-False-min-False-False-bool_-2]", "xarray/tests/test_dataset.py::TestDataset::test_expand_dims_mixed_int_and_coords", "xarray/tests/test_duck_array_ops.py::test_argmin_max[x-False-min-False-False-float-2]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[x-False-max-False-False-float-1]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[x-True-min-False-False-bool_-1]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[x-True-min-False-False-bool_-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_to_pandas", "xarray/tests/test_duck_array_ops.py::test_argmin_max[y-False-max-False-False-float32-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_to_and_from_dict", "xarray/tests/test_duck_array_ops.py::test_argmin_max[x-False-min-False-False-int-2]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[x-True-min-False-False-int-2]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[x-True-max-False-False-float-2]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[x-True-max-False-True-str-1]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[y-False-max-False-False-bool_-2]", "xarray/tests/test_dataset.py::TestDataset::test_isel_dataarray", "xarray/tests/test_duck_array_ops.py::test_argmin_max[x-True-max-False-False-bool_-2]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[y-True-min-False-False-float32-2]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[y-True-min-False-True-str-2]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[y-True-max-False-False-float32-2]", "xarray/tests/test_dataset.py::TestDataset::test_constructor_compat", "xarray/tests/test_dataset.py::TestDataset::test_dataset_math_auto_align", "xarray/tests/test_duck_array_ops.py::test_argmin_max[x-True-min-False-True-str-2]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[y-False-min-False-False-float-2]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[y-True-min-False-False-bool_-2]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[y-True-max-False-False-float-2]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[x-False-max-False-False-int-2]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[x-True-max-False-False-float32-2]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[y-True-max-False-True-str-2]", "xarray/tests/test_dataset.py::TestDataset::test_isel_fancy", "xarray/tests/test_duck_array_ops.py::test_argmin_max[x-False-max-False-False-str-1]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[x-True-max-False-True-bool_-1]", "xarray/tests/test_dataset.py::TestDataset::test_drop_index_labels", "xarray/tests/test_duck_array_ops.py::test_argmin_max[y-False-min-False-False-float32-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_drop_coordinates", "xarray/tests/test_duck_array_ops.py::test_argmin_max[x-False-max-False-False-str-2]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[x-False-min-False-False-str-2]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[y-False-min-False-False-str-2]", "xarray/tests/test_dataset.py::TestDataset::test_coords_set", "xarray/tests/test_dataset.py::TestDataset::test_sel_dataarray", "xarray/tests/test_dataarray.py::TestDataArray::test_drop_index_labels", "xarray/tests/test_duck_array_ops.py::test_argmin_max[x-True-max-False-True-bool_-2]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[y-True-min-False-False-float-2]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[y-False-min-False-False-int-2]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[y-False-max-False-False-int-2]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[x-False-min-False-False-int-1]", "xarray/tests/test_dataset.py::TestDataset::test_info", "xarray/tests/test_duck_array_ops.py::test_argmin_max[y-True-max-False-False-int-2]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[x-True-max-False-False-bool_-1]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[x-True-min-False-False-str-2]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[y-True-max-False-True-bool_-2]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[x-True-min-False-False-float32-2]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[x-False-min-False-False-bool_-1]", "xarray/tests/test_dataset.py::TestDataset::test_drop_variables", "xarray/tests/test_duck_array_ops.py::test_argmin_max[x-True-min-False-True-str-1]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[x-True-max-False-False-float-1]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[x-False-max-False-False-float32-1]", "xarray/tests/test_dataset.py::TestDataset::test_setitem_with_coords", "xarray/tests/test_duck_array_ops.py::test_argmin_max[x-True-min-False-False-float-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_expand_dims_with_greater_dim_size", "xarray/tests/test_duck_array_ops.py::test_argmin_max[x-True-max-False-True-str-2]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[x-True-max-False-False-int-2]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[y-True-max-False-False-bool_-2]", "xarray/tests/test_dataset.py::TestDataset::test_drop_labels_by_keyword", "xarray/tests/test_duck_array_ops.py::test_argmin_max[x-False-min-False-False-str-1]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[x-False-min-False-False-float-1]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[y-True-min-False-False-str-2]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[x-True-min-False-False-int-1]", "xarray/tests/test_dataset.py::TestDataset::test_sel_fancy", "xarray/tests/test_dataarray.py::TestDataArray::test_to_and_from_series", "xarray/tests/test_duck_array_ops.py::test_argmin_max[x-False-min-False-False-bool_-2]", "xarray/tests/test_dataset.py::TestDataset::test_apply", "xarray/tests/test_duck_array_ops.py::test_argmin_max[x-False-min-False-False-float32-1]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[x-False-max-False-False-bool_-1]", "xarray/tests/test_dataset.py::TestDataset::test_drop_dims", "xarray/tests/test_duck_array_ops.py::test_argmin_max[x-True-min-False-False-float-2]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[x-False-max-False-False-float32-2]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[x-False-max-False-False-float-2]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[y-True-min-False-False-int-2]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[x-True-max-False-False-float32-1]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[y-False-max-False-False-str-2]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[x-False-max-False-False-bool_-2]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[x-True-min-False-False-str-1]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[x-True-min-False-True-bool_-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_stack_unstack", "xarray/tests/test_duck_array_ops.py::test_argmin_max[y-False-max-False-False-float-2]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[x-True-max-False-False-str-2]", "xarray/tests/test_duck_array_ops.py::test_argmin_max[x-False-max-False-False-int-1]"], "mask_doc_diff": [{"path": "doc/data-structures.rst", "old_path": "a/doc/data-structures.rst", "new_path": "b/doc/data-structures.rst", "metadata": "diff --git a/doc/data-structures.rst b/doc/data-structures.rst\nindex d5567f48..93cdc7e9 100644\n--- a/doc/data-structures.rst\n+++ b/doc/data-structures.rst\n@@ -393,14 +393,14 @@ methods (like pandas) for transforming datasets into new objects.\n \n For removing variables, you can select and drop an explicit list of\n variables by indexing with a list of names or using the\n-:py:meth:`~xarray.Dataset.drop` methods to return a new ``Dataset``. These\n+:py:meth:`~xarray.Dataset.drop_vars` methods to return a new ``Dataset``. These\n operations keep around coordinates:\n \n .. ipython:: python\n \n ds[['temperature']]\n ds[['temperature', 'temperature_double']]\n- ds.drop('temperature')\n+ ds.drop_vars('temperature')\n \n To remove a dimension, you can use :py:meth:`~xarray.Dataset.drop_dims` method.\n Any variables using that dimension are dropped:\n"}, {"path": "doc/indexing.rst", "old_path": "a/doc/indexing.rst", "new_path": "b/doc/indexing.rst", "metadata": "diff --git a/doc/indexing.rst b/doc/indexing.rst\nindex 9ee8f1dd..ace96068 100644\n--- a/doc/indexing.rst\n+++ b/doc/indexing.rst\n@@ -232,14 +232,14 @@ Using indexing to *assign* values to a subset of dataset (e.g.,\n Dropping labels and dimensions\n ------------------------------\n \n-The :py:meth:`~xarray.Dataset.drop` method returns a new object with the listed\n+The :py:meth:`~xarray.Dataset.drop_sel` method returns a new object with the listed\n index labels along a dimension dropped:\n \n .. ipython:: python\n \n- ds.drop(space=['IN', 'IL'])\n+ ds.drop_sel(space=['IN', 'IL'])\n \n-``drop`` is both a ``Dataset`` and ``DataArray`` method.\n+``drop_sel`` is both a ``Dataset`` and ``DataArray`` method.\n \n Use :py:meth:`~xarray.Dataset.drop_dims` to drop a full dimension from a Dataset.\n Any variables with these dimensions are also dropped:\n"}, {"path": "doc/whats-new.rst", "old_path": "a/doc/whats-new.rst", "new_path": "b/doc/whats-new.rst", "metadata": "diff --git a/doc/whats-new.rst b/doc/whats-new.rst\nindex dcaab011..aed560ac 100644\n--- a/doc/whats-new.rst\n+++ b/doc/whats-new.rst\n@@ -38,6 +38,11 @@ Breaking changes\n \n New Features\n ~~~~~~~~~~~~\n+- :py:meth:`Dataset.drop_sel` & :py:meth:`DataArray.drop_sel` have been added for dropping labels.\n+ :py:meth:`Dataset.drop_vars` & :py:meth:`DataArray.drop_vars` have been added for \n+ dropping variables (including coordinates). The existing ``drop`` methods remain as a backward compatible \n+ option for dropping either lables or variables, but using the more specific methods is encouraged.\n+\n - :py:meth:`Dataset.transpose` and :py:meth:`DataArray.transpose` now support an ellipsis (`...`)\n to represent all 'other' dimensions. For example, to move one dimension to the front,\n use `.transpose('x', ...)`. (:pull:`3421`)\n@@ -3752,6 +3757,7 @@ Enhancements\n explicitly listed variables or index labels:\n \n .. ipython:: python\n+ :okwarning:\n \n # drop variables\n ds = xray.Dataset({'x': 0, 'y': 1})\n"}], "augmentations": {"header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [{"type": "field", "name": "PendingDeprecationWarning"}]}, "problem_statement": "diff --git a/doc/data-structures.rst b/doc/data-structures.rst\nindex d5567f48..93cdc7e9 100644\n--- a/doc/data-structures.rst\n+++ b/doc/data-structures.rst\n@@ -393,14 +393,14 @@ methods (like pandas) for transforming datasets into new objects.\n \n For removing variables, you can select and drop an explicit list of\n variables by indexing with a list of names or using the\n-:py:meth:`~xarray.Dataset.drop` methods to return a new ``Dataset``. These\n+:py:meth:`~xarray.Dataset.drop_vars` methods to return a new ``Dataset``. These\n operations keep around coordinates:\n \n .. ipython:: python\n \n ds[['temperature']]\n ds[['temperature', 'temperature_double']]\n- ds.drop('temperature')\n+ ds.drop_vars('temperature')\n \n To remove a dimension, you can use :py:meth:`~xarray.Dataset.drop_dims` method.\n Any variables using that dimension are dropped:\n\ndiff --git a/doc/indexing.rst b/doc/indexing.rst\nindex 9ee8f1dd..ace96068 100644\n--- a/doc/indexing.rst\n+++ b/doc/indexing.rst\n@@ -232,14 +232,14 @@ Using indexing to *assign* values to a subset of dataset (e.g.,\n Dropping labels and dimensions\n ------------------------------\n \n-The :py:meth:`~xarray.Dataset.drop` method returns a new object with the listed\n+The :py:meth:`~xarray.Dataset.drop_sel` method returns a new object with the listed\n index labels along a dimension dropped:\n \n .. ipython:: python\n \n- ds.drop(space=['IN', 'IL'])\n+ ds.drop_sel(space=['IN', 'IL'])\n \n-``drop`` is both a ``Dataset`` and ``DataArray`` method.\n+``drop_sel`` is both a ``Dataset`` and ``DataArray`` method.\n \n Use :py:meth:`~xarray.Dataset.drop_dims` to drop a full dimension from a Dataset.\n Any variables with these dimensions are also dropped:\n\ndiff --git a/doc/whats-new.rst b/doc/whats-new.rst\nindex dcaab011..aed560ac 100644\n--- a/doc/whats-new.rst\n+++ b/doc/whats-new.rst\n@@ -38,6 +38,11 @@ Breaking changes\n \n New Features\n ~~~~~~~~~~~~\n+- :py:meth:`Dataset.drop_sel` & :py:meth:`DataArray.drop_sel` have been added for dropping labels.\n+ :py:meth:`Dataset.drop_vars` & :py:meth:`DataArray.drop_vars` have been added for \n+ dropping variables (including coordinates). The existing ``drop`` methods remain as a backward compatible \n+ option for dropping either lables or variables, but using the more specific methods is encouraged.\n+\n - :py:meth:`Dataset.transpose` and :py:meth:`DataArray.transpose` now support an ellipsis (`...`)\n to represent all 'other' dimensions. For example, to move one dimension to the front,\n use `.transpose('x', ...)`. (:pull:`3421`)\n@@ -3752,6 +3757,7 @@ Enhancements\n explicitly listed variables or index labels:\n \n .. ipython:: python\n+ :okwarning:\n \n # drop variables\n ds = xray.Dataset({'x': 0, 'y': 1})\n\nIf completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:\n[{'type': 'field', 'name': 'PendingDeprecationWarning'}]\n"} {"repo": "pydata/xarray", "instance_id": "pydata__xarray-3421", "html_url": "https://github.com/pydata/xarray/pull/3421", "feature_patch": "diff --git a/doc/reshaping.rst b/doc/reshaping.rst\nindex 51202f9be41..455a24f9216 100644\n--- a/doc/reshaping.rst\n+++ b/doc/reshaping.rst\n@@ -18,12 +18,14 @@ Reordering dimensions\n ---------------------\n \n To reorder dimensions on a :py:class:`~xarray.DataArray` or across all variables\n-on a :py:class:`~xarray.Dataset`, use :py:meth:`~xarray.DataArray.transpose`:\n+on a :py:class:`~xarray.Dataset`, use :py:meth:`~xarray.DataArray.transpose`. An \n+ellipsis (`...`) can be use to represent all other dimensions:\n \n .. ipython:: python\n \n ds = xr.Dataset({'foo': (('x', 'y', 'z'), [[[42]]]), 'bar': (('y', 'z'), [[24]])})\n ds.transpose('y', 'z', 'x')\n+ ds.transpose(..., 'x') # equivalent\n ds.transpose() # reverses all dimensions\n \n Expand and squeeze dimensions\ndiff --git a/doc/whats-new.rst b/doc/whats-new.rst\nindex dea110b5e46..cced7276ff3 100644\n--- a/doc/whats-new.rst\n+++ b/doc/whats-new.rst\n@@ -25,6 +25,10 @@ Breaking changes\n \n New Features\n ~~~~~~~~~~~~\n+- :py:meth:`Dataset.transpose` and :py:meth:`DataArray.transpose` now support an ellipsis (`...`)\n+ to represent all 'other' dimensions. For example, to move one dimension to the front,\n+ use `.transpose('x', ...)`. (:pull:`3421`)\n+ By `Maximilian Roos `_\n - Changed `xr.ALL_DIMS` to equal python's `Ellipsis` (`...`), and changed internal usages to use\n `...` directly. As before, you can use this to instruct a `groupby` operation\n to reduce over all dimensions. While we have no plans to remove `xr.ALL_DIMS`, we suggest\ndiff --git a/setup.cfg b/setup.cfg\nindex eee8b2477b2..fec2ca6bbe4 100644\n--- a/setup.cfg\n+++ b/setup.cfg\n@@ -117,4 +117,7 @@ tag_prefix = v\n parentdir_prefix = xarray-\n \n [aliases]\n-test = pytest\n\\ No newline at end of file\n+test = pytest\n+\n+[pytest-watch]\n+nobeep = True\n\\ No newline at end of file\ndiff --git a/xarray/core/dataarray.py b/xarray/core/dataarray.py\nindex 5fccb9236e8..33dcad13204 100644\n--- a/xarray/core/dataarray.py\n+++ b/xarray/core/dataarray.py\n@@ -1863,12 +1863,7 @@ def transpose(self, *dims: Hashable, transpose_coords: bool = None) -> \"DataArra\n Dataset.transpose\n \"\"\"\n if dims:\n- if set(dims) ^ set(self.dims):\n- raise ValueError(\n- \"arguments to transpose (%s) must be \"\n- \"permuted array dimensions (%s)\" % (dims, tuple(self.dims))\n- )\n-\n+ dims = tuple(utils.infix_dims(dims, self.dims))\n variable = self.variable.transpose(*dims)\n if transpose_coords:\n coords: Dict[Hashable, Variable] = {}\ndiff --git a/xarray/core/dataset.py b/xarray/core/dataset.py\nindex 55ac0bc6135..2a0464515c6 100644\n--- a/xarray/core/dataset.py\n+++ b/xarray/core/dataset.py\n@@ -3712,14 +3712,14 @@ def transpose(self, *dims: Hashable) -> \"Dataset\":\n DataArray.transpose\n \"\"\"\n if dims:\n- if set(dims) ^ set(self.dims):\n+ if set(dims) ^ set(self.dims) and ... not in dims:\n raise ValueError(\n \"arguments to transpose (%s) must be \"\n \"permuted dataset dimensions (%s)\" % (dims, tuple(self.dims))\n )\n ds = self.copy()\n for name, var in self._variables.items():\n- var_dims = tuple(dim for dim in dims if dim in var.dims)\n+ var_dims = tuple(dim for dim in dims if dim in (var.dims + (...,)))\n ds._variables[name] = var.transpose(*var_dims)\n return ds\n \ndiff --git a/xarray/core/utils.py b/xarray/core/utils.py\nindex 6befe0b5efc..492c595a887 100644\n--- a/xarray/core/utils.py\n+++ b/xarray/core/utils.py\n@@ -10,6 +10,7 @@\n AbstractSet,\n Any,\n Callable,\n+ Collection,\n Container,\n Dict,\n Hashable,\n@@ -660,6 +661,30 @@ def __len__(self) -> int:\n return len(self._data) - num_hidden\n \n \n+def infix_dims(dims_supplied: Collection, dims_all: Collection) -> Iterator:\n+ \"\"\"\n+ Resolves a supplied list containing an ellispsis representing other items, to\n+ a generator with the 'realized' list of all items\n+ \"\"\"\n+ if ... in dims_supplied:\n+ if len(set(dims_all)) != len(dims_all):\n+ raise ValueError(\"Cannot use ellipsis with repeated dims\")\n+ if len([d for d in dims_supplied if d == ...]) > 1:\n+ raise ValueError(\"More than one ellipsis supplied\")\n+ other_dims = [d for d in dims_all if d not in dims_supplied]\n+ for d in dims_supplied:\n+ if d == ...:\n+ yield from other_dims\n+ else:\n+ yield d\n+ else:\n+ if set(dims_supplied) ^ set(dims_all):\n+ raise ValueError(\n+ f\"{dims_supplied} must be a permuted list of {dims_all}, unless `...` is included\"\n+ )\n+ yield from dims_supplied\n+\n+\n def get_temp_dimname(dims: Container[Hashable], new_dim: Hashable) -> Hashable:\n \"\"\" Get an new dimension name based on new_dim, that is not used in dims.\n If the same name exists, we add an underscore(s) in the head.\ndiff --git a/xarray/core/variable.py b/xarray/core/variable.py\nindex 93ad1eafb97..7d03fd58d39 100644\n--- a/xarray/core/variable.py\n+++ b/xarray/core/variable.py\n@@ -25,6 +25,7 @@\n OrderedSet,\n decode_numpy_dict_values,\n either_dict_or_kwargs,\n+ infix_dims,\n ensure_us_time_resolution,\n )\n \n@@ -1228,6 +1229,7 @@ def transpose(self, *dims) -> \"Variable\":\n \"\"\"\n if len(dims) == 0:\n dims = self.dims[::-1]\n+ dims = tuple(infix_dims(dims, self.dims))\n axes = self.get_axis_num(dims)\n if len(dims) < 2: # no need to transpose if only one dimension\n return self.copy(deep=False)\n", "test_patch": "diff --git a/xarray/tests/__init__.py b/xarray/tests/__init__.py\nindex 88476e5e730..f85a33f7a3c 100644\n--- a/xarray/tests/__init__.py\n+++ b/xarray/tests/__init__.py\n@@ -158,18 +158,21 @@ def source_ndarray(array):\n \n \n def assert_equal(a, b):\n+ __tracebackhide__ = True\n xarray.testing.assert_equal(a, b)\n xarray.testing._assert_internal_invariants(a)\n xarray.testing._assert_internal_invariants(b)\n \n \n def assert_identical(a, b):\n+ __tracebackhide__ = True\n xarray.testing.assert_identical(a, b)\n xarray.testing._assert_internal_invariants(a)\n xarray.testing._assert_internal_invariants(b)\n \n \n def assert_allclose(a, b, **kwargs):\n+ __tracebackhide__ = True\n xarray.testing.assert_allclose(a, b, **kwargs)\n xarray.testing._assert_internal_invariants(a)\n xarray.testing._assert_internal_invariants(b)\ndiff --git a/xarray/tests/test_dataarray.py b/xarray/tests/test_dataarray.py\nindex 101bb44660c..ad474d533be 100644\n--- a/xarray/tests/test_dataarray.py\n+++ b/xarray/tests/test_dataarray.py\n@@ -2068,6 +2068,10 @@ def test_transpose(self):\n )\n assert_equal(expected, actual)\n \n+ # same as previous but with ellipsis\n+ actual = da.transpose(\"z\", ..., \"x\", transpose_coords=True)\n+ assert_equal(expected, actual)\n+\n with pytest.raises(ValueError):\n da.transpose(\"x\", \"y\")\n \ndiff --git a/xarray/tests/test_dataset.py b/xarray/tests/test_dataset.py\nindex b3ffdf68e3f..647eb733adb 100644\n--- a/xarray/tests/test_dataset.py\n+++ b/xarray/tests/test_dataset.py\n@@ -4675,6 +4675,10 @@ def test_dataset_transpose(self):\n )\n assert_identical(expected, actual)\n \n+ actual = ds.transpose(...)\n+ expected = ds\n+ assert_identical(expected, actual)\n+\n actual = ds.transpose(\"x\", \"y\")\n expected = ds.apply(lambda x: x.transpose(\"x\", \"y\", transpose_coords=True))\n assert_identical(expected, actual)\n@@ -4690,13 +4694,32 @@ def test_dataset_transpose(self):\n expected_dims = tuple(d for d in new_order if d in ds[k].dims)\n assert actual[k].dims == expected_dims\n \n- with raises_regex(ValueError, \"arguments to transpose\"):\n+ # same as above but with ellipsis\n+ new_order = (\"dim2\", \"dim3\", \"dim1\", \"time\")\n+ actual = ds.transpose(\"dim2\", \"dim3\", ...)\n+ for k in ds.variables:\n+ expected_dims = tuple(d for d in new_order if d in ds[k].dims)\n+ assert actual[k].dims == expected_dims\n+\n+ with raises_regex(ValueError, \"permuted\"):\n ds.transpose(\"dim1\", \"dim2\", \"dim3\")\n- with raises_regex(ValueError, \"arguments to transpose\"):\n+ with raises_regex(ValueError, \"permuted\"):\n ds.transpose(\"dim1\", \"dim2\", \"dim3\", \"time\", \"extra_dim\")\n \n assert \"T\" not in dir(ds)\n \n+ def test_dataset_ellipsis_transpose_different_ordered_vars(self):\n+ # https://github.com/pydata/xarray/issues/1081#issuecomment-544350457\n+ ds = Dataset(\n+ dict(\n+ a=((\"w\", \"x\", \"y\", \"z\"), np.ones((2, 3, 4, 5))),\n+ b=((\"x\", \"w\", \"y\", \"z\"), np.zeros((3, 2, 4, 5))),\n+ )\n+ )\n+ result = ds.transpose(..., \"z\", \"y\")\n+ assert list(result[\"a\"].dims) == list(\"wxzy\")\n+ assert list(result[\"b\"].dims) == list(\"xwzy\")\n+\n def test_dataset_retains_period_index_on_transpose(self):\n \n ds = create_test_data()\ndiff --git a/xarray/tests/test_utils.py b/xarray/tests/test_utils.py\nindex c36e8a1775d..5bb9deaf240 100644\n--- a/xarray/tests/test_utils.py\n+++ b/xarray/tests/test_utils.py\n@@ -275,3 +275,27 @@ def test_either_dict_or_kwargs():\n \n with pytest.raises(ValueError, match=r\"foo\"):\n result = either_dict_or_kwargs(dict(a=1), dict(a=1), \"foo\")\n+\n+\n+@pytest.mark.parametrize(\n+ [\"supplied\", \"all_\", \"expected\"],\n+ [\n+ (list(\"abc\"), list(\"abc\"), list(\"abc\")),\n+ ([\"a\", ..., \"c\"], list(\"abc\"), list(\"abc\")),\n+ ([\"a\", ...], list(\"abc\"), list(\"abc\")),\n+ ([\"c\", ...], list(\"abc\"), list(\"cab\")),\n+ ([..., \"b\"], list(\"abc\"), list(\"acb\")),\n+ ([...], list(\"abc\"), list(\"abc\")),\n+ ],\n+)\n+def test_infix_dims(supplied, all_, expected):\n+ result = list(utils.infix_dims(supplied, all_))\n+ assert result == expected\n+\n+\n+@pytest.mark.parametrize(\n+ [\"supplied\", \"all_\"], [([..., ...], list(\"abc\")), ([...], list(\"aac\"))]\n+)\n+def test_infix_dims_errors(supplied, all_):\n+ with pytest.raises(ValueError):\n+ list(utils.infix_dims(supplied, all_))\ndiff --git a/xarray/tests/test_variable.py b/xarray/tests/test_variable.py\nindex 78723eda013..528027ed149 100644\n--- a/xarray/tests/test_variable.py\n+++ b/xarray/tests/test_variable.py\n@@ -1280,6 +1280,9 @@ def test_transpose(self):\n w2 = Variable([\"d\", \"b\", \"c\", \"a\"], np.einsum(\"abcd->dbca\", x))\n assert w2.shape == (5, 3, 4, 2)\n assert_identical(w2, w.transpose(\"d\", \"b\", \"c\", \"a\"))\n+ assert_identical(w2, w.transpose(\"d\", ..., \"a\"))\n+ assert_identical(w2, w.transpose(\"d\", \"b\", \"c\", ...))\n+ assert_identical(w2, w.transpose(..., \"b\", \"c\", \"a\"))\n assert_identical(w, w2.transpose(\"a\", \"b\", \"c\", \"d\"))\n w3 = Variable([\"b\", \"c\", \"d\", \"a\"], np.einsum(\"abcd->bcda\", x))\n assert_identical(w, w3.transpose(\"a\", \"b\", \"c\", \"d\"))\n", "doc_changes": [{"path": "doc/reshaping.rst", "old_path": "a/doc/reshaping.rst", "new_path": "b/doc/reshaping.rst", "metadata": "diff --git a/doc/reshaping.rst b/doc/reshaping.rst\nindex 51202f9be41..455a24f9216 100644\n--- a/doc/reshaping.rst\n+++ b/doc/reshaping.rst\n@@ -18,12 +18,14 @@ Reordering dimensions\n ---------------------\n \n To reorder dimensions on a :py:class:`~xarray.DataArray` or across all variables\n-on a :py:class:`~xarray.Dataset`, use :py:meth:`~xarray.DataArray.transpose`:\n+on a :py:class:`~xarray.Dataset`, use :py:meth:`~xarray.DataArray.transpose`. An \n+ellipsis (`...`) can be use to represent all other dimensions:\n \n .. ipython:: python\n \n ds = xr.Dataset({'foo': (('x', 'y', 'z'), [[[42]]]), 'bar': (('y', 'z'), [[24]])})\n ds.transpose('y', 'z', 'x')\n+ ds.transpose(..., 'x') # equivalent\n ds.transpose() # reverses all dimensions\n \n Expand and squeeze dimensions\n"}, {"path": "doc/whats-new.rst", "old_path": "a/doc/whats-new.rst", "new_path": "b/doc/whats-new.rst", "metadata": "diff --git a/doc/whats-new.rst b/doc/whats-new.rst\nindex dea110b5e46..cced7276ff3 100644\n--- a/doc/whats-new.rst\n+++ b/doc/whats-new.rst\n@@ -25,6 +25,10 @@ Breaking changes\n \n New Features\n ~~~~~~~~~~~~\n+- :py:meth:`Dataset.transpose` and :py:meth:`DataArray.transpose` now support an ellipsis (`...`)\n+ to represent all 'other' dimensions. For example, to move one dimension to the front,\n+ use `.transpose('x', ...)`. (:pull:`3421`)\n+ By `Maximilian Roos `_\n - Changed `xr.ALL_DIMS` to equal python's `Ellipsis` (`...`), and changed internal usages to use\n `...` directly. As before, you can use this to instruct a `groupby` operation\n to reduce over all dimensions. While we have no plans to remove `xr.ALL_DIMS`, we suggest\n"}], "version": "0014", "base_commit": "fb0cf7b5fe56519a933ffcecbce9e9327fe236a6", "PASS2PASS": ["xarray/tests/test_dataset.py::test_rolling_reduce[max-1-None-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-3-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-4-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-3-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-True-std]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-3-3-False-1]", "xarray/tests/test_variable.py::TestIndexVariable::test_concat_number_strings", "xarray/tests/test_dataarray.py::TestDataArray::test_dataarray_diff_n1", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-None-median]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-1-1-False]", "xarray/tests/test_dataset.py::TestDataset::test_stack", "xarray/tests/test_dataset.py::test_rolling_reduce[var-1-3-True-2]", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords1-unaligned_coords5]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-3-1-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_sel_dataarray", "xarray/tests/test_dataset.py::test_dir_non_string[None]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-2-1-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-1-3-True]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-3-1-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-3-2-True]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-True-median]", "xarray/tests/test_variable.py::TestVariable::test_copy[int-True]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-4-None-False-1]", "xarray/tests/test_variable.py::TestVariable::test_set_dims_object_dtype", "xarray/tests/test_dataset.py::TestDataset::test_reindex_like_fill_value[2]", "xarray/tests/test_dataset.py::TestDataset::test_sel", "xarray/tests/test_dataarray.py::TestDataArray::test_align_mixed_indexes", "xarray/tests/test_dataset.py::test_rolling_reduce[var-2-None-True-1]", "xarray/tests/test_dataset.py::test_differentiate_datetime[True]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-3-3-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-4-1-True]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-False-max]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-4-3-False-2]", "xarray/tests/test_utils.py::test_is_grib_path", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[4-1-True]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-3-2-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-4-3-False]", "xarray/tests/test_accessor_dt.py::TestDatetimeAccessor::test_rounders", "xarray/tests/test_dataset.py::TestDataset::test_align_fill_value[2.0]", "xarray/tests/test_dataset.py::TestDataset::test_coords_properties", "xarray/tests/test_dataset.py::test_rolling_reduce[min-1-3-True-1]", "xarray/tests/test_variable.py::TestVariable::test_shift2d", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-3-2-False-2]", "xarray/tests/test_variable.py::TestIndexVariable::test_index_0d_not_a_time", "xarray/tests/test_dataset.py::TestDataset::test_to_stacked_array_dtype_dims", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-None-None-mean]", "xarray/tests/test_dataset.py::TestDataset::test_to_and_from_dict_with_time_dim", "xarray/tests/test_variable.py::TestVariable::test_rank", "xarray/tests/test_dataarray.py::TestDataArray::test_attr_sources_multiindex", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-1-None-max]", "xarray/tests/test_variable.py::TestVariable::test_getitem_with_mask_size_zero", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[3-3-True]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-4-None-False-1]", "xarray/tests/test_dataset.py::TestDataset::test_to_stacked_array_name", "xarray/tests/test_dataset.py::TestDataset::test_constructor_pandas_sequence", "xarray/tests/test_dataset.py::test_rolling_reduce[median-1-1-True-1]", "xarray/tests/test_variable.py::TestIndexVariable::test_multiindex", "xarray/tests/test_dataset.py::TestDataset::test_roll_coords_none", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-3-None-True-2]", "xarray/tests/test_variable.py::TestIndexVariable::test_equals_all_dtypes", "xarray/tests/test_variable.py::TestVariable::test_setitem_fancy", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[4-1-True]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-3-None-True-2]", "xarray/tests/test_variable.py::TestVariable::test_timedelta64_conversion", "xarray/tests/test_dataarray.py::TestDataArray::test_resample_first", "xarray/tests/test_utils.py::Test_is_uniform_and_sorted::test_sorted_uniform", "xarray/tests/test_dataset.py::TestDataset::test_reindex_method", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-None-None-max]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-3-2-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-4-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[1-1-True]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-3-None-False-2]", "xarray/tests/test_variable.py::TestVariable::test_pad", "xarray/tests/test_variable.py::TestVariable::test_0d_timedelta", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-3-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-4-None-False-2]", "xarray/tests/test_variable.py::TestIndexVariable::test_index_0d_datetime", "xarray/tests/test_dataset.py::test_rolling_reduce[max-1-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-1-2-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-4-1-True]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-3-None-False-1]", "xarray/tests/test_dataset.py::test_coarsen[1-trim-left-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-4-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-4-2-False-1]", "xarray/tests/test_dataset.py::TestDataset::test_assign_multiindex_level", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-1-3-True-1]", "xarray/tests/test_utils.py::TestDictionaries::test_ordered_dict_intersection", "xarray/tests/test_dataset.py::test_rolling_reduce[min-4-3-True-2]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[2-None-True]", "xarray/tests/test_dataset.py::TestDataset::test_variable", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-3-1-False-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_where", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-1-2-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-1-2-True-2]", "xarray/tests/test_variable.py::TestVariable::test_shift[fill_value0]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-3-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-2-1-False-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_dropna", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-1-1-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-3-2-True-2]", "xarray/tests/test_variable.py::TestVariable::test_squeeze", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-2-2-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-2-None-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-1-2-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-3-1-True]", "xarray/tests/test_dataset.py::test_rolling_construct[3-True]", "xarray/tests/test_dataarray.py::TestDataArray::test_struct_array_dims", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords0-unaligned_coords8]", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-None-None-std]", "xarray/tests/test_dataarray.py::TestDataArray::test_resample_bad_resample_dim", "xarray/tests/test_dataset.py::TestDataset::test_coords_merge", "xarray/tests/test_dataset.py::test_rolling_reduce[min-1-3-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-4-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-4-1-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-1-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-None-mean]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-4-None-True-2]", "xarray/tests/test_variable.py::TestIndexVariable::test_load", "xarray/tests/test_dataarray.py::TestDataArray::test_math_with_coords", "xarray/tests/test_dataset.py::TestDataset::test_groupby_nan", "xarray/tests/test_dataset.py::test_rolling_reduce[var-3-2-False-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_loc", "xarray/tests/test_dataset.py::test_rolling_reduce[var-3-1-False-2]", "xarray/tests/test_dataset.py::TestDataset::test_groupby_math_virtual", "xarray/tests/test_variable.py::TestVariable::test_0d_str", "xarray/tests/test_dataarray.py::TestDataArray::test_groupby_apply_changes_metadata", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-3-None-False-2]", "xarray/tests/test_dataset.py::TestDataset::test_where_other", "xarray/tests/test_dataset.py::test_rolling_reduce[std-4-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-1-1-False-2]", "xarray/tests/test_dataset.py::TestDataset::test_rename_old_name", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-4-3-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_constructor_from_0d", "xarray/tests/test_dataset.py::test_rolling_reduce[var-4-2-True-2]", "xarray/tests/test_dataset.py::TestDataset::test_quantile", "xarray/tests/test_dataset.py::test_rolling_reduce[std-2-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-3-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-4-None-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-3-3-False-1]", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-None-False-mean]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-1-2-True-1]", "xarray/tests/test_dataset.py::TestDataset::test_reindex_warning", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[3-1-False]", "xarray/tests/test_dataarray.py::test_rolling_construct[4-True]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-2-1-True]", "xarray/tests/test_dataarray.py::TestDataArray::test_align_without_indexes_exclude", "xarray/tests/test_dataset.py::TestDataset::test_constructor", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-1-None-False-1]", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[3-3-False]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-4-2-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-2-3-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_getitem_dict", "xarray/tests/test_dataset.py::test_rolling_reduce[median-1-2-True-2]", "xarray/tests/test_dataset.py::TestDataset::test_reduce_bad_dim", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-None-True-std]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-2-2-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-4-None-True]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-3-2-True-1]", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[1-1-False]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[3-1-True]", "xarray/tests/test_variable.py::TestIndexVariable::test_name", "xarray/tests/test_dataset.py::TestDataset::test_coords_setitem_multiindex", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-1-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-1-3-True-1]", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-1-False-sum]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-3-None-True-2]", "xarray/tests/test_variable.py::TestIndexVariable::test_multiindex_default_level_names", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-1-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-1-None-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-1-3-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_da_resample_func_args", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-4-2-False-2]", "xarray/tests/test_variable.py::TestIndexVariable::test_attrs", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-True-max]", "xarray/tests/test_dataarray.py::TestDataArray::test_getitem_empty_index", "xarray/tests/test_dataset.py::test_rolling_reduce[max-3-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-4-2-True-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_sel", "xarray/tests/test_dataset.py::TestDataset::test_resample_loffset", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-3-None-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-1-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-1-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-2-3-False-2]", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[3-1-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-3-1-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-4-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-3-None-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-2-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-2-3-True-2]", "xarray/tests/test_dataset.py::TestDataset::test_expand_dims_mixed_int_and_coords", "xarray/tests/test_dataset.py::test_rolling_reduce[var-2-3-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-2-3-False-1]", "xarray/tests/test_variable.py::TestVariable::test_rolling_window", "xarray/tests/test_dataarray.py::TestDataArray::test_groupby_apply_ndarray", "xarray/tests/test_variable.py::TestVariable::test_broadcasting_failures", "xarray/tests/test_accessor_dt.py::TestDatetimeAccessor::test_field_access", "xarray/tests/test_dataarray.py::test_isin[repeating_ints]", "xarray/tests/test_variable.py::TestVariable::test_equals_all_dtypes", "xarray/tests/test_dataset.py::test_rolling_reduce[min-2-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-3-1-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-1-None-False]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-3-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-True-median]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-4-3-False-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_series_categorical_index", "xarray/tests/test_variable.py::TestIndexVariable::test_index_0d_string", "xarray/tests/test_dataarray.py::TestDataArray::test_copy_with_data", "xarray/tests/test_dataset.py::TestDataset::test_shift[fill_value0]", "xarray/tests/test_variable.py::TestVariable::test_indexing_0d_unicode", "xarray/tests/test_dataarray.py::TestDataArray::test_getitem_coords", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-True-median]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-2-2-True-1]", "xarray/tests/test_dataset.py::TestDataset::test_virtual_variable_same_name", "xarray/tests/test_dataset.py::test_trapz_datetime[np-True]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-4-2-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-2-1-True]", "xarray/tests/test_dataset.py::TestDataset::test_resample_old_api", "xarray/tests/test_dataset.py::test_rolling_reduce[max-3-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-4-None-False-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_equals_and_identical", "xarray/tests/test_variable.py::TestAsCompatibleData::test_zeros_like", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-1-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-2-None-True-1]", "xarray/tests/test_dataset.py::TestDataset::test_selection_multiindex", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords1-unaligned_coords1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-1-2-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-1-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-4-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-1-2-False-2]", "xarray/tests/test_variable.py::TestIndexVariable::test_array_interface", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-2-1-True-2]", "xarray/tests/test_variable.py::TestVariable::test_setitem", "xarray/tests/test_dataarray.py::TestDataArray::test_reduce_keep_attrs", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-None-sum]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-3-None-True-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_groupby_sum_default", "xarray/tests/test_dataset.py::TestDataset::test_to_array", "xarray/tests/test_dataset.py::test_rolling_reduce[std-4-3-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-3-3-True]", "xarray/tests/test_variable.py::TestIndexVariable::test_data", "xarray/tests/test_dataset.py::TestDataset::test_ds_resample_apply_func_args", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-2-1-False-2]", "xarray/tests/test_dataset.py::TestDataset::test_align_nocopy", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-True-min]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-None-var]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[3-2-True]", "xarray/tests/test_variable.py::TestVariable::test_big_endian_reduce", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-4-None-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-4-1-False-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_getitem_dataarray", "xarray/tests/test_variable.py::TestVariable::test_1d_reduce", "xarray/tests/test_variable.py::test_raise_no_warning_for_nan_in_binary_ops", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[1-2-True]", "xarray/tests/test_dataset.py::TestDataset::test_resample_min_count", "xarray/tests/test_variable.py::TestIndexVariable::test_copy_index", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-1-None-False-1]", "xarray/tests/test_dataset.py::TestDataset::test_constructor_invalid_dims", "xarray/tests/test_dataset.py::test_rolling_reduce[var-2-2-False-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_to_dataset_whole", "xarray/tests/test_variable.py::TestVariable::test_copy[float-True]", "xarray/tests/test_dataset.py::TestDataset::test_resample_by_mean_with_keep_attrs", "xarray/tests/test_dataset.py::TestDataset::test_expand_dims_coords", "xarray/tests/test_dataset.py::test_rolling_reduce[min-3-1-False-2]", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords0-unaligned_coords7]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-2-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-None-std]", "xarray/tests/test_dataarray.py::TestDataArray::test_sel_drop", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[1-2-False]", "xarray/tests/test_dataset.py::TestDataset::test_ipython_key_completion", "xarray/tests/test_dataset.py::test_rolling_reduce[max-4-2-False-2]", "xarray/tests/test_variable.py::TestVariable::test_numpy_same_methods", "xarray/tests/test_dataset.py::test_rolling_construct[2-False]", "xarray/tests/test_dataset.py::TestDataset::test_setitem_pandas", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-False-min]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-3-3-True-2]", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-1-True-mean]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-1-1-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_dataset_math", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-2-3-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-3-None-False-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_virtual_default_coords", "xarray/tests/test_variable.py::TestVariable::test_copy_index_with_data", "xarray/tests/test_dataarray.py::TestDataArray::test_dot", "xarray/tests/test_dataset.py::test_rolling_reduce[std-3-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-3-None-False-1]", "xarray/tests/test_variable.py::TestVariable::test_unstack_errors", "xarray/tests/test_dataset.py::test_rolling_reduce[var-2-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-4-None-True-2]", "xarray/tests/test_variable.py::TestVariable::test_index_0d_float", "xarray/tests/test_dataarray.py::TestDataArray::test_loc_assign_dataarray", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-2-None-False-1]", "xarray/tests/test_dataset.py::TestDataset::test_constructor_pandas_single", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-3-None-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-2-1-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_to_pandas", "xarray/tests/test_dataset.py::test_rolling_reduce[var-4-3-False-2]", "xarray/tests/test_dataset.py::test_coarsen_coords[1-True]", "xarray/tests/test_dataarray.py::TestDataArray::test_set_coords_update_index", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-4-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-2-2-True-2]", "xarray/tests/test_dataset.py::TestDataset::test_unicode_data", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-1-False-max]", "xarray/tests/test_dataarray.py::TestDataArray::test_to_and_from_dict", "xarray/tests/test_utils.py::TestDictionaries::test_unsafe", "xarray/tests/test_dataset.py::TestDataset::test_time_season", "xarray/tests/test_variable.py::TestVariable::test_as_variable", "xarray/tests/test_dataarray.py::TestDataArray::test_empty_dataarrays_return_empty_result", "xarray/tests/test_dataarray.py::TestDataArray::test_align_copy", "xarray/tests/test_variable.py::TestIndexVariable::test_copy[int-False]", "xarray/tests/test_dataarray.py::TestDataArray::test_inplace_math_basics", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords0-unaligned_coords0]", "xarray/tests/test_dataarray.py::TestDataArray::test_expand_dims_with_scalar_coordinate", "xarray/tests/test_dataarray.py::TestDataArray::test_reduce_keepdims_bottleneck", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-3-1-True-1]", "xarray/tests/test_variable.py::TestVariable::test_getitem_error", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-2-None-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-1-3-False-1]", "xarray/tests/test_variable.py::TestIndexVariable::test_copy[int-True]", "xarray/tests/test_variable.py::TestVariable::test_isel", "xarray/tests/test_dataarray.py::test_rolling_construct[1-True]", "xarray/tests/test_dataset.py::TestDataset::test_convert_dataframe_with_many_types_and_multiindex", "xarray/tests/test_dataset.py::test_rolling_reduce[max-3-3-False-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_resample", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-2-None-False-1]", "xarray/tests/test_utils.py::TestDictionaries::test_frozen", "xarray/tests/test_dataset.py::test_rolling_reduce[min-4-None-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-1-1-True]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-2-3-False]", "xarray/tests/test_dataarray.py::TestDataArray::test_tail", "xarray/tests/test_dataset.py::TestDataset::test_groupby_reduce", "xarray/tests/test_variable.py::TestVariable::test_copy_index", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-2-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-2-1-True-2]", "xarray/tests/test_variable.py::TestVariable::test_broadcasting_math", "xarray/tests/test_dataarray.py::test_rolling_construct[1-False]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[4-1-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-1-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-4-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-4-2-False-2]", "xarray/tests/test_dataset.py::test_integrate[True]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-4-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-4-None-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-4-None-True]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-4-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-4-1-False-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_rename", "xarray/tests/test_dataset.py::TestDataset::test_broadcast_nocopy", "xarray/tests/test_dataarray.py::TestDataArray::test__title_for_slice_truncate", "xarray/tests/test_variable.py::TestIndexVariable::test_datetime64", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-2-1-False-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_setitem_dataarray", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-2-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-3-None-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-1-2-True]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-2-None-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-3-3-True-2]", "xarray/tests/test_dataset.py::TestDataset::test_setitem_original_non_unique_index", "xarray/tests/test_dataarray.py::TestDataArray::test_resample_skipna", "xarray/tests/test_dataarray.py::TestDataArray::test__title_for_slice", "xarray/tests/test_dataset.py::TestDataset::test_reindex_variables_copied", "xarray/tests/test_variable.py::TestIndexVariable::test_index_0d_object", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-4-3-True]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-3-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-4-3-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-3-2-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-4-1-True-1]", "xarray/tests/test_dataset.py::TestDataset::test_to_dict_with_numpy_attrs", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-4-1-False-1]", "xarray/tests/test_variable.py::TestIndexVariable::test_index_0d_timedelta64", "xarray/tests/test_dataarray.py::TestDataArray::test_expand_dims", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords0-unaligned_coords9]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-2-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-4-2-False-2]", "xarray/tests/test_dataarray.py::test_name_in_masking", "xarray/tests/test_dataset.py::TestDataset::test_properties", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-1-True-std]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[4-None-False]", "xarray/tests/test_variable.py::TestIndexVariable::test_level_names", "xarray/tests/test_dataset.py::TestDataset::test_reduce_keepdims", "xarray/tests/test_dataset.py::test_rolling_reduce[min-4-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-3-2-False-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_reindex_like", "xarray/tests/test_utils.py::TestDictionaries::test_equivalent", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-1-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-False-max]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-4-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-3-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-1-1-True-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_shift[fill_value1-float-1]", "xarray/tests/test_dataset.py::TestDataset::test_align_non_unique", "xarray/tests/test_dataset.py::test_rolling_reduce[min-3-1-False-1]", "xarray/tests/test_variable.py::TestVariable::test_getitem_advanced", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-4-1-False-1]", "xarray/tests/test_variable.py::TestVariable::test_repr", "xarray/tests/test_dataset.py::TestDataset::test_virtual_variables_time", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-3-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-3-1-True-2]", "xarray/tests/test_dataset.py::test_dir_unicode[None]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[3-3-False]", "xarray/tests/test_dataset.py::TestDataset::test_resample_and_first", "xarray/tests/test_variable.py::TestBackendIndexing::test_NumpyIndexingAdapter", "xarray/tests/test_utils.py::TestArrayEquiv::test_0d", "xarray/tests/test_dataarray.py::TestDataArray::test_to_and_from_dict_with_time_dim", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-False-std]", "xarray/tests/test_dataset.py::TestDataset::test_coords_to_dataset", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-4-2-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-4-3-True-1]", "xarray/tests/test_dataset.py::TestDataset::test_isel_dataarray", "xarray/tests/test_dataarray.py::TestDataArray::test_broadcast_coordinates", "xarray/tests/test_variable.py::TestAsCompatibleData::test_converted_types", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-2-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-None-var]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-2-3-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-2-1-False-1]", "xarray/tests/test_dataset.py::TestDataset::test_variable_indexing", "xarray/tests/test_dataset.py::TestDataset::test_where_drop_empty", "xarray/tests/test_dataarray.py::TestDataArray::test_groupby_bins_multidim", "xarray/tests/test_dataset.py::test_rolling_reduce[max-2-2-False-2]", "xarray/tests/test_variable.py::TestVariable::test___array__", "xarray/tests/test_dataset.py::TestDataset::test_update_auto_align", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-False-mean]", "xarray/tests/test_dataarray.py::TestDataArray::test_coords_non_string", "xarray/tests/test_dataarray.py::TestDataArray::test_fillna", "xarray/tests/test_variable.py::TestVariable::test_getitem_1d", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-1-2-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-4-None-False-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_groupby_restore_dim_order", "xarray/tests/test_dataset.py::test_rolling_reduce[median-2-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-3-1-True-2]", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-None-False-std]", "xarray/tests/test_utils.py::TestDictionaries::test_sorted_keys_dict", "xarray/tests/test_dataarray.py::TestDataArray::test_selection_multiindex", "xarray/tests/test_dataset.py::test_rolling_reduce[std-4-2-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-3-2-False-2]", "xarray/tests/test_dataset.py::TestDataset::test_reorder_levels", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-4-3-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-2-None-False-1]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-True-mean]", "xarray/tests/test_variable.py::TestVariable::test_repr_lazy_data", "xarray/tests/test_dataset.py::TestDataset::test_reindex_fill_value[2]", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[4-3-False]", "xarray/tests/test_dataset.py::TestDataset::test_getitem_hashable", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-None-median]", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-None-False-min]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-1-3-False-1]", "xarray/tests/test_variable.py::TestVariable::test_0d_datetime", "xarray/tests/test_dataset.py::test_rolling_reduce[median-4-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-True-var]", "xarray/tests/test_variable.py::TestVariable::test_unstack", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords1-unaligned_coords6]", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords0-unaligned_coords6]", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-1-True-sum]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-4-None-True-2]", "xarray/tests/test_dataset.py::TestDataset::test_sel_method", "xarray/tests/test_dataarray.py::TestDataArray::test_set_index", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-None-median]", "xarray/tests/test_dataarray.py::TestDataArray::test_groupby_math", "xarray/tests/test_dataset.py::test_rolling_reduce[min-3-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-4-2-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-2-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-3-1-True-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_assign_coords", "xarray/tests/test_dataarray.py::TestDataArray::test_index_math", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-3-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-3-3-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_constructor", "xarray/tests/test_dataset.py::TestDataset::test_constructor_1d", "xarray/tests/test_dataset.py::test_rolling_reduce[min-2-1-False-2]", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-1-True-median]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-1-None-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-4-None-False-1]", "xarray/tests/test_variable.py::TestVariable::test_index_0d_datetime", "xarray/tests/test_dataset.py::test_rolling_reduce[min-2-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-2-2-False-1]", "xarray/tests/test_variable.py::TestVariable::test_encoding_preserved", "xarray/tests/test_dataset.py::TestDataset::test_constructor_0d", "xarray/tests/test_dataarray.py::TestDataArray::test_reduce_dtype", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-True-var]", "xarray/tests/test_dataset.py::test_isin[test_elements2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-3-1-True-2]", "xarray/tests/test_dataset.py::TestDataset::test_reduce_argmin", "xarray/tests/test_dataset.py::test_rolling_reduce[var-4-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-3-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-3-2-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-3-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-4-3-False-1]", "xarray/tests/test_variable.py::TestVariable::test_getitem_uint", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-2-2-True-1]", "xarray/tests/test_utils.py::Test_is_uniform_and_sorted::test_sorted_not_uniform", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-1-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-False-max]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[3-None-True]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[4-3-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-2-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-2-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-4-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-None-var]", "xarray/tests/test_variable.py::TestIndexVariable::test_copy_index_with_data_errors", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-3-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-1-None-True-1]", "xarray/tests/test_dataset.py::TestDataset::test_loc", "xarray/tests/test_variable.py::TestVariable::test_unstack_2d", "xarray/tests/test_dataarray.py::TestDataArray::test_array_interface", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-4-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-4-3-False-2]", "xarray/tests/test_variable.py::TestIndexVariable::test_object_conversion", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-None-min]", "xarray/tests/test_dataarray.py::TestDataArray::test_sel_dataarray_datetime", "xarray/tests/test_dataset.py::TestDataset::test_unstack_errors", "xarray/tests/test_dataarray.py::TestDataArray::test_repr_multiindex", "xarray/tests/test_dataset.py::TestDataset::test_lazy_load", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[4-2-False]", "xarray/tests/test_variable.py::TestVariable::test_copy[str-False]", "xarray/tests/test_variable.py::TestIndexVariable::test_getitem_with_mask_size_zero", "xarray/tests/test_dataarray.py::TestDataArray::test_roll_coords_none", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-1-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-False-sum]", "xarray/tests/test_variable.py::TestVariable::test_count", "xarray/tests/test_variable.py::TestIndexVariable::test_copy[str-True]", "xarray/tests/test_variable.py::TestIndexVariable::test_real_and_imag", "xarray/tests/test_dataset.py::TestDataset::test_virtual_variables_default_coords", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-1-2-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_to_pandas_name_matches_coordinate", "xarray/tests/test_dataset.py::TestDataset::test_dataset_diff_n2", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-4-1-True-1]", "xarray/tests/test_dataset.py::TestDataset::test_shift[2.0]", "xarray/tests/test_variable.py::TestIndexVariable::test_1d_math", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-4-1-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-4-3-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_to_unstacked_dataset_raises_value_error", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-3-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-1-1-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-4-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-2-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-3-3-True-2]", "xarray/tests/test_dataset.py::TestDataset::test_from_dataframe_non_unique_columns", "xarray/tests/test_dataset.py::test_rolling_reduce[median-4-2-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_coords_alignment", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-2-3-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-2-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-1-3-True-2]", "xarray/tests/test_variable.py::TestIndexVariable::test_copy_with_data_errors", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[4-2-False]", "xarray/tests/test_dataarray.py::TestDataArray::test_groupby_multidim", "xarray/tests/test_dataarray.py::TestDataArray::test_dataset_getitem", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[3-2-True]", "xarray/tests/test_dataset.py::TestDataset::test_full_like", "xarray/tests/test_dataset.py::test_rolling_reduce[var-1-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-4-None-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-1-None-True-1]", "xarray/tests/test_dataset.py::TestDataset::test_align", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-3-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-False-sum]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-3-1-False-1]", "xarray/tests/test_dataset.py::TestDataset::test_constructor_auto_align", "xarray/tests/test_dataset.py::TestDataset::test_align_exclude", "xarray/tests/test_dataset.py::test_differentiate[2-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-1-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-2-3-False-2]", "xarray/tests/test_variable.py::TestBackendIndexing::test_MemoryCachedArray", "xarray/tests/test_dataset.py::TestDataset::test_setitem_multiindex_level", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-1-2-True]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-3-2-True-1]", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords1-unaligned_coords9]", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords1-unaligned_coords3]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-2-3-True-2]", "xarray/tests/test_dataset.py::TestDataset::test_align_indexes", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-4-3-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-1-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-None-std]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-2-None-False-1]", "xarray/tests/test_dataset.py::TestDataset::test_constructor_compat", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-4-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-1-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-4-3-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-1-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-1-1-True-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_math", "xarray/tests/test_dataarray.py::TestDataArray::test_groupby_apply_identity", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-2-1-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-2-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-3-1-False-2]", "xarray/tests/test_dataset.py::TestDataset::test_repr_nep18", "xarray/tests/test_dataset.py::test_rolling_reduce[var-1-3-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-2-3-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-1-3-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-2-3-True-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_groupby_bins_empty", "xarray/tests/test_dataarray.py::TestDataArray::test_data_property", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-3-None-True]", "xarray/tests/test_dataarray.py::TestDataArray::test_cumops", "xarray/tests/test_variable.py::TestIndexVariable::test_index_and_concat_datetime", "xarray/tests/test_variable.py::TestIndexVariable::test___array__", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-False-std]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-4-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-2-1-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-4-None-False-1]", "xarray/tests/test_dataset.py::test_differentiate_datetime[False]", "xarray/tests/test_dataset.py::TestDataset::test_reindex_fill_value[fill_value0]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-2-3-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-3-1-False-1]", "xarray/tests/test_dataset.py::TestDataset::test_update_overwrite_coords", "xarray/tests/test_variable.py::TestVariable::test_detect_indexer_type", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-3-1-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-2-2-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-1-3-False-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_reindex_fill_value[fill_value0]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-1-2-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-3-3-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_non_overlapping_dataarrays_return_empty_result", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-2-2-True-1]", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[2-3-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-2-2-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-2-None-False-2]", "xarray/tests/test_dataset.py::TestDataset::test_dataset_math_auto_align", "xarray/tests/test_dataset.py::test_rolling_reduce[median-3-1-False-2]", "xarray/tests/test_dataset.py::TestDataset::test_attribute_access", "xarray/tests/test_variable.py::TestVariable::test_copy[str-True]", "xarray/tests/test_variable.py::TestIndexVariable::test_concat_mixed_dtypes", "xarray/tests/test_dataset.py::TestDataset::test_dataset_array_math", "xarray/tests/test_dataset.py::TestDataset::test_unstack", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-1-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-4-3-True-1]", "xarray/tests/test_dataset.py::test_isin[test_elements1]", "xarray/tests/test_dataset.py::TestDataset::test_setattr_raises", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-2-2-False-2]", "xarray/tests/test_dataset.py::TestDataset::test_rename_same_name", "xarray/tests/test_dataset.py::test_rolling_reduce[var-4-2-True-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_loc_single_boolean", "xarray/tests/test_variable.py::TestVariable::test_no_conflicts", "xarray/tests/test_dataarray.py::TestDataArray::test_groupby_properties", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-3-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-3-3-True-1]", "xarray/tests/test_variable.py::TestVariable::test_index_0d_int", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-4-3-False-2]", "xarray/tests/test_accessor_dt.py::TestDatetimeAccessor::test_not_datetime_type", "xarray/tests/test_dataset.py::TestDataset::test_update_index", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-1-3-False-1]", "xarray/tests/test_dataset.py::TestDataset::test_rename", "xarray/tests/test_variable.py::TestVariable::test_index_0d_not_a_time", "xarray/tests/test_dataarray.py::TestDataArray::test_shift[fill_value1-float-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-4-1-False-1]", "xarray/tests/test_variable.py::TestIndexVariable::test_getitem_with_mask_nd_indexer", "xarray/tests/test_variable.py::TestIndexVariable::test_timedelta64_conversion", "xarray/tests/test_dataarray.py::TestDataArray::test_coordinate_diff", "xarray/tests/test_dataset.py::TestDataset::test_stack_unstack_slow", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-False-mean]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-3-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-4-3-False-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_align_indexes", "xarray/tests/test_dataset.py::TestDataset::test_rename_vars", "xarray/tests/test_dataset.py::test_rolling_reduce[max-2-1-False-2]", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords0-unaligned_coords5]", "xarray/tests/test_dataarray.py::TestDataArray::test_coords_to_index", "xarray/tests/test_dataarray.py::TestDataArray::test_full_like", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-4-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-4-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-None-min]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-4-2-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-3-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-4-3-False-1]", "xarray/tests/test_utils.py::test_safe_cast_to_index", "xarray/tests/test_dataset.py::test_rolling_reduce[std-3-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-4-None-True-1]", "xarray/tests/test_dataarray.py::test_subclass_slots", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-1-True-min]", "xarray/tests/test_dataset.py::TestDataset::test_groupby_errors", "xarray/tests/test_dataarray.py::test_rolling_construct[3-False]", "xarray/tests/test_dataarray.py::TestDataArray::test_binary_op_join_setting", "xarray/tests/test_variable.py::TestVariable::test_pandas_cateogrical_dtype", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[1-3-False]", "xarray/tests/test_dataset.py::TestDataset::test_broadcast_exclude", "xarray/tests/test_dataarray.py::TestDataArray::test_groupby_restore_coord_dims", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[1-3-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-3-1-False-1]", "xarray/tests/test_variable.py::TestVariable::test_getitem_0d_array", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-4-1-True-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_resample_keep_attrs", "xarray/tests/test_dataarray.py::test_rolling_doc[1]", "xarray/tests/test_dataset.py::TestDataset::test_align_fill_value[fill_value0]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-False-mean]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-3-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-False-min]", "xarray/tests/test_dataset.py::TestDataset::test_constructor_deprecated", "xarray/tests/test_variable.py::TestVariable::test_concat_fixed_len_str", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-1-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-4-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-False-min]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-1-1-False-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_quantile", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords1-unaligned_coords4]", "xarray/tests/test_variable.py::TestVariable::test_pandas_data", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-None-max]", "xarray/tests/test_dataset.py::TestDataset::test_align_override", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[4-None-True]", "xarray/tests/test_dataset.py::TestDataset::test_isel_fancy", "xarray/tests/test_dataset.py::TestDataset::test_setitem_align_new_indexes", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-1-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-2-2-True-2]", "xarray/tests/test_variable.py::TestIndexVariable::test_pandas_datetime64_with_tz", "xarray/tests/test_dataarray.py::TestDataArray::test_thin", "xarray/tests/test_variable.py::TestVariable::test_inplace_math", "xarray/tests/test_dataarray.py::TestDataArray::test_groupby_iter", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-1-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-2-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-2-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-1-None-False-1]", "xarray/tests/test_utils.py::test_multiindex_from_product_levels", "xarray/tests/test_dataset.py::TestDataset::test_reduce_cumsum", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-True-max]", "xarray/tests/test_dataarray.py::test_rolling_properties[1]", "xarray/tests/test_dataset.py::TestDataset::test_squeeze", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-1-None-False-2]", "xarray/tests/test_variable.py::TestVariable::test_0d_object_array_with_list", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-3-1-True]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-3-None-True-2]", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords0-unaligned_coords1]", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords1-unaligned_coords2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-3-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-None-var]", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[4-None-False]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-3-3-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-3-1-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-4-None-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-2-2-True]", "xarray/tests/test_dataarray.py::TestDataArray::test_upsample_tolerance", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-None-None-median]", "xarray/tests/test_dataset.py::test_weakref", "xarray/tests/test_variable.py::TestVariable::test_getitem_with_mask_2d_input", "xarray/tests/test_dataset.py::TestDataset::test_setitem", "xarray/tests/test_dataset.py::TestDataset::test_dataset_diff_n1", "xarray/tests/test_dataarray.py::TestDataArray::test_isel_drop", "xarray/tests/test_dataset.py::TestDataset::test_data_vars_properties", "xarray/tests/test_dataset.py::TestDataset::test_reindex_like_fill_value[2.0]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-2-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-2-None-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-3-2-False]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[4-3-True]", "xarray/tests/test_dataarray.py::TestDataArray::test_roll_coords", "xarray/tests/test_variable.py::TestIndexVariable::test_getitem_with_mask", "xarray/tests/test_dataset.py::test_differentiate[1-True]", "xarray/tests/test_dataarray.py::TestDataArray::test_reduce_keepdims", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords0-unaligned_coords2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-True-min]", "xarray/tests/test_utils.py::Test_hashable::test_hashable", "xarray/tests/test_dataset.py::test_rolling_reduce[max-3-1-False-1]", "xarray/tests/test_utils.py::test_repr_object", "xarray/tests/test_variable.py::TestVariable::test_index_and_concat_datetime", "xarray/tests/test_dataset.py::test_rolling_reduce[var-3-3-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_isel", "xarray/tests/test_dataset.py::test_rolling_reduce[median-3-None-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-2-None-False-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_sel_no_index", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-3-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-1-None-False-1]", "xarray/tests/test_dataset.py::TestDataset::test_broadcast_equals", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-1-2-False-2]", "xarray/tests/test_variable.py::TestAsCompatibleData::test_full_like", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-4-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-False-mean]", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-None-None-sum]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-3-3-True]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-2-1-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-2-3-True]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-4-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-2-3-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-4-None-False-2]", "xarray/tests/test_accessor_dt.py::TestDatetimeAccessor::test_strftime", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-3-2-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-2-2-False]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[1-2-False]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[2-2-True]", "xarray/tests/test_dataset.py::TestDataset::test_squeeze_drop", "xarray/tests/test_dataarray.py::TestDataArray::test_shift[2-int--5]", "xarray/tests/test_dataarray.py::TestDataArray::test_contains", "xarray/tests/test_dataset.py::test_rolling_reduce[min-2-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-4-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-4-1-True-2]", "xarray/tests/test_variable.py::TestAsCompatibleData::test_unchanged_types", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-True-mean]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-4-None-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-1-None-False-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_math_name", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[1-3-True]", "xarray/tests/test_dataset.py::TestDataset::test_binary_op_join_setting", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-3-2-True]", "xarray/tests/test_dataset.py::TestDataset::test_broadcast_misaligned", "xarray/tests/test_variable.py::TestVariable::test_timedelta64_conversion_scalar", "xarray/tests/test_dataset.py::TestDataset::test_drop_index_labels", "xarray/tests/test_dataset.py::TestDataset::test_to_and_from_dataframe", "xarray/tests/test_dataarray.py::TestDataArray::test_pickle", "xarray/tests/test_dataset.py::test_rolling_reduce[min-3-3-True-2]", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[1-1-True]", "xarray/tests/test_dataset.py::TestDataset::test_rename_inplace", "xarray/tests/test_dataset.py::TestDataset::test_groupby_order", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-2-None-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-1-1-False-1]", "xarray/tests/test_variable.py::TestVariable::test_getitem_1d_fancy", "xarray/tests/test_dataset.py::test_coarsen[1-pad-right-True]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-4-1-True-1]", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-1-False-mean]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-4-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-2-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-3-3-True-1]", "xarray/tests/test_variable.py::TestVariable::test_index_0d_string", "xarray/tests/test_dataset.py::test_rolling_reduce[median-3-None-False-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_drop_coordinates", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-1-1-False]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[2-3-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-2-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-2-3-True-1]", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[2-2-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-1-3-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_reindex_like_no_index", "xarray/tests/test_dataset.py::test_rolling_reduce[std-3-None-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-2-1-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-4-None-True-2]", "xarray/tests/test_variable.py::TestIndexVariable::test_properties", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-4-3-True-1]", "xarray/tests/test_dataset.py::TestDataset::test_count", "xarray/tests/test_dataset.py::test_rolling_reduce[std-4-None-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-1-3-True-1]", "xarray/tests/test_variable.py::TestVariable::test_shift[2]", "xarray/tests/test_dataset.py::TestDataset::test_repr", "xarray/tests/test_dataset.py::TestDataset::test_dataset_retains_period_index_on_transpose", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-1-2-False-2]", "xarray/tests/test_variable.py::TestIndexVariable::test_concat_attrs", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-4-2-True]", "xarray/tests/test_dataset.py::TestDataset::test_copy_with_data_errors", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-1-3-True-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_sel_float", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-2-1-True-2]", "xarray/tests/test_dataset.py::TestDataset::test_coords_merge_mismatched_shape", "xarray/tests/test_dataset.py::TestDataset::test_coords_set", "xarray/tests/test_dataset.py::TestDataset::test_broadcast_like", "xarray/tests/test_dataset.py::test_rolling_construct[4-True]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-3-3-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_align_dtype", "xarray/tests/test_dataset.py::test_rolling_reduce[median-4-None-True-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_constructor_from_self_described", "xarray/tests/test_dataset.py::TestDataset::test_to_and_from_empty_dataframe", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-None-True-min]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-1-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-3-2-False-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_groupby_first_and_last", "xarray/tests/test_dataset.py::TestDataset::test_dataset_diff_exception_n_neg", "xarray/tests/test_dataset.py::TestDataset::test_to_stacked_array_to_unstacked_dataset", "xarray/tests/test_dataarray.py::TestDataArray::test_coords_replacement_alignment", "xarray/tests/test_dataset.py::test_rolling_reduce[max-2-3-False-1]", "xarray/tests/test_variable.py::TestIndexVariable::test_init", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-False-std]", "xarray/tests/test_dataset.py::TestDataset::test_stack_unstack_fast", "xarray/tests/test_dataarray.py::TestDataArray::test_groupby_bins_sort", "xarray/tests/test_dataset.py::test_rolling_reduce[median-1-None-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-3-2-False-1]", "xarray/tests/test_variable.py::TestVariable::test_equals_and_identical", "xarray/tests/test_dataset.py::test_rolling_reduce[median-4-None-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-1-1-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-3-3-True-1]", "xarray/tests/test_variable.py::TestIndexVariable::test_concat_periods", "xarray/tests/test_dataset.py::test_rolling_reduce[median-2-2-False-2]", "xarray/tests/test_dataarray.py::test_rolling_iter[1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-4-1-False-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_get_index", "xarray/tests/test_dataarray.py::TestDataArray::test_to_dataset_split", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-1-3-True-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_name", "xarray/tests/test_dataarray.py::TestDataArray::test_align_exclude", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-3-1-False]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[3-2-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-4-None-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-4-3-False-2]", "xarray/tests/test_utils.py::TestDictionaries::test_safe", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-4-3-True]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-1-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[3-None-False]", "xarray/tests/test_dataset.py::TestDataset::test_sel_dataarray", "xarray/tests/test_dataarray.py::TestDataArray::test_drop_index_labels", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-1-None-False-2]", "xarray/tests/test_variable.py::TestIndexVariable::test_1d_reduce", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-1-1-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-2-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-4-2-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-4-1-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-3-2-True-1]", "xarray/tests/test_dataset.py::TestDataset::test_dropna", "xarray/tests/test_dataset.py::test_isin[test_elements0]", "xarray/tests/test_dataarray.py::TestDataArray::test_math_automatic_alignment", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-1-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-2-None-False-2]", "xarray/tests/test_variable.py::TestVariable::test_stack_unstack_consistency", "xarray/tests/test_variable.py::TestVariable::test_copy_with_data", "xarray/tests/test_variable.py::TestVariable::test_array_interface", "xarray/tests/test_variable.py::TestIndexVariable::test_pandas_cateogrical_dtype", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-3-3-True-1]", "xarray/tests/test_dataset.py::TestDataset::test_reindex", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-None-min]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-3-None-True-2]", "xarray/tests/test_variable.py::TestVariable::test_datetime64_conversion", "xarray/tests/test_dataset.py::test_rolling_reduce[median-2-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-2-None-True-2]", "xarray/tests/test_dataset.py::TestDataset::test_setitem_dimension_override", "xarray/tests/test_dataset.py::test_rolling_reduce[max-4-None-False-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_sel_method", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-2-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-2-None-False-2]", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[2-3-True]", "xarray/tests/test_dataarray.py::TestDataArray::test_unstack_pandas_consistency", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-4-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-True-var]", "xarray/tests/test_dataset.py::TestDataset::test_set_index", "xarray/tests/test_dataarray.py::TestDataArray::test_roll_no_coords", "xarray/tests/test_dataset.py::TestDataset::test_constructor_with_coords", "xarray/tests/test_variable.py::TestVariable::test_set_dims", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-1-False-std]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-4-None-True-1]", "xarray/tests/test_dataset.py::TestDataset::test_reindex_fill_value[2.0]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-3-3-False-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_selection_multiindex_remove_unused", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-4-3-True-2]", "xarray/tests/test_dataset.py::TestDataset::test_repr_multiindex", "xarray/tests/test_dataarray.py::TestDataArray::test_shift[2-int-0]", "xarray/tests/test_dataarray.py::TestDataArray::test_align_override_error[darrays0]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-3-None-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-1-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-1-2-True-1]", "xarray/tests/test_variable.py::TestAsCompatibleData::test_ones_like", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-4-2-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-3-1-True-1]", "xarray/tests/test_variable.py::TestIndexVariable::test_getitem_1d_fancy", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-False-max]", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[2-None-False]", "xarray/tests/test_variable.py::TestVariable::test_binary_ops_keep_attrs", "xarray/tests/test_dataset.py::test_rolling_reduce[median-1-None-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-3-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-3-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-1-2-False-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_is_null", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-None-False-median]", "xarray/tests/test_dataset.py::TestDataset::test_info", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-3-None-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-1-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-1-2-True-1]", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[2-2-True]", "xarray/tests/test_variable.py::TestIndexVariable::test_get_level_variable", "xarray/tests/test_variable.py::TestIndexVariable::test_copy_with_data", "xarray/tests/test_dataarray.py::TestDataArray::test_indexes", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-True-min]", "xarray/tests/test_dataarray.py::test_rolling_construct[3-True]", "xarray/tests/test_dataset.py::test_rolling_construct[2-True]", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-None-True-mean]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-1-2-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-3-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-4-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-4-2-False-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_shift[2-int-2]", "xarray/tests/test_variable.py::TestIndexVariable::test_pandas_period_index", "xarray/tests/test_dataset.py::test_rolling_reduce[min-1-2-False-2]", "xarray/tests/test_dataset.py::TestDataset::test_equals_and_identical", "xarray/tests/test_dataset.py::test_rolling_reduce[var-3-None-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_reindex_fill_value[2.0]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-4-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-2-2-True-2]", "xarray/tests/test_dataset.py::TestDataset::test_combine_first", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-1-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-3-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-2-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-2-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-3-None-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-1-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-False-median]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-4-1-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-1-3-True-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-False-sum]", "xarray/tests/test_dataset.py::test_rolling_construct[1-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-3-None-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-3-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-None-mean]", "xarray/tests/test_dataset.py::TestDataset::test_expand_dims_int", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-2-1-False-1]", "xarray/tests/test_dataset.py::test_trapz_datetime[np-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-4-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-4-2-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-4-1-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-2-2-False-1]", "xarray/tests/test_dataset.py::TestDataset::test_sel_drop", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-1-None-False-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_properties", "xarray/tests/test_dataset.py::TestDataset::test_rename_dims", "xarray/tests/test_dataset.py::test_rolling_reduce[max-2-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-3-1-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_align_override", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-3-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[3-3-True]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-3-3-True-2]", "xarray/tests/test_variable.py::TestVariable::test_reduce", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-4-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-1-None-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_broadcast_arrays", "xarray/tests/test_variable.py::TestIndexVariable::test_getitem_uint_1d", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-4-2-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-2-None-True-2]", "xarray/tests/test_dataset.py::TestDataset::test_isel", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-2-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-False-var]", "xarray/tests/test_variable.py::TestVariable::test_multiindex", "xarray/tests/test_dataset.py::TestDataset::test_reduce_strings", "xarray/tests/test_variable.py::TestVariable::test_index_0d_object", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-True-sum]", "xarray/tests/test_dataarray.py::TestDataArray::test_setitem_fancy", "xarray/tests/test_dataset.py::test_rolling_reduce[max-2-2-True-1]", "xarray/tests/test_dataset.py::TestDataset::test_reindex_like_fill_value[fill_value0]", "xarray/tests/test_variable.py::TestVariable::test_concat", "xarray/tests/test_dataset.py::test_rolling_reduce[var-2-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-4-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-2-1-True-1]", "xarray/tests/test_dataset.py::TestDataset::test_roll_coords", "xarray/tests/test_dataset.py::test_rolling_reduce[var-3-None-False-2]", "xarray/tests/test_dataset.py::TestDataset::test_fillna", "xarray/tests/test_dataset.py::test_rolling_reduce[min-2-3-True-2]", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-None-False-max]", "xarray/tests/test_variable.py::TestIndexVariable::test_concat_fixed_len_str", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-3-2-False-1]", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[3-1-True]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-1-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-2-None-True-2]", "xarray/tests/test_dataset.py::test_raise_no_warning_for_nan_in_binary_ops", "xarray/tests/test_variable.py::TestVariable::test_index_0d_timedelta64", "xarray/tests/test_utils.py::Test_is_uniform_and_sorted::test_not_sorted_not_uniform", "xarray/tests/test_dataarray.py::test_rolling_construct[4-False]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-1-1-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-2-2-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-2-3-False-1]", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[2-None-True]", "xarray/tests/test_dataset.py::test_coarsen[1-trim-left-True]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-4-2-False-1]", "xarray/tests/test_dataset.py::TestDataset::test_where_drop_no_indexes", "xarray/tests/test_accessor_dt.py::TestDatetimeAccessor::test_seasons", "xarray/tests/test_dataset.py::TestDataset::test_copy", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-2-3-True-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_shift[2-int-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-4-3-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-3-None-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-2-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-False-median]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-None-sum]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-2-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-2-None-False-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_to_dataframe", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-None-False-sum]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-1-1-True-2]", "xarray/tests/test_dataset.py::TestDataset::test_reduce_cumsum_test_dims", "xarray/tests/test_dataset.py::test_rolling_reduce[max-4-1-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-1-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-3-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-1-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-3-2-False-1]", "xarray/tests/test_dataarray.py::test_weakref", "xarray/tests/test_dataset.py::TestDataset::test_reduce", "xarray/tests/test_dataarray.py::TestDataArray::test_broadcast_arrays_misaligned", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-None-max]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-3-3-False-2]", "xarray/tests/test_variable.py::TestIndexVariable::test_index_0d_int", "xarray/tests/test_dataset.py::test_rolling_reduce[std-2-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-4-None-False-1]", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[4-2-True]", "xarray/tests/test_dataarray.py::TestDataArray::test_groupby_math_not_aligned", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-2-1-False]", "xarray/tests/test_dataarray.py::TestDataArray::test_reindex_regressions", "xarray/tests/test_variable.py::TestVariable::test_coarsen_2d", "xarray/tests/test_dataset.py::TestDataset::test_drop_variables", "xarray/tests/test_dataset.py::TestDataset::test_sortby", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[1-None-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-4-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-3-3-False-1]", "xarray/tests/test_dataset.py::test_differentiate[2-True]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-3-2-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-2-2-True-1]", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[2-1-False]", "xarray/tests/test_variable.py::TestIndexVariable::test_getitem_dict", "xarray/tests/test_dataset.py::TestDataset::test_reduce_dtypes", "xarray/tests/test_dataarray.py::TestDataArray::test_repr_multiindex_long", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[1-2-True]", "xarray/tests/test_dataset.py::TestDataset::test_dataset_number_math", "xarray/tests/test_dataset.py::test_rolling_reduce[var-1-3-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-2-1-False-2]", "xarray/tests/test_variable.py::TestIndexVariable::test_aggregate_complex", "xarray/tests/test_dataset.py::TestDataset::test_virtual_variable_multiindex", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-3-None-False-2]", "xarray/tests/test_variable.py::TestVariable::test_roll", "xarray/tests/test_dataset.py::test_rolling_reduce[var-1-2-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-1-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-1-2-False-1]", "xarray/tests/test_variable.py::TestVariable::test_copy_with_data_errors", "xarray/tests/test_dataarray.py::TestDataArray::test_groupby_multidim_apply", "xarray/tests/test_dataset.py::TestDataset::test_broadcast", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-1-2-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-2-1-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-1-None-True]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-4-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-4-3-True-2]", "xarray/tests/test_dataset.py::TestDataset::test_sel_dataarray_mindex", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[1-1-False]", "xarray/tests/test_dataset.py::TestDataset::test_setitem_with_coords", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-3-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-4-2-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-2-1-True-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_shift[fill_value1-float--5]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-2-3-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-3-3-False-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_assign_attrs", "xarray/tests/test_dataset.py::test_rolling_reduce[min-1-1-False-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_reduce", "xarray/tests/test_dataset.py::test_rolling_reduce[std-2-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-1-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[4-2-True]", "xarray/tests/test_variable.py::TestVariable::test_object_conversion", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-None-True-sum]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-3-2-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-4-None-True-2]", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[2-1-True]", "xarray/tests/test_dataarray.py::TestDataArray::test_reset_index", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-None-max]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-4-3-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-4-None-False-2]", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-None-True-max]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-4-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-4-2-False-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_upsample", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-3-None-True-1]", "xarray/tests/test_utils.py::Test_is_uniform_and_sorted::test_two_numbers", "xarray/tests/test_dataset.py::test_rolling_reduce[var-2-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-3-2-True-2]", "xarray/tests/test_dataset.py::TestDataset::test_assign", "xarray/tests/test_dataarray.py::TestDataArray::test_reduce_out", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-2-3-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_equals_failures", "xarray/tests/test_dataset.py::TestDataset::test_expand_dims_error", "xarray/tests/test_dataarray.py::TestDataArray::test_expand_dims_with_greater_dim_size", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-4-2-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-4-3-True-1]", "xarray/tests/test_dataset.py::TestDataset::test_setitem_auto_align", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-True-max]", "xarray/tests/test_dataset.py::TestDataset::test_dataset_diff_exception_label_str", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-3-None-True]", "xarray/tests/test_dataset.py::test_no_dict", "xarray/tests/test_variable.py::TestVariable::test_reduce_keep_attrs", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-4-1-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-2-None-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-3-3-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-4-3-True-2]", "xarray/tests/test_variable.py::TestVariable::test_stack_errors", "xarray/tests/test_variable.py::TestAsCompatibleData::test_masked_array", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-4-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[1-None-True]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-1-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-4-1-True-1]", "xarray/tests/test_variable.py::TestIndexVariable::test_pandas_data", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-None-mean]", "xarray/tests/test_variable.py::TestVariable::test_aggregate_complex", "xarray/tests/test_dataarray.py::TestDataArray::test_reorder_levels", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-2-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[4-None-True]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-1-1-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-1-3-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-3-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-False-var]", "xarray/tests/test_dataset.py::TestDataset::test_drop_labels_by_keyword", "xarray/tests/test_dataarray.py::TestDataArray::test_sel_invalid_slice", "xarray/tests/test_variable.py::TestBackendIndexing::test_CopyOnWriteArray", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-4-3-True-2]", "xarray/tests/test_variable.py::TestVariable::test_items", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-4-None-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-2-3-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-3-1-True-1]", "xarray/tests/test_dataset.py::TestDataset::test_get_index", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-4-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-3-2-True-2]", "xarray/tests/test_dataset.py::TestDataset::test_dataset_dataset_math", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-False-median]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-3-3-True-2]", "xarray/tests/test_dataset.py::TestDataset::test_roll_no_coords", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-2-1-False-1]", "xarray/tests/test_dataset.py::test_constructor_raises_with_invalid_coords[unaligned_coords0]", "xarray/tests/test_dataarray.py::test_rolling_iter[2]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-2-None-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-4-None-False-2]", "xarray/tests/test_variable.py::TestVariable::test_concat_number_strings", "xarray/tests/test_dataset.py::TestDataset::test_align_exact", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-2-3-False-1]", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-1-True-max]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-3-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-2-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-3-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-4-1-False-2]", "xarray/tests/test_dataset.py::TestDataset::test_to_stacked_array_to_unstacked_dataset_different_dimension", "xarray/tests/test_dataset.py::TestDataset::test_equals_failures", "xarray/tests/test_dataarray.py::TestDataArray::test_matmul", "xarray/tests/test_dataarray.py::TestDataArray::test_combine_first", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-2-2-False-1]", "xarray/tests/test_variable.py::TestVariable::test_reduce_funcs", "xarray/tests/test_variable.py::TestVariable::test_coarsen", "xarray/tests/test_variable.py::TestVariable::test_getitem_with_mask", "xarray/tests/test_variable.py::TestVariable::test_indexer_type", "xarray/tests/test_dataarray.py::TestDataArray::test_init_value", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-1-None-std]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-True-std]", "xarray/tests/test_dataarray.py::test_raise_no_warning_for_nan_in_binary_ops", "xarray/tests/test_dataset.py::TestDataset::test_resample_ds_da_are_the_same", "xarray/tests/test_utils.py::test_multiindex_from_product_levels_non_unique", "xarray/tests/test_dataset.py::test_rolling_reduce[min-1-1-False-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_isel_fancy", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-2-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-3-3-False-1]", "xarray/tests/test_utils.py::Test_is_uniform_and_sorted::test_relative_tolerance", "xarray/tests/test_dataset.py::TestDataset::test_copy_with_data", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-1-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-True-std]", "xarray/tests/test_dataset.py::TestDataset::test_reduce_no_axis", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-2-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-4-1-False-2]", "xarray/tests/test_dataset.py::TestDataset::test_getitem", "xarray/tests/test_variable.py::TestIndexVariable::test_eq_all_dtypes", "xarray/tests/test_dataset.py::test_rolling_reduce[max-3-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-3-2-True-2]", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-1-False-median]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-3-2-False-1]", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-None-True-median]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-1-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-4-None-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-4-3-False-2]", "xarray/tests/test_dataset.py::TestDataset::test_groupby", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-2-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_construct[1-True]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-3-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-1-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-3-None-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-4-2-False]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-1-3-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-1-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-2-1-False-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_coords", "xarray/tests/test_variable.py::TestIndexVariable::test_index_0d_float", "xarray/tests/test_dataarray.py::TestDataArray::test_squeeze_drop", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-4-2-False-2]", "xarray/tests/test_variable.py::TestVariable::test_copy[int-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-4-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-False-median]", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[4-3-True]", "xarray/tests/test_variable.py::TestVariable::test_concat_mixed_dtypes", "xarray/tests/test_dataarray.py::TestDataArray::test_stack_unstack_decreasing_coordinate", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-False-min]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-True-sum]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-2-2-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-2-2-False-2]", "xarray/tests/test_dataset.py::TestDataset::test_groupby_returns_new_type", "xarray/tests/test_dataarray.py::TestDataArray::test_align", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-True-mean]", "xarray/tests/test_variable.py::TestIndexVariable::test_copy[str-False]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-False-std]", "xarray/tests/test_dataset.py::TestDataset::test_to_and_from_dict", "xarray/tests/test_dataarray.py::TestDataArray::test_groupby_bins", "xarray/tests/test_dataset.py::test_rolling_reduce[min-4-2-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-1-None-False-2]", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-1-False-min]", "xarray/tests/test_dataset.py::TestDataset::test_reduce_coords", "xarray/tests/test_variable.py::TestVariable::test_roll_consistency", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-1-None-True]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-2-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-True-sum]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-3-2-False-2]", "xarray/tests/test_dataset.py::TestDataset::test_sel_fancy", "xarray/tests/test_dataset.py::TestDataset::test_reduce_scalars", "xarray/tests/test_dataset.py::test_rolling_reduce[median-2-1-True-2]", "xarray/tests/test_variable.py::TestVariable::test_attrs", "xarray/tests/test_dataset.py::test_rolling_reduce[min-3-2-False-1]", "xarray/tests/test_dataset.py::TestDataset::test_slice_virtual_variable", "xarray/tests/test_dataset.py::test_rolling_reduce[std-2-3-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-2-None-True-2]", "xarray/tests/test_dataset.py::TestDataset::test_where", "xarray/tests/test_dataset.py::test_integrate[False]", "xarray/tests/test_dataarray.py::TestDataArray::test_encoding", "xarray/tests/test_dataset.py::test_rolling_reduce[min-2-None-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-4-1-False-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_to_and_from_series", "xarray/tests/test_dataset.py::test_rolling_reduce[min-3-None-True-1]", "xarray/tests/test_dataset.py::TestDataset::test_to_and_from_dict_with_nan_nat", "xarray/tests/test_dataset.py::test_rolling_reduce[std-3-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-True-min]", "xarray/tests/test_dataset.py::test_rolling_construct[4-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-2-2-True-1]", "xarray/tests/test_dataset.py::TestDataset::test_mean_uint_dtype", "xarray/tests/test_variable.py::TestVariable::test_stack", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-4-None-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-4-None-False]", "xarray/tests/test_dataset.py::TestDataset::test_real_and_imag", "xarray/tests/test_dataarray.py::TestDataArray::test_align_override_error[darrays1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-4-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-2-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-2-1-False-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_where_string", "xarray/tests/test_variable.py::TestIndexVariable::test_copy[float-False]", "xarray/tests/test_dataset.py::test_dir_expected_attrs[None]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-4-None-True-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_to_and_from_empty_series", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-1-1-True-2]", "xarray/tests/test_variable.py::TestVariable::test_quantile", "xarray/tests/test_dataarray.py::TestDataArray::test_dims", "xarray/tests/test_dataset.py::TestDataset::test_reindex_like", "xarray/tests/test_dataset.py::TestDataset::test_assign_coords", "xarray/tests/test_dataset.py::test_rolling_reduce[min-4-1-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-1-None-False]", "xarray/tests/test_dataset.py::TestDataset::test_coords_setitem_with_new_dimension", "xarray/tests/test_dataarray.py::TestDataArray::test_broadcast_equals", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[3-2-False]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-True-max]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-1-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-1-None-True-2]", "xarray/tests/test_variable.py::TestVariable::test_copy_index_with_data_errors", "xarray/tests/test_dataset.py::test_rolling_reduce[std-3-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-3-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-2-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-2-1-True-2]", "xarray/tests/test_variable.py::TestVariable::test_getitem_uint_1d", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-3-None-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-1-3-True]", "xarray/tests/test_dataset.py::TestDataset::test_apply", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-1-2-False-1]", "xarray/tests/test_dataset.py::TestDataset::test_thin", "xarray/tests/test_dataset.py::test_rolling_reduce[min-2-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-True-median]", "xarray/tests/test_dataset.py::test_subclass_slots", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-1-None-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-4-3-False-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_get_index_size_zero", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-True-var]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-2-None-False-2]", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-1-None-sum]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-1-3-False-1]", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[1-None-True]", "xarray/tests/test_variable.py::TestVariable::test_getitem_with_mask_nd_indexer", "xarray/tests/test_dataarray.py::test_no_dict", "xarray/tests/test_dataset.py::TestDataset::test_attr_access", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-1-2-False-2]", "xarray/tests/test_dataset.py::TestDataset::test_rank", "xarray/tests/test_dataset.py::test_rolling_reduce[min-2-3-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-3-3-False]", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-1-None-median]", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[3-None-False]", "xarray/tests/test_variable.py::TestVariable::test_getitem_dict", "xarray/tests/test_dataset.py::TestDataset::test_align_fill_value[2]", "xarray/tests/test_dataset.py::test_rolling_construct[3-False]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-2-2-False]", "xarray/tests/test_dataset.py::test_coarsen_coords[1-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-2-3-False-2]", "xarray/tests/test_variable.py::TestIndexVariable::test_0d_time_data", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-1-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-1-2-True-1]", "xarray/tests/test_variable.py::TestIndexVariable::test_to_index", "xarray/tests/test_variable.py::TestVariable::test_pandas_period_index", "xarray/tests/test_utils.py::TestAlias::test", "xarray/tests/test_dataset.py::TestDataset::test_unary_ops", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-2-None-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-3-1-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-4-1-True-2]", "xarray/tests/test_utils.py::TestDictionaries::test_dict_equiv", "xarray/tests/test_dataset.py::TestDataset::test_resample_by_mean_discarding_attrs", "xarray/tests/test_dataset.py::test_rolling_reduce[max-4-3-True-2]", "xarray/tests/test_variable.py::TestVariable::test_0d_time_data", "xarray/tests/test_dataarray.py::TestDataArray::test_sortby", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-1-3-False-2]", "xarray/tests/test_variable.py::TestBackendIndexing::test_LazilyOuterIndexedArray", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-None-std]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-2-2-False-2]", "xarray/tests/test_variable.py::TestVariable::test_get_axis_num", "xarray/tests/test_utils.py::Test_is_uniform_and_sorted::test_not_sorted_uniform", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-4-2-True]", "xarray/tests/test_utils.py::test_either_dict_or_kwargs", "xarray/tests/test_dataset.py::test_rolling_reduce[median-3-3-False-2]", "xarray/tests/test_variable.py::TestVariable::test_datetime64_conversion_scalar", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-2-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-None-median]", "xarray/tests/test_variable.py::TestVariable::test_1d_math", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-3-None-True-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_stack_nonunique_consistency", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-4-1-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-1-2-False]", "xarray/tests/test_variable.py::TestVariable::test_eq_all_dtypes", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-4-1-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-1-1-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-2-2-True-2]", "xarray/tests/test_dataset.py::TestDataset::test_pickle", "xarray/tests/test_variable.py::TestIndexVariable::test_copy_index_with_data", "xarray/tests/test_variable.py::TestVariable::test_pandas_datetime64_with_tz", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-4-None-True-2]", "xarray/tests/test_dataset.py::TestDataset::test_setitem_both_non_unique_index", "xarray/tests/test_dataset.py::test_rolling_reduce[var-2-1-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-2-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-4-1-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-3-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-1-3-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-4-3-False-1]", "xarray/tests/test_dataset.py::TestDataset::test_dataset_math_errors", "xarray/tests/test_dataset.py::test_differentiate[1-False]", "xarray/tests/test_variable.py::TestAsCompatibleData::test_unsupported_type", "xarray/tests/test_dataset.py::TestDataset::test_filter_by_attrs", "xarray/tests/test_dataset.py::TestDataset::test_to_stacked_array_invalid_sample_dims", "xarray/tests/test_dataset.py::TestDataset::test_reduce_keep_attrs", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords0-unaligned_coords3]", "xarray/tests/test_dataset.py::TestDataset::test_delitem", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords0-unaligned_coords4]", "xarray/tests/test_dataarray.py::TestDataArray::test_setattr_raises", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[2-None-False]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-1-3-True-2]", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[1-None-False]", "xarray/tests/test_variable.py::TestVariable::test_broadcast_equals", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[2-1-False]", "xarray/tests/test_dataarray.py::TestDataArray::test_reindex_method", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-3-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-None-std]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-3-2-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-2-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-4-2-False-1]", "xarray/tests/test_variable.py::TestVariable::test_real_and_imag", "xarray/tests/test_dataarray.py::TestDataArray::test_groupby_sum", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-False-var]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-2-3-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-1-3-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-1-1-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-4-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-3-1-True-1]", "xarray/tests/test_dataset.py::TestDataset::test_update", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-False-sum]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-4-2-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-2-None-True]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-1-2-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-2-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-4-1-False-1]", "xarray/tests/test_dataset.py::TestDataset::test_where_drop", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-1-1-False-2]", "xarray/tests/test_variable.py::TestVariable::test_load", "xarray/tests/test_variable.py::TestVariable::test_properties", "xarray/tests/test_dataset.py::test_rolling_reduce[min-4-1-False-1]", "xarray/tests/test_utils.py::test_is_remote_uri", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-None-None-min]", "xarray/tests/test_dataarray.py::TestDataArray::test_constructor_invalid", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-2-3-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-1-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-1-1-False-2]", "xarray/tests/test_variable.py::TestIndexVariable::test_copy[float-True]", "xarray/tests/test_dataarray.py::test_rolling_count_correct", "xarray/tests/test_dataset.py::TestDataset::test_expand_dims_kwargs_python36plus", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-3-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-3-2-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-1-1-True]", "xarray/tests/test_dataset.py::TestDataset::test_drop_dims", "xarray/tests/test_dataset.py::test_rolling_reduce[median-1-None-True-2]", "xarray/tests/test_dataset.py::TestDataset::test_groupby_iter", "xarray/tests/test_dataset.py::test_rolling_reduce[min-1-1-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-3-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-None-min]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-4-1-True-2]", "xarray/tests/test_dataset.py::TestDataset::test_dataset_diff_n1_label", "xarray/tests/test_dataarray.py::TestDataArray::test_sizes", "xarray/tests/test_dataset.py::test_isin_dataset", "xarray/tests/test_dataset.py::test_rolling_reduce[median-4-3-False-1]", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords1-unaligned_coords7]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[2-2-False]", "xarray/tests/test_dataarray.py::TestDataArray::test_broadcast_like", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-4-2-False-2]", "xarray/tests/test_dataset.py::TestDataset::test_roll_multidim", "xarray/tests/test_dataarray.py::TestDataArray::test_real_and_imag", "xarray/tests/test_dataset.py::test_rolling_reduce[max-2-1-False-1]", "xarray/tests/test_dataset.py::TestDataset::test_tail", "xarray/tests/test_dataset.py::test_rolling_reduce[median-2-1-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-1-None-True-2]", "xarray/tests/test_dataarray.py::test_rolling_construct[2-False]", "xarray/tests/test_variable.py::TestIndexVariable::test_0d_object_array_with_list", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-1-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-3-1-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-2-3-True]", "xarray/tests/test_dataarray.py::TestDataArray::test_rank", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-True-sum]", "xarray/tests/test_variable.py::TestIndexVariable::test_concat", "xarray/tests/test_variable.py::TestVariable::test_transpose_0d", "xarray/tests/test_dataset.py::test_rolling_reduce[max-1-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-1-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-1-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-4-3-False-1]", "xarray/tests/test_dataset.py::TestDataset::test_isel_drop", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-3-None-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-3-2-False-2]", "xarray/tests/test_dataset.py::test_error_message_on_set_supplied", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-None-max]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-1-None-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-1-1-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-4-2-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-2-1-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_to_dataset_retains_keys", "xarray/tests/test_dataset.py::test_rolling_reduce[var-4-3-True-2]", "xarray/tests/test_dataset.py::TestDataset::test_reset_index", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-3-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-1-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-2-1-True-1]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[2-1-True]", "xarray/tests/test_variable.py::TestVariable::test_copy[float-False]", "xarray/tests/test_variable.py::TestIndexVariable::test_getitem_0d_array", "xarray/tests/test_dataset.py::test_rolling_reduce[min-3-3-False-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_broadcast_arrays_exclude", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-4-1-True-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_setitem", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-1-2-False-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_repr", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-2-1-True-1]", "xarray/tests/test_utils.py::test_repr_object_magic_methods", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-1-None-sum]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-3-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-3-3-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-2-None-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-1-2-False-2]", "xarray/tests/test_variable.py::TestIndexVariable::test_coordinate_alias", "xarray/tests/test_dataarray.py::test_rolling_construct[2-True]", "xarray/tests/test_dataarray.py::TestDataArray::test_virtual_time_components", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-1-3-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_to_and_from_dict_with_nan_nat", "xarray/tests/test_dataset.py::test_rolling_reduce[max-1-2-False-1]", "xarray/tests/test_variable.py::TestVariable::test_data_and_values", "xarray/tests/test_dataarray.py::TestDataArray::test_squeeze", "xarray/tests/test_dataset.py::TestDataset::test_reduce_only_one_axis", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-3-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[1-3-True]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-3-None-True-1]", "xarray/tests/test_dataset.py::TestDataset::test_modify_inplace", "xarray/tests/test_variable.py::TestVariable::test_concat_attrs", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-1-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-1-2-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-2-2-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-2-None-True-1]", "xarray/tests/test_dataset.py::TestDataset::test_attrs", "xarray/tests/test_variable.py::TestVariable::test_getitem_fancy", "xarray/tests/test_dataarray.py::TestDataArray::test_groupby_count", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-4-2-False]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-4-None-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-2-3-False-2]", "xarray/tests/test_variable.py::TestVariable::test_index_0d_numpy_string", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[3-None-True]", "xarray/tests/test_dataarray.py::TestDataArray::test_head", "xarray/tests/test_variable.py::TestVariable::test_getitem_basic", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-1-None-mean]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-1-2-True-2]", "xarray/tests/test_variable.py::TestAsCompatibleData::test_datetime", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-2-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-2-2-True-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_shift[fill_value1-float-0]", "xarray/tests/test_dataarray.py::TestDataArray::test_isel_types", "xarray/tests/test_dataset.py::test_rolling_pandas_compat[2-3-True]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-2-None-True]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-2-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-2-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z1-None-False-var]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-1-1-True-2]", "xarray/tests/test_dataset.py::TestDataset::test_isel_expand_dims_roundtrip", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-2-None-False]", "xarray/tests/test_dataset.py::TestDataset::test_reduce_non_numeric", "xarray/tests/test_dataset.py::TestDataset::test_repr_period_index", "xarray/tests/test_dataarray.py::TestDataArray::test_to_masked_array", "xarray/tests/test_dataset.py::test_rolling_reduce[std-3-1-True-1]", "xarray/tests/test_dataset.py::TestDataset::test_swap_dims", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-1-3-False-1]", "xarray/tests/test_dataset.py::TestDataset::test_dataset_diff_n1_simple", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-3-3-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-3-None-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_reindex_fill_value[2]", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-1-None-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-4-2-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-2-None-False-1]", "xarray/tests/test_dataset.py::TestDataset::test_expand_dims_existing_scalar_coord", "xarray/tests/test_dataset.py::test_rolling_reduce[median-2-None-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-3-1-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-1-3-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_coord_coords", "xarray/tests/test_dataset.py::TestDataset::test_merge_multiindex_level", "xarray/tests/test_dataset.py::test_rolling_reduce[max-4-None-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-2-3-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-3-None-False-1]", "xarray/tests/test_dataset.py::TestDataset::test_shift[2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-1-1-True-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-4-1-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-3-1-True-2]", "xarray/tests/test_variable.py::TestIndexVariable::test_datetime64_conversion", "xarray/tests/test_dataarray.py::TestDataArray::test_upsample_nd", "xarray/tests/test_dataset.py::test_rolling_reduce[max-2-3-True-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_getitem", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-1-None-False-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-1-3-False-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-2-None-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-4-3-False]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-3-3-False]", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords1-unaligned_coords0]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-3-None-False-1]", "xarray/tests/test_dataset.py::TestDataset::test_head", "xarray/tests/test_dataset.py::test_rolling_reduce[median-4-2-True-1]", "xarray/tests/test_dataset.py::test_rolling_properties[1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-3-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[sum-1-2-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_to_dict_with_numpy_attrs", "xarray/tests/test_dataset.py::test_rolling_reduce[mean-3-1-False-1]", "xarray/tests/test_dataset.py::TestDataset::test_assign_attrs", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-2-2-True]", "xarray/tests/test_dataset.py::TestDataset::test_coords_modify", "xarray/tests/test_dataset.py::TestDataset::test_resample_by_last_discarding_attrs", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-None-mean]", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-1-1-True-1]", "xarray/tests/test_dataset.py::TestDataset::test_asarray", "xarray/tests/test_dataarray.py::TestDataArray::test_stack_unstack", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-3-3-False-1]", "xarray/tests/test_variable.py::TestVariable::test_shift[2.0]", "xarray/tests/test_variable.py::TestVariable::test_reduce_keepdims", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-3-2-False-2]", "xarray/tests/test_variable.py::TestIndexVariable::test_concat_multiindex", "xarray/tests/test_utils.py::test_hidden_key_dict", "xarray/tests/test_variable.py::TestIndexVariable::test_encoding_preserved", "xarray/tests/test_dataarray.py::test_rolling_reduce[std-1-None-False-1]", "xarray/tests/test_variable.py::TestIndexVariable::test_getitem_1d", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-4-1-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[std-2-3-True-1]", "xarray/tests/test_dataarray.py::TestDataArray::test_reset_coords", "xarray/tests/test_dataarray.py::TestDataArray::test_groupby_apply_center", "xarray/tests/test_dataarray.py::test_rolling_reduce[mean-4-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[var-3-1-False-1]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-2-2-True-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-3-None-False-1]", "xarray/tests/test_dataset.py::TestDataset::test_groupby_math", "xarray/tests/test_dataset.py::test_rolling_reduce[var-2-2-False-2]", "xarray/tests/test_dataarray.py::test_rolling_pandas_compat[4-1-False]", "xarray/tests/test_dataarray.py::TestDataArray::test_broadcast_arrays_nocopy", "xarray/tests/test_dataarray.py::TestDataArray::test_inplace_math_automatic_alignment", "xarray/tests/test_dataset.py::test_dataset_constructor_aligns_to_explicit_coords[coords1-unaligned_coords8]", "xarray/tests/test_dataarray.py::TestDataArray::test_swap_dims", "xarray/tests/test_dataarray.py::TestDataArray::test_loc_assign", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[sum-1-3-False]", "xarray/tests/test_dataarray.py::TestDataArray::test_expand_dims_error", "xarray/tests/test_dataset.py::test_rolling_reduce[std-2-None-True-2]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-3-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-1-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-1-1-True-2]", "xarray/tests/test_dataarray.py::TestDataArray::test_align_without_indexes_errors", "xarray/tests/test_dataarray.py::test_rolling_wrapped_bottleneck[1-1-None-min]", "xarray/tests/test_dataarray.py::test_rolling_reduce_nonnumeric[max-2-1-False]", "xarray/tests/test_dataarray.py::test_rolling_reduce[max-2-1-False-2]", "xarray/tests/test_dataset.py::test_coarsen[1-pad-right-False]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-True-mean]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-1-None-sum]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-2-3-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[max-2-None-False-2]", "xarray/tests/test_dataset.py::test_rolling_reduce[median-4-3-True-1]", "xarray/tests/test_dataset.py::test_rolling_wrapped_bottleneck[1-z2-None-True-std]", "xarray/tests/test_dataarray.py::test_rolling_reduce[sum-3-None-True-1]", "xarray/tests/test_dataset.py::test_rolling_reduce[min-1-None-True-1]"], "FAIL2PASS": ["xarray/tests/test_utils.py::test_infix_dims[supplied1-all_1-expected1]", "xarray/tests/test_utils.py::test_infix_dims_errors[supplied0-all_0]", "xarray/tests/test_utils.py::test_infix_dims[supplied2-all_2-expected2]", "xarray/tests/test_utils.py::test_infix_dims[supplied4-all_4-expected4]", "xarray/tests/test_utils.py::test_infix_dims[supplied3-all_3-expected3]", "xarray/tests/test_utils.py::test_infix_dims[supplied0-all_0-expected0]", "xarray/tests/test_utils.py::test_infix_dims_errors[supplied1-all_1]", "xarray/tests/test_dataset.py::TestDataset::test_dataset_ellipsis_transpose_different_ordered_vars", "xarray/tests/test_utils.py::test_infix_dims[supplied5-all_5-expected5]", "xarray/tests/test_variable.py::TestVariable::test_transpose", "xarray/tests/test_dataarray.py::TestDataArray::test_transpose", "xarray/tests/test_dataset.py::TestDataset::test_dataset_transpose"], "mask_doc_diff": [{"path": "doc/reshaping.rst", "old_path": "a/doc/reshaping.rst", "new_path": "b/doc/reshaping.rst", "metadata": "diff --git a/doc/reshaping.rst b/doc/reshaping.rst\nindex 51202f9b..455a24f9 100644\n--- a/doc/reshaping.rst\n+++ b/doc/reshaping.rst\n@@ -18,12 +18,14 @@ Reordering dimensions\n ---------------------\n \n To reorder dimensions on a :py:class:`~xarray.DataArray` or across all variables\n-on a :py:class:`~xarray.Dataset`, use :py:meth:`~xarray.DataArray.transpose`:\n+on a :py:class:`~xarray.Dataset`, use :py:meth:`~xarray.DataArray.transpose`. An \n+ellipsis (`...`) can be use to represent all other dimensions:\n \n .. ipython:: python\n \n ds = xr.Dataset({'foo': (('x', 'y', 'z'), [[[42]]]), 'bar': (('y', 'z'), [[24]])})\n ds.transpose('y', 'z', 'x')\n+ ds.transpose(..., 'x') # equivalent\n ds.transpose() # reverses all dimensions\n \n Expand and squeeze dimensions\n"}, {"path": "doc/whats-new.rst", "old_path": "a/doc/whats-new.rst", "new_path": "b/doc/whats-new.rst", "metadata": "diff --git a/doc/whats-new.rst b/doc/whats-new.rst\nindex dea110b5..5e7ad542 100644\n--- a/doc/whats-new.rst\n+++ b/doc/whats-new.rst\n@@ -25,6 +25,9 @@ Breaking changes\n \n New Features\n ~~~~~~~~~~~~\n+- :py:meth:`Dataset.transpose` and :py:meth:`DataArray.transpose` now support an ellipsis (`...`)\n+ to represent all 'other' dimensions. For example, to move one dimension to the front,\n+ use `.transpose('x', ...)`. \n - Changed `xr.ALL_DIMS` to equal python's `Ellipsis` (`...`), and changed internal usages to use\n `...` directly. As before, you can use this to instruct a `groupby` operation\n to reduce over all dimensions. While we have no plans to remove `xr.ALL_DIMS`, we suggest\n"}], "augmentations": {"header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [{"type": "field", "name": "infix_dims"}, {"type": "field", "name": "infix_dims"}, {"type": "function", "name": "infix_dims"}]}, "problem_statement": "diff --git a/doc/reshaping.rst b/doc/reshaping.rst\nindex 51202f9b..455a24f9 100644\n--- a/doc/reshaping.rst\n+++ b/doc/reshaping.rst\n@@ -18,12 +18,14 @@ Reordering dimensions\n ---------------------\n \n To reorder dimensions on a :py:class:`~xarray.DataArray` or across all variables\n-on a :py:class:`~xarray.Dataset`, use :py:meth:`~xarray.DataArray.transpose`:\n+on a :py:class:`~xarray.Dataset`, use :py:meth:`~xarray.DataArray.transpose`. An \n+ellipsis (`...`) can be use to represent all other dimensions:\n \n .. ipython:: python\n \n ds = xr.Dataset({'foo': (('x', 'y', 'z'), [[[42]]]), 'bar': (('y', 'z'), [[24]])})\n ds.transpose('y', 'z', 'x')\n+ ds.transpose(..., 'x') # equivalent\n ds.transpose() # reverses all dimensions\n \n Expand and squeeze dimensions\n\ndiff --git a/doc/whats-new.rst b/doc/whats-new.rst\nindex dea110b5..5e7ad542 100644\n--- a/doc/whats-new.rst\n+++ b/doc/whats-new.rst\n@@ -25,6 +25,9 @@ Breaking changes\n \n New Features\n ~~~~~~~~~~~~\n+- :py:meth:`Dataset.transpose` and :py:meth:`DataArray.transpose` now support an ellipsis (`...`)\n+ to represent all 'other' dimensions. For example, to move one dimension to the front,\n+ use `.transpose('x', ...)`. \n - Changed `xr.ALL_DIMS` to equal python's `Ellipsis` (`...`), and changed internal usages to use\n `...` directly. As before, you can use this to instruct a `groupby` operation\n to reduce over all dimensions. While we have no plans to remove `xr.ALL_DIMS`, we suggest\n\nIf completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:\n[{'type': 'field', 'name': 'infix_dims'}, {'type': 'field', 'name': 'infix_dims'}, {'type': 'function', 'name': 'infix_dims'}]\n"} @@ -69,7 +69,7 @@ {"repo": "scikit-learn/scikit-learn", "instance_id": "scikit-learn__scikit-learn-17317", "html_url": "https://github.com/scikit-learn/scikit-learn/pull/17317", "feature_patch": "diff --git a/doc/modules/preprocessing.rst b/doc/modules/preprocessing.rst\nindex 024dd074e2e41..79d57913a9565 100644\n--- a/doc/modules/preprocessing.rst\n+++ b/doc/modules/preprocessing.rst\n@@ -590,6 +590,34 @@ In the transformed `X`, the first column is the encoding of the feature with\n categories \"male\"/\"female\", while the remaining 6 columns is the encoding of\n the 2 features with respectively 3 categories each.\n \n+:class:`OneHotEncoder` supports categorical features with missing values by\n+considering the missing values as an additional category::\n+\n+ >>> X = [['male', 'Safari'],\n+ ... ['female', None],\n+ ... [np.nan, 'Firefox']]\n+ >>> enc = preprocessing.OneHotEncoder(handle_unknown='error').fit(X)\n+ >>> enc.categories_\n+ [array(['female', 'male', nan], dtype=object),\n+ array(['Firefox', 'Safari', None], dtype=object)]\n+ >>> enc.transform(X).toarray()\n+ array([[0., 1., 0., 0., 1., 0.],\n+ [1., 0., 0., 0., 0., 1.],\n+ [0., 0., 1., 1., 0., 0.]])\n+\n+If a feature contains both `np.nan` and `None`, they will be considered\n+separate categories::\n+\n+ >>> X = [['Safari'], [None], [np.nan], ['Firefox']]\n+ >>> enc = preprocessing.OneHotEncoder(handle_unknown='error').fit(X)\n+ >>> enc.categories_\n+ [array(['Firefox', 'Safari', None, nan], dtype=object)]\n+ >>> enc.transform(X).toarray()\n+ array([[0., 1., 0., 0.],\n+ [0., 0., 1., 0.],\n+ [0., 0., 0., 1.],\n+ [1., 0., 0., 0.]])\n+\n See :ref:`dict_feature_extraction` for categorical features that are\n represented as a dict, not as scalars.\n \n@@ -791,5 +819,5 @@ error with a ``filterwarnings``::\n ... category=UserWarning, append=False)\n \n For a full code example that demonstrates using a :class:`FunctionTransformer`\n-to extract features from text data see \n+to extract features from text data see\n :ref:`sphx_glr_auto_examples_compose_plot_column_transformer.py`\ndiff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex f35dcc8f72ee4..b52fbfc14bd40 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -552,6 +552,9 @@ Changelog\n :mod:`sklearn.preprocessing`\n ............................\n \n+- |Feature| :class:`preprocessing.OneHotEncoder` now supports missing\n+ values by treating them as a category. :pr:`17317` by `Thomas Fan`_.\n+\n - |Feature| Add a new ``handle_unknown`` parameter with a\n ``use_encoded_value`` option, along with a new ``unknown_value`` parameter,\n to :class:`preprocessing.OrdinalEncoder` to allow unknown categories during\ndiff --git a/examples/compose/plot_column_transformer_mixed_types.py b/examples/compose/plot_column_transformer_mixed_types.py\nindex 539f38a60bbe4..a2937e041f186 100644\n--- a/examples/compose/plot_column_transformer_mixed_types.py\n+++ b/examples/compose/plot_column_transformer_mixed_types.py\n@@ -72,9 +72,7 @@\n ('scaler', StandardScaler())])\n \n categorical_features = ['embarked', 'sex', 'pclass']\n-categorical_transformer = Pipeline(steps=[\n- ('imputer', SimpleImputer(strategy='constant', fill_value='missing')),\n- ('onehot', OneHotEncoder(handle_unknown='ignore'))])\n+categorical_transformer = OneHotEncoder(handle_unknown='ignore')\n \n preprocessor = ColumnTransformer(\n transformers=[\ndiff --git a/examples/inspection/plot_permutation_importance.py b/examples/inspection/plot_permutation_importance.py\nindex d708aa0fd6756..0751337ef69ff 100644\n--- a/examples/inspection/plot_permutation_importance.py\n+++ b/examples/inspection/plot_permutation_importance.py\n@@ -63,16 +63,13 @@\n X_train, X_test, y_train, y_test = train_test_split(\n X, y, stratify=y, random_state=42)\n \n-categorical_pipe = Pipeline([\n- ('imputer', SimpleImputer(strategy='constant', fill_value='missing')),\n- ('onehot', OneHotEncoder(handle_unknown='ignore'))\n-])\n+categorical_encoder = OneHotEncoder(handle_unknown='ignore')\n numerical_pipe = Pipeline([\n ('imputer', SimpleImputer(strategy='mean'))\n ])\n \n preprocessing = ColumnTransformer(\n- [('cat', categorical_pipe, categorical_columns),\n+ [('cat', categorical_encoder, categorical_columns),\n ('num', numerical_pipe, numerical_columns)])\n \n rf = Pipeline([\n@@ -122,8 +119,7 @@\n # predictions that generalize to the test set (when the model has enough\n # capacity).\n ohe = (rf.named_steps['preprocess']\n- .named_transformers_['cat']\n- .named_steps['onehot'])\n+ .named_transformers_['cat'])\n feature_names = ohe.get_feature_names(input_features=categorical_columns)\n feature_names = np.r_[feature_names, numerical_columns]\n \ndiff --git a/sklearn/preprocessing/_encoders.py b/sklearn/preprocessing/_encoders.py\nindex a621c9b5fb5dd..357a8f5b9a3d0 100644\n--- a/sklearn/preprocessing/_encoders.py\n+++ b/sklearn/preprocessing/_encoders.py\n@@ -27,7 +27,7 @@ class _BaseEncoder(TransformerMixin, BaseEstimator):\n \n \"\"\"\n \n- def _check_X(self, X):\n+ def _check_X(self, X, force_all_finite=True):\n \"\"\"\n Perform custom check_array:\n - convert list of strings to object dtype\n@@ -41,17 +41,19 @@ def _check_X(self, X):\n \"\"\"\n if not (hasattr(X, 'iloc') and getattr(X, 'ndim', 0) == 2):\n # if not a dataframe, do normal check_array validation\n- X_temp = check_array(X, dtype=None)\n+ X_temp = check_array(X, dtype=None,\n+ force_all_finite=force_all_finite)\n if (not hasattr(X, 'dtype')\n and np.issubdtype(X_temp.dtype, np.str_)):\n- X = check_array(X, dtype=object)\n+ X = check_array(X, dtype=object,\n+ force_all_finite=force_all_finite)\n else:\n X = X_temp\n needs_validation = False\n else:\n # pandas dataframe, do validation later column by column, in order\n # to keep the dtype information to be used in the encoder.\n- needs_validation = True\n+ needs_validation = force_all_finite\n \n n_samples, n_features = X.shape\n X_columns = []\n@@ -71,8 +73,9 @@ def _get_feature(self, X, feature_idx):\n # numpy arrays, sparse arrays\n return X[:, feature_idx]\n \n- def _fit(self, X, handle_unknown='error'):\n- X_list, n_samples, n_features = self._check_X(X)\n+ def _fit(self, X, handle_unknown='error', force_all_finite=True):\n+ X_list, n_samples, n_features = self._check_X(\n+ X, force_all_finite=force_all_finite)\n \n if self.categories != 'auto':\n if len(self.categories) != n_features:\n@@ -88,9 +91,16 @@ def _fit(self, X, handle_unknown='error'):\n else:\n cats = np.array(self.categories[i], dtype=Xi.dtype)\n if Xi.dtype != object:\n- if not np.all(np.sort(cats) == cats):\n- raise ValueError(\"Unsorted categories are not \"\n- \"supported for numerical categories\")\n+ sorted_cats = np.sort(cats)\n+ error_msg = (\"Unsorted categories are not \"\n+ \"supported for numerical categories\")\n+ # if there are nans, nan should be the last element\n+ stop_idx = -1 if np.isnan(sorted_cats[-1]) else None\n+ if (np.any(sorted_cats[:stop_idx] != cats[:stop_idx]) or\n+ (np.isnan(sorted_cats[-1]) and\n+ not np.isnan(sorted_cats[-1]))):\n+ raise ValueError(error_msg)\n+\n if handle_unknown == 'error':\n diff = _check_unknown(Xi, cats)\n if diff:\n@@ -99,8 +109,9 @@ def _fit(self, X, handle_unknown='error'):\n raise ValueError(msg)\n self.categories_.append(cats)\n \n- def _transform(self, X, handle_unknown='error'):\n- X_list, n_samples, n_features = self._check_X(X)\n+ def _transform(self, X, handle_unknown='error', force_all_finite=True):\n+ X_list, n_samples, n_features = self._check_X(\n+ X, force_all_finite=force_all_finite)\n \n X_int = np.zeros((n_samples, n_features), dtype=int)\n X_mask = np.ones((n_samples, n_features), dtype=bool)\n@@ -355,8 +366,26 @@ def _compute_drop_idx(self):\n \"of features ({}), got {}\")\n raise ValueError(msg.format(len(self.categories_),\n len(self.drop)))\n- missing_drops = [(i, val) for i, val in enumerate(self.drop)\n- if val not in self.categories_[i]]\n+ missing_drops = []\n+ drop_indices = []\n+ for col_idx, (val, cat_list) in enumerate(zip(self.drop,\n+ self.categories_)):\n+ if not is_scalar_nan(val):\n+ drop_idx = np.where(cat_list == val)[0]\n+ if drop_idx.size: # found drop idx\n+ drop_indices.append(drop_idx[0])\n+ else:\n+ missing_drops.append((col_idx, val))\n+ continue\n+\n+ # val is nan, find nan in categories manually\n+ for cat_idx, cat in enumerate(cat_list):\n+ if is_scalar_nan(cat):\n+ drop_indices.append(cat_idx)\n+ break\n+ else: # loop did not break thus drop is missing\n+ missing_drops.append((col_idx, val))\n+\n if any(missing_drops):\n msg = (\"The following categories were supposed to be \"\n \"dropped, but were not found in the training \"\n@@ -365,10 +394,7 @@ def _compute_drop_idx(self):\n [\"Category: {}, Feature: {}\".format(c, v)\n for c, v in missing_drops])))\n raise ValueError(msg)\n- return np.array([np.where(cat_list == val)[0][0]\n- for (val, cat_list) in\n- zip(self.drop, self.categories_)],\n- dtype=object)\n+ return np.array(drop_indices, dtype=object)\n \n def fit(self, X, y=None):\n \"\"\"\n@@ -388,7 +414,8 @@ def fit(self, X, y=None):\n self\n \"\"\"\n self._validate_keywords()\n- self._fit(X, handle_unknown=self.handle_unknown)\n+ self._fit(X, handle_unknown=self.handle_unknown,\n+ force_all_finite='allow-nan')\n self.drop_idx_ = self._compute_drop_idx()\n return self\n \n@@ -431,7 +458,8 @@ def transform(self, X):\n \"\"\"\n check_is_fitted(self)\n # validation of X happens in _check_X called by _transform\n- X_int, X_mask = self._transform(X, handle_unknown=self.handle_unknown)\n+ X_int, X_mask = self._transform(X, handle_unknown=self.handle_unknown,\n+ force_all_finite='allow-nan')\n \n n_samples, n_features = X_int.shape\n \ndiff --git a/sklearn/utils/_encode.py b/sklearn/utils/_encode.py\nindex f830ff952ac1a..012fe7eb2fe0f 100644\n--- a/sklearn/utils/_encode.py\n+++ b/sklearn/utils/_encode.py\n@@ -1,4 +1,7 @@\n+from typing import NamedTuple\n+\n import numpy as np\n+from . import is_scalar_nan\n \n \n def _unique(values, *, return_inverse=False):\n@@ -27,13 +30,107 @@ def _unique(values, *, return_inverse=False):\n if values.dtype == object:\n return _unique_python(values, return_inverse=return_inverse)\n # numerical\n- return np.unique(values, return_inverse=return_inverse)\n+ out = np.unique(values, return_inverse=return_inverse)\n+\n+ if return_inverse:\n+ uniques, inverse = out\n+ else:\n+ uniques = out\n+\n+ # np.unique will have duplicate missing values at the end of `uniques`\n+ # here we clip the nans and remove it from uniques\n+ if uniques.size and is_scalar_nan(uniques[-1]):\n+ nan_idx = np.searchsorted(uniques, np.nan)\n+ uniques = uniques[:nan_idx + 1]\n+ if return_inverse:\n+ inverse[inverse > nan_idx] = nan_idx\n+\n+ if return_inverse:\n+ return uniques, inverse\n+ return uniques\n+\n+\n+class MissingValues(NamedTuple):\n+ \"\"\"Data class for missing data information\"\"\"\n+ nan: bool\n+ none: bool\n+\n+ def to_list(self):\n+ \"\"\"Convert tuple to a list where None is always first.\"\"\"\n+ output = []\n+ if self.none:\n+ output.append(None)\n+ if self.nan:\n+ output.append(np.nan)\n+ return output\n+\n+\n+def _extract_missing(values):\n+ \"\"\"Extract missing values from `values`.\n+\n+ Parameters\n+ ----------\n+ values: set\n+ Set of values to extract missing from.\n+\n+ Returns\n+ -------\n+ output: set\n+ Set with missing values extracted.\n+\n+ missing_values: MissingValues\n+ Object with missing value information.\n+ \"\"\"\n+ missing_values_set = {value for value in values\n+ if value is None or is_scalar_nan(value)}\n+\n+ if not missing_values_set:\n+ return values, MissingValues(nan=False, none=False)\n+\n+ if None in missing_values_set:\n+ if len(missing_values_set) == 1:\n+ output_missing_values = MissingValues(nan=False, none=True)\n+ else:\n+ # If there is more than one missing value, then it has to be\n+ # float('nan') or np.nan\n+ output_missing_values = MissingValues(nan=True, none=True)\n+ else:\n+ output_missing_values = MissingValues(nan=True, none=False)\n+\n+ # create set without the missing values\n+ output = values - missing_values_set\n+ return output, output_missing_values\n+\n+\n+class _nandict(dict):\n+ \"\"\"Dictionary with support for nans.\"\"\"\n+ def __init__(self, mapping):\n+ super().__init__(mapping)\n+ for key, value in mapping.items():\n+ if is_scalar_nan(key):\n+ self.nan_value = value\n+ break\n+\n+ def __missing__(self, key):\n+ if hasattr(self, 'nan_value') and is_scalar_nan(key):\n+ return self.nan_value\n+ raise KeyError(key)\n+\n+\n+def _map_to_integer(values, uniques):\n+ \"\"\"Map values based on its position in uniques.\"\"\"\n+ table = _nandict({val: i for i, val in enumerate(uniques)})\n+ return np.array([table[v] for v in values])\n \n \n def _unique_python(values, *, return_inverse):\n # Only used in `_uniques`, see docstring there for details\n try:\n- uniques = sorted(set(values))\n+ uniques_set = set(values)\n+ uniques_set, missing_values = _extract_missing(uniques_set)\n+\n+ uniques = sorted(uniques_set)\n+ uniques.extend(missing_values.to_list())\n uniques = np.array(uniques, dtype=values.dtype)\n except TypeError:\n types = sorted(t.__qualname__\n@@ -42,9 +139,7 @@ def _unique_python(values, *, return_inverse):\n f\"strings or numbers. Got {types}\")\n \n if return_inverse:\n- table = {val: i for i, val in enumerate(uniques)}\n- inverse = np.array([table[v] for v in values])\n- return uniques, inverse\n+ return uniques, _map_to_integer(values, uniques)\n \n return uniques\n \n@@ -79,9 +174,8 @@ def _encode(values, *, uniques, check_unknown=True):\n Encoded values\n \"\"\"\n if values.dtype == object:\n- table = {val: i for i, val in enumerate(uniques)}\n try:\n- return np.array([table[v] for v in values])\n+ return _map_to_integer(values, uniques)\n except KeyError as e:\n raise ValueError(f\"y contains previously unseen labels: {str(e)}\")\n else:\n@@ -118,26 +212,58 @@ def _check_unknown(values, known_values, return_mask=False):\n Additionally returned if ``return_mask=True``.\n \n \"\"\"\n- if values.dtype == object:\n+ valid_mask = None\n+\n+ if values.dtype.kind in 'UO':\n+ values_set = set(values)\n+ values_set, missing_in_values = _extract_missing(values_set)\n+\n uniques_set = set(known_values)\n- diff = list(set(values) - uniques_set)\n+ uniques_set, missing_in_uniques = _extract_missing(uniques_set)\n+ diff = values_set - uniques_set\n+\n+ nan_in_diff = missing_in_values.nan and not missing_in_uniques.nan\n+ none_in_diff = missing_in_values.none and not missing_in_uniques.none\n+\n+ def is_valid(value):\n+ return (value in uniques_set or\n+ missing_in_uniques.none and value is None or\n+ missing_in_uniques.nan and is_scalar_nan(value))\n+\n if return_mask:\n- if diff:\n- valid_mask = np.array([val in uniques_set for val in values])\n+ if diff or nan_in_diff or none_in_diff:\n+ valid_mask = np.array([is_valid(value) for value in values])\n else:\n valid_mask = np.ones(len(values), dtype=bool)\n- return diff, valid_mask\n- else:\n- return diff\n+\n+ diff = list(diff)\n+ if none_in_diff:\n+ diff.append(None)\n+ if nan_in_diff:\n+ diff.append(np.nan)\n else:\n unique_values = np.unique(values)\n- diff = list(np.setdiff1d(unique_values, known_values,\n- assume_unique=True))\n+ diff = np.setdiff1d(unique_values, known_values,\n+ assume_unique=True)\n if return_mask:\n- if diff:\n+ if diff.size:\n valid_mask = np.in1d(values, known_values)\n else:\n valid_mask = np.ones(len(values), dtype=bool)\n- return diff, valid_mask\n- else:\n- return diff\n+\n+ # check for nans in the known_values\n+ if np.isnan(known_values).any():\n+ diff_is_nan = np.isnan(diff)\n+ if diff_is_nan.any():\n+ # removes nan from valid_mask\n+ if diff.size and return_mask:\n+ is_nan = np.isnan(values)\n+ valid_mask[is_nan] = 1\n+\n+ # remove nan from diff\n+ diff = diff[~diff_is_nan]\n+ diff = list(diff)\n+\n+ if return_mask:\n+ return diff, valid_mask\n+ return diff\n", "test_patch": "diff --git a/sklearn/preprocessing/tests/test_encoders.py b/sklearn/preprocessing/tests/test_encoders.py\nindex 239d388ebd9d1..aa169597976af 100644\n--- a/sklearn/preprocessing/tests/test_encoders.py\n+++ b/sklearn/preprocessing/tests/test_encoders.py\n@@ -9,6 +9,7 @@\n from sklearn.exceptions import NotFittedError\n from sklearn.utils._testing import assert_array_equal\n from sklearn.utils._testing import assert_allclose\n+from sklearn.utils import is_scalar_nan\n \n from sklearn.preprocessing import OneHotEncoder\n from sklearn.preprocessing import OrdinalEncoder\n@@ -201,8 +202,14 @@ def check_categorical_onehot(X):\n @pytest.mark.parametrize(\"X\", [\n [['def', 1, 55], ['abc', 2, 55]],\n np.array([[10, 1, 55], [5, 2, 55]]),\n- np.array([['b', 'A', 'cat'], ['a', 'B', 'cat']], dtype=object)\n- ], ids=['mixed', 'numeric', 'object'])\n+ np.array([['b', 'A', 'cat'], ['a', 'B', 'cat']], dtype=object),\n+ np.array([['b', 1, 'cat'], ['a', np.nan, 'cat']], dtype=object),\n+ np.array([['b', 1, 'cat'], ['a', float('nan'), 'cat']], dtype=object),\n+ np.array([[None, 1, 'cat'], ['a', 2, 'cat']], dtype=object),\n+ np.array([[None, 1, None], ['a', np.nan, None]], dtype=object),\n+ np.array([[None, 1, None], ['a', float('nan'), None]], dtype=object),\n+ ], ids=['mixed', 'numeric', 'object', 'mixed-nan', 'mixed-float-nan',\n+ 'mixed-None', 'mixed-None-nan', 'mixed-None-float-nan'])\n def test_one_hot_encoder(X):\n Xtr = check_categorical_onehot(np.array(X)[:, [0]])\n assert_allclose(Xtr, [[0, 1], [1, 0]])\n@@ -315,8 +322,14 @@ def test_X_is_not_1D_pandas(method):\n (np.array([['A', 'cat'], ['B', 'cat']], dtype=object),\n [['A', 'B'], ['cat']], np.object_),\n (np.array([['A', 'cat'], ['B', 'cat']]),\n- [['A', 'B'], ['cat']], np.str_)\n- ], ids=['mixed', 'numeric', 'object', 'string'])\n+ [['A', 'B'], ['cat']], np.str_),\n+ (np.array([[1, 2], [np.nan, 2]]), [[1, np.nan], [2]], np.float_),\n+ (np.array([['A', np.nan], [None, np.nan]], dtype=object),\n+ [['A', None], [np.nan]], np.object_),\n+ (np.array([['A', float('nan')], [None, float('nan')]], dtype=object),\n+ [['A', None], [float('nan')]], np.object_),\n+ ], ids=['mixed', 'numeric', 'object', 'string', 'missing-float',\n+ 'missing-np.nan-object', 'missing-float-nan-object'])\n def test_one_hot_encoder_categories(X, cat_exp, cat_dtype):\n # order of categories should not depend on order of samples\n for Xi in [X, X[::-1]]:\n@@ -325,7 +338,12 @@ def test_one_hot_encoder_categories(X, cat_exp, cat_dtype):\n # assert enc.categories == 'auto'\n assert isinstance(enc.categories_, list)\n for res, exp in zip(enc.categories_, cat_exp):\n- assert res.tolist() == exp\n+ res_list = res.tolist()\n+ if is_scalar_nan(exp[-1]):\n+ assert is_scalar_nan(res_list[-1])\n+ assert res_list[:-1] == exp[:-1]\n+ else:\n+ assert res.tolist() == exp\n assert np.issubdtype(res.dtype, cat_dtype)\n \n \n@@ -339,7 +357,21 @@ def test_one_hot_encoder_categories(X, cat_exp, cat_dtype):\n (np.array([['a', 'b']], dtype=object).T,\n np.array([['a', 'd']], dtype=object).T,\n [np.array(['a', 'b', 'c'])], np.object_),\n- ], ids=['object', 'numeric', 'object-string-cat'])\n+ (np.array([[None, 'a']], dtype=object).T,\n+ np.array([[None, 'b']], dtype=object).T,\n+ [[None, 'a', 'z']], object),\n+ (np.array([['a', 'b']], dtype=object).T,\n+ np.array([['a', np.nan]], dtype=object).T,\n+ [['a', 'b', 'z']], object),\n+ (np.array([['a', None]], dtype=object).T,\n+ np.array([['a', np.nan]], dtype=object).T,\n+ [['a', None, 'z']], object),\n+ (np.array([['a', np.nan]], dtype=object).T,\n+ np.array([['a', None]], dtype=object).T,\n+ [['a', np.nan, 'z']], object),\n+ ], ids=['object', 'numeric', 'object-string',\n+ 'object-string-none', 'object-string-nan',\n+ 'object-None-and-nan', 'object-nan-and-None'])\n def test_one_hot_encoder_specified_categories(X, X2, cats, cat_dtype):\n enc = OneHotEncoder(categories=cats)\n exp = np.array([[1., 0., 0.],\n@@ -379,6 +411,12 @@ def test_one_hot_encoder_unsorted_categories():\n with pytest.raises(ValueError, match=msg):\n enc.fit_transform(X)\n \n+ # np.nan must be the last category in categories[0] to be considered sorted\n+ X = np.array([[1, 2, np.nan]]).T\n+ enc = OneHotEncoder(categories=[[1, np.nan, 2]])\n+ with pytest.raises(ValueError, match=msg):\n+ enc.fit_transform(X)\n+\n \n def test_one_hot_encoder_specified_categories_mixed_columns():\n # multiple columns\n@@ -449,36 +487,6 @@ def test_one_hot_encoder_drop_equals_if_binary():\n assert_allclose(result, expected)\n \n \n-@pytest.mark.parametrize(\"X\", [np.array([[1, np.nan]]).T,\n- np.array([['a', np.nan]], dtype=object).T],\n- ids=['numeric', 'object'])\n-@pytest.mark.parametrize(\"as_data_frame\", [False, True],\n- ids=['array', 'dataframe'])\n-@pytest.mark.parametrize(\"handle_unknown\", ['error', 'ignore'])\n-def test_one_hot_encoder_raise_missing(X, as_data_frame, handle_unknown):\n- if as_data_frame:\n- pd = pytest.importorskip('pandas')\n- X = pd.DataFrame(X)\n-\n- ohe = OneHotEncoder(categories='auto', handle_unknown=handle_unknown)\n-\n- with pytest.raises(ValueError, match=\"Input contains NaN\"):\n- ohe.fit(X)\n-\n- with pytest.raises(ValueError, match=\"Input contains NaN\"):\n- ohe.fit_transform(X)\n-\n- if as_data_frame:\n- X_partial = X.iloc[:1, :]\n- else:\n- X_partial = X[:1, :]\n-\n- ohe.fit(X_partial)\n-\n- with pytest.raises(ValueError, match=\"Input contains NaN\"):\n- ohe.transform(X)\n-\n-\n @pytest.mark.parametrize(\"X\", [\n [['abc', 2, 55], ['def', 1, 55]],\n np.array([[10, 2, 55], [20, 1, 55]]),\n@@ -700,23 +708,39 @@ def test_one_hot_encoder_warning():\n np.testing.assert_no_warnings(enc.fit_transform, X)\n \n \n-def test_one_hot_encoder_drop_manual():\n- cats_to_drop = ['def', 12, 3, 56]\n+@pytest.mark.parametrize(\"missing_value\", [np.nan, None, float('nan')])\n+def test_one_hot_encoder_drop_manual(missing_value):\n+ cats_to_drop = ['def', 12, 3, 56, missing_value]\n enc = OneHotEncoder(drop=cats_to_drop)\n- X = [['abc', 12, 2, 55],\n- ['def', 12, 1, 55],\n- ['def', 12, 3, 56]]\n+ X = [['abc', 12, 2, 55, 'a'],\n+ ['def', 12, 1, 55, 'a'],\n+ ['def', 12, 3, 56, missing_value]]\n trans = enc.fit_transform(X).toarray()\n- exp = [[1, 0, 1, 1],\n- [0, 1, 0, 1],\n- [0, 0, 0, 0]]\n+ exp = [[1, 0, 1, 1, 1],\n+ [0, 1, 0, 1, 1],\n+ [0, 0, 0, 0, 0]]\n assert_array_equal(trans, exp)\n dropped_cats = [cat[feature]\n for cat, feature in zip(enc.categories_,\n enc.drop_idx_)]\n- assert_array_equal(dropped_cats, cats_to_drop)\n- assert_array_equal(np.array(X, dtype=object),\n- enc.inverse_transform(trans))\n+ X_inv_trans = enc.inverse_transform(trans)\n+ X_array = np.array(X, dtype=object)\n+\n+ # last value is np.nan\n+ if is_scalar_nan(cats_to_drop[-1]):\n+ assert_array_equal(dropped_cats[:-1], cats_to_drop[:-1])\n+ assert is_scalar_nan(dropped_cats[-1])\n+ assert is_scalar_nan(cats_to_drop[-1])\n+ # do not include the last column which includes missing values\n+ assert_array_equal(X_array[:, :-1], X_inv_trans[:, :-1])\n+\n+ # check last column is the missing value\n+ assert_array_equal(X_array[-1, :-1], X_inv_trans[-1, :-1])\n+ assert is_scalar_nan(X_array[-1, -1])\n+ assert is_scalar_nan(X_inv_trans[-1, -1])\n+ else:\n+ assert_array_equal(dropped_cats, cats_to_drop)\n+ assert_array_equal(X_array, X_inv_trans)\n \n \n @pytest.mark.parametrize(\n@@ -775,9 +799,61 @@ def test_encoders_has_categorical_tags(Encoder):\n assert 'categorical' in Encoder()._get_tags()['X_types']\n \n \n-@pytest.mark.parametrize('Encoder', [OneHotEncoder, OrdinalEncoder])\n-def test_encoders_does_not_support_none_values(Encoder):\n- values = [[\"a\"], [None]]\n- with pytest.raises(TypeError, match=\"Encoders require their input to be \"\n- \"uniformly strings or numbers.\"):\n- Encoder().fit(values)\n+@pytest.mark.parametrize(\"missing_value\", [np.nan, None])\n+def test_ohe_missing_values_get_feature_names(missing_value):\n+ # encoder with missing values with object dtypes\n+ X = np.array([['a', 'b', missing_value, 'a', missing_value]],\n+ dtype=object).T\n+ ohe = OneHotEncoder(sparse=False, handle_unknown='ignore').fit(X)\n+ names = ohe.get_feature_names()\n+ assert_array_equal(names, ['x0_a', 'x0_b', f'x0_{missing_value}'])\n+\n+\n+def test_ohe_missing_value_support_pandas():\n+ # check support for pandas with mixed dtypes and missing values\n+ pd = pytest.importorskip('pandas')\n+ df = pd.DataFrame({\n+ 'col1': ['dog', 'cat', None, 'cat'],\n+ 'col2': np.array([3, 0, 4, np.nan], dtype=float)\n+ }, columns=['col1', 'col2'])\n+ expected_df_trans = np.array([\n+ [0, 1, 0, 0, 1, 0, 0],\n+ [1, 0, 0, 1, 0, 0, 0],\n+ [0, 0, 1, 0, 0, 1, 0],\n+ [1, 0, 0, 0, 0, 0, 1],\n+ ])\n+\n+ Xtr = check_categorical_onehot(df)\n+ assert_allclose(Xtr, expected_df_trans)\n+\n+\n+@pytest.mark.parametrize('pd_nan_type', ['pd.NA', 'np.nan'])\n+def test_ohe_missing_value_support_pandas_categorical(pd_nan_type):\n+ # checks pandas dataframe with categorical features\n+ if pd_nan_type == 'pd.NA':\n+ # pd.NA is in pandas 1.0\n+ pd = pytest.importorskip('pandas', minversion=\"1.0\")\n+ pd_missing_value = pd.NA\n+ else: # np.nan\n+ pd = pytest.importorskip('pandas')\n+ pd_missing_value = np.nan\n+\n+ df = pd.DataFrame({\n+ 'col1': pd.Series(['c', 'a', pd_missing_value, 'b', 'a'],\n+ dtype='category'),\n+ })\n+ expected_df_trans = np.array([\n+ [0, 0, 1, 0],\n+ [1, 0, 0, 0],\n+ [0, 0, 0, 1],\n+ [0, 1, 0, 0],\n+ [1, 0, 0, 0],\n+ ])\n+\n+ ohe = OneHotEncoder(sparse=False, handle_unknown='ignore')\n+ df_trans = ohe.fit_transform(df)\n+ assert_allclose(expected_df_trans, df_trans)\n+\n+ assert len(ohe.categories_) == 1\n+ assert_array_equal(ohe.categories_[0][:-1], ['a', 'b', 'c'])\n+ assert np.isnan(ohe.categories_[0][-1])\ndiff --git a/sklearn/utils/tests/test_encode.py b/sklearn/utils/tests/test_encode.py\nindex 9371fa6e88e3e..53c380e192341 100644\n--- a/sklearn/utils/tests/test_encode.py\n+++ b/sklearn/utils/tests/test_encode.py\n@@ -1,3 +1,5 @@\n+import pickle\n+\n import numpy as np\n import pytest\n from numpy.testing import assert_array_equal\n@@ -44,6 +46,15 @@ def test_encode_with_check_unknown():\n _encode(values, uniques=uniques, check_unknown=False)\n \n \n+def _assert_check_unknown(values, uniques, expected_diff, expected_mask):\n+ diff = _check_unknown(values, uniques)\n+ assert_array_equal(diff, expected_diff)\n+\n+ diff, valid_mask = _check_unknown(values, uniques, return_mask=True)\n+ assert_array_equal(diff, expected_diff)\n+ assert_array_equal(valid_mask, expected_mask)\n+\n+\n @pytest.mark.parametrize(\"values, uniques, expected_diff, expected_mask\", [\n (np.array([1, 2, 3, 4]),\n np.array([1, 2, 3]),\n@@ -53,6 +64,22 @@ def test_encode_with_check_unknown():\n np.array([2, 5, 1]),\n [4],\n [True, True, False, True]),\n+ (np.array([2, 1, np.nan]),\n+ np.array([2, 5, 1]),\n+ [np.nan],\n+ [True, True, False]),\n+ (np.array([2, 1, 4, np.nan]),\n+ np.array([2, 5, 1, np.nan]),\n+ [4],\n+ [True, True, False, True]),\n+ (np.array([2, 1, 4, np.nan]),\n+ np.array([2, 5, 1]),\n+ [4, np.nan],\n+ [True, True, False, False]),\n+ (np.array([2, 1, 4, 5]),\n+ np.array([2, 5, 1, np.nan]),\n+ [4],\n+ [True, True, False, True]),\n (np.array(['a', 'b', 'c', 'd'], dtype=object),\n np.array(['a', 'b', 'c'], dtype=object),\n np.array(['d'], dtype=object),\n@@ -60,14 +87,122 @@ def test_encode_with_check_unknown():\n (np.array(['d', 'c', 'a', 'b'], dtype=object),\n np.array(['a', 'c', 'b'], dtype=object),\n np.array(['d'], dtype=object),\n- [False, True, True, True])\n+ [False, True, True, True]),\n+ (np.array(['a', 'b', 'c', 'd']),\n+ np.array(['a', 'b', 'c']),\n+ np.array(['d']),\n+ [True, True, True, False]),\n+ (np.array(['d', 'c', 'a', 'b']),\n+ np.array(['a', 'c', 'b']),\n+ np.array(['d']),\n+ [False, True, True, True]),\n ])\n def test_check_unknown(values, uniques, expected_diff, expected_mask):\n- diff = _check_unknown(values, uniques)\n+ _assert_check_unknown(values, uniques, expected_diff, expected_mask)\n \n- assert_array_equal(diff, expected_diff)\n \n- diff, valid_mask = _check_unknown(values, uniques, return_mask=True)\n+@pytest.mark.parametrize(\"missing_value\", [None, np.nan, float('nan')])\n+@pytest.mark.parametrize('pickle_uniques', [True, False])\n+def test_check_unknown_missing_values(missing_value, pickle_uniques):\n+ # check for check_unknown with missing values with object dtypes\n+ values = np.array(['d', 'c', 'a', 'b', missing_value], dtype=object)\n+ uniques = np.array(['c', 'a', 'b', missing_value], dtype=object)\n+ if pickle_uniques:\n+ uniques = pickle.loads(pickle.dumps(uniques))\n \n- assert_array_equal(diff, expected_diff)\n- assert_array_equal(valid_mask, expected_mask)\n+ expected_diff = ['d']\n+ expected_mask = [False, True, True, True, True]\n+ _assert_check_unknown(values, uniques, expected_diff, expected_mask)\n+\n+ values = np.array(['d', 'c', 'a', 'b', missing_value], dtype=object)\n+ uniques = np.array(['c', 'a', 'b'], dtype=object)\n+ if pickle_uniques:\n+ uniques = pickle.loads(pickle.dumps(uniques))\n+\n+ expected_diff = ['d', missing_value]\n+\n+ expected_mask = [False, True, True, True, False]\n+ _assert_check_unknown(values, uniques, expected_diff, expected_mask)\n+\n+ values = np.array(['a', missing_value], dtype=object)\n+ uniques = np.array(['a', 'b', 'z'], dtype=object)\n+ if pickle_uniques:\n+ uniques = pickle.loads(pickle.dumps(uniques))\n+\n+ expected_diff = [missing_value]\n+ expected_mask = [True, False]\n+ _assert_check_unknown(values, uniques, expected_diff, expected_mask)\n+\n+\n+@pytest.mark.parametrize('missing_value', [np.nan, None, float('nan')])\n+@pytest.mark.parametrize('pickle_uniques', [True, False])\n+def test_unique_util_missing_values_objects(missing_value, pickle_uniques):\n+ # check for _unique and _encode with missing values with object dtypes\n+ values = np.array(['a', 'c', 'c', missing_value, 'b'], dtype=object)\n+ expected_uniques = np.array(['a', 'b', 'c', missing_value], dtype=object)\n+\n+ uniques = _unique(values)\n+\n+ if missing_value is None:\n+ assert_array_equal(uniques, expected_uniques)\n+ else: # missing_value == np.nan\n+ assert_array_equal(uniques[:-1], expected_uniques[:-1])\n+ assert np.isnan(uniques[-1])\n+\n+ if pickle_uniques:\n+ uniques = pickle.loads(pickle.dumps(uniques))\n+\n+ encoded = _encode(values, uniques=uniques)\n+ assert_array_equal(encoded, np.array([0, 2, 2, 3, 1]))\n+\n+\n+def test_unique_util_missing_values_numeric():\n+ # Check missing values in numerical values\n+ values = np.array([3, 1, np.nan, 5, 3, np.nan], dtype=float)\n+ expected_uniques = np.array([1, 3, 5, np.nan], dtype=float)\n+ expected_inverse = np.array([1, 0, 3, 2, 1, 3])\n+\n+ uniques = _unique(values)\n+ assert_array_equal(uniques, expected_uniques)\n+\n+ uniques, inverse = _unique(values, return_inverse=True)\n+ assert_array_equal(uniques, expected_uniques)\n+ assert_array_equal(inverse, expected_inverse)\n+\n+ encoded = _encode(values, uniques=uniques)\n+ assert_array_equal(encoded, expected_inverse)\n+\n+\n+def test_unique_util_with_all_missing_values():\n+ # test for all types of missing values for object dtype\n+ values = np.array([np.nan, 'a', 'c', 'c', None, float('nan'),\n+ None], dtype=object)\n+\n+ uniques = _unique(values)\n+ assert_array_equal(uniques[:-1], ['a', 'c', None])\n+ # last value is nan\n+ assert np.isnan(uniques[-1])\n+\n+ expected_inverse = [3, 0, 1, 1, 2, 3, 2]\n+ _, inverse = _unique(values, return_inverse=True)\n+ assert_array_equal(inverse, expected_inverse)\n+\n+\n+def test_check_unknown_with_both_missing_values():\n+ # test for both types of missing values for object dtype\n+ values = np.array([np.nan, 'a', 'c', 'c', None, np.nan,\n+ None], dtype=object)\n+\n+ diff = _check_unknown(values,\n+ known_values=np.array(['a', 'c'], dtype=object))\n+ assert diff[0] is None\n+ assert np.isnan(diff[1])\n+\n+ diff, valid_mask = _check_unknown(\n+ values, known_values=np.array(['a', 'c'], dtype=object),\n+ return_mask=True)\n+\n+ assert diff[0] is None\n+ assert np.isnan(diff[1])\n+ assert_array_equal(valid_mask,\n+ [False, True, True, True, False, False, False])\n", "doc_changes": [{"path": "doc/modules/preprocessing.rst", "old_path": "a/doc/modules/preprocessing.rst", "new_path": "b/doc/modules/preprocessing.rst", "metadata": "diff --git a/doc/modules/preprocessing.rst b/doc/modules/preprocessing.rst\nindex 024dd074e2e41..79d57913a9565 100644\n--- a/doc/modules/preprocessing.rst\n+++ b/doc/modules/preprocessing.rst\n@@ -590,6 +590,34 @@ In the transformed `X`, the first column is the encoding of the feature with\n categories \"male\"/\"female\", while the remaining 6 columns is the encoding of\n the 2 features with respectively 3 categories each.\n \n+:class:`OneHotEncoder` supports categorical features with missing values by\n+considering the missing values as an additional category::\n+\n+ >>> X = [['male', 'Safari'],\n+ ... ['female', None],\n+ ... [np.nan, 'Firefox']]\n+ >>> enc = preprocessing.OneHotEncoder(handle_unknown='error').fit(X)\n+ >>> enc.categories_\n+ [array(['female', 'male', nan], dtype=object),\n+ array(['Firefox', 'Safari', None], dtype=object)]\n+ >>> enc.transform(X).toarray()\n+ array([[0., 1., 0., 0., 1., 0.],\n+ [1., 0., 0., 0., 0., 1.],\n+ [0., 0., 1., 1., 0., 0.]])\n+\n+If a feature contains both `np.nan` and `None`, they will be considered\n+separate categories::\n+\n+ >>> X = [['Safari'], [None], [np.nan], ['Firefox']]\n+ >>> enc = preprocessing.OneHotEncoder(handle_unknown='error').fit(X)\n+ >>> enc.categories_\n+ [array(['Firefox', 'Safari', None, nan], dtype=object)]\n+ >>> enc.transform(X).toarray()\n+ array([[0., 1., 0., 0.],\n+ [0., 0., 1., 0.],\n+ [0., 0., 0., 1.],\n+ [1., 0., 0., 0.]])\n+\n See :ref:`dict_feature_extraction` for categorical features that are\n represented as a dict, not as scalars.\n \n@@ -791,5 +819,5 @@ error with a ``filterwarnings``::\n ... category=UserWarning, append=False)\n \n For a full code example that demonstrates using a :class:`FunctionTransformer`\n-to extract features from text data see \n+to extract features from text data see\n :ref:`sphx_glr_auto_examples_compose_plot_column_transformer.py`\n"}, {"path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex f35dcc8f72ee4..b52fbfc14bd40 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -552,6 +552,9 @@ Changelog\n :mod:`sklearn.preprocessing`\n ............................\n \n+- |Feature| :class:`preprocessing.OneHotEncoder` now supports missing\n+ values by treating them as a category. :pr:`17317` by `Thomas Fan`_.\n+\n - |Feature| Add a new ``handle_unknown`` parameter with a\n ``use_encoded_value`` option, along with a new ``unknown_value`` parameter,\n to :class:`preprocessing.OrdinalEncoder` to allow unknown categories during\n"}], "version": "0.24", "base_commit": "73732e5a0bc9b72c7049dc699d69aaedbb70ef0a", "PASS2PASS": ["sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_feature_names_unicode", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse_if_binary", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_pandas", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder[mixed]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[int32-float32]", "sklearn/preprocessing/tests/test_encoders.py::test_X_is_not_1D[X1-fit_transform]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_categories[numeric]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse[None-True]", "sklearn/preprocessing/tests/test_encoders.py::test_encoder_dtypes_pandas", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype_pandas[float32]", "sklearn/preprocessing/tests/test_encoders.py::test_encoder_dtypes", "sklearn/utils/tests/test_encode.py::test_encode_util[str]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_handle_unknown", "sklearn/utils/tests/test_encode.py::test_check_unknown[values6-uniques6-expected_diff6-expected_mask6]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[if_binary-if_binary]", "sklearn/utils/tests/test_encode.py::test_check_unknown[values8-uniques8-expected_diff8-expected_mask8]", "sklearn/preprocessing/tests/test_encoders.py::test_invalid_drop_length[drop1]", "sklearn/utils/tests/test_encode.py::test_check_unknown[values9-uniques9-expected_diff9-expected_mask9]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_set_params", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_handle_unknown_strings", "sklearn/utils/tests/test_encode.py::test_encode_util[int64]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_not_fitted", "sklearn/utils/tests/test_encode.py::test_check_unknown[values7-uniques7-expected_diff7-expected_mask7]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[numeric]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_inverse", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_raise", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_raise_missing[object]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_invalid_params[X_fit2-params2-Wrong input for parameter `drop`]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_feature_names_drop[first]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder[object]", "sklearn/utils/tests/test_encode.py::test_check_unknown[values5-uniques5-expected_diff5-expected_mask5]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse[first-True]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_raise_categories_shape", "sklearn/utils/tests/test_encode.py::test_check_unknown_missing_values[False-None]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_categories[object]", "sklearn/preprocessing/tests/test_encoders.py::test_invalid_drop_length[drop0]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype_pandas[int32]", "sklearn/preprocessing/tests/test_encoders.py::test_X_is_not_1D_pandas[fit_transform]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_invalid_params[X_fit3-params3-The following categories were supposed]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories_mixed_columns", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[float32-float32]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_categories[mixed]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_diff_n_features", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[float64-float64]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_nan_non_float_dtype", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[object]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[first-None]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[float64-float32]", "sklearn/utils/tests/test_encode.py::test_check_unknown_missing_values[True-None]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[int32-float64]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse[first-False]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_specified_categories[numeric]", "sklearn/preprocessing/tests/test_encoders.py::test_categories[first-sparse]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[int32-int32]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_numeric[float]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object-string]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_numeric[int]", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_has_categorical_tags[OrdinalEncoder]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_equals_if_binary", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[None-None]", "sklearn/preprocessing/tests/test_encoders.py::test_X_is_not_1D[X0-fit_transform]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_warning", "sklearn/preprocessing/tests/test_encoders.py::test_X_is_not_1D[X0-fit]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_feature_names", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[numeric]", "sklearn/preprocessing/tests/test_encoders.py::test_categories[first-dense]", "sklearn/preprocessing/tests/test_encoders.py::test_X_is_not_1D_pandas[fit]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_invalid_params[X_fit0-params0-Wrong input for parameter `drop`]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[first-first]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_feature_names_drop[manual]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_raise_missing[numeric]", "sklearn/utils/tests/test_encode.py::test_encode_util[object]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[float32-int32]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_feature_names_drop[binary]", "sklearn/utils/tests/test_encode.py::test_check_unknown[values0-uniques0-expected_diff0-expected_mask0]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_specified_categories[object-string-cat]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_nan", "sklearn/preprocessing/tests/test_encoders.py::test_categories[manual-dense]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[None-if_binary]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_sparse_dense", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object-string-none]", "sklearn/utils/tests/test_encode.py::test_check_unknown[values2-uniques2-expected_diff2-expected_mask2]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_invalid_params[X_fit1-params1-`handle_unknown` must be 'error']", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[if_binary-first]", "sklearn/preprocessing/tests/test_encoders.py::test_categories[manual-sparse]", "sklearn/utils/tests/test_encode.py::test_encode_with_check_unknown", "sklearn/preprocessing/tests/test_encoders.py::test_encoders_has_categorical_tags[OneHotEncoder]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder[numeric]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_categories[string]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_specified_categories[object]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[if_binary-None]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_inverse[None-False]", "sklearn/utils/tests/test_encode.py::test_check_unknown[values4-uniques4-expected_diff4-expected_mask4]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[None-first]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_reset[first-if_binary]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype_pandas[float64]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[float64-int32]", "sklearn/preprocessing/tests/test_encoders.py::test_ordinal_encoder_handle_unknowns_string", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[mixed]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_dtype[float32-float64]", "sklearn/utils/tests/test_encode.py::test_check_unknown[values1-uniques1-expected_diff1-expected_mask1]", "sklearn/preprocessing/tests/test_encoders.py::test_X_is_not_1D[X1-fit]"], "FAIL2PASS": ["sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[mixed-float-nan]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_missing_value_support_pandas", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_missing_value_support_pandas_categorical[pd.NA]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object-string-nan]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_missing_values_get_feature_names[None]", "sklearn/utils/tests/test_encode.py::test_check_unknown_missing_values[False-nan0]", "sklearn/utils/tests/test_encode.py::test_unique_util_missing_values_objects[False-nan0]", "sklearn/utils/tests/test_encode.py::test_unique_util_missing_values_objects[False-None]", "sklearn/utils/tests/test_encode.py::test_check_unknown_missing_values[True-nan1]", "sklearn/utils/tests/test_encode.py::test_unique_util_missing_values_objects[False-nan1]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_manual[None]", "sklearn/utils/tests/test_encode.py::test_check_unknown_with_both_missing_values", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[mixed-None]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_missing_values_get_feature_names[nan]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_categories[missing-float]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_categories[missing-float-nan-object]", "sklearn/utils/tests/test_encode.py::test_unique_util_missing_values_numeric", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_manual[nan0]", "sklearn/utils/tests/test_encode.py::test_unique_util_missing_values_objects[True-nan1]", "sklearn/utils/tests/test_encode.py::test_unique_util_with_all_missing_values", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_unsorted_categories", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object-nan-and-None]", "sklearn/utils/tests/test_encode.py::test_check_unknown_missing_values[True-nan0]", "sklearn/utils/tests/test_encode.py::test_unique_util_missing_values_objects[True-nan0]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[mixed-None-nan]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_specified_categories[object-None-and-nan]", "sklearn/utils/tests/test_encode.py::test_check_unknown[values3-uniques3-expected_diff3-expected_mask3]", "sklearn/preprocessing/tests/test_encoders.py::test_ohe_missing_value_support_pandas_categorical[np.nan]", "sklearn/utils/tests/test_encode.py::test_unique_util_missing_values_objects[True-None]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[mixed-None-float-nan]", "sklearn/utils/tests/test_encode.py::test_check_unknown_missing_values[False-nan1]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder[mixed-nan]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_drop_manual[nan1]", "sklearn/preprocessing/tests/test_encoders.py::test_one_hot_encoder_categories[missing-np.nan-object]"], "mask_doc_diff": [{"path": "doc/modules/preprocessing.rst", "old_path": "a/doc/modules/preprocessing.rst", "new_path": "b/doc/modules/preprocessing.rst", "metadata": "diff --git a/doc/modules/preprocessing.rst b/doc/modules/preprocessing.rst\nindex 024dd074e..79d57913a 100644\n--- a/doc/modules/preprocessing.rst\n+++ b/doc/modules/preprocessing.rst\n@@ -590,6 +590,34 @@ In the transformed `X`, the first column is the encoding of the feature with\n categories \"male\"/\"female\", while the remaining 6 columns is the encoding of\n the 2 features with respectively 3 categories each.\n \n+:class:`OneHotEncoder` supports categorical features with missing values by\n+considering the missing values as an additional category::\n+\n+ >>> X = [['male', 'Safari'],\n+ ... ['female', None],\n+ ... [np.nan, 'Firefox']]\n+ >>> enc = preprocessing.OneHotEncoder(handle_unknown='error').fit(X)\n+ >>> enc.categories_\n+ [array(['female', 'male', nan], dtype=object),\n+ array(['Firefox', 'Safari', None], dtype=object)]\n+ >>> enc.transform(X).toarray()\n+ array([[0., 1., 0., 0., 1., 0.],\n+ [1., 0., 0., 0., 0., 1.],\n+ [0., 0., 1., 1., 0., 0.]])\n+\n+If a feature contains both `np.nan` and `None`, they will be considered\n+separate categories::\n+\n+ >>> X = [['Safari'], [None], [np.nan], ['Firefox']]\n+ >>> enc = preprocessing.OneHotEncoder(handle_unknown='error').fit(X)\n+ >>> enc.categories_\n+ [array(['Firefox', 'Safari', None, nan], dtype=object)]\n+ >>> enc.transform(X).toarray()\n+ array([[0., 1., 0., 0.],\n+ [0., 0., 1., 0.],\n+ [0., 0., 0., 1.],\n+ [1., 0., 0., 0.]])\n+\n See :ref:`dict_feature_extraction` for categorical features that are\n represented as a dict, not as scalars.\n \n@@ -791,5 +819,5 @@ error with a ``filterwarnings``::\n ... category=UserWarning, append=False)\n \n For a full code example that demonstrates using a :class:`FunctionTransformer`\n-to extract features from text data see \n+to extract features from text data see\n :ref:`sphx_glr_auto_examples_compose_plot_column_transformer.py`\n"}, {"path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex f35dcc8f7..a0733ffa0 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -552,6 +552,9 @@ Changelog\n :mod:`sklearn.preprocessing`\n ............................\n \n+- |Feature| :class:`preprocessing.OneHotEncoder` now supports missing\n+ values by treating them as a category.\n+\n - |Feature| Add a new ``handle_unknown`` parameter with a\n ``use_encoded_value`` option, along with a new ``unknown_value`` parameter,\n to :class:`preprocessing.OrdinalEncoder` to allow unknown categories during\n"}], "augmentations": {"header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": []}, "problem_statement": "diff --git a/doc/modules/preprocessing.rst b/doc/modules/preprocessing.rst\nindex 024dd074e..79d57913a 100644\n--- a/doc/modules/preprocessing.rst\n+++ b/doc/modules/preprocessing.rst\n@@ -590,6 +590,34 @@ In the transformed `X`, the first column is the encoding of the feature with\n categories \"male\"/\"female\", while the remaining 6 columns is the encoding of\n the 2 features with respectively 3 categories each.\n \n+:class:`OneHotEncoder` supports categorical features with missing values by\n+considering the missing values as an additional category::\n+\n+ >>> X = [['male', 'Safari'],\n+ ... ['female', None],\n+ ... [np.nan, 'Firefox']]\n+ >>> enc = preprocessing.OneHotEncoder(handle_unknown='error').fit(X)\n+ >>> enc.categories_\n+ [array(['female', 'male', nan], dtype=object),\n+ array(['Firefox', 'Safari', None], dtype=object)]\n+ >>> enc.transform(X).toarray()\n+ array([[0., 1., 0., 0., 1., 0.],\n+ [1., 0., 0., 0., 0., 1.],\n+ [0., 0., 1., 1., 0., 0.]])\n+\n+If a feature contains both `np.nan` and `None`, they will be considered\n+separate categories::\n+\n+ >>> X = [['Safari'], [None], [np.nan], ['Firefox']]\n+ >>> enc = preprocessing.OneHotEncoder(handle_unknown='error').fit(X)\n+ >>> enc.categories_\n+ [array(['Firefox', 'Safari', None, nan], dtype=object)]\n+ >>> enc.transform(X).toarray()\n+ array([[0., 1., 0., 0.],\n+ [0., 0., 1., 0.],\n+ [0., 0., 0., 1.],\n+ [1., 0., 0., 0.]])\n+\n See :ref:`dict_feature_extraction` for categorical features that are\n represented as a dict, not as scalars.\n \n@@ -791,5 +819,5 @@ error with a ``filterwarnings``::\n ... category=UserWarning, append=False)\n \n For a full code example that demonstrates using a :class:`FunctionTransformer`\n-to extract features from text data see \n+to extract features from text data see\n :ref:`sphx_glr_auto_examples_compose_plot_column_transformer.py`\n\ndiff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex f35dcc8f7..a0733ffa0 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -552,6 +552,9 @@ Changelog\n :mod:`sklearn.preprocessing`\n ............................\n \n+- |Feature| :class:`preprocessing.OneHotEncoder` now supports missing\n+ values by treating them as a category.\n+\n - |Feature| Add a new ``handle_unknown`` parameter with a\n ``use_encoded_value`` option, along with a new ``unknown_value`` parameter,\n to :class:`preprocessing.OrdinalEncoder` to allow unknown categories during\n\n"} {"repo": "scikit-learn/scikit-learn", "instance_id": "scikit-learn__scikit-learn-17379", "html_url": "https://github.com/scikit-learn/scikit-learn/pull/17379", "feature_patch": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex 9e31762d62c29..b5d0145af4822 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -158,6 +158,9 @@ Changelog\n :pr:`16289` by :user:`Masashi Kishimoto ` and\n :user:`Olivier Grisel `.\n \n+- |Enhancement| :class:`isotonic.IsotonicRegression` now accepts 2darray with 1 feature as\n+ input array. :pr:`17379` by :user:`Jiaxiang `.\n+\n :mod:`sklearn.metrics`\n ......................\n \ndiff --git a/sklearn/isotonic.py b/sklearn/isotonic.py\nindex 50fa0654f7585..905528d3b25f0 100644\n--- a/sklearn/isotonic.py\n+++ b/sklearn/isotonic.py\n@@ -211,7 +211,7 @@ class IsotonicRegression(RegressorMixin, TransformerMixin, BaseEstimator):\n >>> from sklearn.datasets import make_regression\n >>> from sklearn.isotonic import IsotonicRegression\n >>> X, y = make_regression(n_samples=10, n_features=1, random_state=41)\n- >>> iso_reg = IsotonicRegression().fit(X.flatten(), y)\n+ >>> iso_reg = IsotonicRegression().fit(X, y)\n >>> iso_reg.predict([.1, .2])\n array([1.8628..., 3.7256...])\n \"\"\"\n@@ -223,9 +223,11 @@ def __init__(self, *, y_min=None, y_max=None, increasing=True,\n self.increasing = increasing\n self.out_of_bounds = out_of_bounds\n \n- def _check_fit_data(self, X, y, sample_weight=None):\n- if len(X.shape) != 1:\n- raise ValueError(\"X should be a 1d array\")\n+ def _check_input_data_shape(self, X):\n+ if not (X.ndim == 1 or (X.ndim == 2 and X.shape[1] == 1)):\n+ msg = \"Isotonic regression input X should be a 1d array or \" \\\n+ \"2d array with 1 feature\"\n+ raise ValueError(msg)\n \n def _build_f(self, X, y):\n \"\"\"Build the f_ interp1d function.\"\"\"\n@@ -246,7 +248,8 @@ def _build_f(self, X, y):\n \n def _build_y(self, X, y, sample_weight, trim_duplicates=True):\n \"\"\"Build the y_ IsotonicRegression.\"\"\"\n- self._check_fit_data(X, y, sample_weight)\n+ self._check_input_data_shape(X)\n+ X = X.reshape(-1) # use 1d view\n \n # Determine increasing if auto-determination requested\n if self.increasing == 'auto':\n@@ -295,7 +298,7 @@ def fit(self, X, y, sample_weight=None):\n \n Parameters\n ----------\n- X : array-like of shape (n_samples,)\n+ X : array-like of shape (n_samples,) or (n_samples, 1)\n Training data.\n \n y : array-like of shape (n_samples,)\n@@ -339,7 +342,7 @@ def transform(self, T):\n \n Parameters\n ----------\n- T : array-like of shape (n_samples,)\n+ T : array-like of shape (n_samples,) or (n_samples, 1)\n Data to transform.\n \n Returns\n@@ -355,8 +358,8 @@ def transform(self, T):\n \n T = check_array(T, dtype=dtype, ensure_2d=False)\n \n- if len(T.shape) != 1:\n- raise ValueError(\"Isotonic regression input should be a 1d array\")\n+ self._check_input_data_shape(T)\n+ T = T.reshape(-1) # use 1d view\n \n # Handle the out_of_bounds argument by clipping if needed\n if self.out_of_bounds not in [\"raise\", \"nan\", \"clip\"]:\n@@ -379,7 +382,7 @@ def predict(self, T):\n \n Parameters\n ----------\n- T : array-like of shape (n_samples,)\n+ T : array-like of shape (n_samples,) or (n_samples, 1)\n Data to transform.\n \n Returns\n", "test_patch": "diff --git a/sklearn/tests/test_isotonic.py b/sklearn/tests/test_isotonic.py\nindex 3da76c1f0bb88..66892370f06f0 100644\n--- a/sklearn/tests/test_isotonic.py\n+++ b/sklearn/tests/test_isotonic.py\n@@ -9,7 +9,8 @@\n IsotonicRegression, _make_unique)\n \n from sklearn.utils.validation import check_array\n-from sklearn.utils._testing import (assert_raises, assert_array_equal,\n+from sklearn.utils._testing import (assert_raises, assert_allclose,\n+ assert_array_equal,\n assert_array_almost_equal,\n assert_warns_message, assert_no_warnings)\n from sklearn.utils import shuffle\n@@ -535,3 +536,43 @@ def test_isotonic_thresholds(increasing):\n assert all(np.diff(y_thresholds) >= 0)\n else:\n assert all(np.diff(y_thresholds) <= 0)\n+\n+\n+def test_input_shape_validation():\n+ # Test from #15012\n+ # Check that IsotonicRegression can handle 2darray with only 1 feature\n+ X = np.arange(10)\n+ X_2d = X.reshape(-1, 1)\n+ y = np.arange(10)\n+\n+ iso_reg = IsotonicRegression().fit(X, y)\n+ iso_reg_2d = IsotonicRegression().fit(X_2d, y)\n+\n+ assert iso_reg.X_max_ == iso_reg_2d.X_max_\n+ assert iso_reg.X_min_ == iso_reg_2d.X_min_\n+ assert iso_reg.y_max == iso_reg_2d.y_max\n+ assert iso_reg.y_min == iso_reg_2d.y_min\n+ assert_array_equal(iso_reg.X_thresholds_, iso_reg_2d.X_thresholds_)\n+ assert_array_equal(iso_reg.y_thresholds_, iso_reg_2d.y_thresholds_)\n+\n+ y_pred1 = iso_reg.predict(X)\n+ y_pred2 = iso_reg_2d.predict(X_2d)\n+ assert_allclose(y_pred1, y_pred2)\n+\n+\n+def test_isotonic_2darray_more_than_1_feature():\n+ # Ensure IsotonicRegression raises error if input has more than 1 feature\n+ X = np.arange(10)\n+ X_2d = np.c_[X, X]\n+ y = np.arange(10)\n+\n+ msg = \"should be a 1d array or 2d array with 1 feature\"\n+ with pytest.raises(ValueError, match=msg):\n+ IsotonicRegression().fit(X_2d, y)\n+\n+ iso_reg = IsotonicRegression().fit(X, y)\n+ with pytest.raises(ValueError, match=msg):\n+ iso_reg.predict(X_2d)\n+\n+ with pytest.raises(ValueError, match=msg):\n+ iso_reg.transform(X_2d)\n", "doc_changes": [{"path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex 9e31762d62c29..b5d0145af4822 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -158,6 +158,9 @@ Changelog\n :pr:`16289` by :user:`Masashi Kishimoto ` and\n :user:`Olivier Grisel `.\n \n+- |Enhancement| :class:`isotonic.IsotonicRegression` now accepts 2darray with 1 feature as\n+ input array. :pr:`17379` by :user:`Jiaxiang `.\n+\n :mod:`sklearn.metrics`\n ......................\n \n"}], "version": "0.24", "base_commit": "3a49e5f209f08c00f73d8895cf27d228fbae25f1", "PASS2PASS": ["sklearn/tests/test_isotonic.py::test_isotonic_regression_oob_bad", "sklearn/tests/test_isotonic.py::test_check_increasing_down_extreme", "sklearn/tests/test_isotonic.py::test_isotonic_thresholds[True]", "sklearn/tests/test_isotonic.py::test_isotonic_sample_weight_parameter_default_value", "sklearn/tests/test_isotonic.py::test_isotonic_sample_weight", "sklearn/tests/test_isotonic.py::test_isotonic_regression_oob_raise", "sklearn/tests/test_isotonic.py::test_check_increasing_down", "sklearn/tests/test_isotonic.py::test_isotonic_regression_oob_nan", "sklearn/tests/test_isotonic.py::test_isotonic_regression_oob_clip", "sklearn/tests/test_isotonic.py::test_isotonic_regression_pickle", "sklearn/tests/test_isotonic.py::test_isotonic_ymin_ymax", "sklearn/tests/test_isotonic.py::test_make_unique_dtype", "sklearn/tests/test_isotonic.py::test_isotonic_regression_auto_decreasing", "sklearn/tests/test_isotonic.py::test_isotonic_mismatched_dtype[float64]", "sklearn/tests/test_isotonic.py::test_check_increasing_up_extreme", "sklearn/tests/test_isotonic.py::test_isotonic_zero_weight_loop", "sklearn/tests/test_isotonic.py::test_check_increasing_up", "sklearn/tests/test_isotonic.py::test_isotonic_mismatched_dtype[int32]", "sklearn/tests/test_isotonic.py::test_isotonic_mismatched_dtype[float32]", "sklearn/tests/test_isotonic.py::test_isotonic_duplicate_min_entry", "sklearn/tests/test_isotonic.py::test_isotonic_min_max_boundaries", "sklearn/tests/test_isotonic.py::test_assert_raises_exceptions", "sklearn/tests/test_isotonic.py::test_check_ci_warn", "sklearn/tests/test_isotonic.py::test_isotonic_copy_before_fit", "sklearn/tests/test_isotonic.py::test_isotonic_mismatched_dtype[int64]", "sklearn/tests/test_isotonic.py::test_isotonic_regression", "sklearn/tests/test_isotonic.py::test_isotonic_regression_ties_secondary_", "sklearn/tests/test_isotonic.py::test_isotonic_regression_with_ties_in_differently_sized_groups", "sklearn/tests/test_isotonic.py::test_fast_predict", "sklearn/tests/test_isotonic.py::test_isotonic_thresholds[False]", "sklearn/tests/test_isotonic.py::test_permutation_invariance", "sklearn/tests/test_isotonic.py::test_check_increasing_small_number_of_samples", "sklearn/tests/test_isotonic.py::test_isotonic_regression_ties_max", "sklearn/tests/test_isotonic.py::test_isotonic_dtype", "sklearn/tests/test_isotonic.py::test_isotonic_regression_reversed", "sklearn/tests/test_isotonic.py::test_isotonic_regression_ties_min", "sklearn/tests/test_isotonic.py::test_isotonic_regression_oob_bad_after", "sklearn/tests/test_isotonic.py::test_isotonic_regression_auto_increasing"], "FAIL2PASS": ["sklearn/tests/test_isotonic.py::test_input_shape_validation", "sklearn/tests/test_isotonic.py::test_isotonic_2darray_more_than_1_feature"], "mask_doc_diff": [{"path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex 9e31762d6..a30006b15 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -158,6 +158,9 @@ Changelog\n :pr:`16289` by :user:`Masashi Kishimoto ` and\n :user:`Olivier Grisel `.\n \n+- |Enhancement| :class:`isotonic.IsotonicRegression` now accepts 2darray with 1 feature as\n+ input array.\n+\n :mod:`sklearn.metrics`\n ......................\n \n"}], "augmentations": {"header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": []}, "problem_statement": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex 9e31762d6..a30006b15 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -158,6 +158,9 @@ Changelog\n :pr:`16289` by :user:`Masashi Kishimoto ` and\n :user:`Olivier Grisel `.\n \n+- |Enhancement| :class:`isotonic.IsotonicRegression` now accepts 2darray with 1 feature as\n+ input array.\n+\n :mod:`sklearn.metrics`\n ......................\n \n\n"} {"repo": "scikit-learn/scikit-learn", "instance_id": "scikit-learn__scikit-learn-18280", "html_url": "https://github.com/scikit-learn/scikit-learn/pull/18280", "feature_patch": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex c6ef6e5994cdf..9294bab242432 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -112,7 +112,15 @@ Changelog\n - |Enhancement| :func:`datasets.fetch_covtype` now now supports the optional\n argument `as_frame`; when it is set to True, the returned Bunch object's\n `data` and `frame` members are pandas DataFrames, and the `target` member is\n- a pandas Series. :pr:`17491` by :user:`Alex Liang `.\n+ a pandas Series.\n+ :pr:`17491` by :user:`Alex Liang `.\n+\n+- |Enhancement| :func:`datasets.fetch_kddcup99` now now supports the optional\n+ argument `as_frame`; when it is set to True, the returned Bunch object's\n+ `data` and `frame` members are pandas DataFrames, and the `target` member is\n+ a pandas Series.\n+ :pr:`18280` by :user:`Alex Liang ` and\n+ `Guillaume Lemaitre`_.\n \n - |API| The default value of `as_frame` in :func:`datasets.fetch_openml` is\n changed from False to 'auto'.\ndiff --git a/sklearn/datasets/_kddcup99.py b/sklearn/datasets/_kddcup99.py\nindex 2c9263701e0c4..e5c8bb2f298de 100644\n--- a/sklearn/datasets/_kddcup99.py\n+++ b/sklearn/datasets/_kddcup99.py\n@@ -18,6 +18,7 @@\n import joblib\n \n from ._base import _fetch_remote\n+from ._base import _convert_data_dataframe\n from . import get_data_home\n from ._base import RemoteFileMetadata\n from ..utils import Bunch\n@@ -48,7 +49,8 @@\n @_deprecate_positional_args\n def fetch_kddcup99(*, subset=None, data_home=None, shuffle=False,\n random_state=None,\n- percent10=True, download_if_missing=True, return_X_y=False):\n+ percent10=True, download_if_missing=True, return_X_y=False,\n+ as_frame=False):\n \"\"\"Load the kddcup99 dataset (classification).\n \n Download it if necessary.\n@@ -97,29 +99,48 @@ def fetch_kddcup99(*, subset=None, data_home=None, shuffle=False,\n \n .. versionadded:: 0.20\n \n+ as_frame : bool, default=False\n+ If `True`, returns a pandas Dataframe for the ``data`` and ``target``\n+ objects in the `Bunch` returned object; `Bunch` return object will also\n+ have a ``frame`` member.\n+\n+ .. versionadded:: 0.24\n+\n Returns\n -------\n data : :class:`~sklearn.utils.Bunch`\n Dictionary-like object, with the following attributes.\n \n- data : ndarray of shape (494021, 41)\n- The data matrix to learn.\n- target : ndarray of shape (494021,)\n- The regression target for each sample.\n+ data : {ndarray, dataframe} of shape (494021, 41)\n+ The data matrix to learn. If `as_frame=True`, `data` will be a\n+ pandas DataFrame.\n+ target : {ndarray, series} of shape (494021,)\n+ The regression target for each sample. If `as_frame=True`, `target`\n+ will be a pandas Series.\n+ frame : dataframe of shape (494021, 42)\n+ Only present when `as_frame=True`. Contains `data` and `target`.\n DESCR : str\n The full description of the dataset.\n+ feature_names : list\n+ The names of the dataset columns\n+ target_names: list\n+ The names of the target columns\n \n (data, target) : tuple if ``return_X_y`` is True\n \n .. versionadded:: 0.20\n \"\"\"\n data_home = get_data_home(data_home=data_home)\n- kddcup99 = _fetch_brute_kddcup99(data_home=data_home,\n- percent10=percent10,\n- download_if_missing=download_if_missing)\n+ kddcup99 = _fetch_brute_kddcup99(\n+ data_home=data_home,\n+ percent10=percent10,\n+ download_if_missing=download_if_missing\n+ )\n \n data = kddcup99.data\n target = kddcup99.target\n+ feature_names = kddcup99.feature_names\n+ target_names = kddcup99.target_names\n \n if subset == 'SA':\n s = target == b'normal.'\n@@ -143,6 +164,7 @@ def fetch_kddcup99(*, subset=None, data_home=None, shuffle=False,\n # select all samples with positive logged_in attribute:\n s = data[:, 11] == 1\n data = np.c_[data[s, :11], data[s, 12:]]\n+ feature_names = feature_names[:11] + feature_names[12:]\n target = target[s]\n \n data[:, 0] = np.log((data[:, 0] + 0.1).astype(float, copy=False))\n@@ -154,15 +176,21 @@ def fetch_kddcup99(*, subset=None, data_home=None, shuffle=False,\n data = data[s]\n target = target[s]\n data = np.c_[data[:, 0], data[:, 4], data[:, 5]]\n+ feature_names = [feature_names[0], feature_names[4],\n+ feature_names[5]]\n \n if subset == 'smtp':\n s = data[:, 2] == b'smtp'\n data = data[s]\n target = target[s]\n data = np.c_[data[:, 0], data[:, 4], data[:, 5]]\n+ feature_names = [feature_names[0], feature_names[4],\n+ feature_names[5]]\n \n if subset == 'SF':\n data = np.c_[data[:, 0], data[:, 2], data[:, 4], data[:, 5]]\n+ feature_names = [feature_names[0], feature_names[2],\n+ feature_names[4], feature_names[5]]\n \n if shuffle:\n data, target = shuffle_method(data, target, random_state=random_state)\n@@ -174,7 +202,20 @@ def fetch_kddcup99(*, subset=None, data_home=None, shuffle=False,\n if return_X_y:\n return data, target\n \n- return Bunch(data=data, target=target, DESCR=fdescr)\n+ frame = None\n+ if as_frame:\n+ frame, data, target = _convert_data_dataframe(\n+ \"fetch_kddcup99\", data, target, feature_names, target_names\n+ )\n+\n+ return Bunch(\n+ data=data,\n+ target=target,\n+ frame=frame,\n+ target_names=target_names,\n+ feature_names=feature_names,\n+ DESCR=fdescr,\n+ )\n \n \n def _fetch_brute_kddcup99(data_home=None,\n@@ -205,6 +246,10 @@ def _fetch_brute_kddcup99(data_home=None,\n target : ndarray of shape (494021,)\n Each value corresponds to one of the 21 attack types or to the\n label 'normal.'.\n+ feature_names : list\n+ The names of the dataset columns\n+ target_names: list\n+ The names of the target columns\n DESCR : str\n Description of the kddcup99 dataset.\n \n@@ -224,52 +269,56 @@ def _fetch_brute_kddcup99(data_home=None,\n targets_path = join(kddcup_dir, \"targets\")\n available = exists(samples_path)\n \n+ dt = [('duration', int),\n+ ('protocol_type', 'S4'),\n+ ('service', 'S11'),\n+ ('flag', 'S6'),\n+ ('src_bytes', int),\n+ ('dst_bytes', int),\n+ ('land', int),\n+ ('wrong_fragment', int),\n+ ('urgent', int),\n+ ('hot', int),\n+ ('num_failed_logins', int),\n+ ('logged_in', int),\n+ ('num_compromised', int),\n+ ('root_shell', int),\n+ ('su_attempted', int),\n+ ('num_root', int),\n+ ('num_file_creations', int),\n+ ('num_shells', int),\n+ ('num_access_files', int),\n+ ('num_outbound_cmds', int),\n+ ('is_host_login', int),\n+ ('is_guest_login', int),\n+ ('count', int),\n+ ('srv_count', int),\n+ ('serror_rate', float),\n+ ('srv_serror_rate', float),\n+ ('rerror_rate', float),\n+ ('srv_rerror_rate', float),\n+ ('same_srv_rate', float),\n+ ('diff_srv_rate', float),\n+ ('srv_diff_host_rate', float),\n+ ('dst_host_count', int),\n+ ('dst_host_srv_count', int),\n+ ('dst_host_same_srv_rate', float),\n+ ('dst_host_diff_srv_rate', float),\n+ ('dst_host_same_src_port_rate', float),\n+ ('dst_host_srv_diff_host_rate', float),\n+ ('dst_host_serror_rate', float),\n+ ('dst_host_srv_serror_rate', float),\n+ ('dst_host_rerror_rate', float),\n+ ('dst_host_srv_rerror_rate', float),\n+ ('labels', 'S16')]\n+\n+ column_names = [c[0] for c in dt]\n+ target_names = column_names[-1]\n+ feature_names = column_names[:-1]\n if download_if_missing and not available:\n _mkdirp(kddcup_dir)\n logger.info(\"Downloading %s\" % archive.url)\n _fetch_remote(archive, dirname=kddcup_dir)\n- dt = [('duration', int),\n- ('protocol_type', 'S4'),\n- ('service', 'S11'),\n- ('flag', 'S6'),\n- ('src_bytes', int),\n- ('dst_bytes', int),\n- ('land', int),\n- ('wrong_fragment', int),\n- ('urgent', int),\n- ('hot', int),\n- ('num_failed_logins', int),\n- ('logged_in', int),\n- ('num_compromised', int),\n- ('root_shell', int),\n- ('su_attempted', int),\n- ('num_root', int),\n- ('num_file_creations', int),\n- ('num_shells', int),\n- ('num_access_files', int),\n- ('num_outbound_cmds', int),\n- ('is_host_login', int),\n- ('is_guest_login', int),\n- ('count', int),\n- ('srv_count', int),\n- ('serror_rate', float),\n- ('srv_serror_rate', float),\n- ('rerror_rate', float),\n- ('srv_rerror_rate', float),\n- ('same_srv_rate', float),\n- ('diff_srv_rate', float),\n- ('srv_diff_host_rate', float),\n- ('dst_host_count', int),\n- ('dst_host_srv_count', int),\n- ('dst_host_same_srv_rate', float),\n- ('dst_host_diff_srv_rate', float),\n- ('dst_host_same_src_port_rate', float),\n- ('dst_host_srv_diff_host_rate', float),\n- ('dst_host_serror_rate', float),\n- ('dst_host_srv_serror_rate', float),\n- ('dst_host_rerror_rate', float),\n- ('dst_host_srv_rerror_rate', float),\n- ('labels', 'S16')]\n DT = np.dtype(dt)\n logger.debug(\"extracting archive\")\n archive_path = join(kddcup_dir, archive.filename)\n@@ -304,7 +353,12 @@ def _fetch_brute_kddcup99(data_home=None,\n X = joblib.load(samples_path)\n y = joblib.load(targets_path)\n \n- return Bunch(data=X, target=y)\n+ return Bunch(\n+ data=X,\n+ target=y,\n+ feature_names=feature_names,\n+ target_names=[target_names],\n+ )\n \n \n def _mkdirp(d):\ndiff --git a/sklearn/datasets/descr/kddcup99.rst b/sklearn/datasets/descr/kddcup99.rst\nindex 00427ac08b748..8bdcccf7973ea 100644\n--- a/sklearn/datasets/descr/kddcup99.rst\n+++ b/sklearn/datasets/descr/kddcup99.rst\n@@ -78,8 +78,9 @@ General KDD structure :\n \n :func:`sklearn.datasets.fetch_kddcup99` will load the kddcup99 dataset; it\n returns a dictionary-like object with the feature matrix in the ``data`` member\n-and the target values in ``target``. The dataset will be downloaded from the\n-web if necessary.\n+and the target values in ``target``. The \"as_frame\" optional argument converts\n+``data`` into a pandas DataFrame and ``target`` into a pandas Series. The\n+dataset will be downloaded from the web if necessary.\n \n .. topic: References\n \n@@ -92,4 +93,3 @@ web if necessary.\n discounting learning algorithms. In Proceedings of the sixth\n ACM SIGKDD international conference on Knowledge discovery\n and data mining, pages 320-324. ACM Press, 2000.\n-\n", "test_patch": "diff --git a/sklearn/datasets/tests/test_kddcup99.py b/sklearn/datasets/tests/test_kddcup99.py\nindex 414c1bab1acd5..11adaacfaae20 100644\n--- a/sklearn/datasets/tests/test_kddcup99.py\n+++ b/sklearn/datasets/tests/test_kddcup99.py\n@@ -6,41 +6,56 @@\n is too big to use in unit-testing.\n \"\"\"\n \n-from sklearn.datasets.tests.test_common import check_return_X_y\n from functools import partial\n+import pytest\n \n+from sklearn.datasets import fetch_kddcup99\n+from sklearn.datasets.tests.test_common import check_as_frame\n+from sklearn.datasets.tests.test_common import check_pandas_dependency_message\n+from sklearn.datasets.tests.test_common import check_return_X_y\n \n-def test_percent10(fetch_kddcup99_fxt):\n- data = fetch_kddcup99_fxt()\n-\n- assert data.data.shape == (494021, 41)\n- assert data.target.shape == (494021,)\n-\n- data_shuffled = fetch_kddcup99_fxt(shuffle=True, random_state=0)\n- assert data.data.shape == data_shuffled.data.shape\n- assert data.target.shape == data_shuffled.target.shape\n \n- data = fetch_kddcup99_fxt(subset='SA')\n- assert data.data.shape == (100655, 41)\n- assert data.target.shape == (100655,)\n+@pytest.mark.parametrize(\"as_frame\", [True, False])\n+@pytest.mark.parametrize(\n+ \"subset, n_samples, n_features\",\n+ [(None, 494021, 41),\n+ (\"SA\", 100655, 41),\n+ (\"SF\", 73237, 4),\n+ (\"http\", 58725, 3),\n+ (\"smtp\", 9571, 3)]\n+)\n+def test_fetch_kddcup99_percent10(\n+ fetch_kddcup99_fxt, as_frame, subset, n_samples, n_features\n+):\n+ data = fetch_kddcup99_fxt(subset=subset, as_frame=as_frame)\n+ assert data.data.shape == (n_samples, n_features)\n+ assert data.target.shape == (n_samples,)\n+ if as_frame:\n+ assert data.frame.shape == (n_samples, n_features + 1)\n+\n+\n+def test_fetch_kddcup99_return_X_y(fetch_kddcup99_fxt):\n+ fetch_func = partial(fetch_kddcup99_fxt, subset='smtp')\n+ data = fetch_func()\n+ check_return_X_y(data, fetch_func)\n \n- data = fetch_kddcup99_fxt(subset='SF')\n- assert data.data.shape == (73237, 4)\n- assert data.target.shape == (73237,)\n \n- data = fetch_kddcup99_fxt(subset='http')\n- assert data.data.shape == (58725, 3)\n- assert data.target.shape == (58725,)\n+def test_fetch_kddcup99_as_frame(fetch_kddcup99_fxt):\n+ bunch = fetch_kddcup99_fxt()\n+ check_as_frame(bunch, fetch_kddcup99_fxt)\n \n- data = fetch_kddcup99_fxt(subset='smtp')\n- assert data.data.shape == (9571, 3)\n- assert data.target.shape == (9571,)\n \n- fetch_func = partial(fetch_kddcup99_fxt, subset='smtp')\n- check_return_X_y(data, fetch_func)\n+def test_fetch_kddcup99_shuffle(fetch_kddcup99_fxt):\n+ dataset = fetch_kddcup99_fxt(\n+ random_state=0, subset='SA', percent10=True,\n+ )\n+ dataset_shuffled = fetch_kddcup99_fxt(\n+ random_state=0, subset='SA', shuffle=True, percent10=True,\n+ )\n+ assert set(dataset['target']) == set(dataset_shuffled['target'])\n+ assert dataset_shuffled.data.shape == dataset.data.shape\n+ assert dataset_shuffled.target.shape == dataset.target.shape\n \n \n-def test_shuffle(fetch_kddcup99_fxt):\n- dataset = fetch_kddcup99_fxt(random_state=0, subset='SA', shuffle=True,\n- percent10=True)\n- assert(any(dataset.target[-100:] == b'normal.'))\n+def test_pandas_dependency_message(fetch_kddcup99_fxt, hide_available_pandas):\n+ check_pandas_dependency_message(fetch_kddcup99)\n", "doc_changes": [{"path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex c6ef6e5994cdf..9294bab242432 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -112,7 +112,15 @@ Changelog\n - |Enhancement| :func:`datasets.fetch_covtype` now now supports the optional\n argument `as_frame`; when it is set to True, the returned Bunch object's\n `data` and `frame` members are pandas DataFrames, and the `target` member is\n- a pandas Series. :pr:`17491` by :user:`Alex Liang `.\n+ a pandas Series.\n+ :pr:`17491` by :user:`Alex Liang `.\n+\n+- |Enhancement| :func:`datasets.fetch_kddcup99` now now supports the optional\n+ argument `as_frame`; when it is set to True, the returned Bunch object's\n+ `data` and `frame` members are pandas DataFrames, and the `target` member is\n+ a pandas Series.\n+ :pr:`18280` by :user:`Alex Liang ` and\n+ `Guillaume Lemaitre`_.\n \n - |API| The default value of `as_frame` in :func:`datasets.fetch_openml` is\n changed from False to 'auto'.\n"}], "version": "0.24", "base_commit": "138dd7b88f1634447f838bc58088e594ffaf5549", "PASS2PASS": [], "FAIL2PASS": ["sklearn/datasets/tests/test_kddcup99.py::test_pandas_dependency_message"], "mask_doc_diff": [{"path": "doc/whats_new/v0.24.rst", "old_path": "a/doc/whats_new/v0.24.rst", "new_path": "b/doc/whats_new/v0.24.rst", "metadata": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex c6ef6e599..03ec5788e 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -112,7 +112,13 @@ Changelog\n - |Enhancement| :func:`datasets.fetch_covtype` now now supports the optional\n argument `as_frame`; when it is set to True, the returned Bunch object's\n `data` and `frame` members are pandas DataFrames, and the `target` member is\n- a pandas Series. :pr:`17491` by :user:`Alex Liang `.\n+ a pandas Series.\n+ :pr:`17491` by :user:`Alex Liang `.\n+\n+- |Enhancement| :func:`datasets.fetch_kddcup99` now now supports the optional\n+ argument `as_frame`; when it is set to True, the returned Bunch object's\n+ `data` and `frame` members are pandas DataFrames, and the `target` member is\n+ a pandas Series.\n \n - |API| The default value of `as_frame` in :func:`datasets.fetch_openml` is\n changed from False to 'auto'.\n"}], "augmentations": {"header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": []}, "problem_statement": "diff --git a/doc/whats_new/v0.24.rst b/doc/whats_new/v0.24.rst\nindex c6ef6e599..03ec5788e 100644\n--- a/doc/whats_new/v0.24.rst\n+++ b/doc/whats_new/v0.24.rst\n@@ -112,7 +112,13 @@ Changelog\n - |Enhancement| :func:`datasets.fetch_covtype` now now supports the optional\n argument `as_frame`; when it is set to True, the returned Bunch object's\n `data` and `frame` members are pandas DataFrames, and the `target` member is\n- a pandas Series. :pr:`17491` by :user:`Alex Liang `.\n+ a pandas Series.\n+ :pr:`17491` by :user:`Alex Liang `.\n+\n+- |Enhancement| :func:`datasets.fetch_kddcup99` now now supports the optional\n+ argument `as_frame`; when it is set to True, the returned Bunch object's\n+ `data` and `frame` members are pandas DataFrames, and the `target` member is\n+ a pandas Series.\n \n - |API| The default value of `as_frame` in :func:`datasets.fetch_openml` is\n changed from False to 'auto'.\n\n"} -{"repo": "scikit-learn/scikit-learn", "instance_id": "scikit-learn__scikit-learn-12069", "html_url": "https://github.com/scikit-learn/scikit-learn/pull/12069", "feature_patch": "diff --git a/benchmarks/bench_kernel_pca_solvers_time_vs_n_components.py b/benchmarks/bench_kernel_pca_solvers_time_vs_n_components.py\nnew file mode 100644\nindex 0000000000000..d871967ad1327\n--- /dev/null\n+++ b/benchmarks/bench_kernel_pca_solvers_time_vs_n_components.py\n@@ -0,0 +1,148 @@\n+\"\"\"\n+=============================================================\n+Kernel PCA Solvers comparison benchmark: time vs n_components\n+=============================================================\n+\n+This benchmark shows that the approximate solvers provided in Kernel PCA can\n+help significantly improve its execution speed when an approximate solution\n+(small `n_components`) is acceptable. In many real-world datasets a few\n+hundreds of principal components are indeed sufficient enough to capture the\n+underlying distribution.\n+\n+Description:\n+------------\n+A fixed number of training (default: 2000) and test (default: 1000) samples\n+with 2 features is generated using the `make_circles` helper method.\n+\n+KernelPCA models are trained on the training set with an increasing number of\n+principal components, between 1 and `max_n_compo` (default: 1999), with\n+`n_compo_grid_size` positions (default: 10). For each value of `n_components`\n+to try, KernelPCA models are trained for the various possible `eigen_solver`\n+values. The execution times are displayed in a plot at the end of the\n+experiment.\n+\n+What you can observe:\n+---------------------\n+When the number of requested principal components is small, the dense solver\n+takes more time to complete, while the randomized method returns similar\n+results with shorter execution times.\n+\n+Going further:\n+--------------\n+You can adjust `max_n_compo` and `n_compo_grid_size` if you wish to explore a\n+different range of values for `n_components`.\n+\n+You can also set `arpack_all=True` to activate arpack solver for large number\n+of components (this takes more time).\n+\"\"\"\n+# Authors: Sylvain MARIE, Schneider Electric\n+\n+import time\n+\n+import numpy as np\n+import matplotlib.pyplot as plt\n+\n+from numpy.testing import assert_array_almost_equal\n+from sklearn.decomposition import KernelPCA\n+from sklearn.datasets import make_circles\n+\n+\n+print(__doc__)\n+\n+\n+# 1- Design the Experiment\n+# ------------------------\n+n_train, n_test = 2000, 1000 # the sample sizes to use\n+max_n_compo = 1999 # max n_components to try\n+n_compo_grid_size = 10 # nb of positions in the grid to try\n+# generate the grid\n+n_compo_range = [np.round(np.exp((x / (n_compo_grid_size - 1))\n+ * np.log(max_n_compo)))\n+ for x in range(0, n_compo_grid_size)]\n+\n+n_iter = 3 # the number of times each experiment will be repeated\n+arpack_all = False # set to True if you wish to run arpack for all n_compo\n+\n+\n+# 2- Generate random data\n+# -----------------------\n+n_features = 2\n+X, y = make_circles(n_samples=(n_train + n_test), factor=.3, noise=.05,\n+ random_state=0)\n+X_train, X_test = X[:n_train, :], X[n_train:, :]\n+\n+\n+# 3- Benchmark\n+# ------------\n+# init\n+ref_time = np.empty((len(n_compo_range), n_iter)) * np.nan\n+a_time = np.empty((len(n_compo_range), n_iter)) * np.nan\n+r_time = np.empty((len(n_compo_range), n_iter)) * np.nan\n+# loop\n+for j, n_components in enumerate(n_compo_range):\n+\n+ n_components = int(n_components)\n+ print(\"Performing kPCA with n_components = %i\" % n_components)\n+\n+ # A- reference (dense)\n+ print(\" - dense solver\")\n+ for i in range(n_iter):\n+ start_time = time.perf_counter()\n+ ref_pred = KernelPCA(n_components, eigen_solver=\"dense\") \\\n+ .fit(X_train).transform(X_test)\n+ ref_time[j, i] = time.perf_counter() - start_time\n+\n+ # B- arpack (for small number of components only, too slow otherwise)\n+ if arpack_all or n_components < 100:\n+ print(\" - arpack solver\")\n+ for i in range(n_iter):\n+ start_time = time.perf_counter()\n+ a_pred = KernelPCA(n_components, eigen_solver=\"arpack\") \\\n+ .fit(X_train).transform(X_test)\n+ a_time[j, i] = time.perf_counter() - start_time\n+ # check that the result is still correct despite the approx\n+ assert_array_almost_equal(np.abs(a_pred), np.abs(ref_pred))\n+\n+ # C- randomized\n+ print(\" - randomized solver\")\n+ for i in range(n_iter):\n+ start_time = time.perf_counter()\n+ r_pred = KernelPCA(n_components, eigen_solver=\"randomized\") \\\n+ .fit(X_train).transform(X_test)\n+ r_time[j, i] = time.perf_counter() - start_time\n+ # check that the result is still correct despite the approximation\n+ assert_array_almost_equal(np.abs(r_pred), np.abs(ref_pred))\n+\n+# Compute statistics for the 3 methods\n+avg_ref_time = ref_time.mean(axis=1)\n+std_ref_time = ref_time.std(axis=1)\n+avg_a_time = a_time.mean(axis=1)\n+std_a_time = a_time.std(axis=1)\n+avg_r_time = r_time.mean(axis=1)\n+std_r_time = r_time.std(axis=1)\n+\n+\n+# 4- Plots\n+# --------\n+fig, ax = plt.subplots(figsize=(12, 8))\n+\n+# Display 1 plot with error bars per method\n+ax.errorbar(n_compo_range, avg_ref_time, yerr=std_ref_time,\n+ marker='x', linestyle='', color='r', label='full')\n+ax.errorbar(n_compo_range, avg_a_time, yerr=std_a_time, marker='x',\n+ linestyle='', color='g', label='arpack')\n+ax.errorbar(n_compo_range, avg_r_time, yerr=std_r_time, marker='x',\n+ linestyle='', color='b', label='randomized')\n+ax.legend(loc='upper left')\n+\n+# customize axes\n+ax.set_xscale('log')\n+ax.set_xlim(1, max(n_compo_range) * 1.1)\n+ax.set_ylabel(\"Execution time (s)\")\n+ax.set_xlabel(\"n_components\")\n+\n+ax.set_title(\"kPCA Execution time comparison on %i samples with %i \"\n+ \"features, according to the choice of `eigen_solver`\"\n+ \"\" % (n_train, n_features))\n+\n+plt.show()\ndiff --git a/benchmarks/bench_kernel_pca_solvers_time_vs_n_samples.py b/benchmarks/bench_kernel_pca_solvers_time_vs_n_samples.py\nnew file mode 100644\nindex 0000000000000..d238802a68d64\n--- /dev/null\n+++ b/benchmarks/bench_kernel_pca_solvers_time_vs_n_samples.py\n@@ -0,0 +1,153 @@\n+\"\"\"\n+==========================================================\n+Kernel PCA Solvers comparison benchmark: time vs n_samples\n+==========================================================\n+\n+This benchmark shows that the approximate solvers provided in Kernel PCA can\n+help significantly improve its execution speed when an approximate solution\n+(small `n_components`) is acceptable. In many real-world datasets the number of\n+samples is very large, but a few hundreds of principal components are\n+sufficient enough to capture the underlying distribution.\n+\n+Description:\n+------------\n+An increasing number of examples is used to train a KernelPCA, between\n+`min_n_samples` (default: 101) and `max_n_samples` (default: 4000) with\n+`n_samples_grid_size` positions (default: 4). Samples have 2 features, and are\n+generated using `make_circles`. For each training sample size, KernelPCA models\n+are trained for the various possible `eigen_solver` values. All of them are\n+trained to obtain `n_components` principal components (default: 100). The\n+execution times are displayed in a plot at the end of the experiment.\n+\n+What you can observe:\n+---------------------\n+When the number of samples provided gets large, the dense solver takes a lot\n+of time to complete, while the randomized method returns similar results in\n+much shorter execution times.\n+\n+Going further:\n+--------------\n+You can increase `max_n_samples` and `nb_n_samples_to_try` if you wish to\n+explore a wider range of values for `n_samples`.\n+\n+You can also set `include_arpack=True` to add this other solver in the\n+experiments (much slower).\n+\n+Finally you can have a look at the second example of this series, \"Kernel PCA\n+Solvers comparison benchmark: time vs n_components\", where this time the number\n+of examples is fixed, and the desired number of components varies.\n+\"\"\"\n+# Author: Sylvain MARIE, Schneider Electric\n+\n+import time\n+\n+import numpy as np\n+import matplotlib.pyplot as plt\n+\n+from numpy.testing import assert_array_almost_equal\n+from sklearn.decomposition import KernelPCA\n+from sklearn.datasets import make_circles\n+\n+\n+print(__doc__)\n+\n+\n+# 1- Design the Experiment\n+# ------------------------\n+min_n_samples, max_n_samples = 101, 4000 # min and max n_samples to try\n+n_samples_grid_size = 4 # nb of positions in the grid to try\n+# generate the grid\n+n_samples_range = [min_n_samples + np.floor((x / (n_samples_grid_size - 1))\n+ * (max_n_samples - min_n_samples))\n+ for x in range(0, n_samples_grid_size)]\n+\n+n_components = 100 # the number of principal components we want to use\n+n_iter = 3 # the number of times each experiment will be repeated\n+include_arpack = False # set this to True to include arpack solver (slower)\n+\n+\n+# 2- Generate random data\n+# -----------------------\n+n_features = 2\n+X, y = make_circles(n_samples=max_n_samples, factor=.3, noise=.05,\n+ random_state=0)\n+\n+\n+# 3- Benchmark\n+# ------------\n+# init\n+ref_time = np.empty((len(n_samples_range), n_iter)) * np.nan\n+a_time = np.empty((len(n_samples_range), n_iter)) * np.nan\n+r_time = np.empty((len(n_samples_range), n_iter)) * np.nan\n+\n+# loop\n+for j, n_samples in enumerate(n_samples_range):\n+\n+ n_samples = int(n_samples)\n+ print(\"Performing kPCA with n_samples = %i\" % n_samples)\n+\n+ X_train = X[:n_samples, :]\n+ X_test = X_train\n+\n+ # A- reference (dense)\n+ print(\" - dense\")\n+ for i in range(n_iter):\n+ start_time = time.perf_counter()\n+ ref_pred = KernelPCA(n_components, eigen_solver=\"dense\") \\\n+ .fit(X_train).transform(X_test)\n+ ref_time[j, i] = time.perf_counter() - start_time\n+\n+ # B- arpack\n+ if include_arpack:\n+ print(\" - arpack\")\n+ for i in range(n_iter):\n+ start_time = time.perf_counter()\n+ a_pred = KernelPCA(n_components, eigen_solver=\"arpack\") \\\n+ .fit(X_train).transform(X_test)\n+ a_time[j, i] = time.perf_counter() - start_time\n+ # check that the result is still correct despite the approx\n+ assert_array_almost_equal(np.abs(a_pred), np.abs(ref_pred))\n+\n+ # C- randomized\n+ print(\" - randomized\")\n+ for i in range(n_iter):\n+ start_time = time.perf_counter()\n+ r_pred = KernelPCA(n_components, eigen_solver=\"randomized\") \\\n+ .fit(X_train).transform(X_test)\n+ r_time[j, i] = time.perf_counter() - start_time\n+ # check that the result is still correct despite the approximation\n+ assert_array_almost_equal(np.abs(r_pred), np.abs(ref_pred))\n+\n+# Compute statistics for the 3 methods\n+avg_ref_time = ref_time.mean(axis=1)\n+std_ref_time = ref_time.std(axis=1)\n+avg_a_time = a_time.mean(axis=1)\n+std_a_time = a_time.std(axis=1)\n+avg_r_time = r_time.mean(axis=1)\n+std_r_time = r_time.std(axis=1)\n+\n+\n+# 4- Plots\n+# --------\n+fig, ax = plt.subplots(figsize=(12, 8))\n+\n+# Display 1 plot with error bars per method\n+ax.errorbar(n_samples_range, avg_ref_time, yerr=std_ref_time,\n+ marker='x', linestyle='', color='r', label='full')\n+if include_arpack:\n+ ax.errorbar(n_samples_range, avg_a_time, yerr=std_a_time, marker='x',\n+ linestyle='', color='g', label='arpack')\n+ax.errorbar(n_samples_range, avg_r_time, yerr=std_r_time, marker='x',\n+ linestyle='', color='b', label='randomized')\n+ax.legend(loc='upper left')\n+\n+# customize axes\n+ax.set_xlim(min(n_samples_range) * 0.9, max(n_samples_range) * 1.1)\n+ax.set_ylabel(\"Execution time (s)\")\n+ax.set_xlabel(\"n_samples\")\n+\n+ax.set_title(\"Execution time comparison of kPCA with %i components on samples \"\n+ \"with %i features, according to the choice of `eigen_solver`\"\n+ \"\" % (n_components, n_features))\n+\n+plt.show()\ndiff --git a/doc/modules/decomposition.rst b/doc/modules/decomposition.rst\nindex e971d784c63d6..fd51f60d8bfc6 100644\n--- a/doc/modules/decomposition.rst\n+++ b/doc/modules/decomposition.rst\n@@ -166,32 +166,16 @@ Note: the implementation of ``inverse_transform`` in :class:`PCA` with\n \n .. topic:: References:\n \n- * `\"Finding structure with randomness: Stochastic algorithms for\n+ * Algorithm 4.3 in\n+ `\"Finding structure with randomness: Stochastic algorithms for\n constructing approximate matrix decompositions\"\n `_\n Halko, et al., 2009\n \n-\n-.. _kernel_PCA:\n-\n-Kernel PCA\n-----------\n-\n-:class:`KernelPCA` is an extension of PCA which achieves non-linear\n-dimensionality reduction through the use of kernels (see :ref:`metrics`). It\n-has many applications including denoising, compression and structured\n-prediction (kernel dependency estimation). :class:`KernelPCA` supports both\n-``transform`` and ``inverse_transform``.\n-\n-.. figure:: ../auto_examples/decomposition/images/sphx_glr_plot_kernel_pca_001.png\n- :target: ../auto_examples/decomposition/plot_kernel_pca.html\n- :align: center\n- :scale: 75%\n-\n-.. topic:: Examples:\n-\n- * :ref:`sphx_glr_auto_examples_decomposition_plot_kernel_pca.py`\n-\n+ * `\"An implementation of a randomized algorithm for principal component\n+ analysis\"\n+ `_\n+ A. Szlam et al. 2014\n \n .. _SparsePCA:\n \n@@ -278,6 +262,100 @@ factorization, while larger values shrink many coefficients to zero.\n R. Jenatton, G. Obozinski, F. Bach, 2009\n \n \n+.. _kernel_PCA:\n+\n+Kernel Principal Component Analysis (kPCA)\n+==========================================\n+\n+Exact Kernel PCA\n+----------------\n+\n+:class:`KernelPCA` is an extension of PCA which achieves non-linear\n+dimensionality reduction through the use of kernels (see :ref:`metrics`). It\n+has many applications including denoising, compression and structured\n+prediction (kernel dependency estimation). :class:`KernelPCA` supports both\n+``transform`` and ``inverse_transform``.\n+\n+.. figure:: ../auto_examples/decomposition/images/sphx_glr_plot_kernel_pca_001.png\n+ :target: ../auto_examples/decomposition/plot_kernel_pca.html\n+ :align: center\n+ :scale: 75%\n+\n+.. topic:: Examples:\n+\n+ * :ref:`sphx_glr_auto_examples_decomposition_plot_kernel_pca.py`\n+\n+.. topic:: References:\n+\n+ * Kernel PCA was introduced in \"Kernel principal component analysis\"\n+ Bernhard Schoelkopf, Alexander J. Smola, and Klaus-Robert Mueller. 1999.\n+ In Advances in kernel methods, MIT Press, Cambridge, MA, USA 327-352.\n+\n+\n+.. _kPCA_Solvers:\n+\n+Choice of solver for Kernel PCA\n+-------------------------------\n+\n+While in :class:`PCA` the number of components is bounded by the number of\n+features, in :class:`KernelPCA` the number of components is bounded by the\n+number of samples. Many real-world datasets have large number of samples! In\n+these cases finding *all* the components with a full kPCA is a waste of\n+computation time, as data is mostly described by the first few components\n+(e.g. ``n_components<=100``). In other words, the centered Gram matrix that\n+is eigendecomposed in the Kernel PCA fitting process has an effective rank that\n+is much smaller than its size. This is a situation where approximate\n+eigensolvers can provide speedup with very low precision loss.\n+\n+The optional parameter ``eigen_solver='randomized'`` can be used to\n+*significantly* reduce the computation time when the number of requested\n+``n_components`` is small compared with the number of samples. It relies on\n+randomized decomposition methods to find an approximate solution in a shorter\n+time.\n+\n+The time complexity of the randomized :class:`KernelPCA` is\n+:math:`O(n_{\\mathrm{samples}}^2 \\cdot n_{\\mathrm{components}})`\n+instead of :math:`O(n_{\\mathrm{samples}}^3)` for the exact method\n+implemented with ``eigen_solver='dense'``.\n+\n+The memory footprint of randomized :class:`KernelPCA` is also proportional to\n+:math:`2 \\cdot n_{\\mathrm{samples}} \\cdot n_{\\mathrm{components}}` instead of\n+:math:`n_{\\mathrm{samples}}^2` for the exact method.\n+\n+Note: this technique is the same as in :ref:`RandomizedPCA`.\n+\n+In addition to the above two solvers, ``eigen_solver='arpack'`` can be used as\n+an alternate way to get an approximate decomposition. In practice, this method\n+only provides reasonable execution times when the number of components to find\n+is extremely small. It is enabled by default when the desired number of\n+components is less than 10 (strict) and the number of samples is more than 200\n+(strict). See :class:`KernelPCA` for details.\n+\n+.. topic:: References:\n+\n+ * *dense* solver:\n+ `scipy.linalg.eigh documentation\n+ `_\n+\n+ * *randomized* solver:\n+\n+ - Algorithm 4.3 in\n+ `\"Finding structure with randomness: Stochastic algorithms for\n+ constructing approximate matrix decompositions\"\n+ `_\n+ Halko, et al., 2009\n+\n+ - `\"An implementation of a randomized algorithm for principal component\n+ analysis\"\n+ `_\n+ A. Szlam et al. 2014\n+\n+ * *arpack* solver:\n+ `scipy.sparse.linalg.eigsh documentation\n+ `_\n+ R. B. Lehoucq, D. C. Sorensen, and C. Yang, 1998\n+\n+\n .. _LSA:\n \n Truncated singular value decomposition and latent semantic analysis\ndiff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 3b3884e68e185..e89eecfe0874c 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -159,14 +159,17 @@ Changelog\n - |Fix| Fixes incorrect multiple data-conversion warnings when clustering\n boolean data. :pr:`19046` by :user:`Surya Prakash `.\n \n-:mod:`sklearn.decomposition`\n-............................\n-\n - |Fix| Fixed :func:`dict_learning`, used by :class:`DictionaryLearning`, to\n ensure determinism of the output. Achieved by flipping signs of the SVD\n output which is used to initialize the code.\n :pr:`18433` by :user:`Bruno Charron `.\n \n+- |Enhancement| added a new approximate solver (randomized SVD, available with\n+ `eigen_solver='randomized'`) to :class:`decomposition.KernelPCA`. This\n+ significantly accelerates computation when the number of samples is much\n+ larger than the desired number of components.\n+ :pr:`12069` by :user:`Sylvain Mari\u00e9 `.\n+\n - |Fix| Fixed a bug in :class:`MiniBatchDictionaryLearning`,\n :class:`MiniBatchSparsePCA` and :func:`dict_learning_online` where the\n update of the dictionary was incorrect. :pr:`19198` by\n@@ -389,8 +392,8 @@ Changelog\n supporting sparse matrix and raise the appropriate error message.\n :pr:`19879` by :user:`Guillaume Lemaitre `.\n \n-- |Efficiency| Changed ``algorithm`` argument for :class:`cluster.KMeans` in \n- :class:`preprocessing.KBinsDiscretizer` from ``auto`` to ``full``. \n+- |Efficiency| Changed ``algorithm`` argument for :class:`cluster.KMeans` in\n+ :class:`preprocessing.KBinsDiscretizer` from ``auto`` to ``full``.\n :pr:`19934` by :user:`Gleb Levitskiy `.\n \n :mod:`sklearn.tree`\ndiff --git a/sklearn/decomposition/_kernel_pca.py b/sklearn/decomposition/_kernel_pca.py\nindex 415ee034c1769..8663193a8383e 100644\n--- a/sklearn/decomposition/_kernel_pca.py\n+++ b/sklearn/decomposition/_kernel_pca.py\n@@ -1,6 +1,7 @@\n \"\"\"Kernel Principal Components Analysis.\"\"\"\n \n # Author: Mathieu Blondel \n+# Sylvain Marie \n # License: BSD 3 clause\n \n import numpy as np\n@@ -8,7 +9,7 @@\n from scipy.sparse.linalg import eigsh\n \n from ..utils._arpack import _init_arpack_v0\n-from ..utils.extmath import svd_flip\n+from ..utils.extmath import svd_flip, _randomized_eigsh\n from ..utils.validation import check_is_fitted, _check_psd_eigenvalues\n from ..utils.deprecation import deprecated\n from ..exceptions import NotFittedError\n@@ -24,6 +25,12 @@ class KernelPCA(TransformerMixin, BaseEstimator):\n Non-linear dimensionality reduction through the use of kernels (see\n :ref:`metrics`).\n \n+ It uses the `scipy.linalg.eigh` LAPACK implementation of the full SVD or\n+ the `scipy.sparse.linalg.eigsh` ARPACK implementation of the truncated SVD,\n+ depending on the shape of the input data and the number of components to\n+ extract. It can also use a randomized truncated SVD by the method of\n+ Halko et al. 2009, see `eigen_solver`.\n+\n Read more in the :ref:`User Guide `.\n \n Parameters\n@@ -59,10 +66,37 @@ class KernelPCA(TransformerMixin, BaseEstimator):\n Learn the inverse transform for non-precomputed kernels.\n (i.e. learn to find the pre-image of a point)\n \n- eigen_solver : {'auto', 'dense', 'arpack'}, default='auto'\n- Select eigensolver to use. If n_components is much less than\n- the number of training samples, arpack may be more efficient\n- than the dense eigensolver.\n+ eigen_solver : {'auto', 'dense', 'arpack', 'randomized'}, \\\n+ default='auto'\n+ Select eigensolver to use. If `n_components` is much\n+ less than the number of training samples, randomized (or arpack to a\n+ smaller extend) may be more efficient than the dense eigensolver.\n+ Randomized SVD is performed according to the method of Halko et al.\n+\n+ auto :\n+ the solver is selected by a default policy based on n_samples\n+ (the number of training samples) and `n_components`:\n+ if the number of components to extract is less than 10 (strict) and\n+ the number of samples is more than 200 (strict), the 'arpack'\n+ method is enabled. Otherwise the exact full eigenvalue\n+ decomposition is computed and optionally truncated afterwards\n+ ('dense' method).\n+ dense :\n+ run exact full eigenvalue decomposition calling the standard\n+ LAPACK solver via `scipy.linalg.eigh`, and select the components\n+ by postprocessing\n+ arpack :\n+ run SVD truncated to n_components calling ARPACK solver using\n+ `scipy.sparse.linalg.eigsh`. It requires strictly\n+ 0 < n_components < n_samples\n+ randomized :\n+ run randomized SVD by the method of Halko et al. The current\n+ implementation selects eigenvalues based on their module; therefore\n+ using this method can lead to unexpected results if the kernel is\n+ not positive semi-definite.\n+\n+ .. versionchanged:: 1.0\n+ `'randomized'` was added.\n \n tol : float, default=0\n Convergence tolerance for arpack.\n@@ -72,6 +106,13 @@ class KernelPCA(TransformerMixin, BaseEstimator):\n Maximum number of iterations for arpack.\n If None, optimal value will be chosen by arpack.\n \n+ iterated_power : int >= 0, or 'auto', default='auto'\n+ Number of iterations for the power method computed by\n+ svd_solver == 'randomized'. When 'auto', it is set to 7 when\n+ `n_components < 0.1 * min(X.shape)`, other it is set to 4.\n+\n+ .. versionadded:: 1.0\n+\n remove_zero_eig : bool, default=False\n If True, then all components with zero eigenvalues are removed, so\n that the number of components in the output may be < n_components\n@@ -80,8 +121,8 @@ class KernelPCA(TransformerMixin, BaseEstimator):\n with zero eigenvalues are removed regardless.\n \n random_state : int, RandomState instance or None, default=None\n- Used when ``eigen_solver`` == 'arpack'. Pass an int for reproducible\n- results across multiple function calls.\n+ Used when ``eigen_solver`` == 'arpack' or 'randomized'. Pass an int\n+ for reproducible results across multiple function calls.\n See :term:`Glossary `.\n \n .. versionadded:: 0.18\n@@ -141,12 +182,22 @@ class KernelPCA(TransformerMixin, BaseEstimator):\n and Klaus-Robert Mueller. 1999. Kernel principal\n component analysis. In Advances in kernel methods,\n MIT Press, Cambridge, MA, USA 327-352.\n+\n+ For eigen_solver == 'arpack', refer to `scipy.sparse.linalg.eigsh`.\n+\n+ For eigen_solver == 'randomized', see:\n+ Finding structure with randomness: Stochastic algorithms\n+ for constructing approximate matrix decompositions Halko, et al., 2009\n+ (arXiv:909)\n+ A randomized algorithm for the decomposition of matrices\n+ Per-Gunnar Martinsson, Vladimir Rokhlin and Mark Tygert\n \"\"\"\n @_deprecate_positional_args\n def __init__(self, n_components=None, *, kernel=\"linear\",\n gamma=None, degree=3, coef0=1, kernel_params=None,\n alpha=1.0, fit_inverse_transform=False, eigen_solver='auto',\n- tol=0, max_iter=None, remove_zero_eig=False,\n+ tol=0, max_iter=None, iterated_power='auto',\n+ remove_zero_eig=False,\n random_state=None, copy_X=True, n_jobs=None):\n if fit_inverse_transform and kernel == 'precomputed':\n raise ValueError(\n@@ -160,9 +211,10 @@ def __init__(self, n_components=None, *, kernel=\"linear\",\n self.alpha = alpha\n self.fit_inverse_transform = fit_inverse_transform\n self.eigen_solver = eigen_solver\n- self.remove_zero_eig = remove_zero_eig\n self.tol = tol\n self.max_iter = max_iter\n+ self.iterated_power = iterated_power\n+ self.remove_zero_eig = remove_zero_eig\n self.random_state = random_state\n self.n_jobs = n_jobs\n self.copy_X = copy_X\n@@ -191,9 +243,14 @@ def _fit_transform(self, K):\n # center kernel\n K = self._centerer.fit_transform(K)\n \n+ # adjust n_components according to user inputs\n if self.n_components is None:\n- n_components = K.shape[0]\n+ n_components = K.shape[0] # use all dimensions\n else:\n+ if self.n_components < 1:\n+ raise ValueError(\n+ f\"`n_components` should be >= 1, got: {self.n_component}\"\n+ )\n n_components = min(K.shape[0], self.n_components)\n \n # compute eigenvectors\n@@ -206,6 +263,7 @@ def _fit_transform(self, K):\n eigen_solver = self.eigen_solver\n \n if eigen_solver == 'dense':\n+ # Note: eigvals specifies the indices of smallest/largest to return\n self.lambdas_, self.alphas_ = linalg.eigh(\n K, eigvals=(K.shape[0] - n_components, K.shape[0] - 1))\n elif eigen_solver == 'arpack':\n@@ -215,6 +273,14 @@ def _fit_transform(self, K):\n tol=self.tol,\n maxiter=self.max_iter,\n v0=v0)\n+ elif eigen_solver == 'randomized':\n+ self.lambdas_, self.alphas_ = _randomized_eigsh(\n+ K, n_components=n_components, n_iter=self.iterated_power,\n+ random_state=self.random_state, selection='module'\n+ )\n+ else:\n+ raise ValueError(\"Unsupported value for `eigen_solver`: %r\"\n+ % eigen_solver)\n \n # make sure that the eigenvalues are ok and fix numerical issues\n self.lambdas_ = _check_psd_eigenvalues(self.lambdas_,\ndiff --git a/sklearn/utils/extmath.py b/sklearn/utils/extmath.py\nindex add8c5883a751..c72c54bd1aa4d 100644\n--- a/sklearn/utils/extmath.py\n+++ b/sklearn/utils/extmath.py\n@@ -249,6 +249,9 @@ def randomized_svd(M, n_components, *, n_oversamples=10, n_iter='auto',\n flip_sign=True, random_state='warn'):\n \"\"\"Computes a truncated randomized SVD.\n \n+ This method solves the fixed-rank approximation problem described in the\n+ Halko et al paper (problem (1.5), p5).\n+\n Parameters\n ----------\n M : {ndarray, sparse matrix}\n@@ -262,13 +265,23 @@ def randomized_svd(M, n_components, *, n_oversamples=10, n_iter='auto',\n to ensure proper conditioning. The total number of random vectors\n used to find the range of M is n_components + n_oversamples. Smaller\n number can improve speed but can negatively impact the quality of\n- approximation of singular vectors and singular values.\n+ approximation of singular vectors and singular values. Users might wish\n+ to increase this parameter up to `2*k - n_components` where k is the\n+ effective rank, for large matrices, noisy problems, matrices with\n+ slowly decaying spectrums, or to increase precision accuracy. See Halko\n+ et al (pages 5, 23 and 26).\n \n n_iter : int or 'auto', default='auto'\n Number of power iterations. It can be used to deal with very noisy\n problems. When 'auto', it is set to 4, unless `n_components` is small\n- (< .1 * min(X.shape)) `n_iter` in which case is set to 7.\n- This improves precision with few components.\n+ (< .1 * min(X.shape)) in which case `n_iter` is set to 7.\n+ This improves precision with few components. Note that in general\n+ users should rather increase `n_oversamples` before increasing `n_iter`\n+ as the principle of the randomized method is to avoid usage of these\n+ more costly power iterations steps. When `n_components` is equal\n+ or greater to the effective matrix rank and the spectrum does not\n+ present a slow decay, `n_iter=0` or `1` should even work fine in theory\n+ (see Halko et al paper, page 9).\n \n .. versionchanged:: 0.18\n \n@@ -316,12 +329,15 @@ def randomized_svd(M, n_components, *, n_oversamples=10, n_iter='auto',\n computations. It is particularly fast on large matrices on which\n you wish to extract only a small number of components. In order to\n obtain further speed up, `n_iter` can be set <=2 (at the cost of\n- loss of precision).\n+ loss of precision). To increase the precision it is recommended to\n+ increase `n_oversamples`, up to `2*k-n_components` where k is the\n+ effective rank. Usually, `n_components` is chosen to be greater than k\n+ so increasing `n_oversamples` up to `n_components` should be enough.\n \n References\n ----------\n * Finding structure with randomness: Stochastic algorithms for constructing\n- approximate matrix decompositions\n+ approximate matrix decompositions (Algorithm 4.3)\n Halko, et al., 2009 https://arxiv.org/abs/0909.4061\n \n * A randomized algorithm for the decomposition of matrices\n@@ -393,6 +409,152 @@ def randomized_svd(M, n_components, *, n_oversamples=10, n_iter='auto',\n return U[:, :n_components], s[:n_components], Vt[:n_components, :]\n \n \n+@_deprecate_positional_args\n+def _randomized_eigsh(M, n_components, *, n_oversamples=10, n_iter='auto',\n+ power_iteration_normalizer='auto',\n+ selection='module', random_state=None):\n+ \"\"\"Computes a truncated eigendecomposition using randomized methods\n+\n+ This method solves the fixed-rank approximation problem described in the\n+ Halko et al paper.\n+\n+ The choice of which components to select can be tuned with the `selection`\n+ parameter.\n+\n+ .. versionadded:: 0.24\n+\n+ Parameters\n+ ----------\n+ M : ndarray or sparse matrix\n+ Matrix to decompose, it should be real symmetric square or complex\n+ hermitian\n+\n+ n_components : int\n+ Number of eigenvalues and vectors to extract.\n+\n+ n_oversamples : int, default=10\n+ Additional number of random vectors to sample the range of M so as\n+ to ensure proper conditioning. The total number of random vectors\n+ used to find the range of M is n_components + n_oversamples. Smaller\n+ number can improve speed but can negatively impact the quality of\n+ approximation of eigenvectors and eigenvalues. Users might wish\n+ to increase this parameter up to `2*k - n_components` where k is the\n+ effective rank, for large matrices, noisy problems, matrices with\n+ slowly decaying spectrums, or to increase precision accuracy. See Halko\n+ et al (pages 5, 23 and 26).\n+\n+ n_iter : int or 'auto', default='auto'\n+ Number of power iterations. It can be used to deal with very noisy\n+ problems. When 'auto', it is set to 4, unless `n_components` is small\n+ (< .1 * min(X.shape)) in which case `n_iter` is set to 7.\n+ This improves precision with few components. Note that in general\n+ users should rather increase `n_oversamples` before increasing `n_iter`\n+ as the principle of the randomized method is to avoid usage of these\n+ more costly power iterations steps. When `n_components` is equal\n+ or greater to the effective matrix rank and the spectrum does not\n+ present a slow decay, `n_iter=0` or `1` should even work fine in theory\n+ (see Halko et al paper, page 9).\n+\n+ power_iteration_normalizer : {'auto', 'QR', 'LU', 'none'}, default='auto'\n+ Whether the power iterations are normalized with step-by-step\n+ QR factorization (the slowest but most accurate), 'none'\n+ (the fastest but numerically unstable when `n_iter` is large, e.g.\n+ typically 5 or larger), or 'LU' factorization (numerically stable\n+ but can lose slightly in accuracy). The 'auto' mode applies no\n+ normalization if `n_iter` <= 2 and switches to LU otherwise.\n+\n+ selection : {'value', 'module'}, default='module'\n+ Strategy used to select the n components. When `selection` is `'value'`\n+ (not yet implemented, will become the default when implemented), the\n+ components corresponding to the n largest eigenvalues are returned.\n+ When `selection` is `'module'`, the components corresponding to the n\n+ eigenvalues with largest modules are returned.\n+\n+ random_state : int, RandomState instance, default=None\n+ The seed of the pseudo random number generator to use when shuffling\n+ the data, i.e. getting the random vectors to initialize the algorithm.\n+ Pass an int for reproducible results across multiple function calls.\n+ See :term:`Glossary `.\n+\n+ Notes\n+ -----\n+ This algorithm finds a (usually very good) approximate truncated\n+ eigendecomposition using randomized methods to speed up the computations.\n+\n+ This method is particularly fast on large matrices on which\n+ you wish to extract only a small number of components. In order to\n+ obtain further speed up, `n_iter` can be set <=2 (at the cost of\n+ loss of precision). To increase the precision it is recommended to\n+ increase `n_oversamples`, up to `2*k-n_components` where k is the\n+ effective rank. Usually, `n_components` is chosen to be greater than k\n+ so increasing `n_oversamples` up to `n_components` should be enough.\n+\n+ Strategy 'value': not implemented yet.\n+ Algorithms 5.3, 5.4 and 5.5 in the Halko et al paper should provide good\n+ condidates for a future implementation.\n+\n+ Strategy 'module':\n+ The principle is that for diagonalizable matrices, the singular values and\n+ eigenvalues are related: if t is an eigenvalue of A, then :math:`|t|` is a\n+ singular value of A. This method relies on a randomized SVD to find the n\n+ singular components corresponding to the n singular values with largest\n+ modules, and then uses the signs of the singular vectors to find the true\n+ sign of t: if the sign of left and right singular vectors are different\n+ then the corresponding eigenvalue is negative.\n+\n+ Returns\n+ -------\n+ eigvals : 1D array of shape (n_components,) containing the `n_components`\n+ eigenvalues selected (see ``selection`` parameter).\n+ eigvecs : 2D array of shape (M.shape[0], n_components) containing the\n+ `n_components` eigenvectors corresponding to the `eigvals`, in the\n+ corresponding order. Note that this follows the `scipy.linalg.eigh`\n+ convention.\n+\n+ See Also\n+ --------\n+ :func:`randomized_svd`\n+\n+ References\n+ ----------\n+ * Finding structure with randomness: Stochastic algorithms for constructing\n+ approximate matrix decompositions (Algorithm 4.3 for strategy 'module')\n+ Halko, et al., 2009 https://arxiv.org/abs/0909.4061\n+\n+ \"\"\"\n+ if selection == 'value': # pragma: no cover\n+ # to do : an algorithm can be found in the Halko et al reference\n+ raise NotImplementedError()\n+\n+ elif selection == 'module':\n+ # Note: no need for deterministic U and Vt (flip_sign=True),\n+ # as we only use the dot product UVt afterwards\n+ U, S, Vt = randomized_svd(\n+ M, n_components=n_components, n_oversamples=n_oversamples,\n+ n_iter=n_iter,\n+ power_iteration_normalizer=power_iteration_normalizer,\n+ flip_sign=False, random_state=random_state)\n+\n+ eigvecs = U[:, :n_components]\n+ eigvals = S[:n_components]\n+\n+ # Conversion of Singular values into Eigenvalues:\n+ # For any eigenvalue t, the corresponding singular value is |t|.\n+ # So if there is a negative eigenvalue t, the corresponding singular\n+ # value will be -t, and the left (U) and right (V) singular vectors\n+ # will have opposite signs.\n+ # Fastest way: see \n+ diag_VtU = np.einsum('ji,ij->j',\n+ Vt[:n_components, :], U[:, :n_components])\n+ signs = np.sign(diag_VtU)\n+ eigvals = eigvals * signs\n+\n+ else: # pragma: no cover\n+ raise ValueError(\"Invalid `selection`: %r\" % selection)\n+\n+ return eigvals, eigvecs\n+\n+\n @_deprecate_positional_args\n def weighted_mode(a, w, *, axis=0):\n \"\"\"Returns an array of the weighted modal (most common) value in a.\n", "test_patch": "diff --git a/sklearn/decomposition/tests/test_kernel_pca.py b/sklearn/decomposition/tests/test_kernel_pca.py\nindex adf68f1db1a6c..5c8d052a7aa14 100644\n--- a/sklearn/decomposition/tests/test_kernel_pca.py\n+++ b/sklearn/decomposition/tests/test_kernel_pca.py\n@@ -3,11 +3,13 @@\n import pytest\n \n from sklearn.utils._testing import (assert_array_almost_equal,\n- assert_allclose)\n+ assert_array_equal,\n+ assert_allclose)\n \n from sklearn.decomposition import PCA, KernelPCA\n from sklearn.datasets import make_circles\n from sklearn.datasets import make_blobs\n+from sklearn.exceptions import NotFittedError\n from sklearn.linear_model import Perceptron\n from sklearn.pipeline import Pipeline\n from sklearn.preprocessing import StandardScaler\n@@ -17,6 +19,12 @@\n \n \n def test_kernel_pca():\n+ \"\"\"Nominal test for all solvers and all known kernels + a custom one\n+\n+ It tests\n+ - that fit_transform is equivalent to fit+transform\n+ - that the shapes of transforms and inverse transforms are correct\n+ \"\"\"\n rng = np.random.RandomState(0)\n X_fit = rng.random_sample((5, 4))\n X_pred = rng.random_sample((2, 4))\n@@ -26,7 +34,7 @@ def histogram(x, y, **kwargs):\n assert kwargs == {} # no kernel_params that we didn't ask for\n return np.minimum(x, y).sum()\n \n- for eigen_solver in (\"auto\", \"dense\", \"arpack\"):\n+ for eigen_solver in (\"auto\", \"dense\", \"arpack\", \"randomized\"):\n for kernel in (\"linear\", \"rbf\", \"poly\", histogram):\n # histogram kernel produces singular matrix inside linalg.solve\n # XXX use a least-squares approximation?\n@@ -55,12 +63,31 @@ def histogram(x, y, **kwargs):\n assert X_pred2.shape == X_pred.shape\n \n \n+def test_kernel_pca_invalid_solver():\n+ \"\"\"Check that kPCA raises an error if the solver parameter is invalid\n+\n+ \"\"\"\n+ with pytest.raises(ValueError):\n+ KernelPCA(eigen_solver=\"unknown\").fit(np.random.randn(10, 10))\n+\n+\n def test_kernel_pca_invalid_parameters():\n+ \"\"\"Check that kPCA raises an error if the parameters are invalid\n+\n+ Tests fitting inverse transform with a precomputed kernel raises a\n+ ValueError.\n+ \"\"\"\n with pytest.raises(ValueError):\n KernelPCA(10, fit_inverse_transform=True, kernel='precomputed')\n \n \n def test_kernel_pca_consistent_transform():\n+ \"\"\"Check robustness to mutations in the original training array\n+\n+ Test that after fitting a kPCA model, it stays independent of any\n+ mutation of the values of the original data object by relying on an\n+ internal copy.\n+ \"\"\"\n # X_fit_ needs to retain the old, unmodified copy of X\n state = np.random.RandomState(0)\n X = state.rand(10, 10)\n@@ -74,6 +101,10 @@ def test_kernel_pca_consistent_transform():\n \n \n def test_kernel_pca_deterministic_output():\n+ \"\"\"Test that Kernel PCA produces deterministic output\n+\n+ Tests that the same inputs and random state produce the same output.\n+ \"\"\"\n rng = np.random.RandomState(0)\n X = rng.rand(10, 10)\n eigen_solver = ('arpack', 'dense')\n@@ -89,15 +120,20 @@ def test_kernel_pca_deterministic_output():\n \n \n def test_kernel_pca_sparse():\n+ \"\"\"Test that kPCA works on a sparse data input.\n+\n+ Same test as ``test_kernel_pca except inverse_transform`` since it's not\n+ implemented for sparse matrices.\n+ \"\"\"\n rng = np.random.RandomState(0)\n X_fit = sp.csr_matrix(rng.random_sample((5, 4)))\n X_pred = sp.csr_matrix(rng.random_sample((2, 4)))\n \n- for eigen_solver in (\"auto\", \"arpack\"):\n+ for eigen_solver in (\"auto\", \"arpack\", \"randomized\"):\n for kernel in (\"linear\", \"rbf\", \"poly\"):\n # transform fit data\n kpca = KernelPCA(4, kernel=kernel, eigen_solver=eigen_solver,\n- fit_inverse_transform=False)\n+ fit_inverse_transform=False, random_state=0)\n X_fit_transformed = kpca.fit_transform(X_fit)\n X_fit_transformed2 = kpca.fit(X_fit).transform(X_fit)\n assert_array_almost_equal(np.abs(X_fit_transformed),\n@@ -108,31 +144,47 @@ def test_kernel_pca_sparse():\n assert (X_pred_transformed.shape[1] ==\n X_fit_transformed.shape[1])\n \n- # inverse transform\n- # X_pred2 = kpca.inverse_transform(X_pred_transformed)\n- # assert X_pred2.shape == X_pred.shape)\n+ # inverse transform: not available for sparse matrices\n+ # XXX: should we raise another exception type here? For instance:\n+ # NotImplementedError.\n+ with pytest.raises(NotFittedError):\n+ kpca.inverse_transform(X_pred_transformed)\n \n \n-def test_kernel_pca_linear_kernel():\n+@pytest.mark.parametrize(\"solver\", [\"auto\", \"dense\", \"arpack\", \"randomized\"])\n+@pytest.mark.parametrize(\"n_features\", [4, 10])\n+def test_kernel_pca_linear_kernel(solver, n_features):\n+ \"\"\"Test that kPCA with linear kernel is equivalent to PCA for all solvers.\n+\n+ KernelPCA with linear kernel should produce the same output as PCA.\n+ \"\"\"\n rng = np.random.RandomState(0)\n- X_fit = rng.random_sample((5, 4))\n- X_pred = rng.random_sample((2, 4))\n+ X_fit = rng.random_sample((5, n_features))\n+ X_pred = rng.random_sample((2, n_features))\n \n # for a linear kernel, kernel PCA should find the same projection as PCA\n # modulo the sign (direction)\n # fit only the first four components: fifth is near zero eigenvalue, so\n # can be trimmed due to roundoff error\n+ n_comps = 3 if solver == \"arpack\" else 4\n assert_array_almost_equal(\n- np.abs(KernelPCA(4).fit(X_fit).transform(X_pred)),\n- np.abs(PCA(4).fit(X_fit).transform(X_pred)))\n+ np.abs(KernelPCA(n_comps, eigen_solver=solver).fit(X_fit)\n+ .transform(X_pred)),\n+ np.abs(PCA(n_comps, svd_solver=solver if solver != \"dense\" else \"full\")\n+ .fit(X_fit).transform(X_pred)))\n \n \n def test_kernel_pca_n_components():\n+ \"\"\"Test that `n_components` is correctly taken into account for projections\n+\n+ For all solvers this tests that the output has the correct shape depending\n+ on the selected number of components.\n+ \"\"\"\n rng = np.random.RandomState(0)\n X_fit = rng.random_sample((5, 4))\n X_pred = rng.random_sample((2, 4))\n \n- for eigen_solver in (\"dense\", \"arpack\"):\n+ for eigen_solver in (\"dense\", \"arpack\", \"randomized\"):\n for c in [1, 2, 4]:\n kpca = KernelPCA(n_components=c, eigen_solver=eigen_solver)\n shape = kpca.fit(X_fit).transform(X_pred).shape\n@@ -141,6 +193,11 @@ def test_kernel_pca_n_components():\n \n \n def test_remove_zero_eig():\n+ \"\"\"Check that the ``remove_zero_eig`` parameter works correctly.\n+\n+ Tests that the null-space (Zero) eigenvalues are removed when\n+ remove_zero_eig=True, whereas they are not by default.\n+ \"\"\"\n X = np.array([[1 - 1e-30, 1], [1, 1], [1, 1 - 1e-20]])\n \n # n_components=None (default) => remove_zero_eig is True\n@@ -158,9 +215,11 @@ def test_remove_zero_eig():\n \n \n def test_leave_zero_eig():\n- \"\"\"This test checks that fit().transform() returns the same result as\n+ \"\"\"Non-regression test for issue #12141 (PR #12143)\n+\n+ This test checks that fit().transform() returns the same result as\n fit_transform() in case of non-removed zero eigenvalue.\n- Non-regression test for issue #12141 (PR #12143)\"\"\"\n+ \"\"\"\n X_fit = np.array([[1, 1], [0, 0]])\n \n # Assert that even with all np warnings on, there is no div by zero warning\n@@ -184,23 +243,29 @@ def test_leave_zero_eig():\n \n \n def test_kernel_pca_precomputed():\n+ \"\"\"Test that kPCA works with a precomputed kernel, for all solvers\n+\n+ \"\"\"\n rng = np.random.RandomState(0)\n X_fit = rng.random_sample((5, 4))\n X_pred = rng.random_sample((2, 4))\n \n- for eigen_solver in (\"dense\", \"arpack\"):\n- X_kpca = KernelPCA(4, eigen_solver=eigen_solver).\\\n- fit(X_fit).transform(X_pred)\n+ for eigen_solver in (\"dense\", \"arpack\", \"randomized\"):\n+ X_kpca = KernelPCA(\n+ 4, eigen_solver=eigen_solver, random_state=0\n+ ).fit(X_fit).transform(X_pred)\n+\n X_kpca2 = KernelPCA(\n- 4, eigen_solver=eigen_solver, kernel='precomputed').fit(\n- np.dot(X_fit, X_fit.T)).transform(np.dot(X_pred, X_fit.T))\n+ 4, eigen_solver=eigen_solver, kernel='precomputed', random_state=0\n+ ).fit(np.dot(X_fit, X_fit.T)).transform(np.dot(X_pred, X_fit.T))\n \n X_kpca_train = KernelPCA(\n- 4, eigen_solver=eigen_solver,\n- kernel='precomputed').fit_transform(np.dot(X_fit, X_fit.T))\n+ 4, eigen_solver=eigen_solver, kernel='precomputed', random_state=0\n+ ).fit_transform(np.dot(X_fit, X_fit.T))\n+\n X_kpca_train2 = KernelPCA(\n- 4, eigen_solver=eigen_solver, kernel='precomputed').fit(\n- np.dot(X_fit, X_fit.T)).transform(np.dot(X_fit, X_fit.T))\n+ 4, eigen_solver=eigen_solver, kernel='precomputed', random_state=0\n+ ).fit(np.dot(X_fit, X_fit.T)).transform(np.dot(X_fit, X_fit.T))\n \n assert_array_almost_equal(np.abs(X_kpca),\n np.abs(X_kpca2))\n@@ -209,7 +274,42 @@ def test_kernel_pca_precomputed():\n np.abs(X_kpca_train2))\n \n \n+@pytest.mark.parametrize(\"solver\", [\"auto\", \"dense\", \"arpack\", \"randomized\"])\n+def test_kernel_pca_precomputed_non_symmetric(solver):\n+ \"\"\"Check that the kernel centerer works.\n+\n+ Tests that a non symmetric precomputed kernel is actually accepted\n+ because the kernel centerer does its job correctly.\n+ \"\"\"\n+\n+ # a non symmetric gram matrix\n+ K = [\n+ [1, 2],\n+ [3, 40]\n+ ]\n+ kpca = KernelPCA(kernel=\"precomputed\", eigen_solver=solver,\n+ n_components=1, random_state=0)\n+ kpca.fit(K) # no error\n+\n+ # same test with centered kernel\n+ Kc = [\n+ [9, -9],\n+ [-9, 9]\n+ ]\n+ kpca_c = KernelPCA(kernel=\"precomputed\", eigen_solver=solver,\n+ n_components=1, random_state=0)\n+ kpca_c.fit(Kc)\n+\n+ # comparison between the non-centered and centered versions\n+ assert_array_equal(kpca.alphas_, kpca_c.alphas_)\n+ assert_array_equal(kpca.lambdas_, kpca_c.lambdas_)\n+\n+\n def test_kernel_pca_invalid_kernel():\n+ \"\"\"Tests that using an invalid kernel name raises a ValueError\n+\n+ An invalid kernel name should raise a ValueError at fit time.\n+ \"\"\"\n rng = np.random.RandomState(0)\n X_fit = rng.random_sample((2, 4))\n kpca = KernelPCA(kernel=\"tototiti\")\n@@ -218,8 +318,11 @@ def test_kernel_pca_invalid_kernel():\n \n \n def test_gridsearch_pipeline():\n- # Test if we can do a grid-search to find parameters to separate\n- # circles with a perceptron model.\n+ \"\"\"Check that kPCA works as expected in a grid search pipeline\n+\n+ Test if we can do a grid-search to find parameters to separate\n+ circles with a perceptron model.\n+ \"\"\"\n X, y = make_circles(n_samples=400, factor=.3, noise=.05,\n random_state=0)\n kpca = KernelPCA(kernel=\"rbf\", n_components=2)\n@@ -232,8 +335,11 @@ def test_gridsearch_pipeline():\n \n \n def test_gridsearch_pipeline_precomputed():\n- # Test if we can do a grid-search to find parameters to separate\n- # circles with a perceptron model using a precomputed kernel.\n+ \"\"\"Check that kPCA works as expected in a grid search pipeline (2)\n+\n+ Test if we can do a grid-search to find parameters to separate\n+ circles with a perceptron model. This test uses a precomputed kernel.\n+ \"\"\"\n X, y = make_circles(n_samples=400, factor=.3, noise=.05,\n random_state=0)\n kpca = KernelPCA(kernel=\"precomputed\", n_components=2)\n@@ -247,7 +353,12 @@ def test_gridsearch_pipeline_precomputed():\n \n \n def test_nested_circles():\n- # Test the linear separability of the first 2D KPCA transform\n+ \"\"\"Check that kPCA projects in a space where nested circles are separable\n+\n+ Tests that 2D nested circles become separable with a perceptron when\n+ projected in the first 2 kPCA using an RBF kernel, while raw samples\n+ are not directly separable in the original space.\n+ \"\"\"\n X, y = make_circles(n_samples=400, factor=.3, noise=.05,\n random_state=0)\n \n@@ -270,8 +381,10 @@ def test_nested_circles():\n \n \n def test_kernel_conditioning():\n- \"\"\" Test that ``_check_psd_eigenvalues`` is correctly called\n- Non-regression test for issue #12140 (PR #12145)\"\"\"\n+ \"\"\"Check that ``_check_psd_eigenvalues`` is correctly called in kPCA\n+\n+ Non-regression test for issue #12140 (PR #12145).\n+ \"\"\"\n \n # create a pathological X leading to small non-zero eigenvalue\n X = [[5, 1],\n@@ -286,11 +399,93 @@ def test_kernel_conditioning():\n assert np.all(kpca.lambdas_ == _check_psd_eigenvalues(kpca.lambdas_))\n \n \n+@pytest.mark.parametrize(\"solver\", [\"auto\", \"dense\", \"arpack\", \"randomized\"])\n+def test_precomputed_kernel_not_psd(solver):\n+ \"\"\"Check how KernelPCA works with non-PSD kernels depending on n_components\n+\n+ Tests for all methods what happens with a non PSD gram matrix (this\n+ can happen in an isomap scenario, or with custom kernel functions, or\n+ maybe with ill-posed datasets).\n+\n+ When ``n_component`` is large enough to capture a negative eigenvalue, an\n+ error should be raised. Otherwise, KernelPCA should run without error\n+ since the negative eigenvalues are not selected.\n+ \"\"\"\n+\n+ # a non PSD kernel with large eigenvalues, already centered\n+ # it was captured from an isomap call and multiplied by 100 for compacity\n+ K = [\n+ [4.48, -1., 8.07, 2.33, 2.33, 2.33, -5.76, -12.78],\n+ [-1., -6.48, 4.5, -1.24, -1.24, -1.24, -0.81, 7.49],\n+ [8.07, 4.5, 15.48, 2.09, 2.09, 2.09, -11.1, -23.23],\n+ [2.33, -1.24, 2.09, 4., -3.65, -3.65, 1.02, -0.9],\n+ [2.33, -1.24, 2.09, -3.65, 4., -3.65, 1.02, -0.9],\n+ [2.33, -1.24, 2.09, -3.65, -3.65, 4., 1.02, -0.9],\n+ [-5.76, -0.81, -11.1, 1.02, 1.02, 1.02, 4.86, 9.75],\n+ [-12.78, 7.49, -23.23, -0.9, -0.9, -0.9, 9.75, 21.46]\n+ ]\n+ # this gram matrix has 5 positive eigenvalues and 3 negative ones\n+ # [ 52.72, 7.65, 7.65, 5.02, 0. , -0. , -6.13, -15.11]\n+\n+ # 1. ask for enough components to get a significant negative one\n+ kpca = KernelPCA(kernel=\"precomputed\", eigen_solver=solver, n_components=7)\n+ # make sure that the appropriate error is raised\n+ with pytest.raises(ValueError,\n+ match=\"There are significant negative eigenvalues\"):\n+ kpca.fit(K)\n+\n+ # 2. ask for a small enough n_components to get only positive ones\n+ kpca = KernelPCA(kernel=\"precomputed\", eigen_solver=solver, n_components=2)\n+ if solver == 'randomized':\n+ # the randomized method is still inconsistent with the others on this\n+ # since it selects the eigenvalues based on the largest 2 modules, not\n+ # on the largest 2 values.\n+ #\n+ # At least we can ensure that we return an error instead of returning\n+ # the wrong eigenvalues\n+ with pytest.raises(ValueError,\n+ match=\"There are significant negative eigenvalues\"):\n+ kpca.fit(K)\n+ else:\n+ # general case: make sure that it works\n+ kpca.fit(K)\n+\n+\n+@pytest.mark.parametrize(\"n_components\", [4, 10, 20])\n+def test_kernel_pca_solvers_equivalence(n_components):\n+ \"\"\"Check that 'dense' 'arpack' & 'randomized' solvers give similar results\n+ \"\"\"\n+\n+ # Generate random data\n+ n_train, n_test = 2000, 100\n+ X, _ = make_circles(n_samples=(n_train + n_test), factor=.3, noise=.05,\n+ random_state=0)\n+ X_fit, X_pred = X[:n_train, :], X[n_train:, :]\n+\n+ # reference (full)\n+ ref_pred = KernelPCA(n_components, eigen_solver=\"dense\", random_state=0\n+ ).fit(X_fit).transform(X_pred)\n+\n+ # arpack\n+ a_pred = KernelPCA(n_components, eigen_solver=\"arpack\", random_state=0\n+ ).fit(X_fit).transform(X_pred)\n+ # check that the result is still correct despite the approx\n+ assert_array_almost_equal(np.abs(a_pred), np.abs(ref_pred))\n+\n+ # randomized\n+ r_pred = KernelPCA(n_components, eigen_solver=\"randomized\", random_state=0\n+ ).fit(X_fit).transform(X_pred)\n+ # check that the result is still correct despite the approximation\n+ assert_array_almost_equal(np.abs(r_pred), np.abs(ref_pred))\n+\n+\n def test_kernel_pca_inverse_transform_reconstruction():\n- # Test if the reconstruction is a good approximation.\n- # Note that in general it is not possible to get an arbitrarily good\n- # reconstruction because of kernel centering that does not\n- # preserve all the information of the original data.\n+ \"\"\"Test if the reconstruction is a good approximation.\n+\n+ Note that in general it is not possible to get an arbitrarily good\n+ reconstruction because of kernel centering that does not\n+ preserve all the information of the original data.\n+ \"\"\"\n X, *_ = make_blobs(n_samples=100, n_features=4, random_state=0)\n \n kpca = KernelPCA(\n@@ -302,8 +497,11 @@ def test_kernel_pca_inverse_transform_reconstruction():\n \n \n def test_32_64_decomposition_shape():\n- \"\"\" Test that the decomposition is similar for 32 and 64 bits data \"\"\"\n- # see https://github.com/scikit-learn/scikit-learn/issues/18146\n+ \"\"\"Test that the decomposition is similar for 32 and 64 bits data\n+\n+ Non regression test for\n+ https://github.com/scikit-learn/scikit-learn/issues/18146\n+ \"\"\"\n X, y = make_blobs(\n n_samples=30,\n centers=[[0, 0, 0], [1, 1, 1]],\n@@ -321,6 +519,10 @@ def test_32_64_decomposition_shape():\n \n # TODO: Remove in 1.1\n def test_kernel_pcc_pairwise_is_deprecated():\n+ \"\"\"Check that `_pairwise` is correctly marked with deprecation warning\n+\n+ Tests that a `FutureWarning` is issued when `_pairwise` is accessed.\n+ \"\"\"\n kp = KernelPCA(kernel='precomputed')\n msg = r\"Attribute _pairwise was deprecated in version 0\\.24\"\n with pytest.warns(FutureWarning, match=msg):\ndiff --git a/sklearn/utils/tests/test_extmath.py b/sklearn/utils/tests/test_extmath.py\nindex 8e53d94d911f0..1a77d08b12388 100644\n--- a/sklearn/utils/tests/test_extmath.py\n+++ b/sklearn/utils/tests/test_extmath.py\n@@ -8,11 +8,12 @@\n from scipy import sparse\n from scipy import linalg\n from scipy import stats\n+from scipy.sparse.linalg import eigsh\n from scipy.special import expit\n \n import pytest\n from sklearn.utils import gen_batches\n-\n+from sklearn.utils._arpack import _init_arpack_v0\n from sklearn.utils._testing import assert_almost_equal\n from sklearn.utils._testing import assert_allclose\n from sklearn.utils._testing import assert_allclose_dense_sparse\n@@ -23,7 +24,7 @@\n from sklearn.utils._testing import skip_if_32bit\n \n from sklearn.utils.extmath import density, _safe_accumulator_op\n-from sklearn.utils.extmath import randomized_svd\n+from sklearn.utils.extmath import randomized_svd, _randomized_eigsh\n from sklearn.utils.extmath import row_norms\n from sklearn.utils.extmath import weighted_mode\n from sklearn.utils.extmath import cartesian\n@@ -34,7 +35,7 @@\n from sklearn.utils.extmath import softmax\n from sklearn.utils.extmath import stable_cumsum\n from sklearn.utils.extmath import safe_sparse_dot\n-from sklearn.datasets import make_low_rank_matrix\n+from sklearn.datasets import make_low_rank_matrix, make_sparse_spd_matrix\n \n \n def test_density():\n@@ -161,6 +162,128 @@ def test_randomized_svd_low_rank_all_dtypes(dtype):\n check_randomized_svd_low_rank(dtype)\n \n \n+@pytest.mark.parametrize('dtype',\n+ (np.int32, np.int64, np.float32, np.float64))\n+def test_randomized_eigsh(dtype):\n+ \"\"\"Test that `_randomized_eigsh` returns the appropriate components\"\"\"\n+\n+ rng = np.random.RandomState(42)\n+ X = np.diag(np.array([1., -2., 0., 3.], dtype=dtype))\n+ # random rotation that preserves the eigenvalues of X\n+ rand_rot = np.linalg.qr(rng.normal(size=X.shape))[0]\n+ X = rand_rot @ X @ rand_rot.T\n+\n+ # with 'module' selection method, the negative eigenvalue shows up\n+ eigvals, eigvecs = _randomized_eigsh(X, n_components=2, selection='module')\n+ # eigenvalues\n+ assert eigvals.shape == (2,)\n+ assert_array_almost_equal(eigvals, [3., -2.]) # negative eigenvalue here\n+ # eigenvectors\n+ assert eigvecs.shape == (4, 2)\n+\n+ # with 'value' selection method, the negative eigenvalue does not show up\n+ with pytest.raises(NotImplementedError):\n+ _randomized_eigsh(X, n_components=2, selection='value')\n+\n+\n+@pytest.mark.parametrize('k', (10, 50, 100, 199, 200))\n+def test_randomized_eigsh_compared_to_others(k):\n+ \"\"\"Check that `_randomized_eigsh` is similar to other `eigsh`\n+\n+ Tests that for a random PSD matrix, `_randomized_eigsh` provides results\n+ comparable to LAPACK (scipy.linalg.eigh) and ARPACK\n+ (scipy.sparse.linalg.eigsh).\n+\n+ Note: some versions of ARPACK do not support k=n_features.\n+ \"\"\"\n+\n+ # make a random PSD matrix\n+ n_features = 200\n+ X = make_sparse_spd_matrix(n_features, random_state=0)\n+\n+ # compare two versions of randomized\n+ # rough and fast\n+ eigvals, eigvecs = _randomized_eigsh(X, n_components=k, selection='module',\n+ n_iter=25, random_state=0)\n+ # more accurate but slow (TODO find realistic settings here)\n+ eigvals_qr, eigvecs_qr = _randomized_eigsh(\n+ X, n_components=k, n_iter=25, n_oversamples=20, random_state=0,\n+ power_iteration_normalizer=\"QR\", selection='module'\n+ )\n+\n+ # with LAPACK\n+ eigvals_lapack, eigvecs_lapack = linalg.eigh(X, eigvals=(n_features - k,\n+ n_features - 1))\n+ indices = eigvals_lapack.argsort()[::-1]\n+ eigvals_lapack = eigvals_lapack[indices]\n+ eigvecs_lapack = eigvecs_lapack[:, indices]\n+\n+ # -- eigenvalues comparison\n+ assert eigvals_lapack.shape == (k,)\n+ # comparison precision\n+ assert_array_almost_equal(eigvals, eigvals_lapack, decimal=6)\n+ assert_array_almost_equal(eigvals_qr, eigvals_lapack, decimal=6)\n+\n+ # -- eigenvectors comparison\n+ assert eigvecs_lapack.shape == (n_features, k)\n+ # flip eigenvectors' sign to enforce deterministic output\n+ dummy_vecs = np.zeros_like(eigvecs).T\n+ eigvecs, _ = svd_flip(eigvecs, dummy_vecs)\n+ eigvecs_qr, _ = svd_flip(eigvecs_qr, dummy_vecs)\n+ eigvecs_lapack, _ = svd_flip(eigvecs_lapack, dummy_vecs)\n+ assert_array_almost_equal(eigvecs, eigvecs_lapack, decimal=4)\n+ assert_array_almost_equal(eigvecs_qr, eigvecs_lapack, decimal=6)\n+\n+ # comparison ARPACK ~ LAPACK (some ARPACK implems do not support k=n)\n+ if k < n_features:\n+ v0 = _init_arpack_v0(n_features, random_state=0)\n+ # \"LA\" largest algebraic <=> selection=\"value\" in randomized_eigsh\n+ eigvals_arpack, eigvecs_arpack = eigsh(X, k, which=\"LA\", tol=0,\n+ maxiter=None, v0=v0)\n+ indices = eigvals_arpack.argsort()[::-1]\n+ # eigenvalues\n+ eigvals_arpack = eigvals_arpack[indices]\n+ assert_array_almost_equal(eigvals_lapack, eigvals_arpack, decimal=10)\n+ # eigenvectors\n+ eigvecs_arpack = eigvecs_arpack[:, indices]\n+ eigvecs_arpack, _ = svd_flip(eigvecs_arpack, dummy_vecs)\n+ assert_array_almost_equal(eigvecs_arpack, eigvecs_lapack, decimal=8)\n+\n+\n+@pytest.mark.parametrize(\"n,rank\", [\n+ (10, 7),\n+ (100, 10),\n+ (100, 80),\n+ (500, 10),\n+ (500, 250),\n+ (500, 400),\n+])\n+def test_randomized_eigsh_reconst_low_rank(n, rank):\n+ \"\"\"Check that randomized_eigsh is able to reconstruct a low rank psd matrix\n+\n+ Tests that the decomposition provided by `_randomized_eigsh` leads to\n+ orthonormal eigenvectors, and that a low rank PSD matrix can be effectively\n+ reconstructed with good accuracy using it.\n+ \"\"\"\n+ assert rank < n\n+\n+ # create a low rank PSD\n+ rng = np.random.RandomState(69)\n+ X = rng.randn(n, rank)\n+ A = X @ X.T\n+\n+ # approximate A with the \"right\" number of components\n+ S, V = _randomized_eigsh(A, n_components=rank, random_state=rng)\n+ # orthonormality checks\n+ assert_array_almost_equal(np.linalg.norm(V, axis=0), np.ones(S.shape))\n+ assert_array_almost_equal(V.T @ V, np.diag(np.ones(S.shape)))\n+ # reconstruction\n+ A_reconstruct = V @ np.diag(S) @ V.T\n+\n+ # test that the approximation is good\n+ assert_array_almost_equal(A_reconstruct, A, decimal=6)\n+\n+\n @pytest.mark.parametrize('dtype',\n (np.float32, np.float64))\n def test_row_norms(dtype):\n", "doc_changes": [{"path": "doc/modules/decomposition.rst", "old_path": "a/doc/modules/decomposition.rst", "new_path": "b/doc/modules/decomposition.rst", "metadata": "diff --git a/doc/modules/decomposition.rst b/doc/modules/decomposition.rst\nindex e971d784c63d6..fd51f60d8bfc6 100644\n--- a/doc/modules/decomposition.rst\n+++ b/doc/modules/decomposition.rst\n@@ -166,32 +166,16 @@ Note: the implementation of ``inverse_transform`` in :class:`PCA` with\n \n .. topic:: References:\n \n- * `\"Finding structure with randomness: Stochastic algorithms for\n+ * Algorithm 4.3 in\n+ `\"Finding structure with randomness: Stochastic algorithms for\n constructing approximate matrix decompositions\"\n `_\n Halko, et al., 2009\n \n-\n-.. _kernel_PCA:\n-\n-Kernel PCA\n-----------\n-\n-:class:`KernelPCA` is an extension of PCA which achieves non-linear\n-dimensionality reduction through the use of kernels (see :ref:`metrics`). It\n-has many applications including denoising, compression and structured\n-prediction (kernel dependency estimation). :class:`KernelPCA` supports both\n-``transform`` and ``inverse_transform``.\n-\n-.. figure:: ../auto_examples/decomposition/images/sphx_glr_plot_kernel_pca_001.png\n- :target: ../auto_examples/decomposition/plot_kernel_pca.html\n- :align: center\n- :scale: 75%\n-\n-.. topic:: Examples:\n-\n- * :ref:`sphx_glr_auto_examples_decomposition_plot_kernel_pca.py`\n-\n+ * `\"An implementation of a randomized algorithm for principal component\n+ analysis\"\n+ `_\n+ A. Szlam et al. 2014\n \n .. _SparsePCA:\n \n@@ -278,6 +262,100 @@ factorization, while larger values shrink many coefficients to zero.\n R. Jenatton, G. Obozinski, F. Bach, 2009\n \n \n+.. _kernel_PCA:\n+\n+Kernel Principal Component Analysis (kPCA)\n+==========================================\n+\n+Exact Kernel PCA\n+----------------\n+\n+:class:`KernelPCA` is an extension of PCA which achieves non-linear\n+dimensionality reduction through the use of kernels (see :ref:`metrics`). It\n+has many applications including denoising, compression and structured\n+prediction (kernel dependency estimation). :class:`KernelPCA` supports both\n+``transform`` and ``inverse_transform``.\n+\n+.. figure:: ../auto_examples/decomposition/images/sphx_glr_plot_kernel_pca_001.png\n+ :target: ../auto_examples/decomposition/plot_kernel_pca.html\n+ :align: center\n+ :scale: 75%\n+\n+.. topic:: Examples:\n+\n+ * :ref:`sphx_glr_auto_examples_decomposition_plot_kernel_pca.py`\n+\n+.. topic:: References:\n+\n+ * Kernel PCA was introduced in \"Kernel principal component analysis\"\n+ Bernhard Schoelkopf, Alexander J. Smola, and Klaus-Robert Mueller. 1999.\n+ In Advances in kernel methods, MIT Press, Cambridge, MA, USA 327-352.\n+\n+\n+.. _kPCA_Solvers:\n+\n+Choice of solver for Kernel PCA\n+-------------------------------\n+\n+While in :class:`PCA` the number of components is bounded by the number of\n+features, in :class:`KernelPCA` the number of components is bounded by the\n+number of samples. Many real-world datasets have large number of samples! In\n+these cases finding *all* the components with a full kPCA is a waste of\n+computation time, as data is mostly described by the first few components\n+(e.g. ``n_components<=100``). In other words, the centered Gram matrix that\n+is eigendecomposed in the Kernel PCA fitting process has an effective rank that\n+is much smaller than its size. This is a situation where approximate\n+eigensolvers can provide speedup with very low precision loss.\n+\n+The optional parameter ``eigen_solver='randomized'`` can be used to\n+*significantly* reduce the computation time when the number of requested\n+``n_components`` is small compared with the number of samples. It relies on\n+randomized decomposition methods to find an approximate solution in a shorter\n+time.\n+\n+The time complexity of the randomized :class:`KernelPCA` is\n+:math:`O(n_{\\mathrm{samples}}^2 \\cdot n_{\\mathrm{components}})`\n+instead of :math:`O(n_{\\mathrm{samples}}^3)` for the exact method\n+implemented with ``eigen_solver='dense'``.\n+\n+The memory footprint of randomized :class:`KernelPCA` is also proportional to\n+:math:`2 \\cdot n_{\\mathrm{samples}} \\cdot n_{\\mathrm{components}}` instead of\n+:math:`n_{\\mathrm{samples}}^2` for the exact method.\n+\n+Note: this technique is the same as in :ref:`RandomizedPCA`.\n+\n+In addition to the above two solvers, ``eigen_solver='arpack'`` can be used as\n+an alternate way to get an approximate decomposition. In practice, this method\n+only provides reasonable execution times when the number of components to find\n+is extremely small. It is enabled by default when the desired number of\n+components is less than 10 (strict) and the number of samples is more than 200\n+(strict). See :class:`KernelPCA` for details.\n+\n+.. topic:: References:\n+\n+ * *dense* solver:\n+ `scipy.linalg.eigh documentation\n+ `_\n+\n+ * *randomized* solver:\n+\n+ - Algorithm 4.3 in\n+ `\"Finding structure with randomness: Stochastic algorithms for\n+ constructing approximate matrix decompositions\"\n+ `_\n+ Halko, et al., 2009\n+\n+ - `\"An implementation of a randomized algorithm for principal component\n+ analysis\"\n+ `_\n+ A. Szlam et al. 2014\n+\n+ * *arpack* solver:\n+ `scipy.sparse.linalg.eigsh documentation\n+ `_\n+ R. B. Lehoucq, D. C. Sorensen, and C. Yang, 1998\n+\n+\n .. _LSA:\n \n Truncated singular value decomposition and latent semantic analysis\n"}, {"path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 3b3884e68e185..e89eecfe0874c 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -159,14 +159,17 @@ Changelog\n - |Fix| Fixes incorrect multiple data-conversion warnings when clustering\n boolean data. :pr:`19046` by :user:`Surya Prakash `.\n \n-:mod:`sklearn.decomposition`\n-............................\n-\n - |Fix| Fixed :func:`dict_learning`, used by :class:`DictionaryLearning`, to\n ensure determinism of the output. Achieved by flipping signs of the SVD\n output which is used to initialize the code.\n :pr:`18433` by :user:`Bruno Charron `.\n \n+- |Enhancement| added a new approximate solver (randomized SVD, available with\n+ `eigen_solver='randomized'`) to :class:`decomposition.KernelPCA`. This\n+ significantly accelerates computation when the number of samples is much\n+ larger than the desired number of components.\n+ :pr:`12069` by :user:`Sylvain Mari\u00e9 `.\n+\n - |Fix| Fixed a bug in :class:`MiniBatchDictionaryLearning`,\n :class:`MiniBatchSparsePCA` and :func:`dict_learning_online` where the\n update of the dictionary was incorrect. :pr:`19198` by\n@@ -389,8 +392,8 @@ Changelog\n supporting sparse matrix and raise the appropriate error message.\n :pr:`19879` by :user:`Guillaume Lemaitre `.\n \n-- |Efficiency| Changed ``algorithm`` argument for :class:`cluster.KMeans` in \n- :class:`preprocessing.KBinsDiscretizer` from ``auto`` to ``full``. \n+- |Efficiency| Changed ``algorithm`` argument for :class:`cluster.KMeans` in\n+ :class:`preprocessing.KBinsDiscretizer` from ``auto`` to ``full``.\n :pr:`19934` by :user:`Gleb Levitskiy `.\n \n :mod:`sklearn.tree`\n"}], "version": "1.00", "base_commit": "2641baf16d9de5191316745ec46120cc8b57a666", "PASS2PASS": ["sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_deterministic_output", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_inverse_transform_reconstruction", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_linear_kernel[4-auto]", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_conditioning", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_precomputed_non_symmetric[dense]", "sklearn/decomposition/tests/test_kernel_pca.py::test_remove_zero_eig", "sklearn/decomposition/tests/test_kernel_pca.py::test_gridsearch_pipeline_precomputed", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_linear_kernel[10-arpack]", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_invalid_parameters", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pcc_pairwise_is_deprecated", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_linear_kernel[10-dense]", "sklearn/decomposition/tests/test_kernel_pca.py::test_precomputed_kernel_not_psd[auto]", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_precomputed_non_symmetric[arpack]", "sklearn/decomposition/tests/test_kernel_pca.py::test_precomputed_kernel_not_psd[dense]", "sklearn/decomposition/tests/test_kernel_pca.py::test_nested_circles", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_precomputed_non_symmetric[auto]", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_invalid_kernel", "sklearn/decomposition/tests/test_kernel_pca.py::test_gridsearch_pipeline", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_linear_kernel[4-dense]", "sklearn/decomposition/tests/test_kernel_pca.py::test_32_64_decomposition_shape", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_consistent_transform", "sklearn/decomposition/tests/test_kernel_pca.py::test_precomputed_kernel_not_psd[arpack]", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_linear_kernel[4-arpack]", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_linear_kernel[10-auto]"], "FAIL2PASS": ["sklearn/utils/tests/test_extmath.py::test_randomized_svd_sign_flip_with_transpose", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10000000.0-1-1e-08-0]", "sklearn/utils/tests/test_extmath.py::test_uniform_weights", "sklearn/utils/tests/test_extmath.py::test_randomized_eigsh_reconst_low_rank[500-400]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1-1--10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10000000.0-1-1e-08--10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1-1e-08-0]", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_sparse", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_precomputed", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10000000.0-1-100000.0-0]", "sklearn/utils/tests/test_extmath.py::test_safe_sparse_dot_2d[sparse-dense]", "sklearn/utils/tests/test_extmath.py::test_incremental_mean_and_variance_ignore_nan", "sklearn/utils/tests/test_extmath.py::test_randomized_eigsh[float64]", "sklearn/utils/tests/test_extmath.py::test_randomized_eigsh_compared_to_others[200]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10-1-100000.0--10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1e-08-1e-08-0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance_ignore_nan[float64]", "sklearn/utils/tests/test_extmath.py::test_randomized_eigsh_compared_to_others[10]", "sklearn/utils/tests/test_extmath.py::test_randomized_svd_sparse_warnings", "sklearn/decomposition/tests/test_kernel_pca.py::test_precomputed_kernel_not_psd[randomized]", "sklearn/utils/tests/test_extmath.py::test_randomized_svd_low_rank_all_dtypes[int64]", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca", "sklearn/utils/tests/test_extmath.py::test_randomized_eigsh_compared_to_others[100]", "sklearn/utils/tests/test_extmath.py::test_softmax", "sklearn/utils/tests/test_extmath.py::test_randomized_eigsh_compared_to_others[50]", "sklearn/utils/tests/test_extmath.py::test_cartesian", "sklearn/utils/tests/test_extmath.py::test_randomized_svd_transpose_consistency", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_n_components", "sklearn/utils/tests/test_extmath.py::test_vector_sign_flip", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10000000.0-1-1-10000000.0]", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_precomputed_non_symmetric[randomized]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1e-08-1e-08-10000000.0]", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_solvers_equivalence[10]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10-1-1e-08-0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1e-08-1-0]", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_linear_kernel[4-randomized]", "sklearn/utils/tests/test_extmath.py::test_incremental_variance_update_formulas", "sklearn/utils/tests/test_extmath.py::test_svd_flip", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_invalid_solver", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10000000.0-1-100000.0--10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[1-1e-08-1-0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10-1-1e-08-10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10000000.0-1-1-0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1-1e-08--10000000.0]", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_solvers_equivalence[4]", "sklearn/utils/tests/test_extmath.py::test_randomized_eigsh[float32]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1e-08-100000.0-0]", "sklearn/utils/tests/test_extmath.py::test_randomized_svd_low_rank_all_dtypes[int32]", "sklearn/utils/tests/test_extmath.py::test_safe_sparse_dot_2d_1d[sparse]", "sklearn/utils/tests/test_extmath.py::test_randomized_svd_low_rank_all_dtypes[float64]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10000000.0-1-1e-08-10000000.0]", "sklearn/utils/tests/test_extmath.py::test_safe_sparse_dot_2d_1d[dense]", "sklearn/utils/tests/test_extmath.py::test_safe_sparse_dot_dense_output[True]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[1-1e-08-1--10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10000000.0-1-100000.0-10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[1-1e-08-100000.0-0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[1-1e-08-100000.0--10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1e-08-1e-08--10000000.0]", "sklearn/utils/tests/test_extmath.py::test_randomized_eigsh_reconst_low_rank[500-10]", "sklearn/utils/tests/test_extmath.py::test_randomized_svd_sign_flip", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_linear_kernel[10-randomized]", "sklearn/utils/tests/test_extmath.py::test_randomized_svd_low_rank_with_noise", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[1-1e-08-1e-08-10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance_simple[float64]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1-100000.0--10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1e-08-100000.0-10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[1-1e-08-1e-08--10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10-1-1-0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1e-08-1-10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance_ignore_nan[float32]", "sklearn/utils/tests/test_extmath.py::test_incremental_variance_ddof", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10000000.0-1-1--10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1e-08-1--10000000.0]", "sklearn/utils/tests/test_extmath.py::test_safe_sparse_dot_nd", "sklearn/utils/tests/test_extmath.py::test_row_norms[float64]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10-1-100000.0-10000000.0]", "sklearn/utils/tests/test_extmath.py::test_randomized_svd_infinite_rank", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10-1-100000.0-0]", "sklearn/utils/tests/test_extmath.py::test_randomized_eigsh[int32]", "sklearn/utils/tests/test_extmath.py::test_safe_sparse_dot_2d[sparse-sparse]", "sklearn/utils/tests/test_extmath.py::test_randomized_eigsh[int64]", "sklearn/utils/tests/test_extmath.py::test_safe_sparse_dot_dense_output[False]", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_solvers_equivalence[20]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance_simple[float32]", "sklearn/utils/tests/test_extmath.py::test_incremental_variance_numerical_stability", "sklearn/utils/tests/test_extmath.py::test_randomized_svd_power_iteration_normalizer", "sklearn/utils/tests/test_extmath.py::test_row_norms[float32]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[1-1e-08-1e-08-0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1-1e-08-10000000.0]", "sklearn/utils/tests/test_extmath.py::test_density", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10-1-1-10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1-1-0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10-1-1--10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10-1-1e-08--10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1-1-10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1-100000.0-0]", "sklearn/utils/tests/test_extmath.py::test_logistic_sigmoid", "sklearn/utils/tests/test_extmath.py::test_randomized_svd_low_rank_all_dtypes[float32]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1e-08-100000.0--10000000.0]", "sklearn/utils/tests/test_extmath.py::test_randomized_eigsh_compared_to_others[199]", "sklearn/utils/tests/test_extmath.py::test_safe_sparse_dot_2d[dense-dense]", "sklearn/utils/tests/test_extmath.py::test_stable_cumsum", "sklearn/utils/tests/test_extmath.py::test_randomized_eigsh_reconst_low_rank[100-80]", "sklearn/utils/tests/test_extmath.py::test_random_weights", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[1-1e-08-1-10000000.0]", "sklearn/utils/tests/test_extmath.py::test_randomized_eigsh_reconst_low_rank[500-250]", "sklearn/utils/tests/test_extmath.py::test_randomized_eigsh_reconst_low_rank[10-7]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1-100000.0-10000000.0]", "sklearn/utils/tests/test_extmath.py::test_safe_sparse_dot_2d[dense-sparse]", "sklearn/utils/tests/test_extmath.py::test_randomized_eigsh_reconst_low_rank[100-10]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[1-1e-08-100000.0-10000000.0]"], "mask_doc_diff": [{"path": "doc/modules/decomposition.rst", "old_path": "a/doc/modules/decomposition.rst", "new_path": "b/doc/modules/decomposition.rst", "metadata": "diff --git a/doc/modules/decomposition.rst b/doc/modules/decomposition.rst\nindex e971d784c..fd51f60d8 100644\n--- a/doc/modules/decomposition.rst\n+++ b/doc/modules/decomposition.rst\n@@ -166,32 +166,16 @@ Note: the implementation of ``inverse_transform`` in :class:`PCA` with\n \n .. topic:: References:\n \n- * `\"Finding structure with randomness: Stochastic algorithms for\n+ * Algorithm 4.3 in\n+ `\"Finding structure with randomness: Stochastic algorithms for\n constructing approximate matrix decompositions\"\n `_\n Halko, et al., 2009\n \n-\n-.. _kernel_PCA:\n-\n-Kernel PCA\n-----------\n-\n-:class:`KernelPCA` is an extension of PCA which achieves non-linear\n-dimensionality reduction through the use of kernels (see :ref:`metrics`). It\n-has many applications including denoising, compression and structured\n-prediction (kernel dependency estimation). :class:`KernelPCA` supports both\n-``transform`` and ``inverse_transform``.\n-\n-.. figure:: ../auto_examples/decomposition/images/sphx_glr_plot_kernel_pca_001.png\n- :target: ../auto_examples/decomposition/plot_kernel_pca.html\n- :align: center\n- :scale: 75%\n-\n-.. topic:: Examples:\n-\n- * :ref:`sphx_glr_auto_examples_decomposition_plot_kernel_pca.py`\n-\n+ * `\"An implementation of a randomized algorithm for principal component\n+ analysis\"\n+ `_\n+ A. Szlam et al. 2014\n \n .. _SparsePCA:\n \n@@ -278,6 +262,100 @@ factorization, while larger values shrink many coefficients to zero.\n R. Jenatton, G. Obozinski, F. Bach, 2009\n \n \n+.. _kernel_PCA:\n+\n+Kernel Principal Component Analysis (kPCA)\n+==========================================\n+\n+Exact Kernel PCA\n+----------------\n+\n+:class:`KernelPCA` is an extension of PCA which achieves non-linear\n+dimensionality reduction through the use of kernels (see :ref:`metrics`). It\n+has many applications including denoising, compression and structured\n+prediction (kernel dependency estimation). :class:`KernelPCA` supports both\n+``transform`` and ``inverse_transform``.\n+\n+.. figure:: ../auto_examples/decomposition/images/sphx_glr_plot_kernel_pca_001.png\n+ :target: ../auto_examples/decomposition/plot_kernel_pca.html\n+ :align: center\n+ :scale: 75%\n+\n+.. topic:: Examples:\n+\n+ * :ref:`sphx_glr_auto_examples_decomposition_plot_kernel_pca.py`\n+\n+.. topic:: References:\n+\n+ * Kernel PCA was introduced in \"Kernel principal component analysis\"\n+ Bernhard Schoelkopf, Alexander J. Smola, and Klaus-Robert Mueller. 1999.\n+ In Advances in kernel methods, MIT Press, Cambridge, MA, USA 327-352.\n+\n+\n+.. _kPCA_Solvers:\n+\n+Choice of solver for Kernel PCA\n+-------------------------------\n+\n+While in :class:`PCA` the number of components is bounded by the number of\n+features, in :class:`KernelPCA` the number of components is bounded by the\n+number of samples. Many real-world datasets have large number of samples! In\n+these cases finding *all* the components with a full kPCA is a waste of\n+computation time, as data is mostly described by the first few components\n+(e.g. ``n_components<=100``). In other words, the centered Gram matrix that\n+is eigendecomposed in the Kernel PCA fitting process has an effective rank that\n+is much smaller than its size. This is a situation where approximate\n+eigensolvers can provide speedup with very low precision loss.\n+\n+The optional parameter ``eigen_solver='randomized'`` can be used to\n+*significantly* reduce the computation time when the number of requested\n+``n_components`` is small compared with the number of samples. It relies on\n+randomized decomposition methods to find an approximate solution in a shorter\n+time.\n+\n+The time complexity of the randomized :class:`KernelPCA` is\n+:math:`O(n_{\\mathrm{samples}}^2 \\cdot n_{\\mathrm{components}})`\n+instead of :math:`O(n_{\\mathrm{samples}}^3)` for the exact method\n+implemented with ``eigen_solver='dense'``.\n+\n+The memory footprint of randomized :class:`KernelPCA` is also proportional to\n+:math:`2 \\cdot n_{\\mathrm{samples}} \\cdot n_{\\mathrm{components}}` instead of\n+:math:`n_{\\mathrm{samples}}^2` for the exact method.\n+\n+Note: this technique is the same as in :ref:`RandomizedPCA`.\n+\n+In addition to the above two solvers, ``eigen_solver='arpack'`` can be used as\n+an alternate way to get an approximate decomposition. In practice, this method\n+only provides reasonable execution times when the number of components to find\n+is extremely small. It is enabled by default when the desired number of\n+components is less than 10 (strict) and the number of samples is more than 200\n+(strict). See :class:`KernelPCA` for details.\n+\n+.. topic:: References:\n+\n+ * *dense* solver:\n+ `scipy.linalg.eigh documentation\n+ `_\n+\n+ * *randomized* solver:\n+\n+ - Algorithm 4.3 in\n+ `\"Finding structure with randomness: Stochastic algorithms for\n+ constructing approximate matrix decompositions\"\n+ `_\n+ Halko, et al., 2009\n+\n+ - `\"An implementation of a randomized algorithm for principal component\n+ analysis\"\n+ `_\n+ A. Szlam et al. 2014\n+\n+ * *arpack* solver:\n+ `scipy.sparse.linalg.eigsh documentation\n+ `_\n+ R. B. Lehoucq, D. C. Sorensen, and C. Yang, 1998\n+\n+\n .. _LSA:\n \n Truncated singular value decomposition and latent semantic analysis\n"}, {"path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 3b3884e68..7faf6bdf6 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -159,14 +159,16 @@ Changelog\n - |Fix| Fixes incorrect multiple data-conversion warnings when clustering\n boolean data. :pr:`19046` by :user:`Surya Prakash `.\n \n-:mod:`sklearn.decomposition`\n-............................\n-\n - |Fix| Fixed :func:`dict_learning`, used by :class:`DictionaryLearning`, to\n ensure determinism of the output. Achieved by flipping signs of the SVD\n output which is used to initialize the code.\n :pr:`18433` by :user:`Bruno Charron `.\n \n+- |Enhancement| added a new approximate solver (randomized SVD, available with\n+ `eigen_solver='randomized'`) to :class:`decomposition.KernelPCA`. This\n+ significantly accelerates computation when the number of samples is much\n+ larger than the desired number of components.\n+\n - |Fix| Fixed a bug in :class:`MiniBatchDictionaryLearning`,\n :class:`MiniBatchSparsePCA` and :func:`dict_learning_online` where the\n update of the dictionary was incorrect. :pr:`19198` by\n@@ -389,8 +391,8 @@ Changelog\n supporting sparse matrix and raise the appropriate error message.\n :pr:`19879` by :user:`Guillaume Lemaitre `.\n \n-- |Efficiency| Changed ``algorithm`` argument for :class:`cluster.KMeans` in \n- :class:`preprocessing.KBinsDiscretizer` from ``auto`` to ``full``. \n+- |Efficiency| Changed ``algorithm`` argument for :class:`cluster.KMeans` in\n+ :class:`preprocessing.KBinsDiscretizer` from ``auto`` to ``full``.\n :pr:`19934` by :user:`Gleb Levitskiy `.\n \n :mod:`sklearn.tree`\n"}], "augmentations": {"header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [{"type": "file", "name": "benchmarks/bench_kernel_pca_solvers_time_vs_n_samples.py"}, {"type": "file", "name": "benchmarks/bench_kernel_pca_solvers_time_vs_n_components.py"}]}, "problem_statement": "diff --git a/doc/modules/decomposition.rst b/doc/modules/decomposition.rst\nindex e971d784c..fd51f60d8 100644\n--- a/doc/modules/decomposition.rst\n+++ b/doc/modules/decomposition.rst\n@@ -166,32 +166,16 @@ Note: the implementation of ``inverse_transform`` in :class:`PCA` with\n \n .. topic:: References:\n \n- * `\"Finding structure with randomness: Stochastic algorithms for\n+ * Algorithm 4.3 in\n+ `\"Finding structure with randomness: Stochastic algorithms for\n constructing approximate matrix decompositions\"\n `_\n Halko, et al., 2009\n \n-\n-.. _kernel_PCA:\n-\n-Kernel PCA\n-----------\n-\n-:class:`KernelPCA` is an extension of PCA which achieves non-linear\n-dimensionality reduction through the use of kernels (see :ref:`metrics`). It\n-has many applications including denoising, compression and structured\n-prediction (kernel dependency estimation). :class:`KernelPCA` supports both\n-``transform`` and ``inverse_transform``.\n-\n-.. figure:: ../auto_examples/decomposition/images/sphx_glr_plot_kernel_pca_001.png\n- :target: ../auto_examples/decomposition/plot_kernel_pca.html\n- :align: center\n- :scale: 75%\n-\n-.. topic:: Examples:\n-\n- * :ref:`sphx_glr_auto_examples_decomposition_plot_kernel_pca.py`\n-\n+ * `\"An implementation of a randomized algorithm for principal component\n+ analysis\"\n+ `_\n+ A. Szlam et al. 2014\n \n .. _SparsePCA:\n \n@@ -278,6 +262,100 @@ factorization, while larger values shrink many coefficients to zero.\n R. Jenatton, G. Obozinski, F. Bach, 2009\n \n \n+.. _kernel_PCA:\n+\n+Kernel Principal Component Analysis (kPCA)\n+==========================================\n+\n+Exact Kernel PCA\n+----------------\n+\n+:class:`KernelPCA` is an extension of PCA which achieves non-linear\n+dimensionality reduction through the use of kernels (see :ref:`metrics`). It\n+has many applications including denoising, compression and structured\n+prediction (kernel dependency estimation). :class:`KernelPCA` supports both\n+``transform`` and ``inverse_transform``.\n+\n+.. figure:: ../auto_examples/decomposition/images/sphx_glr_plot_kernel_pca_001.png\n+ :target: ../auto_examples/decomposition/plot_kernel_pca.html\n+ :align: center\n+ :scale: 75%\n+\n+.. topic:: Examples:\n+\n+ * :ref:`sphx_glr_auto_examples_decomposition_plot_kernel_pca.py`\n+\n+.. topic:: References:\n+\n+ * Kernel PCA was introduced in \"Kernel principal component analysis\"\n+ Bernhard Schoelkopf, Alexander J. Smola, and Klaus-Robert Mueller. 1999.\n+ In Advances in kernel methods, MIT Press, Cambridge, MA, USA 327-352.\n+\n+\n+.. _kPCA_Solvers:\n+\n+Choice of solver for Kernel PCA\n+-------------------------------\n+\n+While in :class:`PCA` the number of components is bounded by the number of\n+features, in :class:`KernelPCA` the number of components is bounded by the\n+number of samples. Many real-world datasets have large number of samples! In\n+these cases finding *all* the components with a full kPCA is a waste of\n+computation time, as data is mostly described by the first few components\n+(e.g. ``n_components<=100``). In other words, the centered Gram matrix that\n+is eigendecomposed in the Kernel PCA fitting process has an effective rank that\n+is much smaller than its size. This is a situation where approximate\n+eigensolvers can provide speedup with very low precision loss.\n+\n+The optional parameter ``eigen_solver='randomized'`` can be used to\n+*significantly* reduce the computation time when the number of requested\n+``n_components`` is small compared with the number of samples. It relies on\n+randomized decomposition methods to find an approximate solution in a shorter\n+time.\n+\n+The time complexity of the randomized :class:`KernelPCA` is\n+:math:`O(n_{\\mathrm{samples}}^2 \\cdot n_{\\mathrm{components}})`\n+instead of :math:`O(n_{\\mathrm{samples}}^3)` for the exact method\n+implemented with ``eigen_solver='dense'``.\n+\n+The memory footprint of randomized :class:`KernelPCA` is also proportional to\n+:math:`2 \\cdot n_{\\mathrm{samples}} \\cdot n_{\\mathrm{components}}` instead of\n+:math:`n_{\\mathrm{samples}}^2` for the exact method.\n+\n+Note: this technique is the same as in :ref:`RandomizedPCA`.\n+\n+In addition to the above two solvers, ``eigen_solver='arpack'`` can be used as\n+an alternate way to get an approximate decomposition. In practice, this method\n+only provides reasonable execution times when the number of components to find\n+is extremely small. It is enabled by default when the desired number of\n+components is less than 10 (strict) and the number of samples is more than 200\n+(strict). See :class:`KernelPCA` for details.\n+\n+.. topic:: References:\n+\n+ * *dense* solver:\n+ `scipy.linalg.eigh documentation\n+ `_\n+\n+ * *randomized* solver:\n+\n+ - Algorithm 4.3 in\n+ `\"Finding structure with randomness: Stochastic algorithms for\n+ constructing approximate matrix decompositions\"\n+ `_\n+ Halko, et al., 2009\n+\n+ - `\"An implementation of a randomized algorithm for principal component\n+ analysis\"\n+ `_\n+ A. Szlam et al. 2014\n+\n+ * *arpack* solver:\n+ `scipy.sparse.linalg.eigsh documentation\n+ `_\n+ R. B. Lehoucq, D. C. Sorensen, and C. Yang, 1998\n+\n+\n .. _LSA:\n \n Truncated singular value decomposition and latent semantic analysis\n\ndiff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 3b3884e68..7faf6bdf6 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -159,14 +159,16 @@ Changelog\n - |Fix| Fixes incorrect multiple data-conversion warnings when clustering\n boolean data. :pr:`19046` by :user:`Surya Prakash `.\n \n-:mod:`sklearn.decomposition`\n-............................\n-\n - |Fix| Fixed :func:`dict_learning`, used by :class:`DictionaryLearning`, to\n ensure determinism of the output. Achieved by flipping signs of the SVD\n output which is used to initialize the code.\n :pr:`18433` by :user:`Bruno Charron `.\n \n+- |Enhancement| added a new approximate solver (randomized SVD, available with\n+ `eigen_solver='randomized'`) to :class:`decomposition.KernelPCA`. This\n+ significantly accelerates computation when the number of samples is much\n+ larger than the desired number of components.\n+\n - |Fix| Fixed a bug in :class:`MiniBatchDictionaryLearning`,\n :class:`MiniBatchSparsePCA` and :func:`dict_learning_online` where the\n update of the dictionary was incorrect. :pr:`19198` by\n@@ -389,8 +391,8 @@ Changelog\n supporting sparse matrix and raise the appropriate error message.\n :pr:`19879` by :user:`Guillaume Lemaitre `.\n \n-- |Efficiency| Changed ``algorithm`` argument for :class:`cluster.KMeans` in \n- :class:`preprocessing.KBinsDiscretizer` from ``auto`` to ``full``. \n+- |Efficiency| Changed ``algorithm`` argument for :class:`cluster.KMeans` in\n+ :class:`preprocessing.KBinsDiscretizer` from ``auto`` to ``full``.\n :pr:`19934` by :user:`Gleb Levitskiy `.\n \n :mod:`sklearn.tree`\n\nIf completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:\n[{'type': 'file', 'name': 'benchmarks/bench_kernel_pca_solvers_time_vs_n_samples.py'}, {'type': 'file', 'name': 'benchmarks/bench_kernel_pca_solvers_time_vs_n_components.py'}]\n"} +{"repo": "scikit-learn/scikit-learn", "instance_id": "scikit-learn__scikit-learn-12069", "html_url": "https://github.com/scikit-learn/scikit-learn/pull/12069", "feature_patch": "diff --git a/benchmarks/bench_kernel_pca_solvers_time_vs_n_components.py b/benchmarks/bench_kernel_pca_solvers_time_vs_n_components.py\nnew file mode 100644\nindex 0000000000000..d871967ad1327\n--- /dev/null\n+++ b/benchmarks/bench_kernel_pca_solvers_time_vs_n_components.py\n@@ -0,0 +1,148 @@\n+\"\"\"\n+=============================================================\n+Kernel PCA Solvers comparison benchmark: time vs n_components\n+=============================================================\n+\n+This benchmark shows that the approximate solvers provided in Kernel PCA can\n+help significantly improve its execution speed when an approximate solution\n+(small `n_components`) is acceptable. In many real-world datasets a few\n+hundreds of principal components are indeed sufficient enough to capture the\n+underlying distribution.\n+\n+Description:\n+------------\n+A fixed number of training (default: 2000) and test (default: 1000) samples\n+with 2 features is generated using the `make_circles` helper method.\n+\n+KernelPCA models are trained on the training set with an increasing number of\n+principal components, between 1 and `max_n_compo` (default: 1999), with\n+`n_compo_grid_size` positions (default: 10). For each value of `n_components`\n+to try, KernelPCA models are trained for the various possible `eigen_solver`\n+values. The execution times are displayed in a plot at the end of the\n+experiment.\n+\n+What you can observe:\n+---------------------\n+When the number of requested principal components is small, the dense solver\n+takes more time to complete, while the randomized method returns similar\n+results with shorter execution times.\n+\n+Going further:\n+--------------\n+You can adjust `max_n_compo` and `n_compo_grid_size` if you wish to explore a\n+different range of values for `n_components`.\n+\n+You can also set `arpack_all=True` to activate arpack solver for large number\n+of components (this takes more time).\n+\"\"\"\n+# Authors: Sylvain MARIE, Schneider Electric\n+\n+import time\n+\n+import numpy as np\n+import matplotlib.pyplot as plt\n+\n+from numpy.testing import assert_array_almost_equal\n+from sklearn.decomposition import KernelPCA\n+from sklearn.datasets import make_circles\n+\n+\n+print(__doc__)\n+\n+\n+# 1- Design the Experiment\n+# ------------------------\n+n_train, n_test = 2000, 1000 # the sample sizes to use\n+max_n_compo = 1999 # max n_components to try\n+n_compo_grid_size = 10 # nb of positions in the grid to try\n+# generate the grid\n+n_compo_range = [np.round(np.exp((x / (n_compo_grid_size - 1))\n+ * np.log(max_n_compo)))\n+ for x in range(0, n_compo_grid_size)]\n+\n+n_iter = 3 # the number of times each experiment will be repeated\n+arpack_all = False # set to True if you wish to run arpack for all n_compo\n+\n+\n+# 2- Generate random data\n+# -----------------------\n+n_features = 2\n+X, y = make_circles(n_samples=(n_train + n_test), factor=.3, noise=.05,\n+ random_state=0)\n+X_train, X_test = X[:n_train, :], X[n_train:, :]\n+\n+\n+# 3- Benchmark\n+# ------------\n+# init\n+ref_time = np.empty((len(n_compo_range), n_iter)) * np.nan\n+a_time = np.empty((len(n_compo_range), n_iter)) * np.nan\n+r_time = np.empty((len(n_compo_range), n_iter)) * np.nan\n+# loop\n+for j, n_components in enumerate(n_compo_range):\n+\n+ n_components = int(n_components)\n+ print(\"Performing kPCA with n_components = %i\" % n_components)\n+\n+ # A- reference (dense)\n+ print(\" - dense solver\")\n+ for i in range(n_iter):\n+ start_time = time.perf_counter()\n+ ref_pred = KernelPCA(n_components, eigen_solver=\"dense\") \\\n+ .fit(X_train).transform(X_test)\n+ ref_time[j, i] = time.perf_counter() - start_time\n+\n+ # B- arpack (for small number of components only, too slow otherwise)\n+ if arpack_all or n_components < 100:\n+ print(\" - arpack solver\")\n+ for i in range(n_iter):\n+ start_time = time.perf_counter()\n+ a_pred = KernelPCA(n_components, eigen_solver=\"arpack\") \\\n+ .fit(X_train).transform(X_test)\n+ a_time[j, i] = time.perf_counter() - start_time\n+ # check that the result is still correct despite the approx\n+ assert_array_almost_equal(np.abs(a_pred), np.abs(ref_pred))\n+\n+ # C- randomized\n+ print(\" - randomized solver\")\n+ for i in range(n_iter):\n+ start_time = time.perf_counter()\n+ r_pred = KernelPCA(n_components, eigen_solver=\"randomized\") \\\n+ .fit(X_train).transform(X_test)\n+ r_time[j, i] = time.perf_counter() - start_time\n+ # check that the result is still correct despite the approximation\n+ assert_array_almost_equal(np.abs(r_pred), np.abs(ref_pred))\n+\n+# Compute statistics for the 3 methods\n+avg_ref_time = ref_time.mean(axis=1)\n+std_ref_time = ref_time.std(axis=1)\n+avg_a_time = a_time.mean(axis=1)\n+std_a_time = a_time.std(axis=1)\n+avg_r_time = r_time.mean(axis=1)\n+std_r_time = r_time.std(axis=1)\n+\n+\n+# 4- Plots\n+# --------\n+fig, ax = plt.subplots(figsize=(12, 8))\n+\n+# Display 1 plot with error bars per method\n+ax.errorbar(n_compo_range, avg_ref_time, yerr=std_ref_time,\n+ marker='x', linestyle='', color='r', label='full')\n+ax.errorbar(n_compo_range, avg_a_time, yerr=std_a_time, marker='x',\n+ linestyle='', color='g', label='arpack')\n+ax.errorbar(n_compo_range, avg_r_time, yerr=std_r_time, marker='x',\n+ linestyle='', color='b', label='randomized')\n+ax.legend(loc='upper left')\n+\n+# customize axes\n+ax.set_xscale('log')\n+ax.set_xlim(1, max(n_compo_range) * 1.1)\n+ax.set_ylabel(\"Execution time (s)\")\n+ax.set_xlabel(\"n_components\")\n+\n+ax.set_title(\"kPCA Execution time comparison on %i samples with %i \"\n+ \"features, according to the choice of `eigen_solver`\"\n+ \"\" % (n_train, n_features))\n+\n+plt.show()\ndiff --git a/benchmarks/bench_kernel_pca_solvers_time_vs_n_samples.py b/benchmarks/bench_kernel_pca_solvers_time_vs_n_samples.py\nnew file mode 100644\nindex 0000000000000..d238802a68d64\n--- /dev/null\n+++ b/benchmarks/bench_kernel_pca_solvers_time_vs_n_samples.py\n@@ -0,0 +1,153 @@\n+\"\"\"\n+==========================================================\n+Kernel PCA Solvers comparison benchmark: time vs n_samples\n+==========================================================\n+\n+This benchmark shows that the approximate solvers provided in Kernel PCA can\n+help significantly improve its execution speed when an approximate solution\n+(small `n_components`) is acceptable. In many real-world datasets the number of\n+samples is very large, but a few hundreds of principal components are\n+sufficient enough to capture the underlying distribution.\n+\n+Description:\n+------------\n+An increasing number of examples is used to train a KernelPCA, between\n+`min_n_samples` (default: 101) and `max_n_samples` (default: 4000) with\n+`n_samples_grid_size` positions (default: 4). Samples have 2 features, and are\n+generated using `make_circles`. For each training sample size, KernelPCA models\n+are trained for the various possible `eigen_solver` values. All of them are\n+trained to obtain `n_components` principal components (default: 100). The\n+execution times are displayed in a plot at the end of the experiment.\n+\n+What you can observe:\n+---------------------\n+When the number of samples provided gets large, the dense solver takes a lot\n+of time to complete, while the randomized method returns similar results in\n+much shorter execution times.\n+\n+Going further:\n+--------------\n+You can increase `max_n_samples` and `nb_n_samples_to_try` if you wish to\n+explore a wider range of values for `n_samples`.\n+\n+You can also set `include_arpack=True` to add this other solver in the\n+experiments (much slower).\n+\n+Finally you can have a look at the second example of this series, \"Kernel PCA\n+Solvers comparison benchmark: time vs n_components\", where this time the number\n+of examples is fixed, and the desired number of components varies.\n+\"\"\"\n+# Author: Sylvain MARIE, Schneider Electric\n+\n+import time\n+\n+import numpy as np\n+import matplotlib.pyplot as plt\n+\n+from numpy.testing import assert_array_almost_equal\n+from sklearn.decomposition import KernelPCA\n+from sklearn.datasets import make_circles\n+\n+\n+print(__doc__)\n+\n+\n+# 1- Design the Experiment\n+# ------------------------\n+min_n_samples, max_n_samples = 101, 4000 # min and max n_samples to try\n+n_samples_grid_size = 4 # nb of positions in the grid to try\n+# generate the grid\n+n_samples_range = [min_n_samples + np.floor((x / (n_samples_grid_size - 1))\n+ * (max_n_samples - min_n_samples))\n+ for x in range(0, n_samples_grid_size)]\n+\n+n_components = 100 # the number of principal components we want to use\n+n_iter = 3 # the number of times each experiment will be repeated\n+include_arpack = False # set this to True to include arpack solver (slower)\n+\n+\n+# 2- Generate random data\n+# -----------------------\n+n_features = 2\n+X, y = make_circles(n_samples=max_n_samples, factor=.3, noise=.05,\n+ random_state=0)\n+\n+\n+# 3- Benchmark\n+# ------------\n+# init\n+ref_time = np.empty((len(n_samples_range), n_iter)) * np.nan\n+a_time = np.empty((len(n_samples_range), n_iter)) * np.nan\n+r_time = np.empty((len(n_samples_range), n_iter)) * np.nan\n+\n+# loop\n+for j, n_samples in enumerate(n_samples_range):\n+\n+ n_samples = int(n_samples)\n+ print(\"Performing kPCA with n_samples = %i\" % n_samples)\n+\n+ X_train = X[:n_samples, :]\n+ X_test = X_train\n+\n+ # A- reference (dense)\n+ print(\" - dense\")\n+ for i in range(n_iter):\n+ start_time = time.perf_counter()\n+ ref_pred = KernelPCA(n_components, eigen_solver=\"dense\") \\\n+ .fit(X_train).transform(X_test)\n+ ref_time[j, i] = time.perf_counter() - start_time\n+\n+ # B- arpack\n+ if include_arpack:\n+ print(\" - arpack\")\n+ for i in range(n_iter):\n+ start_time = time.perf_counter()\n+ a_pred = KernelPCA(n_components, eigen_solver=\"arpack\") \\\n+ .fit(X_train).transform(X_test)\n+ a_time[j, i] = time.perf_counter() - start_time\n+ # check that the result is still correct despite the approx\n+ assert_array_almost_equal(np.abs(a_pred), np.abs(ref_pred))\n+\n+ # C- randomized\n+ print(\" - randomized\")\n+ for i in range(n_iter):\n+ start_time = time.perf_counter()\n+ r_pred = KernelPCA(n_components, eigen_solver=\"randomized\") \\\n+ .fit(X_train).transform(X_test)\n+ r_time[j, i] = time.perf_counter() - start_time\n+ # check that the result is still correct despite the approximation\n+ assert_array_almost_equal(np.abs(r_pred), np.abs(ref_pred))\n+\n+# Compute statistics for the 3 methods\n+avg_ref_time = ref_time.mean(axis=1)\n+std_ref_time = ref_time.std(axis=1)\n+avg_a_time = a_time.mean(axis=1)\n+std_a_time = a_time.std(axis=1)\n+avg_r_time = r_time.mean(axis=1)\n+std_r_time = r_time.std(axis=1)\n+\n+\n+# 4- Plots\n+# --------\n+fig, ax = plt.subplots(figsize=(12, 8))\n+\n+# Display 1 plot with error bars per method\n+ax.errorbar(n_samples_range, avg_ref_time, yerr=std_ref_time,\n+ marker='x', linestyle='', color='r', label='full')\n+if include_arpack:\n+ ax.errorbar(n_samples_range, avg_a_time, yerr=std_a_time, marker='x',\n+ linestyle='', color='g', label='arpack')\n+ax.errorbar(n_samples_range, avg_r_time, yerr=std_r_time, marker='x',\n+ linestyle='', color='b', label='randomized')\n+ax.legend(loc='upper left')\n+\n+# customize axes\n+ax.set_xlim(min(n_samples_range) * 0.9, max(n_samples_range) * 1.1)\n+ax.set_ylabel(\"Execution time (s)\")\n+ax.set_xlabel(\"n_samples\")\n+\n+ax.set_title(\"Execution time comparison of kPCA with %i components on samples \"\n+ \"with %i features, according to the choice of `eigen_solver`\"\n+ \"\" % (n_components, n_features))\n+\n+plt.show()\ndiff --git a/doc/modules/decomposition.rst b/doc/modules/decomposition.rst\nindex e971d784c63d6..fd51f60d8bfc6 100644\n--- a/doc/modules/decomposition.rst\n+++ b/doc/modules/decomposition.rst\n@@ -166,32 +166,16 @@ Note: the implementation of ``inverse_transform`` in :class:`PCA` with\n \n .. topic:: References:\n \n- * `\"Finding structure with randomness: Stochastic algorithms for\n+ * Algorithm 4.3 in\n+ `\"Finding structure with randomness: Stochastic algorithms for\n constructing approximate matrix decompositions\"\n `_\n Halko, et al., 2009\n \n-\n-.. _kernel_PCA:\n-\n-Kernel PCA\n-----------\n-\n-:class:`KernelPCA` is an extension of PCA which achieves non-linear\n-dimensionality reduction through the use of kernels (see :ref:`metrics`). It\n-has many applications including denoising, compression and structured\n-prediction (kernel dependency estimation). :class:`KernelPCA` supports both\n-``transform`` and ``inverse_transform``.\n-\n-.. figure:: ../auto_examples/decomposition/images/sphx_glr_plot_kernel_pca_001.png\n- :target: ../auto_examples/decomposition/plot_kernel_pca.html\n- :align: center\n- :scale: 75%\n-\n-.. topic:: Examples:\n-\n- * :ref:`sphx_glr_auto_examples_decomposition_plot_kernel_pca.py`\n-\n+ * `\"An implementation of a randomized algorithm for principal component\n+ analysis\"\n+ `_\n+ A. Szlam et al. 2014\n \n .. _SparsePCA:\n \n@@ -278,6 +262,100 @@ factorization, while larger values shrink many coefficients to zero.\n R. Jenatton, G. Obozinski, F. Bach, 2009\n \n \n+.. _kernel_PCA:\n+\n+Kernel Principal Component Analysis (kPCA)\n+==========================================\n+\n+Exact Kernel PCA\n+----------------\n+\n+:class:`KernelPCA` is an extension of PCA which achieves non-linear\n+dimensionality reduction through the use of kernels (see :ref:`metrics`). It\n+has many applications including denoising, compression and structured\n+prediction (kernel dependency estimation). :class:`KernelPCA` supports both\n+``transform`` and ``inverse_transform``.\n+\n+.. figure:: ../auto_examples/decomposition/images/sphx_glr_plot_kernel_pca_001.png\n+ :target: ../auto_examples/decomposition/plot_kernel_pca.html\n+ :align: center\n+ :scale: 75%\n+\n+.. topic:: Examples:\n+\n+ * :ref:`sphx_glr_auto_examples_decomposition_plot_kernel_pca.py`\n+\n+.. topic:: References:\n+\n+ * Kernel PCA was introduced in \"Kernel principal component analysis\"\n+ Bernhard Schoelkopf, Alexander J. Smola, and Klaus-Robert Mueller. 1999.\n+ In Advances in kernel methods, MIT Press, Cambridge, MA, USA 327-352.\n+\n+\n+.. _kPCA_Solvers:\n+\n+Choice of solver for Kernel PCA\n+-------------------------------\n+\n+While in :class:`PCA` the number of components is bounded by the number of\n+features, in :class:`KernelPCA` the number of components is bounded by the\n+number of samples. Many real-world datasets have large number of samples! In\n+these cases finding *all* the components with a full kPCA is a waste of\n+computation time, as data is mostly described by the first few components\n+(e.g. ``n_components<=100``). In other words, the centered Gram matrix that\n+is eigendecomposed in the Kernel PCA fitting process has an effective rank that\n+is much smaller than its size. This is a situation where approximate\n+eigensolvers can provide speedup with very low precision loss.\n+\n+The optional parameter ``eigen_solver='randomized'`` can be used to\n+*significantly* reduce the computation time when the number of requested\n+``n_components`` is small compared with the number of samples. It relies on\n+randomized decomposition methods to find an approximate solution in a shorter\n+time.\n+\n+The time complexity of the randomized :class:`KernelPCA` is\n+:math:`O(n_{\\mathrm{samples}}^2 \\cdot n_{\\mathrm{components}})`\n+instead of :math:`O(n_{\\mathrm{samples}}^3)` for the exact method\n+implemented with ``eigen_solver='dense'``.\n+\n+The memory footprint of randomized :class:`KernelPCA` is also proportional to\n+:math:`2 \\cdot n_{\\mathrm{samples}} \\cdot n_{\\mathrm{components}}` instead of\n+:math:`n_{\\mathrm{samples}}^2` for the exact method.\n+\n+Note: this technique is the same as in :ref:`RandomizedPCA`.\n+\n+In addition to the above two solvers, ``eigen_solver='arpack'`` can be used as\n+an alternate way to get an approximate decomposition. In practice, this method\n+only provides reasonable execution times when the number of components to find\n+is extremely small. It is enabled by default when the desired number of\n+components is less than 10 (strict) and the number of samples is more than 200\n+(strict). See :class:`KernelPCA` for details.\n+\n+.. topic:: References:\n+\n+ * *dense* solver:\n+ `scipy.linalg.eigh documentation\n+ `_\n+\n+ * *randomized* solver:\n+\n+ - Algorithm 4.3 in\n+ `\"Finding structure with randomness: Stochastic algorithms for\n+ constructing approximate matrix decompositions\"\n+ `_\n+ Halko, et al., 2009\n+\n+ - `\"An implementation of a randomized algorithm for principal component\n+ analysis\"\n+ `_\n+ A. Szlam et al. 2014\n+\n+ * *arpack* solver:\n+ `scipy.sparse.linalg.eigsh documentation\n+ `_\n+ R. B. Lehoucq, D. C. Sorensen, and C. Yang, 1998\n+\n+\n .. _LSA:\n \n Truncated singular value decomposition and latent semantic analysis\ndiff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 3b3884e68e185..e89eecfe0874c 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -159,14 +159,17 @@ Changelog\n - |Fix| Fixes incorrect multiple data-conversion warnings when clustering\n boolean data. :pr:`19046` by :user:`Surya Prakash `.\n \n-:mod:`sklearn.decomposition`\n-............................\n-\n - |Fix| Fixed :func:`dict_learning`, used by :class:`DictionaryLearning`, to\n ensure determinism of the output. Achieved by flipping signs of the SVD\n output which is used to initialize the code.\n :pr:`18433` by :user:`Bruno Charron `.\n \n+- |Enhancement| added a new approximate solver (randomized SVD, available with\n+ `eigen_solver='randomized'`) to :class:`decomposition.KernelPCA`. This\n+ significantly accelerates computation when the number of samples is much\n+ larger than the desired number of components.\n+ :pr:`12069` by :user:`Sylvain Mari\u00e9 `.\n+\n - |Fix| Fixed a bug in :class:`MiniBatchDictionaryLearning`,\n :class:`MiniBatchSparsePCA` and :func:`dict_learning_online` where the\n update of the dictionary was incorrect. :pr:`19198` by\n@@ -389,8 +392,8 @@ Changelog\n supporting sparse matrix and raise the appropriate error message.\n :pr:`19879` by :user:`Guillaume Lemaitre `.\n \n-- |Efficiency| Changed ``algorithm`` argument for :class:`cluster.KMeans` in \n- :class:`preprocessing.KBinsDiscretizer` from ``auto`` to ``full``. \n+- |Efficiency| Changed ``algorithm`` argument for :class:`cluster.KMeans` in\n+ :class:`preprocessing.KBinsDiscretizer` from ``auto`` to ``full``.\n :pr:`19934` by :user:`Gleb Levitskiy `.\n \n :mod:`sklearn.tree`\ndiff --git a/sklearn/decomposition/_kernel_pca.py b/sklearn/decomposition/_kernel_pca.py\nindex 415ee034c1769..8663193a8383e 100644\n--- a/sklearn/decomposition/_kernel_pca.py\n+++ b/sklearn/decomposition/_kernel_pca.py\n@@ -1,6 +1,7 @@\n \"\"\"Kernel Principal Components Analysis.\"\"\"\n \n # Author: Mathieu Blondel \n+# Sylvain Marie \n # License: BSD 3 clause\n \n import numpy as np\n@@ -8,7 +9,7 @@\n from scipy.sparse.linalg import eigsh\n \n from ..utils._arpack import _init_arpack_v0\n-from ..utils.extmath import svd_flip\n+from ..utils.extmath import svd_flip, _randomized_eigsh\n from ..utils.validation import check_is_fitted, _check_psd_eigenvalues\n from ..utils.deprecation import deprecated\n from ..exceptions import NotFittedError\n@@ -24,6 +25,12 @@ class KernelPCA(TransformerMixin, BaseEstimator):\n Non-linear dimensionality reduction through the use of kernels (see\n :ref:`metrics`).\n \n+ It uses the `scipy.linalg.eigh` LAPACK implementation of the full SVD or\n+ the `scipy.sparse.linalg.eigsh` ARPACK implementation of the truncated SVD,\n+ depending on the shape of the input data and the number of components to\n+ extract. It can also use a randomized truncated SVD by the method of\n+ Halko et al. 2009, see `eigen_solver`.\n+\n Read more in the :ref:`User Guide `.\n \n Parameters\n@@ -59,10 +66,37 @@ class KernelPCA(TransformerMixin, BaseEstimator):\n Learn the inverse transform for non-precomputed kernels.\n (i.e. learn to find the pre-image of a point)\n \n- eigen_solver : {'auto', 'dense', 'arpack'}, default='auto'\n- Select eigensolver to use. If n_components is much less than\n- the number of training samples, arpack may be more efficient\n- than the dense eigensolver.\n+ eigen_solver : {'auto', 'dense', 'arpack', 'randomized'}, \\\n+ default='auto'\n+ Select eigensolver to use. If `n_components` is much\n+ less than the number of training samples, randomized (or arpack to a\n+ smaller extend) may be more efficient than the dense eigensolver.\n+ Randomized SVD is performed according to the method of Halko et al.\n+\n+ auto :\n+ the solver is selected by a default policy based on n_samples\n+ (the number of training samples) and `n_components`:\n+ if the number of components to extract is less than 10 (strict) and\n+ the number of samples is more than 200 (strict), the 'arpack'\n+ method is enabled. Otherwise the exact full eigenvalue\n+ decomposition is computed and optionally truncated afterwards\n+ ('dense' method).\n+ dense :\n+ run exact full eigenvalue decomposition calling the standard\n+ LAPACK solver via `scipy.linalg.eigh`, and select the components\n+ by postprocessing\n+ arpack :\n+ run SVD truncated to n_components calling ARPACK solver using\n+ `scipy.sparse.linalg.eigsh`. It requires strictly\n+ 0 < n_components < n_samples\n+ randomized :\n+ run randomized SVD by the method of Halko et al. The current\n+ implementation selects eigenvalues based on their module; therefore\n+ using this method can lead to unexpected results if the kernel is\n+ not positive semi-definite.\n+\n+ .. versionchanged:: 1.0\n+ `'randomized'` was added.\n \n tol : float, default=0\n Convergence tolerance for arpack.\n@@ -72,6 +106,13 @@ class KernelPCA(TransformerMixin, BaseEstimator):\n Maximum number of iterations for arpack.\n If None, optimal value will be chosen by arpack.\n \n+ iterated_power : int >= 0, or 'auto', default='auto'\n+ Number of iterations for the power method computed by\n+ svd_solver == 'randomized'. When 'auto', it is set to 7 when\n+ `n_components < 0.1 * min(X.shape)`, other it is set to 4.\n+\n+ .. versionadded:: 1.0\n+\n remove_zero_eig : bool, default=False\n If True, then all components with zero eigenvalues are removed, so\n that the number of components in the output may be < n_components\n@@ -80,8 +121,8 @@ class KernelPCA(TransformerMixin, BaseEstimator):\n with zero eigenvalues are removed regardless.\n \n random_state : int, RandomState instance or None, default=None\n- Used when ``eigen_solver`` == 'arpack'. Pass an int for reproducible\n- results across multiple function calls.\n+ Used when ``eigen_solver`` == 'arpack' or 'randomized'. Pass an int\n+ for reproducible results across multiple function calls.\n See :term:`Glossary `.\n \n .. versionadded:: 0.18\n@@ -141,12 +182,22 @@ class KernelPCA(TransformerMixin, BaseEstimator):\n and Klaus-Robert Mueller. 1999. Kernel principal\n component analysis. In Advances in kernel methods,\n MIT Press, Cambridge, MA, USA 327-352.\n+\n+ For eigen_solver == 'arpack', refer to `scipy.sparse.linalg.eigsh`.\n+\n+ For eigen_solver == 'randomized', see:\n+ Finding structure with randomness: Stochastic algorithms\n+ for constructing approximate matrix decompositions Halko, et al., 2009\n+ (arXiv:909)\n+ A randomized algorithm for the decomposition of matrices\n+ Per-Gunnar Martinsson, Vladimir Rokhlin and Mark Tygert\n \"\"\"\n @_deprecate_positional_args\n def __init__(self, n_components=None, *, kernel=\"linear\",\n gamma=None, degree=3, coef0=1, kernel_params=None,\n alpha=1.0, fit_inverse_transform=False, eigen_solver='auto',\n- tol=0, max_iter=None, remove_zero_eig=False,\n+ tol=0, max_iter=None, iterated_power='auto',\n+ remove_zero_eig=False,\n random_state=None, copy_X=True, n_jobs=None):\n if fit_inverse_transform and kernel == 'precomputed':\n raise ValueError(\n@@ -160,9 +211,10 @@ def __init__(self, n_components=None, *, kernel=\"linear\",\n self.alpha = alpha\n self.fit_inverse_transform = fit_inverse_transform\n self.eigen_solver = eigen_solver\n- self.remove_zero_eig = remove_zero_eig\n self.tol = tol\n self.max_iter = max_iter\n+ self.iterated_power = iterated_power\n+ self.remove_zero_eig = remove_zero_eig\n self.random_state = random_state\n self.n_jobs = n_jobs\n self.copy_X = copy_X\n@@ -191,9 +243,14 @@ def _fit_transform(self, K):\n # center kernel\n K = self._centerer.fit_transform(K)\n \n+ # adjust n_components according to user inputs\n if self.n_components is None:\n- n_components = K.shape[0]\n+ n_components = K.shape[0] # use all dimensions\n else:\n+ if self.n_components < 1:\n+ raise ValueError(\n+ f\"`n_components` should be >= 1, got: {self.n_component}\"\n+ )\n n_components = min(K.shape[0], self.n_components)\n \n # compute eigenvectors\n@@ -206,6 +263,7 @@ def _fit_transform(self, K):\n eigen_solver = self.eigen_solver\n \n if eigen_solver == 'dense':\n+ # Note: eigvals specifies the indices of smallest/largest to return\n self.lambdas_, self.alphas_ = linalg.eigh(\n K, eigvals=(K.shape[0] - n_components, K.shape[0] - 1))\n elif eigen_solver == 'arpack':\n@@ -215,6 +273,14 @@ def _fit_transform(self, K):\n tol=self.tol,\n maxiter=self.max_iter,\n v0=v0)\n+ elif eigen_solver == 'randomized':\n+ self.lambdas_, self.alphas_ = _randomized_eigsh(\n+ K, n_components=n_components, n_iter=self.iterated_power,\n+ random_state=self.random_state, selection='module'\n+ )\n+ else:\n+ raise ValueError(\"Unsupported value for `eigen_solver`: %r\"\n+ % eigen_solver)\n \n # make sure that the eigenvalues are ok and fix numerical issues\n self.lambdas_ = _check_psd_eigenvalues(self.lambdas_,\ndiff --git a/sklearn/utils/extmath.py b/sklearn/utils/extmath.py\nindex add8c5883a751..c72c54bd1aa4d 100644\n--- a/sklearn/utils/extmath.py\n+++ b/sklearn/utils/extmath.py\n@@ -249,6 +249,9 @@ def randomized_svd(M, n_components, *, n_oversamples=10, n_iter='auto',\n flip_sign=True, random_state='warn'):\n \"\"\"Computes a truncated randomized SVD.\n \n+ This method solves the fixed-rank approximation problem described in the\n+ Halko et al paper (problem (1.5), p5).\n+\n Parameters\n ----------\n M : {ndarray, sparse matrix}\n@@ -262,13 +265,23 @@ def randomized_svd(M, n_components, *, n_oversamples=10, n_iter='auto',\n to ensure proper conditioning. The total number of random vectors\n used to find the range of M is n_components + n_oversamples. Smaller\n number can improve speed but can negatively impact the quality of\n- approximation of singular vectors and singular values.\n+ approximation of singular vectors and singular values. Users might wish\n+ to increase this parameter up to `2*k - n_components` where k is the\n+ effective rank, for large matrices, noisy problems, matrices with\n+ slowly decaying spectrums, or to increase precision accuracy. See Halko\n+ et al (pages 5, 23 and 26).\n \n n_iter : int or 'auto', default='auto'\n Number of power iterations. It can be used to deal with very noisy\n problems. When 'auto', it is set to 4, unless `n_components` is small\n- (< .1 * min(X.shape)) `n_iter` in which case is set to 7.\n- This improves precision with few components.\n+ (< .1 * min(X.shape)) in which case `n_iter` is set to 7.\n+ This improves precision with few components. Note that in general\n+ users should rather increase `n_oversamples` before increasing `n_iter`\n+ as the principle of the randomized method is to avoid usage of these\n+ more costly power iterations steps. When `n_components` is equal\n+ or greater to the effective matrix rank and the spectrum does not\n+ present a slow decay, `n_iter=0` or `1` should even work fine in theory\n+ (see Halko et al paper, page 9).\n \n .. versionchanged:: 0.18\n \n@@ -316,12 +329,15 @@ def randomized_svd(M, n_components, *, n_oversamples=10, n_iter='auto',\n computations. It is particularly fast on large matrices on which\n you wish to extract only a small number of components. In order to\n obtain further speed up, `n_iter` can be set <=2 (at the cost of\n- loss of precision).\n+ loss of precision). To increase the precision it is recommended to\n+ increase `n_oversamples`, up to `2*k-n_components` where k is the\n+ effective rank. Usually, `n_components` is chosen to be greater than k\n+ so increasing `n_oversamples` up to `n_components` should be enough.\n \n References\n ----------\n * Finding structure with randomness: Stochastic algorithms for constructing\n- approximate matrix decompositions\n+ approximate matrix decompositions (Algorithm 4.3)\n Halko, et al., 2009 https://arxiv.org/abs/0909.4061\n \n * A randomized algorithm for the decomposition of matrices\n@@ -393,6 +409,152 @@ def randomized_svd(M, n_components, *, n_oversamples=10, n_iter='auto',\n return U[:, :n_components], s[:n_components], Vt[:n_components, :]\n \n \n+@_deprecate_positional_args\n+def _randomized_eigsh(M, n_components, *, n_oversamples=10, n_iter='auto',\n+ power_iteration_normalizer='auto',\n+ selection='module', random_state=None):\n+ \"\"\"Computes a truncated eigendecomposition using randomized methods\n+\n+ This method solves the fixed-rank approximation problem described in the\n+ Halko et al paper.\n+\n+ The choice of which components to select can be tuned with the `selection`\n+ parameter.\n+\n+ .. versionadded:: 0.24\n+\n+ Parameters\n+ ----------\n+ M : ndarray or sparse matrix\n+ Matrix to decompose, it should be real symmetric square or complex\n+ hermitian\n+\n+ n_components : int\n+ Number of eigenvalues and vectors to extract.\n+\n+ n_oversamples : int, default=10\n+ Additional number of random vectors to sample the range of M so as\n+ to ensure proper conditioning. The total number of random vectors\n+ used to find the range of M is n_components + n_oversamples. Smaller\n+ number can improve speed but can negatively impact the quality of\n+ approximation of eigenvectors and eigenvalues. Users might wish\n+ to increase this parameter up to `2*k - n_components` where k is the\n+ effective rank, for large matrices, noisy problems, matrices with\n+ slowly decaying spectrums, or to increase precision accuracy. See Halko\n+ et al (pages 5, 23 and 26).\n+\n+ n_iter : int or 'auto', default='auto'\n+ Number of power iterations. It can be used to deal with very noisy\n+ problems. When 'auto', it is set to 4, unless `n_components` is small\n+ (< .1 * min(X.shape)) in which case `n_iter` is set to 7.\n+ This improves precision with few components. Note that in general\n+ users should rather increase `n_oversamples` before increasing `n_iter`\n+ as the principle of the randomized method is to avoid usage of these\n+ more costly power iterations steps. When `n_components` is equal\n+ or greater to the effective matrix rank and the spectrum does not\n+ present a slow decay, `n_iter=0` or `1` should even work fine in theory\n+ (see Halko et al paper, page 9).\n+\n+ power_iteration_normalizer : {'auto', 'QR', 'LU', 'none'}, default='auto'\n+ Whether the power iterations are normalized with step-by-step\n+ QR factorization (the slowest but most accurate), 'none'\n+ (the fastest but numerically unstable when `n_iter` is large, e.g.\n+ typically 5 or larger), or 'LU' factorization (numerically stable\n+ but can lose slightly in accuracy). The 'auto' mode applies no\n+ normalization if `n_iter` <= 2 and switches to LU otherwise.\n+\n+ selection : {'value', 'module'}, default='module'\n+ Strategy used to select the n components. When `selection` is `'value'`\n+ (not yet implemented, will become the default when implemented), the\n+ components corresponding to the n largest eigenvalues are returned.\n+ When `selection` is `'module'`, the components corresponding to the n\n+ eigenvalues with largest modules are returned.\n+\n+ random_state : int, RandomState instance, default=None\n+ The seed of the pseudo random number generator to use when shuffling\n+ the data, i.e. getting the random vectors to initialize the algorithm.\n+ Pass an int for reproducible results across multiple function calls.\n+ See :term:`Glossary `.\n+\n+ Notes\n+ -----\n+ This algorithm finds a (usually very good) approximate truncated\n+ eigendecomposition using randomized methods to speed up the computations.\n+\n+ This method is particularly fast on large matrices on which\n+ you wish to extract only a small number of components. In order to\n+ obtain further speed up, `n_iter` can be set <=2 (at the cost of\n+ loss of precision). To increase the precision it is recommended to\n+ increase `n_oversamples`, up to `2*k-n_components` where k is the\n+ effective rank. Usually, `n_components` is chosen to be greater than k\n+ so increasing `n_oversamples` up to `n_components` should be enough.\n+\n+ Strategy 'value': not implemented yet.\n+ Algorithms 5.3, 5.4 and 5.5 in the Halko et al paper should provide good\n+ condidates for a future implementation.\n+\n+ Strategy 'module':\n+ The principle is that for diagonalizable matrices, the singular values and\n+ eigenvalues are related: if t is an eigenvalue of A, then :math:`|t|` is a\n+ singular value of A. This method relies on a randomized SVD to find the n\n+ singular components corresponding to the n singular values with largest\n+ modules, and then uses the signs of the singular vectors to find the true\n+ sign of t: if the sign of left and right singular vectors are different\n+ then the corresponding eigenvalue is negative.\n+\n+ Returns\n+ -------\n+ eigvals : 1D array of shape (n_components,) containing the `n_components`\n+ eigenvalues selected (see ``selection`` parameter).\n+ eigvecs : 2D array of shape (M.shape[0], n_components) containing the\n+ `n_components` eigenvectors corresponding to the `eigvals`, in the\n+ corresponding order. Note that this follows the `scipy.linalg.eigh`\n+ convention.\n+\n+ See Also\n+ --------\n+ :func:`randomized_svd`\n+\n+ References\n+ ----------\n+ * Finding structure with randomness: Stochastic algorithms for constructing\n+ approximate matrix decompositions (Algorithm 4.3 for strategy 'module')\n+ Halko, et al., 2009 https://arxiv.org/abs/0909.4061\n+\n+ \"\"\"\n+ if selection == 'value': # pragma: no cover\n+ # to do : an algorithm can be found in the Halko et al reference\n+ raise NotImplementedError()\n+\n+ elif selection == 'module':\n+ # Note: no need for deterministic U and Vt (flip_sign=True),\n+ # as we only use the dot product UVt afterwards\n+ U, S, Vt = randomized_svd(\n+ M, n_components=n_components, n_oversamples=n_oversamples,\n+ n_iter=n_iter,\n+ power_iteration_normalizer=power_iteration_normalizer,\n+ flip_sign=False, random_state=random_state)\n+\n+ eigvecs = U[:, :n_components]\n+ eigvals = S[:n_components]\n+\n+ # Conversion of Singular values into Eigenvalues:\n+ # For any eigenvalue t, the corresponding singular value is |t|.\n+ # So if there is a negative eigenvalue t, the corresponding singular\n+ # value will be -t, and the left (U) and right (V) singular vectors\n+ # will have opposite signs.\n+ # Fastest way: see \n+ diag_VtU = np.einsum('ji,ij->j',\n+ Vt[:n_components, :], U[:, :n_components])\n+ signs = np.sign(diag_VtU)\n+ eigvals = eigvals * signs\n+\n+ else: # pragma: no cover\n+ raise ValueError(\"Invalid `selection`: %r\" % selection)\n+\n+ return eigvals, eigvecs\n+\n+\n @_deprecate_positional_args\n def weighted_mode(a, w, *, axis=0):\n \"\"\"Returns an array of the weighted modal (most common) value in a.\n", "test_patch": "diff --git a/sklearn/decomposition/tests/test_kernel_pca.py b/sklearn/decomposition/tests/test_kernel_pca.py\nindex adf68f1db1a6c..5c8d052a7aa14 100644\n--- a/sklearn/decomposition/tests/test_kernel_pca.py\n+++ b/sklearn/decomposition/tests/test_kernel_pca.py\n@@ -3,11 +3,13 @@\n import pytest\n \n from sklearn.utils._testing import (assert_array_almost_equal,\n- assert_allclose)\n+ assert_array_equal,\n+ assert_allclose)\n \n from sklearn.decomposition import PCA, KernelPCA\n from sklearn.datasets import make_circles\n from sklearn.datasets import make_blobs\n+from sklearn.exceptions import NotFittedError\n from sklearn.linear_model import Perceptron\n from sklearn.pipeline import Pipeline\n from sklearn.preprocessing import StandardScaler\n@@ -17,6 +19,12 @@\n \n \n def test_kernel_pca():\n+ \"\"\"Nominal test for all solvers and all known kernels + a custom one\n+\n+ It tests\n+ - that fit_transform is equivalent to fit+transform\n+ - that the shapes of transforms and inverse transforms are correct\n+ \"\"\"\n rng = np.random.RandomState(0)\n X_fit = rng.random_sample((5, 4))\n X_pred = rng.random_sample((2, 4))\n@@ -26,7 +34,7 @@ def histogram(x, y, **kwargs):\n assert kwargs == {} # no kernel_params that we didn't ask for\n return np.minimum(x, y).sum()\n \n- for eigen_solver in (\"auto\", \"dense\", \"arpack\"):\n+ for eigen_solver in (\"auto\", \"dense\", \"arpack\", \"randomized\"):\n for kernel in (\"linear\", \"rbf\", \"poly\", histogram):\n # histogram kernel produces singular matrix inside linalg.solve\n # XXX use a least-squares approximation?\n@@ -55,12 +63,31 @@ def histogram(x, y, **kwargs):\n assert X_pred2.shape == X_pred.shape\n \n \n+def test_kernel_pca_invalid_solver():\n+ \"\"\"Check that kPCA raises an error if the solver parameter is invalid\n+\n+ \"\"\"\n+ with pytest.raises(ValueError):\n+ KernelPCA(eigen_solver=\"unknown\").fit(np.random.randn(10, 10))\n+\n+\n def test_kernel_pca_invalid_parameters():\n+ \"\"\"Check that kPCA raises an error if the parameters are invalid\n+\n+ Tests fitting inverse transform with a precomputed kernel raises a\n+ ValueError.\n+ \"\"\"\n with pytest.raises(ValueError):\n KernelPCA(10, fit_inverse_transform=True, kernel='precomputed')\n \n \n def test_kernel_pca_consistent_transform():\n+ \"\"\"Check robustness to mutations in the original training array\n+\n+ Test that after fitting a kPCA model, it stays independent of any\n+ mutation of the values of the original data object by relying on an\n+ internal copy.\n+ \"\"\"\n # X_fit_ needs to retain the old, unmodified copy of X\n state = np.random.RandomState(0)\n X = state.rand(10, 10)\n@@ -74,6 +101,10 @@ def test_kernel_pca_consistent_transform():\n \n \n def test_kernel_pca_deterministic_output():\n+ \"\"\"Test that Kernel PCA produces deterministic output\n+\n+ Tests that the same inputs and random state produce the same output.\n+ \"\"\"\n rng = np.random.RandomState(0)\n X = rng.rand(10, 10)\n eigen_solver = ('arpack', 'dense')\n@@ -89,15 +120,20 @@ def test_kernel_pca_deterministic_output():\n \n \n def test_kernel_pca_sparse():\n+ \"\"\"Test that kPCA works on a sparse data input.\n+\n+ Same test as ``test_kernel_pca except inverse_transform`` since it's not\n+ implemented for sparse matrices.\n+ \"\"\"\n rng = np.random.RandomState(0)\n X_fit = sp.csr_matrix(rng.random_sample((5, 4)))\n X_pred = sp.csr_matrix(rng.random_sample((2, 4)))\n \n- for eigen_solver in (\"auto\", \"arpack\"):\n+ for eigen_solver in (\"auto\", \"arpack\", \"randomized\"):\n for kernel in (\"linear\", \"rbf\", \"poly\"):\n # transform fit data\n kpca = KernelPCA(4, kernel=kernel, eigen_solver=eigen_solver,\n- fit_inverse_transform=False)\n+ fit_inverse_transform=False, random_state=0)\n X_fit_transformed = kpca.fit_transform(X_fit)\n X_fit_transformed2 = kpca.fit(X_fit).transform(X_fit)\n assert_array_almost_equal(np.abs(X_fit_transformed),\n@@ -108,31 +144,47 @@ def test_kernel_pca_sparse():\n assert (X_pred_transformed.shape[1] ==\n X_fit_transformed.shape[1])\n \n- # inverse transform\n- # X_pred2 = kpca.inverse_transform(X_pred_transformed)\n- # assert X_pred2.shape == X_pred.shape)\n+ # inverse transform: not available for sparse matrices\n+ # XXX: should we raise another exception type here? For instance:\n+ # NotImplementedError.\n+ with pytest.raises(NotFittedError):\n+ kpca.inverse_transform(X_pred_transformed)\n \n \n-def test_kernel_pca_linear_kernel():\n+@pytest.mark.parametrize(\"solver\", [\"auto\", \"dense\", \"arpack\", \"randomized\"])\n+@pytest.mark.parametrize(\"n_features\", [4, 10])\n+def test_kernel_pca_linear_kernel(solver, n_features):\n+ \"\"\"Test that kPCA with linear kernel is equivalent to PCA for all solvers.\n+\n+ KernelPCA with linear kernel should produce the same output as PCA.\n+ \"\"\"\n rng = np.random.RandomState(0)\n- X_fit = rng.random_sample((5, 4))\n- X_pred = rng.random_sample((2, 4))\n+ X_fit = rng.random_sample((5, n_features))\n+ X_pred = rng.random_sample((2, n_features))\n \n # for a linear kernel, kernel PCA should find the same projection as PCA\n # modulo the sign (direction)\n # fit only the first four components: fifth is near zero eigenvalue, so\n # can be trimmed due to roundoff error\n+ n_comps = 3 if solver == \"arpack\" else 4\n assert_array_almost_equal(\n- np.abs(KernelPCA(4).fit(X_fit).transform(X_pred)),\n- np.abs(PCA(4).fit(X_fit).transform(X_pred)))\n+ np.abs(KernelPCA(n_comps, eigen_solver=solver).fit(X_fit)\n+ .transform(X_pred)),\n+ np.abs(PCA(n_comps, svd_solver=solver if solver != \"dense\" else \"full\")\n+ .fit(X_fit).transform(X_pred)))\n \n \n def test_kernel_pca_n_components():\n+ \"\"\"Test that `n_components` is correctly taken into account for projections\n+\n+ For all solvers this tests that the output has the correct shape depending\n+ on the selected number of components.\n+ \"\"\"\n rng = np.random.RandomState(0)\n X_fit = rng.random_sample((5, 4))\n X_pred = rng.random_sample((2, 4))\n \n- for eigen_solver in (\"dense\", \"arpack\"):\n+ for eigen_solver in (\"dense\", \"arpack\", \"randomized\"):\n for c in [1, 2, 4]:\n kpca = KernelPCA(n_components=c, eigen_solver=eigen_solver)\n shape = kpca.fit(X_fit).transform(X_pred).shape\n@@ -141,6 +193,11 @@ def test_kernel_pca_n_components():\n \n \n def test_remove_zero_eig():\n+ \"\"\"Check that the ``remove_zero_eig`` parameter works correctly.\n+\n+ Tests that the null-space (Zero) eigenvalues are removed when\n+ remove_zero_eig=True, whereas they are not by default.\n+ \"\"\"\n X = np.array([[1 - 1e-30, 1], [1, 1], [1, 1 - 1e-20]])\n \n # n_components=None (default) => remove_zero_eig is True\n@@ -158,9 +215,11 @@ def test_remove_zero_eig():\n \n \n def test_leave_zero_eig():\n- \"\"\"This test checks that fit().transform() returns the same result as\n+ \"\"\"Non-regression test for issue #12141 (PR #12143)\n+\n+ This test checks that fit().transform() returns the same result as\n fit_transform() in case of non-removed zero eigenvalue.\n- Non-regression test for issue #12141 (PR #12143)\"\"\"\n+ \"\"\"\n X_fit = np.array([[1, 1], [0, 0]])\n \n # Assert that even with all np warnings on, there is no div by zero warning\n@@ -184,23 +243,29 @@ def test_leave_zero_eig():\n \n \n def test_kernel_pca_precomputed():\n+ \"\"\"Test that kPCA works with a precomputed kernel, for all solvers\n+\n+ \"\"\"\n rng = np.random.RandomState(0)\n X_fit = rng.random_sample((5, 4))\n X_pred = rng.random_sample((2, 4))\n \n- for eigen_solver in (\"dense\", \"arpack\"):\n- X_kpca = KernelPCA(4, eigen_solver=eigen_solver).\\\n- fit(X_fit).transform(X_pred)\n+ for eigen_solver in (\"dense\", \"arpack\", \"randomized\"):\n+ X_kpca = KernelPCA(\n+ 4, eigen_solver=eigen_solver, random_state=0\n+ ).fit(X_fit).transform(X_pred)\n+\n X_kpca2 = KernelPCA(\n- 4, eigen_solver=eigen_solver, kernel='precomputed').fit(\n- np.dot(X_fit, X_fit.T)).transform(np.dot(X_pred, X_fit.T))\n+ 4, eigen_solver=eigen_solver, kernel='precomputed', random_state=0\n+ ).fit(np.dot(X_fit, X_fit.T)).transform(np.dot(X_pred, X_fit.T))\n \n X_kpca_train = KernelPCA(\n- 4, eigen_solver=eigen_solver,\n- kernel='precomputed').fit_transform(np.dot(X_fit, X_fit.T))\n+ 4, eigen_solver=eigen_solver, kernel='precomputed', random_state=0\n+ ).fit_transform(np.dot(X_fit, X_fit.T))\n+\n X_kpca_train2 = KernelPCA(\n- 4, eigen_solver=eigen_solver, kernel='precomputed').fit(\n- np.dot(X_fit, X_fit.T)).transform(np.dot(X_fit, X_fit.T))\n+ 4, eigen_solver=eigen_solver, kernel='precomputed', random_state=0\n+ ).fit(np.dot(X_fit, X_fit.T)).transform(np.dot(X_fit, X_fit.T))\n \n assert_array_almost_equal(np.abs(X_kpca),\n np.abs(X_kpca2))\n@@ -209,7 +274,42 @@ def test_kernel_pca_precomputed():\n np.abs(X_kpca_train2))\n \n \n+@pytest.mark.parametrize(\"solver\", [\"auto\", \"dense\", \"arpack\", \"randomized\"])\n+def test_kernel_pca_precomputed_non_symmetric(solver):\n+ \"\"\"Check that the kernel centerer works.\n+\n+ Tests that a non symmetric precomputed kernel is actually accepted\n+ because the kernel centerer does its job correctly.\n+ \"\"\"\n+\n+ # a non symmetric gram matrix\n+ K = [\n+ [1, 2],\n+ [3, 40]\n+ ]\n+ kpca = KernelPCA(kernel=\"precomputed\", eigen_solver=solver,\n+ n_components=1, random_state=0)\n+ kpca.fit(K) # no error\n+\n+ # same test with centered kernel\n+ Kc = [\n+ [9, -9],\n+ [-9, 9]\n+ ]\n+ kpca_c = KernelPCA(kernel=\"precomputed\", eigen_solver=solver,\n+ n_components=1, random_state=0)\n+ kpca_c.fit(Kc)\n+\n+ # comparison between the non-centered and centered versions\n+ assert_array_equal(kpca.alphas_, kpca_c.alphas_)\n+ assert_array_equal(kpca.lambdas_, kpca_c.lambdas_)\n+\n+\n def test_kernel_pca_invalid_kernel():\n+ \"\"\"Tests that using an invalid kernel name raises a ValueError\n+\n+ An invalid kernel name should raise a ValueError at fit time.\n+ \"\"\"\n rng = np.random.RandomState(0)\n X_fit = rng.random_sample((2, 4))\n kpca = KernelPCA(kernel=\"tototiti\")\n@@ -218,8 +318,11 @@ def test_kernel_pca_invalid_kernel():\n \n \n def test_gridsearch_pipeline():\n- # Test if we can do a grid-search to find parameters to separate\n- # circles with a perceptron model.\n+ \"\"\"Check that kPCA works as expected in a grid search pipeline\n+\n+ Test if we can do a grid-search to find parameters to separate\n+ circles with a perceptron model.\n+ \"\"\"\n X, y = make_circles(n_samples=400, factor=.3, noise=.05,\n random_state=0)\n kpca = KernelPCA(kernel=\"rbf\", n_components=2)\n@@ -232,8 +335,11 @@ def test_gridsearch_pipeline():\n \n \n def test_gridsearch_pipeline_precomputed():\n- # Test if we can do a grid-search to find parameters to separate\n- # circles with a perceptron model using a precomputed kernel.\n+ \"\"\"Check that kPCA works as expected in a grid search pipeline (2)\n+\n+ Test if we can do a grid-search to find parameters to separate\n+ circles with a perceptron model. This test uses a precomputed kernel.\n+ \"\"\"\n X, y = make_circles(n_samples=400, factor=.3, noise=.05,\n random_state=0)\n kpca = KernelPCA(kernel=\"precomputed\", n_components=2)\n@@ -247,7 +353,12 @@ def test_gridsearch_pipeline_precomputed():\n \n \n def test_nested_circles():\n- # Test the linear separability of the first 2D KPCA transform\n+ \"\"\"Check that kPCA projects in a space where nested circles are separable\n+\n+ Tests that 2D nested circles become separable with a perceptron when\n+ projected in the first 2 kPCA using an RBF kernel, while raw samples\n+ are not directly separable in the original space.\n+ \"\"\"\n X, y = make_circles(n_samples=400, factor=.3, noise=.05,\n random_state=0)\n \n@@ -270,8 +381,10 @@ def test_nested_circles():\n \n \n def test_kernel_conditioning():\n- \"\"\" Test that ``_check_psd_eigenvalues`` is correctly called\n- Non-regression test for issue #12140 (PR #12145)\"\"\"\n+ \"\"\"Check that ``_check_psd_eigenvalues`` is correctly called in kPCA\n+\n+ Non-regression test for issue #12140 (PR #12145).\n+ \"\"\"\n \n # create a pathological X leading to small non-zero eigenvalue\n X = [[5, 1],\n@@ -286,11 +399,93 @@ def test_kernel_conditioning():\n assert np.all(kpca.lambdas_ == _check_psd_eigenvalues(kpca.lambdas_))\n \n \n+@pytest.mark.parametrize(\"solver\", [\"auto\", \"dense\", \"arpack\", \"randomized\"])\n+def test_precomputed_kernel_not_psd(solver):\n+ \"\"\"Check how KernelPCA works with non-PSD kernels depending on n_components\n+\n+ Tests for all methods what happens with a non PSD gram matrix (this\n+ can happen in an isomap scenario, or with custom kernel functions, or\n+ maybe with ill-posed datasets).\n+\n+ When ``n_component`` is large enough to capture a negative eigenvalue, an\n+ error should be raised. Otherwise, KernelPCA should run without error\n+ since the negative eigenvalues are not selected.\n+ \"\"\"\n+\n+ # a non PSD kernel with large eigenvalues, already centered\n+ # it was captured from an isomap call and multiplied by 100 for compacity\n+ K = [\n+ [4.48, -1., 8.07, 2.33, 2.33, 2.33, -5.76, -12.78],\n+ [-1., -6.48, 4.5, -1.24, -1.24, -1.24, -0.81, 7.49],\n+ [8.07, 4.5, 15.48, 2.09, 2.09, 2.09, -11.1, -23.23],\n+ [2.33, -1.24, 2.09, 4., -3.65, -3.65, 1.02, -0.9],\n+ [2.33, -1.24, 2.09, -3.65, 4., -3.65, 1.02, -0.9],\n+ [2.33, -1.24, 2.09, -3.65, -3.65, 4., 1.02, -0.9],\n+ [-5.76, -0.81, -11.1, 1.02, 1.02, 1.02, 4.86, 9.75],\n+ [-12.78, 7.49, -23.23, -0.9, -0.9, -0.9, 9.75, 21.46]\n+ ]\n+ # this gram matrix has 5 positive eigenvalues and 3 negative ones\n+ # [ 52.72, 7.65, 7.65, 5.02, 0. , -0. , -6.13, -15.11]\n+\n+ # 1. ask for enough components to get a significant negative one\n+ kpca = KernelPCA(kernel=\"precomputed\", eigen_solver=solver, n_components=7)\n+ # make sure that the appropriate error is raised\n+ with pytest.raises(ValueError,\n+ match=\"There are significant negative eigenvalues\"):\n+ kpca.fit(K)\n+\n+ # 2. ask for a small enough n_components to get only positive ones\n+ kpca = KernelPCA(kernel=\"precomputed\", eigen_solver=solver, n_components=2)\n+ if solver == 'randomized':\n+ # the randomized method is still inconsistent with the others on this\n+ # since it selects the eigenvalues based on the largest 2 modules, not\n+ # on the largest 2 values.\n+ #\n+ # At least we can ensure that we return an error instead of returning\n+ # the wrong eigenvalues\n+ with pytest.raises(ValueError,\n+ match=\"There are significant negative eigenvalues\"):\n+ kpca.fit(K)\n+ else:\n+ # general case: make sure that it works\n+ kpca.fit(K)\n+\n+\n+@pytest.mark.parametrize(\"n_components\", [4, 10, 20])\n+def test_kernel_pca_solvers_equivalence(n_components):\n+ \"\"\"Check that 'dense' 'arpack' & 'randomized' solvers give similar results\n+ \"\"\"\n+\n+ # Generate random data\n+ n_train, n_test = 2000, 100\n+ X, _ = make_circles(n_samples=(n_train + n_test), factor=.3, noise=.05,\n+ random_state=0)\n+ X_fit, X_pred = X[:n_train, :], X[n_train:, :]\n+\n+ # reference (full)\n+ ref_pred = KernelPCA(n_components, eigen_solver=\"dense\", random_state=0\n+ ).fit(X_fit).transform(X_pred)\n+\n+ # arpack\n+ a_pred = KernelPCA(n_components, eigen_solver=\"arpack\", random_state=0\n+ ).fit(X_fit).transform(X_pred)\n+ # check that the result is still correct despite the approx\n+ assert_array_almost_equal(np.abs(a_pred), np.abs(ref_pred))\n+\n+ # randomized\n+ r_pred = KernelPCA(n_components, eigen_solver=\"randomized\", random_state=0\n+ ).fit(X_fit).transform(X_pred)\n+ # check that the result is still correct despite the approximation\n+ assert_array_almost_equal(np.abs(r_pred), np.abs(ref_pred))\n+\n+\n def test_kernel_pca_inverse_transform_reconstruction():\n- # Test if the reconstruction is a good approximation.\n- # Note that in general it is not possible to get an arbitrarily good\n- # reconstruction because of kernel centering that does not\n- # preserve all the information of the original data.\n+ \"\"\"Test if the reconstruction is a good approximation.\n+\n+ Note that in general it is not possible to get an arbitrarily good\n+ reconstruction because of kernel centering that does not\n+ preserve all the information of the original data.\n+ \"\"\"\n X, *_ = make_blobs(n_samples=100, n_features=4, random_state=0)\n \n kpca = KernelPCA(\n@@ -302,8 +497,11 @@ def test_kernel_pca_inverse_transform_reconstruction():\n \n \n def test_32_64_decomposition_shape():\n- \"\"\" Test that the decomposition is similar for 32 and 64 bits data \"\"\"\n- # see https://github.com/scikit-learn/scikit-learn/issues/18146\n+ \"\"\"Test that the decomposition is similar for 32 and 64 bits data\n+\n+ Non regression test for\n+ https://github.com/scikit-learn/scikit-learn/issues/18146\n+ \"\"\"\n X, y = make_blobs(\n n_samples=30,\n centers=[[0, 0, 0], [1, 1, 1]],\n@@ -321,6 +519,10 @@ def test_32_64_decomposition_shape():\n \n # TODO: Remove in 1.1\n def test_kernel_pcc_pairwise_is_deprecated():\n+ \"\"\"Check that `_pairwise` is correctly marked with deprecation warning\n+\n+ Tests that a `FutureWarning` is issued when `_pairwise` is accessed.\n+ \"\"\"\n kp = KernelPCA(kernel='precomputed')\n msg = r\"Attribute _pairwise was deprecated in version 0\\.24\"\n with pytest.warns(FutureWarning, match=msg):\ndiff --git a/sklearn/utils/tests/test_extmath.py b/sklearn/utils/tests/test_extmath.py\nindex 8e53d94d911f0..1a77d08b12388 100644\n--- a/sklearn/utils/tests/test_extmath.py\n+++ b/sklearn/utils/tests/test_extmath.py\n@@ -8,11 +8,12 @@\n from scipy import sparse\n from scipy import linalg\n from scipy import stats\n+from scipy.sparse.linalg import eigsh\n from scipy.special import expit\n \n import pytest\n from sklearn.utils import gen_batches\n-\n+from sklearn.utils._arpack import _init_arpack_v0\n from sklearn.utils._testing import assert_almost_equal\n from sklearn.utils._testing import assert_allclose\n from sklearn.utils._testing import assert_allclose_dense_sparse\n@@ -23,7 +24,7 @@\n from sklearn.utils._testing import skip_if_32bit\n \n from sklearn.utils.extmath import density, _safe_accumulator_op\n-from sklearn.utils.extmath import randomized_svd\n+from sklearn.utils.extmath import randomized_svd, _randomized_eigsh\n from sklearn.utils.extmath import row_norms\n from sklearn.utils.extmath import weighted_mode\n from sklearn.utils.extmath import cartesian\n@@ -34,7 +35,7 @@\n from sklearn.utils.extmath import softmax\n from sklearn.utils.extmath import stable_cumsum\n from sklearn.utils.extmath import safe_sparse_dot\n-from sklearn.datasets import make_low_rank_matrix\n+from sklearn.datasets import make_low_rank_matrix, make_sparse_spd_matrix\n \n \n def test_density():\n@@ -161,6 +162,128 @@ def test_randomized_svd_low_rank_all_dtypes(dtype):\n check_randomized_svd_low_rank(dtype)\n \n \n+@pytest.mark.parametrize('dtype',\n+ (np.int32, np.int64, np.float32, np.float64))\n+def test_randomized_eigsh(dtype):\n+ \"\"\"Test that `_randomized_eigsh` returns the appropriate components\"\"\"\n+\n+ rng = np.random.RandomState(42)\n+ X = np.diag(np.array([1., -2., 0., 3.], dtype=dtype))\n+ # random rotation that preserves the eigenvalues of X\n+ rand_rot = np.linalg.qr(rng.normal(size=X.shape))[0]\n+ X = rand_rot @ X @ rand_rot.T\n+\n+ # with 'module' selection method, the negative eigenvalue shows up\n+ eigvals, eigvecs = _randomized_eigsh(X, n_components=2, selection='module')\n+ # eigenvalues\n+ assert eigvals.shape == (2,)\n+ assert_array_almost_equal(eigvals, [3., -2.]) # negative eigenvalue here\n+ # eigenvectors\n+ assert eigvecs.shape == (4, 2)\n+\n+ # with 'value' selection method, the negative eigenvalue does not show up\n+ with pytest.raises(NotImplementedError):\n+ _randomized_eigsh(X, n_components=2, selection='value')\n+\n+\n+@pytest.mark.parametrize('k', (10, 50, 100, 199, 200))\n+def test_randomized_eigsh_compared_to_others(k):\n+ \"\"\"Check that `_randomized_eigsh` is similar to other `eigsh`\n+\n+ Tests that for a random PSD matrix, `_randomized_eigsh` provides results\n+ comparable to LAPACK (scipy.linalg.eigh) and ARPACK\n+ (scipy.sparse.linalg.eigsh).\n+\n+ Note: some versions of ARPACK do not support k=n_features.\n+ \"\"\"\n+\n+ # make a random PSD matrix\n+ n_features = 200\n+ X = make_sparse_spd_matrix(n_features, random_state=0)\n+\n+ # compare two versions of randomized\n+ # rough and fast\n+ eigvals, eigvecs = _randomized_eigsh(X, n_components=k, selection='module',\n+ n_iter=25, random_state=0)\n+ # more accurate but slow (TODO find realistic settings here)\n+ eigvals_qr, eigvecs_qr = _randomized_eigsh(\n+ X, n_components=k, n_iter=25, n_oversamples=20, random_state=0,\n+ power_iteration_normalizer=\"QR\", selection='module'\n+ )\n+\n+ # with LAPACK\n+ eigvals_lapack, eigvecs_lapack = linalg.eigh(X, eigvals=(n_features - k,\n+ n_features - 1))\n+ indices = eigvals_lapack.argsort()[::-1]\n+ eigvals_lapack = eigvals_lapack[indices]\n+ eigvecs_lapack = eigvecs_lapack[:, indices]\n+\n+ # -- eigenvalues comparison\n+ assert eigvals_lapack.shape == (k,)\n+ # comparison precision\n+ assert_array_almost_equal(eigvals, eigvals_lapack, decimal=6)\n+ assert_array_almost_equal(eigvals_qr, eigvals_lapack, decimal=6)\n+\n+ # -- eigenvectors comparison\n+ assert eigvecs_lapack.shape == (n_features, k)\n+ # flip eigenvectors' sign to enforce deterministic output\n+ dummy_vecs = np.zeros_like(eigvecs).T\n+ eigvecs, _ = svd_flip(eigvecs, dummy_vecs)\n+ eigvecs_qr, _ = svd_flip(eigvecs_qr, dummy_vecs)\n+ eigvecs_lapack, _ = svd_flip(eigvecs_lapack, dummy_vecs)\n+ assert_array_almost_equal(eigvecs, eigvecs_lapack, decimal=4)\n+ assert_array_almost_equal(eigvecs_qr, eigvecs_lapack, decimal=6)\n+\n+ # comparison ARPACK ~ LAPACK (some ARPACK implems do not support k=n)\n+ if k < n_features:\n+ v0 = _init_arpack_v0(n_features, random_state=0)\n+ # \"LA\" largest algebraic <=> selection=\"value\" in randomized_eigsh\n+ eigvals_arpack, eigvecs_arpack = eigsh(X, k, which=\"LA\", tol=0,\n+ maxiter=None, v0=v0)\n+ indices = eigvals_arpack.argsort()[::-1]\n+ # eigenvalues\n+ eigvals_arpack = eigvals_arpack[indices]\n+ assert_array_almost_equal(eigvals_lapack, eigvals_arpack, decimal=10)\n+ # eigenvectors\n+ eigvecs_arpack = eigvecs_arpack[:, indices]\n+ eigvecs_arpack, _ = svd_flip(eigvecs_arpack, dummy_vecs)\n+ assert_array_almost_equal(eigvecs_arpack, eigvecs_lapack, decimal=8)\n+\n+\n+@pytest.mark.parametrize(\"n,rank\", [\n+ (10, 7),\n+ (100, 10),\n+ (100, 80),\n+ (500, 10),\n+ (500, 250),\n+ (500, 400),\n+])\n+def test_randomized_eigsh_reconst_low_rank(n, rank):\n+ \"\"\"Check that randomized_eigsh is able to reconstruct a low rank psd matrix\n+\n+ Tests that the decomposition provided by `_randomized_eigsh` leads to\n+ orthonormal eigenvectors, and that a low rank PSD matrix can be effectively\n+ reconstructed with good accuracy using it.\n+ \"\"\"\n+ assert rank < n\n+\n+ # create a low rank PSD\n+ rng = np.random.RandomState(69)\n+ X = rng.randn(n, rank)\n+ A = X @ X.T\n+\n+ # approximate A with the \"right\" number of components\n+ S, V = _randomized_eigsh(A, n_components=rank, random_state=rng)\n+ # orthonormality checks\n+ assert_array_almost_equal(np.linalg.norm(V, axis=0), np.ones(S.shape))\n+ assert_array_almost_equal(V.T @ V, np.diag(np.ones(S.shape)))\n+ # reconstruction\n+ A_reconstruct = V @ np.diag(S) @ V.T\n+\n+ # test that the approximation is good\n+ assert_array_almost_equal(A_reconstruct, A, decimal=6)\n+\n+\n @pytest.mark.parametrize('dtype',\n (np.float32, np.float64))\n def test_row_norms(dtype):\n", "doc_changes": [{"path": "doc/modules/decomposition.rst", "old_path": "a/doc/modules/decomposition.rst", "new_path": "b/doc/modules/decomposition.rst", "metadata": "diff --git a/doc/modules/decomposition.rst b/doc/modules/decomposition.rst\nindex e971d784c63d6..fd51f60d8bfc6 100644\n--- a/doc/modules/decomposition.rst\n+++ b/doc/modules/decomposition.rst\n@@ -166,32 +166,16 @@ Note: the implementation of ``inverse_transform`` in :class:`PCA` with\n \n .. topic:: References:\n \n- * `\"Finding structure with randomness: Stochastic algorithms for\n+ * Algorithm 4.3 in\n+ `\"Finding structure with randomness: Stochastic algorithms for\n constructing approximate matrix decompositions\"\n `_\n Halko, et al., 2009\n \n-\n-.. _kernel_PCA:\n-\n-Kernel PCA\n-----------\n-\n-:class:`KernelPCA` is an extension of PCA which achieves non-linear\n-dimensionality reduction through the use of kernels (see :ref:`metrics`). It\n-has many applications including denoising, compression and structured\n-prediction (kernel dependency estimation). :class:`KernelPCA` supports both\n-``transform`` and ``inverse_transform``.\n-\n-.. figure:: ../auto_examples/decomposition/images/sphx_glr_plot_kernel_pca_001.png\n- :target: ../auto_examples/decomposition/plot_kernel_pca.html\n- :align: center\n- :scale: 75%\n-\n-.. topic:: Examples:\n-\n- * :ref:`sphx_glr_auto_examples_decomposition_plot_kernel_pca.py`\n-\n+ * `\"An implementation of a randomized algorithm for principal component\n+ analysis\"\n+ `_\n+ A. Szlam et al. 2014\n \n .. _SparsePCA:\n \n@@ -278,6 +262,100 @@ factorization, while larger values shrink many coefficients to zero.\n R. Jenatton, G. Obozinski, F. Bach, 2009\n \n \n+.. _kernel_PCA:\n+\n+Kernel Principal Component Analysis (kPCA)\n+==========================================\n+\n+Exact Kernel PCA\n+----------------\n+\n+:class:`KernelPCA` is an extension of PCA which achieves non-linear\n+dimensionality reduction through the use of kernels (see :ref:`metrics`). It\n+has many applications including denoising, compression and structured\n+prediction (kernel dependency estimation). :class:`KernelPCA` supports both\n+``transform`` and ``inverse_transform``.\n+\n+.. figure:: ../auto_examples/decomposition/images/sphx_glr_plot_kernel_pca_001.png\n+ :target: ../auto_examples/decomposition/plot_kernel_pca.html\n+ :align: center\n+ :scale: 75%\n+\n+.. topic:: Examples:\n+\n+ * :ref:`sphx_glr_auto_examples_decomposition_plot_kernel_pca.py`\n+\n+.. topic:: References:\n+\n+ * Kernel PCA was introduced in \"Kernel principal component analysis\"\n+ Bernhard Schoelkopf, Alexander J. Smola, and Klaus-Robert Mueller. 1999.\n+ In Advances in kernel methods, MIT Press, Cambridge, MA, USA 327-352.\n+\n+\n+.. _kPCA_Solvers:\n+\n+Choice of solver for Kernel PCA\n+-------------------------------\n+\n+While in :class:`PCA` the number of components is bounded by the number of\n+features, in :class:`KernelPCA` the number of components is bounded by the\n+number of samples. Many real-world datasets have large number of samples! In\n+these cases finding *all* the components with a full kPCA is a waste of\n+computation time, as data is mostly described by the first few components\n+(e.g. ``n_components<=100``). In other words, the centered Gram matrix that\n+is eigendecomposed in the Kernel PCA fitting process has an effective rank that\n+is much smaller than its size. This is a situation where approximate\n+eigensolvers can provide speedup with very low precision loss.\n+\n+The optional parameter ``eigen_solver='randomized'`` can be used to\n+*significantly* reduce the computation time when the number of requested\n+``n_components`` is small compared with the number of samples. It relies on\n+randomized decomposition methods to find an approximate solution in a shorter\n+time.\n+\n+The time complexity of the randomized :class:`KernelPCA` is\n+:math:`O(n_{\\mathrm{samples}}^2 \\cdot n_{\\mathrm{components}})`\n+instead of :math:`O(n_{\\mathrm{samples}}^3)` for the exact method\n+implemented with ``eigen_solver='dense'``.\n+\n+The memory footprint of randomized :class:`KernelPCA` is also proportional to\n+:math:`2 \\cdot n_{\\mathrm{samples}} \\cdot n_{\\mathrm{components}}` instead of\n+:math:`n_{\\mathrm{samples}}^2` for the exact method.\n+\n+Note: this technique is the same as in :ref:`RandomizedPCA`.\n+\n+In addition to the above two solvers, ``eigen_solver='arpack'`` can be used as\n+an alternate way to get an approximate decomposition. In practice, this method\n+only provides reasonable execution times when the number of components to find\n+is extremely small. It is enabled by default when the desired number of\n+components is less than 10 (strict) and the number of samples is more than 200\n+(strict). See :class:`KernelPCA` for details.\n+\n+.. topic:: References:\n+\n+ * *dense* solver:\n+ `scipy.linalg.eigh documentation\n+ `_\n+\n+ * *randomized* solver:\n+\n+ - Algorithm 4.3 in\n+ `\"Finding structure with randomness: Stochastic algorithms for\n+ constructing approximate matrix decompositions\"\n+ `_\n+ Halko, et al., 2009\n+\n+ - `\"An implementation of a randomized algorithm for principal component\n+ analysis\"\n+ `_\n+ A. Szlam et al. 2014\n+\n+ * *arpack* solver:\n+ `scipy.sparse.linalg.eigsh documentation\n+ `_\n+ R. B. Lehoucq, D. C. Sorensen, and C. Yang, 1998\n+\n+\n .. _LSA:\n \n Truncated singular value decomposition and latent semantic analysis\n"}, {"path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 3b3884e68e185..e89eecfe0874c 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -159,14 +159,17 @@ Changelog\n - |Fix| Fixes incorrect multiple data-conversion warnings when clustering\n boolean data. :pr:`19046` by :user:`Surya Prakash `.\n \n-:mod:`sklearn.decomposition`\n-............................\n-\n - |Fix| Fixed :func:`dict_learning`, used by :class:`DictionaryLearning`, to\n ensure determinism of the output. Achieved by flipping signs of the SVD\n output which is used to initialize the code.\n :pr:`18433` by :user:`Bruno Charron `.\n \n+- |Enhancement| added a new approximate solver (randomized SVD, available with\n+ `eigen_solver='randomized'`) to :class:`decomposition.KernelPCA`. This\n+ significantly accelerates computation when the number of samples is much\n+ larger than the desired number of components.\n+ :pr:`12069` by :user:`Sylvain Mari\u00e9 `.\n+\n - |Fix| Fixed a bug in :class:`MiniBatchDictionaryLearning`,\n :class:`MiniBatchSparsePCA` and :func:`dict_learning_online` where the\n update of the dictionary was incorrect. :pr:`19198` by\n@@ -389,8 +392,8 @@ Changelog\n supporting sparse matrix and raise the appropriate error message.\n :pr:`19879` by :user:`Guillaume Lemaitre `.\n \n-- |Efficiency| Changed ``algorithm`` argument for :class:`cluster.KMeans` in \n- :class:`preprocessing.KBinsDiscretizer` from ``auto`` to ``full``. \n+- |Efficiency| Changed ``algorithm`` argument for :class:`cluster.KMeans` in\n+ :class:`preprocessing.KBinsDiscretizer` from ``auto`` to ``full``.\n :pr:`19934` by :user:`Gleb Levitskiy `.\n \n :mod:`sklearn.tree`\n"}], "version": "1.00", "base_commit": "2641baf16d9de5191316745ec46120cc8b57a666", "PASS2PASS": ["sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_deterministic_output", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_inverse_transform_reconstruction", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_linear_kernel[4-auto]", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_conditioning", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_precomputed_non_symmetric[dense]", "sklearn/decomposition/tests/test_kernel_pca.py::test_remove_zero_eig", "sklearn/decomposition/tests/test_kernel_pca.py::test_gridsearch_pipeline_precomputed", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_linear_kernel[10-arpack]", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_invalid_parameters", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pcc_pairwise_is_deprecated", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_linear_kernel[10-dense]", "sklearn/decomposition/tests/test_kernel_pca.py::test_precomputed_kernel_not_psd[auto]", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_precomputed_non_symmetric[arpack]", "sklearn/decomposition/tests/test_kernel_pca.py::test_precomputed_kernel_not_psd[dense]", "sklearn/decomposition/tests/test_kernel_pca.py::test_nested_circles", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_precomputed_non_symmetric[auto]", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_invalid_kernel", "sklearn/decomposition/tests/test_kernel_pca.py::test_gridsearch_pipeline", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_linear_kernel[4-dense]", "sklearn/decomposition/tests/test_kernel_pca.py::test_32_64_decomposition_shape", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_consistent_transform", "sklearn/decomposition/tests/test_kernel_pca.py::test_precomputed_kernel_not_psd[arpack]", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_linear_kernel[4-arpack]", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_linear_kernel[10-auto]"], "FAIL2PASS": ["sklearn/utils/tests/test_extmath.py::test_randomized_svd_sign_flip_with_transpose", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10000000.0-1-1e-08-0]", "sklearn/utils/tests/test_extmath.py::test_uniform_weights", "sklearn/utils/tests/test_extmath.py::test_randomized_eigsh_reconst_low_rank[500-400]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1-1--10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10000000.0-1-1e-08--10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1-1e-08-0]", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_sparse", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_precomputed", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10000000.0-1-100000.0-0]", "sklearn/utils/tests/test_extmath.py::test_safe_sparse_dot_2d[sparse-dense]", "sklearn/utils/tests/test_extmath.py::test_incremental_mean_and_variance_ignore_nan", "sklearn/utils/tests/test_extmath.py::test_randomized_eigsh[float64]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10-1-100000.0--10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1e-08-1e-08-0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance_ignore_nan[float64]", "sklearn/utils/tests/test_extmath.py::test_randomized_eigsh_compared_to_others[10]", "sklearn/utils/tests/test_extmath.py::test_randomized_svd_sparse_warnings", "sklearn/decomposition/tests/test_kernel_pca.py::test_precomputed_kernel_not_psd[randomized]", "sklearn/utils/tests/test_extmath.py::test_randomized_svd_low_rank_all_dtypes[int64]", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca", "sklearn/utils/tests/test_extmath.py::test_randomized_eigsh_compared_to_others[100]", "sklearn/utils/tests/test_extmath.py::test_softmax", "sklearn/utils/tests/test_extmath.py::test_randomized_eigsh_compared_to_others[50]", "sklearn/utils/tests/test_extmath.py::test_cartesian", "sklearn/utils/tests/test_extmath.py::test_randomized_svd_transpose_consistency", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_n_components", "sklearn/utils/tests/test_extmath.py::test_vector_sign_flip", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10000000.0-1-1-10000000.0]", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_precomputed_non_symmetric[randomized]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1e-08-1e-08-10000000.0]", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_solvers_equivalence[10]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10-1-1e-08-0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1e-08-1-0]", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_linear_kernel[4-randomized]", "sklearn/utils/tests/test_extmath.py::test_incremental_variance_update_formulas", "sklearn/utils/tests/test_extmath.py::test_svd_flip", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_invalid_solver", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10000000.0-1-100000.0--10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[1-1e-08-1-0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10-1-1e-08-10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10000000.0-1-1-0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1-1e-08--10000000.0]", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_solvers_equivalence[4]", "sklearn/utils/tests/test_extmath.py::test_randomized_eigsh[float32]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1e-08-100000.0-0]", "sklearn/utils/tests/test_extmath.py::test_randomized_svd_low_rank_all_dtypes[int32]", "sklearn/utils/tests/test_extmath.py::test_safe_sparse_dot_2d_1d[sparse]", "sklearn/utils/tests/test_extmath.py::test_randomized_svd_low_rank_all_dtypes[float64]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10000000.0-1-1e-08-10000000.0]", "sklearn/utils/tests/test_extmath.py::test_safe_sparse_dot_2d_1d[dense]", "sklearn/utils/tests/test_extmath.py::test_safe_sparse_dot_dense_output[True]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[1-1e-08-1--10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10000000.0-1-100000.0-10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[1-1e-08-100000.0-0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[1-1e-08-100000.0--10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1e-08-1e-08--10000000.0]", "sklearn/utils/tests/test_extmath.py::test_randomized_eigsh_reconst_low_rank[500-10]", "sklearn/utils/tests/test_extmath.py::test_randomized_svd_sign_flip", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_linear_kernel[10-randomized]", "sklearn/utils/tests/test_extmath.py::test_randomized_svd_low_rank_with_noise", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[1-1e-08-1e-08-10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance_simple[float64]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1-100000.0--10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1e-08-100000.0-10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[1-1e-08-1e-08--10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10-1-1-0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1e-08-1-10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance_ignore_nan[float32]", "sklearn/utils/tests/test_extmath.py::test_incremental_variance_ddof", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10000000.0-1-1--10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1e-08-1--10000000.0]", "sklearn/utils/tests/test_extmath.py::test_safe_sparse_dot_nd", "sklearn/utils/tests/test_extmath.py::test_row_norms[float64]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10-1-100000.0-10000000.0]", "sklearn/utils/tests/test_extmath.py::test_randomized_svd_infinite_rank", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10-1-100000.0-0]", "sklearn/utils/tests/test_extmath.py::test_randomized_eigsh[int32]", "sklearn/utils/tests/test_extmath.py::test_safe_sparse_dot_2d[sparse-sparse]", "sklearn/utils/tests/test_extmath.py::test_randomized_eigsh[int64]", "sklearn/utils/tests/test_extmath.py::test_safe_sparse_dot_dense_output[False]", "sklearn/decomposition/tests/test_kernel_pca.py::test_kernel_pca_solvers_equivalence[20]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance_simple[float32]", "sklearn/utils/tests/test_extmath.py::test_incremental_variance_numerical_stability", "sklearn/utils/tests/test_extmath.py::test_randomized_svd_power_iteration_normalizer", "sklearn/utils/tests/test_extmath.py::test_row_norms[float32]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[1-1e-08-1e-08-0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1-1e-08-10000000.0]", "sklearn/utils/tests/test_extmath.py::test_density", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10-1-1-10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1-1-0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10-1-1--10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[10-1-1e-08--10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1-1-10000000.0]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1-100000.0-0]", "sklearn/utils/tests/test_extmath.py::test_logistic_sigmoid", "sklearn/utils/tests/test_extmath.py::test_randomized_svd_low_rank_all_dtypes[float32]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1e-08-100000.0--10000000.0]", "sklearn/utils/tests/test_extmath.py::test_randomized_eigsh_compared_to_others[199]", "sklearn/utils/tests/test_extmath.py::test_safe_sparse_dot_2d[dense-dense]", "sklearn/utils/tests/test_extmath.py::test_stable_cumsum", "sklearn/utils/tests/test_extmath.py::test_randomized_eigsh_reconst_low_rank[100-80]", "sklearn/utils/tests/test_extmath.py::test_random_weights", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[1-1e-08-1-10000000.0]", "sklearn/utils/tests/test_extmath.py::test_randomized_eigsh_reconst_low_rank[500-250]", "sklearn/utils/tests/test_extmath.py::test_randomized_eigsh_reconst_low_rank[10-7]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[0-1-100000.0-10000000.0]", "sklearn/utils/tests/test_extmath.py::test_safe_sparse_dot_2d[dense-sparse]", "sklearn/utils/tests/test_extmath.py::test_randomized_eigsh_reconst_low_rank[100-10]", "sklearn/utils/tests/test_extmath.py::test_incremental_weighted_mean_and_variance[1-1e-08-100000.0-10000000.0]"], "mask_doc_diff": [{"path": "doc/modules/decomposition.rst", "old_path": "a/doc/modules/decomposition.rst", "new_path": "b/doc/modules/decomposition.rst", "metadata": "diff --git a/doc/modules/decomposition.rst b/doc/modules/decomposition.rst\nindex e971d784c..fd51f60d8 100644\n--- a/doc/modules/decomposition.rst\n+++ b/doc/modules/decomposition.rst\n@@ -166,32 +166,16 @@ Note: the implementation of ``inverse_transform`` in :class:`PCA` with\n \n .. topic:: References:\n \n- * `\"Finding structure with randomness: Stochastic algorithms for\n+ * Algorithm 4.3 in\n+ `\"Finding structure with randomness: Stochastic algorithms for\n constructing approximate matrix decompositions\"\n `_\n Halko, et al., 2009\n \n-\n-.. _kernel_PCA:\n-\n-Kernel PCA\n-----------\n-\n-:class:`KernelPCA` is an extension of PCA which achieves non-linear\n-dimensionality reduction through the use of kernels (see :ref:`metrics`). It\n-has many applications including denoising, compression and structured\n-prediction (kernel dependency estimation). :class:`KernelPCA` supports both\n-``transform`` and ``inverse_transform``.\n-\n-.. figure:: ../auto_examples/decomposition/images/sphx_glr_plot_kernel_pca_001.png\n- :target: ../auto_examples/decomposition/plot_kernel_pca.html\n- :align: center\n- :scale: 75%\n-\n-.. topic:: Examples:\n-\n- * :ref:`sphx_glr_auto_examples_decomposition_plot_kernel_pca.py`\n-\n+ * `\"An implementation of a randomized algorithm for principal component\n+ analysis\"\n+ `_\n+ A. Szlam et al. 2014\n \n .. _SparsePCA:\n \n@@ -278,6 +262,100 @@ factorization, while larger values shrink many coefficients to zero.\n R. Jenatton, G. Obozinski, F. Bach, 2009\n \n \n+.. _kernel_PCA:\n+\n+Kernel Principal Component Analysis (kPCA)\n+==========================================\n+\n+Exact Kernel PCA\n+----------------\n+\n+:class:`KernelPCA` is an extension of PCA which achieves non-linear\n+dimensionality reduction through the use of kernels (see :ref:`metrics`). It\n+has many applications including denoising, compression and structured\n+prediction (kernel dependency estimation). :class:`KernelPCA` supports both\n+``transform`` and ``inverse_transform``.\n+\n+.. figure:: ../auto_examples/decomposition/images/sphx_glr_plot_kernel_pca_001.png\n+ :target: ../auto_examples/decomposition/plot_kernel_pca.html\n+ :align: center\n+ :scale: 75%\n+\n+.. topic:: Examples:\n+\n+ * :ref:`sphx_glr_auto_examples_decomposition_plot_kernel_pca.py`\n+\n+.. topic:: References:\n+\n+ * Kernel PCA was introduced in \"Kernel principal component analysis\"\n+ Bernhard Schoelkopf, Alexander J. Smola, and Klaus-Robert Mueller. 1999.\n+ In Advances in kernel methods, MIT Press, Cambridge, MA, USA 327-352.\n+\n+\n+.. _kPCA_Solvers:\n+\n+Choice of solver for Kernel PCA\n+-------------------------------\n+\n+While in :class:`PCA` the number of components is bounded by the number of\n+features, in :class:`KernelPCA` the number of components is bounded by the\n+number of samples. Many real-world datasets have large number of samples! In\n+these cases finding *all* the components with a full kPCA is a waste of\n+computation time, as data is mostly described by the first few components\n+(e.g. ``n_components<=100``). In other words, the centered Gram matrix that\n+is eigendecomposed in the Kernel PCA fitting process has an effective rank that\n+is much smaller than its size. This is a situation where approximate\n+eigensolvers can provide speedup with very low precision loss.\n+\n+The optional parameter ``eigen_solver='randomized'`` can be used to\n+*significantly* reduce the computation time when the number of requested\n+``n_components`` is small compared with the number of samples. It relies on\n+randomized decomposition methods to find an approximate solution in a shorter\n+time.\n+\n+The time complexity of the randomized :class:`KernelPCA` is\n+:math:`O(n_{\\mathrm{samples}}^2 \\cdot n_{\\mathrm{components}})`\n+instead of :math:`O(n_{\\mathrm{samples}}^3)` for the exact method\n+implemented with ``eigen_solver='dense'``.\n+\n+The memory footprint of randomized :class:`KernelPCA` is also proportional to\n+:math:`2 \\cdot n_{\\mathrm{samples}} \\cdot n_{\\mathrm{components}}` instead of\n+:math:`n_{\\mathrm{samples}}^2` for the exact method.\n+\n+Note: this technique is the same as in :ref:`RandomizedPCA`.\n+\n+In addition to the above two solvers, ``eigen_solver='arpack'`` can be used as\n+an alternate way to get an approximate decomposition. In practice, this method\n+only provides reasonable execution times when the number of components to find\n+is extremely small. It is enabled by default when the desired number of\n+components is less than 10 (strict) and the number of samples is more than 200\n+(strict). See :class:`KernelPCA` for details.\n+\n+.. topic:: References:\n+\n+ * *dense* solver:\n+ `scipy.linalg.eigh documentation\n+ `_\n+\n+ * *randomized* solver:\n+\n+ - Algorithm 4.3 in\n+ `\"Finding structure with randomness: Stochastic algorithms for\n+ constructing approximate matrix decompositions\"\n+ `_\n+ Halko, et al., 2009\n+\n+ - `\"An implementation of a randomized algorithm for principal component\n+ analysis\"\n+ `_\n+ A. Szlam et al. 2014\n+\n+ * *arpack* solver:\n+ `scipy.sparse.linalg.eigsh documentation\n+ `_\n+ R. B. Lehoucq, D. C. Sorensen, and C. Yang, 1998\n+\n+\n .. _LSA:\n \n Truncated singular value decomposition and latent semantic analysis\n"}, {"path": "doc/whats_new/v1.0.rst", "old_path": "a/doc/whats_new/v1.0.rst", "new_path": "b/doc/whats_new/v1.0.rst", "metadata": "diff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 3b3884e68..7faf6bdf6 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -159,14 +159,16 @@ Changelog\n - |Fix| Fixes incorrect multiple data-conversion warnings when clustering\n boolean data. :pr:`19046` by :user:`Surya Prakash `.\n \n-:mod:`sklearn.decomposition`\n-............................\n-\n - |Fix| Fixed :func:`dict_learning`, used by :class:`DictionaryLearning`, to\n ensure determinism of the output. Achieved by flipping signs of the SVD\n output which is used to initialize the code.\n :pr:`18433` by :user:`Bruno Charron `.\n \n+- |Enhancement| added a new approximate solver (randomized SVD, available with\n+ `eigen_solver='randomized'`) to :class:`decomposition.KernelPCA`. This\n+ significantly accelerates computation when the number of samples is much\n+ larger than the desired number of components.\n+\n - |Fix| Fixed a bug in :class:`MiniBatchDictionaryLearning`,\n :class:`MiniBatchSparsePCA` and :func:`dict_learning_online` where the\n update of the dictionary was incorrect. :pr:`19198` by\n@@ -389,8 +391,8 @@ Changelog\n supporting sparse matrix and raise the appropriate error message.\n :pr:`19879` by :user:`Guillaume Lemaitre `.\n \n-- |Efficiency| Changed ``algorithm`` argument for :class:`cluster.KMeans` in \n- :class:`preprocessing.KBinsDiscretizer` from ``auto`` to ``full``. \n+- |Efficiency| Changed ``algorithm`` argument for :class:`cluster.KMeans` in\n+ :class:`preprocessing.KBinsDiscretizer` from ``auto`` to ``full``.\n :pr:`19934` by :user:`Gleb Levitskiy `.\n \n :mod:`sklearn.tree`\n"}], "augmentations": {"header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": [{"type": "file", "name": "benchmarks/bench_kernel_pca_solvers_time_vs_n_samples.py"}, {"type": "file", "name": "benchmarks/bench_kernel_pca_solvers_time_vs_n_components.py"}]}, "problem_statement": "diff --git a/doc/modules/decomposition.rst b/doc/modules/decomposition.rst\nindex e971d784c..fd51f60d8 100644\n--- a/doc/modules/decomposition.rst\n+++ b/doc/modules/decomposition.rst\n@@ -166,32 +166,16 @@ Note: the implementation of ``inverse_transform`` in :class:`PCA` with\n \n .. topic:: References:\n \n- * `\"Finding structure with randomness: Stochastic algorithms for\n+ * Algorithm 4.3 in\n+ `\"Finding structure with randomness: Stochastic algorithms for\n constructing approximate matrix decompositions\"\n `_\n Halko, et al., 2009\n \n-\n-.. _kernel_PCA:\n-\n-Kernel PCA\n-----------\n-\n-:class:`KernelPCA` is an extension of PCA which achieves non-linear\n-dimensionality reduction through the use of kernels (see :ref:`metrics`). It\n-has many applications including denoising, compression and structured\n-prediction (kernel dependency estimation). :class:`KernelPCA` supports both\n-``transform`` and ``inverse_transform``.\n-\n-.. figure:: ../auto_examples/decomposition/images/sphx_glr_plot_kernel_pca_001.png\n- :target: ../auto_examples/decomposition/plot_kernel_pca.html\n- :align: center\n- :scale: 75%\n-\n-.. topic:: Examples:\n-\n- * :ref:`sphx_glr_auto_examples_decomposition_plot_kernel_pca.py`\n-\n+ * `\"An implementation of a randomized algorithm for principal component\n+ analysis\"\n+ `_\n+ A. Szlam et al. 2014\n \n .. _SparsePCA:\n \n@@ -278,6 +262,100 @@ factorization, while larger values shrink many coefficients to zero.\n R. Jenatton, G. Obozinski, F. Bach, 2009\n \n \n+.. _kernel_PCA:\n+\n+Kernel Principal Component Analysis (kPCA)\n+==========================================\n+\n+Exact Kernel PCA\n+----------------\n+\n+:class:`KernelPCA` is an extension of PCA which achieves non-linear\n+dimensionality reduction through the use of kernels (see :ref:`metrics`). It\n+has many applications including denoising, compression and structured\n+prediction (kernel dependency estimation). :class:`KernelPCA` supports both\n+``transform`` and ``inverse_transform``.\n+\n+.. figure:: ../auto_examples/decomposition/images/sphx_glr_plot_kernel_pca_001.png\n+ :target: ../auto_examples/decomposition/plot_kernel_pca.html\n+ :align: center\n+ :scale: 75%\n+\n+.. topic:: Examples:\n+\n+ * :ref:`sphx_glr_auto_examples_decomposition_plot_kernel_pca.py`\n+\n+.. topic:: References:\n+\n+ * Kernel PCA was introduced in \"Kernel principal component analysis\"\n+ Bernhard Schoelkopf, Alexander J. Smola, and Klaus-Robert Mueller. 1999.\n+ In Advances in kernel methods, MIT Press, Cambridge, MA, USA 327-352.\n+\n+\n+.. _kPCA_Solvers:\n+\n+Choice of solver for Kernel PCA\n+-------------------------------\n+\n+While in :class:`PCA` the number of components is bounded by the number of\n+features, in :class:`KernelPCA` the number of components is bounded by the\n+number of samples. Many real-world datasets have large number of samples! In\n+these cases finding *all* the components with a full kPCA is a waste of\n+computation time, as data is mostly described by the first few components\n+(e.g. ``n_components<=100``). In other words, the centered Gram matrix that\n+is eigendecomposed in the Kernel PCA fitting process has an effective rank that\n+is much smaller than its size. This is a situation where approximate\n+eigensolvers can provide speedup with very low precision loss.\n+\n+The optional parameter ``eigen_solver='randomized'`` can be used to\n+*significantly* reduce the computation time when the number of requested\n+``n_components`` is small compared with the number of samples. It relies on\n+randomized decomposition methods to find an approximate solution in a shorter\n+time.\n+\n+The time complexity of the randomized :class:`KernelPCA` is\n+:math:`O(n_{\\mathrm{samples}}^2 \\cdot n_{\\mathrm{components}})`\n+instead of :math:`O(n_{\\mathrm{samples}}^3)` for the exact method\n+implemented with ``eigen_solver='dense'``.\n+\n+The memory footprint of randomized :class:`KernelPCA` is also proportional to\n+:math:`2 \\cdot n_{\\mathrm{samples}} \\cdot n_{\\mathrm{components}}` instead of\n+:math:`n_{\\mathrm{samples}}^2` for the exact method.\n+\n+Note: this technique is the same as in :ref:`RandomizedPCA`.\n+\n+In addition to the above two solvers, ``eigen_solver='arpack'`` can be used as\n+an alternate way to get an approximate decomposition. In practice, this method\n+only provides reasonable execution times when the number of components to find\n+is extremely small. It is enabled by default when the desired number of\n+components is less than 10 (strict) and the number of samples is more than 200\n+(strict). See :class:`KernelPCA` for details.\n+\n+.. topic:: References:\n+\n+ * *dense* solver:\n+ `scipy.linalg.eigh documentation\n+ `_\n+\n+ * *randomized* solver:\n+\n+ - Algorithm 4.3 in\n+ `\"Finding structure with randomness: Stochastic algorithms for\n+ constructing approximate matrix decompositions\"\n+ `_\n+ Halko, et al., 2009\n+\n+ - `\"An implementation of a randomized algorithm for principal component\n+ analysis\"\n+ `_\n+ A. Szlam et al. 2014\n+\n+ * *arpack* solver:\n+ `scipy.sparse.linalg.eigsh documentation\n+ `_\n+ R. B. Lehoucq, D. C. Sorensen, and C. Yang, 1998\n+\n+\n .. _LSA:\n \n Truncated singular value decomposition and latent semantic analysis\n\ndiff --git a/doc/whats_new/v1.0.rst b/doc/whats_new/v1.0.rst\nindex 3b3884e68..7faf6bdf6 100644\n--- a/doc/whats_new/v1.0.rst\n+++ b/doc/whats_new/v1.0.rst\n@@ -159,14 +159,16 @@ Changelog\n - |Fix| Fixes incorrect multiple data-conversion warnings when clustering\n boolean data. :pr:`19046` by :user:`Surya Prakash `.\n \n-:mod:`sklearn.decomposition`\n-............................\n-\n - |Fix| Fixed :func:`dict_learning`, used by :class:`DictionaryLearning`, to\n ensure determinism of the output. Achieved by flipping signs of the SVD\n output which is used to initialize the code.\n :pr:`18433` by :user:`Bruno Charron `.\n \n+- |Enhancement| added a new approximate solver (randomized SVD, available with\n+ `eigen_solver='randomized'`) to :class:`decomposition.KernelPCA`. This\n+ significantly accelerates computation when the number of samples is much\n+ larger than the desired number of components.\n+\n - |Fix| Fixed a bug in :class:`MiniBatchDictionaryLearning`,\n :class:`MiniBatchSparsePCA` and :func:`dict_learning_online` where the\n update of the dictionary was incorrect. :pr:`19198` by\n@@ -389,8 +391,8 @@ Changelog\n supporting sparse matrix and raise the appropriate error message.\n :pr:`19879` by :user:`Guillaume Lemaitre `.\n \n-- |Efficiency| Changed ``algorithm`` argument for :class:`cluster.KMeans` in \n- :class:`preprocessing.KBinsDiscretizer` from ``auto`` to ``full``. \n+- |Efficiency| Changed ``algorithm`` argument for :class:`cluster.KMeans` in\n+ :class:`preprocessing.KBinsDiscretizer` from ``auto`` to ``full``.\n :pr:`19934` by :user:`Gleb Levitskiy `.\n \n :mod:`sklearn.tree`\n\nIf completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:\n[{'type': 'file', 'name': 'benchmarks/bench_kernel_pca_solvers_time_vs_n_samples.py'}, {'type': 'file', 'name': 'benchmarks/bench_kernel_pca_solvers_time_vs_n_components.py'}]\n"} {"repo": "scikit-learn/scikit-learn", "instance_id": "scikit-learn__scikit-learn-21701", "html_url": "https://github.com/scikit-learn/scikit-learn/pull/21701", "feature_patch": "diff --git a/doc/modules/random_projection.rst b/doc/modules/random_projection.rst\nindex adb2d53bd14d6..7d3341f0244bb 100644\n--- a/doc/modules/random_projection.rst\n+++ b/doc/modules/random_projection.rst\n@@ -160,3 +160,42 @@ projection transformer::\n In Proceedings of the 12th ACM SIGKDD international conference on\n Knowledge discovery and data mining (KDD '06). ACM, New York, NY, USA,\n 287-296.\n+\n+\n+.. _random_projection_inverse_transform:\n+\n+Inverse Transform\n+=================\n+The random projection transformers have ``compute_inverse_components`` parameter. When\n+set to True, after creating the random ``components_`` matrix during fitting,\n+the transformer computes the pseudo-inverse of this matrix and stores it as\n+``inverse_components_``. The ``inverse_components_`` matrix has shape\n+:math:`n_{features} \\times n_{components}`, and it is always a dense matrix,\n+regardless of whether the components matrix is sparse or dense. So depending on\n+the number of features and components, it may use a lot of memory.\n+\n+When the ``inverse_transform`` method is called, it computes the product of the\n+input ``X`` and the transpose of the inverse components. If the inverse components have\n+been computed during fit, they are reused at each call to ``inverse_transform``.\n+Otherwise they are recomputed each time, which can be costly. The result is always\n+dense, even if ``X`` is sparse.\n+\n+Here a small code example which illustrates how to use the inverse transform\n+feature::\n+\n+ >>> import numpy as np\n+ >>> from sklearn.random_projection import SparseRandomProjection\n+ >>> X = np.random.rand(100, 10000)\n+ >>> transformer = SparseRandomProjection(\n+ ... compute_inverse_components=True\n+ ... )\n+ ...\n+ >>> X_new = transformer.fit_transform(X)\n+ >>> X_new.shape\n+ (100, 3947)\n+ >>> X_new_inversed = transformer.inverse_transform(X_new)\n+ >>> X_new_inversed.shape\n+ (100, 10000)\n+ >>> X_new_again = transformer.transform(X_new_inversed)\n+ >>> np.allclose(X_new, X_new_again)\n+ True\ndiff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 5030ed8faa4a1..e66640cfd2d21 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -791,6 +791,14 @@ Changelog\n :class:`random_projection.GaussianRandomProjection` preserves dtype for\n `numpy.float32`. :pr:`22114` by :user:`Takeshi Oura `.\n \n+- |Enhancement| Adds an :meth:`inverse_transform` method and a\n+ `compute_inverse_transform` parameter to all transformers in the\n+ :mod:`~sklearn.random_projection` module:\n+ :class:`~sklearn.random_projection.GaussianRandomProjection` and\n+ :class:`~sklearn.random_projection.SparseRandomProjection`. When the parameter is set\n+ to True, the pseudo-inverse of the components is computed during `fit` and stored as\n+ `inverse_components_`. :pr:`21701` by `Aur\u00e9lien Geron `.\n+\n - |API| Adds :term:`get_feature_names_out` to all transformers in the\n :mod:`~sklearn.random_projection` module:\n :class:`~sklearn.random_projection.GaussianRandomProjection` and\ndiff --git a/sklearn/random_projection.py b/sklearn/random_projection.py\nindex 31ebfdddd8928..000eca478553e 100644\n--- a/sklearn/random_projection.py\n+++ b/sklearn/random_projection.py\n@@ -31,6 +31,7 @@\n from abc import ABCMeta, abstractmethod\n \n import numpy as np\n+from scipy import linalg\n import scipy.sparse as sp\n \n from .base import BaseEstimator, TransformerMixin\n@@ -39,10 +40,9 @@\n from .utils import check_random_state\n from .utils.extmath import safe_sparse_dot\n from .utils.random import sample_without_replacement\n-from .utils.validation import check_is_fitted\n+from .utils.validation import check_array, check_is_fitted\n from .exceptions import DataDimensionalityWarning\n \n-\n __all__ = [\n \"SparseRandomProjection\",\n \"GaussianRandomProjection\",\n@@ -302,11 +302,18 @@ class BaseRandomProjection(\n \n @abstractmethod\n def __init__(\n- self, n_components=\"auto\", *, eps=0.1, dense_output=False, random_state=None\n+ self,\n+ n_components=\"auto\",\n+ *,\n+ eps=0.1,\n+ dense_output=False,\n+ compute_inverse_components=False,\n+ random_state=None,\n ):\n self.n_components = n_components\n self.eps = eps\n self.dense_output = dense_output\n+ self.compute_inverse_components = compute_inverse_components\n self.random_state = random_state\n \n @abstractmethod\n@@ -323,12 +330,18 @@ def _make_random_matrix(self, n_components, n_features):\n \n Returns\n -------\n- components : {ndarray, sparse matrix} of shape \\\n- (n_components, n_features)\n+ components : {ndarray, sparse matrix} of shape (n_components, n_features)\n The generated random matrix. Sparse matrix will be of CSR format.\n \n \"\"\"\n \n+ def _compute_inverse_components(self):\n+ \"\"\"Compute the pseudo-inverse of the (densified) components.\"\"\"\n+ components = self.components_\n+ if sp.issparse(components):\n+ components = components.toarray()\n+ return linalg.pinv(components, check_finite=False)\n+\n def fit(self, X, y=None):\n \"\"\"Generate a sparse random projection matrix.\n \n@@ -399,6 +412,9 @@ def fit(self, X, y=None):\n \" not the proper shape.\"\n )\n \n+ if self.compute_inverse_components:\n+ self.inverse_components_ = self._compute_inverse_components()\n+\n return self\n \n def transform(self, X):\n@@ -437,6 +453,35 @@ def _n_features_out(self):\n \"\"\"\n return self.n_components\n \n+ def inverse_transform(self, X):\n+ \"\"\"Project data back to its original space.\n+\n+ Returns an array X_original whose transform would be X. Note that even\n+ if X is sparse, X_original is dense: this may use a lot of RAM.\n+\n+ If `compute_inverse_components` is False, the inverse of the components is\n+ computed during each call to `inverse_transform` which can be costly.\n+\n+ Parameters\n+ ----------\n+ X : {array-like, sparse matrix} of shape (n_samples, n_components)\n+ Data to be transformed back.\n+\n+ Returns\n+ -------\n+ X_original : ndarray of shape (n_samples, n_features)\n+ Reconstructed data.\n+ \"\"\"\n+ check_is_fitted(self)\n+\n+ X = check_array(X, dtype=[np.float64, np.float32], accept_sparse=(\"csr\", \"csc\"))\n+\n+ if self.compute_inverse_components:\n+ return X @ self.inverse_components_.T\n+\n+ inverse_components = self._compute_inverse_components()\n+ return X @ inverse_components.T\n+\n def _more_tags(self):\n return {\n \"preserves_dtype\": [np.float64, np.float32],\n@@ -474,6 +519,11 @@ class GaussianRandomProjection(BaseRandomProjection):\n Smaller values lead to better embedding and higher number of\n dimensions (n_components) in the target projection space.\n \n+ compute_inverse_components : bool, default=False\n+ Learn the inverse transform by computing the pseudo-inverse of the\n+ components during fit. Note that computing the pseudo-inverse does not\n+ scale well to large matrices.\n+\n random_state : int, RandomState instance or None, default=None\n Controls the pseudo random number generator used to generate the\n projection matrix at fit time.\n@@ -488,6 +538,12 @@ class GaussianRandomProjection(BaseRandomProjection):\n components_ : ndarray of shape (n_components, n_features)\n Random matrix used for the projection.\n \n+ inverse_components_ : ndarray of shape (n_features, n_components)\n+ Pseudo-inverse of the components, only computed if\n+ `compute_inverse_components` is True.\n+\n+ .. versionadded:: 1.1\n+\n n_features_in_ : int\n Number of features seen during :term:`fit`.\n \n@@ -516,11 +572,19 @@ class GaussianRandomProjection(BaseRandomProjection):\n (25, 2759)\n \"\"\"\n \n- def __init__(self, n_components=\"auto\", *, eps=0.1, random_state=None):\n+ def __init__(\n+ self,\n+ n_components=\"auto\",\n+ *,\n+ eps=0.1,\n+ compute_inverse_components=False,\n+ random_state=None,\n+ ):\n super().__init__(\n n_components=n_components,\n eps=eps,\n dense_output=True,\n+ compute_inverse_components=compute_inverse_components,\n random_state=random_state,\n )\n \n@@ -610,6 +674,14 @@ class SparseRandomProjection(BaseRandomProjection):\n If False, the projected data uses a sparse representation if\n the input is sparse.\n \n+ compute_inverse_components : bool, default=False\n+ Learn the inverse transform by computing the pseudo-inverse of the\n+ components during fit. Note that the pseudo-inverse is always a dense\n+ array, even if the training data was sparse. This means that it might be\n+ necessary to call `inverse_transform` on a small batch of samples at a\n+ time to avoid exhausting the available memory on the host. Moreover,\n+ computing the pseudo-inverse does not scale well to large matrices.\n+\n random_state : int, RandomState instance or None, default=None\n Controls the pseudo random number generator used to generate the\n projection matrix at fit time.\n@@ -625,6 +697,12 @@ class SparseRandomProjection(BaseRandomProjection):\n Random matrix used for the projection. Sparse matrix will be of CSR\n format.\n \n+ inverse_components_ : ndarray of shape (n_features, n_components)\n+ Pseudo-inverse of the components, only computed if\n+ `compute_inverse_components` is True.\n+\n+ .. versionadded:: 1.1\n+\n density_ : float in range 0.0 - 1.0\n Concrete density computed from when density = \"auto\".\n \n@@ -676,12 +754,14 @@ def __init__(\n density=\"auto\",\n eps=0.1,\n dense_output=False,\n+ compute_inverse_components=False,\n random_state=None,\n ):\n super().__init__(\n n_components=n_components,\n eps=eps,\n dense_output=dense_output,\n+ compute_inverse_components=compute_inverse_components,\n random_state=random_state,\n )\n \n", "test_patch": "diff --git a/sklearn/tests/test_random_projection.py b/sklearn/tests/test_random_projection.py\nindex a3a6b1ae2a49f..4d21090a3e6fb 100644\n--- a/sklearn/tests/test_random_projection.py\n+++ b/sklearn/tests/test_random_projection.py\n@@ -1,5 +1,6 @@\n import functools\n from typing import List, Any\n+import warnings\n \n import numpy as np\n import scipy.sparse as sp\n@@ -31,8 +32,8 @@\n \n # Make some random data with uniformly located non zero entries with\n # Gaussian distributed values\n-def make_sparse_random_data(n_samples, n_features, n_nonzeros):\n- rng = np.random.RandomState(0)\n+def make_sparse_random_data(n_samples, n_features, n_nonzeros, random_state=0):\n+ rng = np.random.RandomState(random_state)\n data_coo = sp.coo_matrix(\n (\n rng.randn(n_nonzeros),\n@@ -377,6 +378,57 @@ def test_random_projection_feature_names_out(random_projection_cls):\n assert_array_equal(names_out, expected_names_out)\n \n \n+@pytest.mark.parametrize(\"n_samples\", (2, 9, 10, 11, 1000))\n+@pytest.mark.parametrize(\"n_features\", (2, 9, 10, 11, 1000))\n+@pytest.mark.parametrize(\"random_projection_cls\", all_RandomProjection)\n+@pytest.mark.parametrize(\"compute_inverse_components\", [True, False])\n+def test_inverse_transform(\n+ n_samples,\n+ n_features,\n+ random_projection_cls,\n+ compute_inverse_components,\n+ global_random_seed,\n+):\n+ n_components = 10\n+\n+ random_projection = random_projection_cls(\n+ n_components=n_components,\n+ compute_inverse_components=compute_inverse_components,\n+ random_state=global_random_seed,\n+ )\n+\n+ X_dense, X_csr = make_sparse_random_data(\n+ n_samples,\n+ n_features,\n+ n_samples * n_features // 100 + 1,\n+ random_state=global_random_seed,\n+ )\n+\n+ for X in [X_dense, X_csr]:\n+ with warnings.catch_warnings():\n+ warnings.filterwarnings(\n+ \"ignore\",\n+ message=(\n+ \"The number of components is higher than the number of features\"\n+ ),\n+ category=DataDimensionalityWarning,\n+ )\n+ projected = random_projection.fit_transform(X)\n+\n+ if compute_inverse_components:\n+ assert hasattr(random_projection, \"inverse_components_\")\n+ inv_components = random_projection.inverse_components_\n+ assert inv_components.shape == (n_features, n_components)\n+\n+ projected_back = random_projection.inverse_transform(projected)\n+ assert projected_back.shape == X.shape\n+\n+ projected_again = random_projection.transform(projected_back)\n+ if hasattr(projected, \"toarray\"):\n+ projected = projected.toarray()\n+ assert_allclose(projected, projected_again, rtol=1e-7, atol=1e-10)\n+\n+\n @pytest.mark.parametrize(\"random_projection_cls\", all_RandomProjection)\n @pytest.mark.parametrize(\n \"input_dtype, expected_dtype\",\n", "doc_changes": [{"path": "doc/modules/random_projection.rst", "old_path": "a/doc/modules/random_projection.rst", "new_path": "b/doc/modules/random_projection.rst", "metadata": "diff --git a/doc/modules/random_projection.rst b/doc/modules/random_projection.rst\nindex adb2d53bd14d6..7d3341f0244bb 100644\n--- a/doc/modules/random_projection.rst\n+++ b/doc/modules/random_projection.rst\n@@ -160,3 +160,42 @@ projection transformer::\n In Proceedings of the 12th ACM SIGKDD international conference on\n Knowledge discovery and data mining (KDD '06). ACM, New York, NY, USA,\n 287-296.\n+\n+\n+.. _random_projection_inverse_transform:\n+\n+Inverse Transform\n+=================\n+The random projection transformers have ``compute_inverse_components`` parameter. When\n+set to True, after creating the random ``components_`` matrix during fitting,\n+the transformer computes the pseudo-inverse of this matrix and stores it as\n+``inverse_components_``. The ``inverse_components_`` matrix has shape\n+:math:`n_{features} \\times n_{components}`, and it is always a dense matrix,\n+regardless of whether the components matrix is sparse or dense. So depending on\n+the number of features and components, it may use a lot of memory.\n+\n+When the ``inverse_transform`` method is called, it computes the product of the\n+input ``X`` and the transpose of the inverse components. If the inverse components have\n+been computed during fit, they are reused at each call to ``inverse_transform``.\n+Otherwise they are recomputed each time, which can be costly. The result is always\n+dense, even if ``X`` is sparse.\n+\n+Here a small code example which illustrates how to use the inverse transform\n+feature::\n+\n+ >>> import numpy as np\n+ >>> from sklearn.random_projection import SparseRandomProjection\n+ >>> X = np.random.rand(100, 10000)\n+ >>> transformer = SparseRandomProjection(\n+ ... compute_inverse_components=True\n+ ... )\n+ ...\n+ >>> X_new = transformer.fit_transform(X)\n+ >>> X_new.shape\n+ (100, 3947)\n+ >>> X_new_inversed = transformer.inverse_transform(X_new)\n+ >>> X_new_inversed.shape\n+ (100, 10000)\n+ >>> X_new_again = transformer.transform(X_new_inversed)\n+ >>> np.allclose(X_new, X_new_again)\n+ True\n"}, {"path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 5030ed8faa4a1..e66640cfd2d21 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -791,6 +791,14 @@ Changelog\n :class:`random_projection.GaussianRandomProjection` preserves dtype for\n `numpy.float32`. :pr:`22114` by :user:`Takeshi Oura `.\n \n+- |Enhancement| Adds an :meth:`inverse_transform` method and a\n+ `compute_inverse_transform` parameter to all transformers in the\n+ :mod:`~sklearn.random_projection` module:\n+ :class:`~sklearn.random_projection.GaussianRandomProjection` and\n+ :class:`~sklearn.random_projection.SparseRandomProjection`. When the parameter is set\n+ to True, the pseudo-inverse of the components is computed during `fit` and stored as\n+ `inverse_components_`. :pr:`21701` by `Aur\u00e9lien Geron `.\n+\n - |API| Adds :term:`get_feature_names_out` to all transformers in the\n :mod:`~sklearn.random_projection` module:\n :class:`~sklearn.random_projection.GaussianRandomProjection` and\n"}], "version": "1.01", "base_commit": "a794c58692a1f3e7a85a42d8c7f7ddd5fcf18baa", "PASS2PASS": ["sklearn/tests/test_random_projection.py::test_sparse_random_projection_transformer_invalid_density[0]", "sklearn/tests/test_random_projection.py::test_random_projection_feature_names_out[GaussianRandomProjection]", "sklearn/tests/test_random_projection.py::test_try_to_transform_before_fit", "sklearn/tests/test_random_projection.py::test_warning_n_components_greater_than_n_features", "sklearn/tests/test_random_projection.py::test_random_projection_numerical_consistency[SparseRandomProjection]", "sklearn/tests/test_random_projection.py::test_random_projection_dtype_match[float32-float32-SparseRandomProjection]", "sklearn/tests/test_random_projection.py::test_too_many_samples_to_find_a_safe_embedding", "sklearn/tests/test_random_projection.py::test_random_projection_dtype_match[int32-float64-SparseRandomProjection]", "sklearn/tests/test_random_projection.py::test_sparse_random_projection_transformer_invalid_density[1.1]", "sklearn/tests/test_random_projection.py::test_invalid_jl_domain[0-0.5]", "sklearn/tests/test_random_projection.py::test_basic_property_of_random_matrix[_gaussian_random_matrix]", "sklearn/tests/test_random_projection.py::test_invalid_jl_domain[100--0.1]", "sklearn/tests/test_random_projection.py::test_random_projection_numerical_consistency[GaussianRandomProjection]", "sklearn/tests/test_random_projection.py::test_random_projection_dtype_match[float64-float64-SparseRandomProjection]", "sklearn/tests/test_random_projection.py::test_random_projection_dtype_match[float32-float32-GaussianRandomProjection]", "sklearn/tests/test_random_projection.py::test_random_projection_dtype_match[int32-float64-GaussianRandomProjection]", "sklearn/tests/test_random_projection.py::test_johnson_lindenstrauss_min_dim", "sklearn/tests/test_random_projection.py::test_random_projection_dtype_match[int64-float64-GaussianRandomProjection]", "sklearn/tests/test_random_projection.py::test_invalid_jl_domain[100-1.1]", "sklearn/tests/test_random_projection.py::test_basic_property_of_sparse_random_matrix[_sparse_random_matrix]", "sklearn/tests/test_random_projection.py::test_input_size_jl_min_dim", "sklearn/tests/test_random_projection.py::test_random_projection_transformer_invalid_input[auto-fit_data0]", "sklearn/tests/test_random_projection.py::test_sparse_random_matrix", "sklearn/tests/test_random_projection.py::test_random_projection_dtype_match[int64-float64-SparseRandomProjection]", "sklearn/tests/test_random_projection.py::test_invalid_jl_domain[100-0.0]", "sklearn/tests/test_random_projection.py::test_random_projection_transformer_invalid_input[-10-fit_data1]", "sklearn/tests/test_random_projection.py::test_correct_RandomProjection_dimensions_embedding", "sklearn/tests/test_random_projection.py::test_random_projection_dtype_match[float64-float64-GaussianRandomProjection]", "sklearn/tests/test_random_projection.py::test_random_projection_feature_names_out[SparseRandomProjection]", "sklearn/tests/test_random_projection.py::test_works_with_sparse_data", "sklearn/tests/test_random_projection.py::test_random_projection_embedding_quality", "sklearn/tests/test_random_projection.py::test_SparseRandomProj_output_representation", "sklearn/tests/test_random_projection.py::test_sparse_random_projection_transformer_invalid_density[-0.1]", "sklearn/tests/test_random_projection.py::test_gaussian_random_matrix", "sklearn/tests/test_random_projection.py::test_basic_property_of_random_matrix[_sparse_random_matrix]"], "FAIL2PASS": ["sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-1000-9]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-9-2]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-9-9]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-2-2]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-10-2]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-1000-11]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-9-10]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-1000-10]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-10-1000]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-9-11]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-1000-11]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-2-10]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-11-1000]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-2-11]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-2-1000]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-11-1000]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-1000-9]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-11-11]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-2-9]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-10-10]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-10-10]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-1000-10]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-2-11]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-9-1000]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-2-10]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-10-11]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-2-9]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-2-9]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-11-10]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-1000-2]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-1000-1000]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-10-2]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-9-1000]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-9-10]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-9-11]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-10-10]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-1000-2]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-10-2]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-9-11]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-10-9]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-1000-2]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-2-11]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-11-2]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-10-11]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-11-1000]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-2-10]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-9-9]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-10-10]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-10-2]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-11-10]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-1000-9]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-1000-11]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-11-10]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-10-11]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-9-2]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-11-1000]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-10-1000]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-2-1000]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-2-2]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-10-1000]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-2-2]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-2-2]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-2-10]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-9-10]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-9-9]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-11-9]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-11-11]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-10-9]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-11-9]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-2-1000]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-10-1000]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-11-9]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-1000-10]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-9-11]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-9-2]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-1000-1000]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-10-9]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-11-2]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-9-9]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-1000-10]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-2-1000]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-1000-1000]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-11-11]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-1000-9]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-11-2]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-9-10]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-1000-11]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-11-11]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-11-10]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-GaussianRandomProjection-11-2]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-10-9]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-2-9]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-11-9]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-1000-2]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-True-SparseRandomProjection-9-1000]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-9-2]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-10-11]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-2-11]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-GaussianRandomProjection-1000-1000]", "sklearn/tests/test_random_projection.py::test_inverse_transform[42-False-SparseRandomProjection-9-1000]"], "mask_doc_diff": [{"path": "doc/modules/random_projection.rst", "old_path": "a/doc/modules/random_projection.rst", "new_path": "b/doc/modules/random_projection.rst", "metadata": "diff --git a/doc/modules/random_projection.rst b/doc/modules/random_projection.rst\nindex adb2d53bd..7d3341f02 100644\n--- a/doc/modules/random_projection.rst\n+++ b/doc/modules/random_projection.rst\n@@ -160,3 +160,42 @@ projection transformer::\n In Proceedings of the 12th ACM SIGKDD international conference on\n Knowledge discovery and data mining (KDD '06). ACM, New York, NY, USA,\n 287-296.\n+\n+\n+.. _random_projection_inverse_transform:\n+\n+Inverse Transform\n+=================\n+The random projection transformers have ``compute_inverse_components`` parameter. When\n+set to True, after creating the random ``components_`` matrix during fitting,\n+the transformer computes the pseudo-inverse of this matrix and stores it as\n+``inverse_components_``. The ``inverse_components_`` matrix has shape\n+:math:`n_{features} \\times n_{components}`, and it is always a dense matrix,\n+regardless of whether the components matrix is sparse or dense. So depending on\n+the number of features and components, it may use a lot of memory.\n+\n+When the ``inverse_transform`` method is called, it computes the product of the\n+input ``X`` and the transpose of the inverse components. If the inverse components have\n+been computed during fit, they are reused at each call to ``inverse_transform``.\n+Otherwise they are recomputed each time, which can be costly. The result is always\n+dense, even if ``X`` is sparse.\n+\n+Here a small code example which illustrates how to use the inverse transform\n+feature::\n+\n+ >>> import numpy as np\n+ >>> from sklearn.random_projection import SparseRandomProjection\n+ >>> X = np.random.rand(100, 10000)\n+ >>> transformer = SparseRandomProjection(\n+ ... compute_inverse_components=True\n+ ... )\n+ ...\n+ >>> X_new = transformer.fit_transform(X)\n+ >>> X_new.shape\n+ (100, 3947)\n+ >>> X_new_inversed = transformer.inverse_transform(X_new)\n+ >>> X_new_inversed.shape\n+ (100, 10000)\n+ >>> X_new_again = transformer.transform(X_new_inversed)\n+ >>> np.allclose(X_new, X_new_again)\n+ True\n"}, {"path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 5030ed8fa..e75c70abd 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -791,6 +791,14 @@ Changelog\n :class:`random_projection.GaussianRandomProjection` preserves dtype for\n `numpy.float32`. :pr:`22114` by :user:`Takeshi Oura `.\n \n+- |Enhancement| Adds an :meth:`inverse_transform` method and a\n+ `compute_inverse_transform` parameter to all transformers in the\n+ :mod:`~sklearn.random_projection` module:\n+ :class:`~sklearn.random_projection.GaussianRandomProjection` and\n+ :class:`~sklearn.random_projection.SparseRandomProjection`. When the parameter is set\n+ to True, the pseudo-inverse of the components is computed during `fit` and stored as\n+ `inverse_components_`.\n+\n - |API| Adds :term:`get_feature_names_out` to all transformers in the\n :mod:`~sklearn.random_projection` module:\n :class:`~sklearn.random_projection.GaussianRandomProjection` and\n"}], "augmentations": {"header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": []}, "problem_statement": "diff --git a/doc/modules/random_projection.rst b/doc/modules/random_projection.rst\nindex adb2d53bd..7d3341f02 100644\n--- a/doc/modules/random_projection.rst\n+++ b/doc/modules/random_projection.rst\n@@ -160,3 +160,42 @@ projection transformer::\n In Proceedings of the 12th ACM SIGKDD international conference on\n Knowledge discovery and data mining (KDD '06). ACM, New York, NY, USA,\n 287-296.\n+\n+\n+.. _random_projection_inverse_transform:\n+\n+Inverse Transform\n+=================\n+The random projection transformers have ``compute_inverse_components`` parameter. When\n+set to True, after creating the random ``components_`` matrix during fitting,\n+the transformer computes the pseudo-inverse of this matrix and stores it as\n+``inverse_components_``. The ``inverse_components_`` matrix has shape\n+:math:`n_{features} \\times n_{components}`, and it is always a dense matrix,\n+regardless of whether the components matrix is sparse or dense. So depending on\n+the number of features and components, it may use a lot of memory.\n+\n+When the ``inverse_transform`` method is called, it computes the product of the\n+input ``X`` and the transpose of the inverse components. If the inverse components have\n+been computed during fit, they are reused at each call to ``inverse_transform``.\n+Otherwise they are recomputed each time, which can be costly. The result is always\n+dense, even if ``X`` is sparse.\n+\n+Here a small code example which illustrates how to use the inverse transform\n+feature::\n+\n+ >>> import numpy as np\n+ >>> from sklearn.random_projection import SparseRandomProjection\n+ >>> X = np.random.rand(100, 10000)\n+ >>> transformer = SparseRandomProjection(\n+ ... compute_inverse_components=True\n+ ... )\n+ ...\n+ >>> X_new = transformer.fit_transform(X)\n+ >>> X_new.shape\n+ (100, 3947)\n+ >>> X_new_inversed = transformer.inverse_transform(X_new)\n+ >>> X_new_inversed.shape\n+ (100, 10000)\n+ >>> X_new_again = transformer.transform(X_new_inversed)\n+ >>> np.allclose(X_new, X_new_again)\n+ True\n\ndiff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 5030ed8fa..e75c70abd 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -791,6 +791,14 @@ Changelog\n :class:`random_projection.GaussianRandomProjection` preserves dtype for\n `numpy.float32`. :pr:`22114` by :user:`Takeshi Oura `.\n \n+- |Enhancement| Adds an :meth:`inverse_transform` method and a\n+ `compute_inverse_transform` parameter to all transformers in the\n+ :mod:`~sklearn.random_projection` module:\n+ :class:`~sklearn.random_projection.GaussianRandomProjection` and\n+ :class:`~sklearn.random_projection.SparseRandomProjection`. When the parameter is set\n+ to True, the pseudo-inverse of the components is computed during `fit` and stored as\n+ `inverse_components_`.\n+\n - |API| Adds :term:`get_feature_names_out` to all transformers in the\n :mod:`~sklearn.random_projection` module:\n :class:`~sklearn.random_projection.GaussianRandomProjection` and\n\n"} {"repo": "scikit-learn/scikit-learn", "instance_id": "scikit-learn__scikit-learn-22950", "html_url": "https://github.com/scikit-learn/scikit-learn/pull/22950", "feature_patch": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 732d2e8035aa6..4c61e08c15149 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -636,6 +636,10 @@ Changelog\n of sample weights when the input is sparse.\n :pr:`22899` by :user:`J\u00e9r\u00e9mie du Boisberranger `.\n \n+- |Feature| :class:`Ridge` with `solver=\"lsqr\"` now supports to fit sparse input with\n+ `fit_intercept=True`.\n+ :pr:`22950` by :user:`Christian Lorentzen `.\n+\n :mod:`sklearn.manifold`\n .......................\n \ndiff --git a/sklearn/linear_model/_ridge.py b/sklearn/linear_model/_ridge.py\nindex 900b5f7c221db..e05f68388ffd6 100644\n--- a/sklearn/linear_model/_ridge.py\n+++ b/sklearn/linear_model/_ridge.py\n@@ -40,6 +40,22 @@\n from ..utils.sparsefuncs import mean_variance_axis\n \n \n+def _get_rescaled_operator(X, X_offset, sample_weight_sqrt):\n+ \"\"\"Create LinearOperator for matrix products with implicit centering.\n+\n+ Matrix product `LinearOperator @ coef` returns `(X - X_offset) @ coef`.\n+ \"\"\"\n+\n+ def matvec(b):\n+ return X.dot(b) - sample_weight_sqrt * b.dot(X_offset)\n+\n+ def rmatvec(b):\n+ return X.T.dot(b) - X_offset * b.dot(sample_weight_sqrt)\n+\n+ X1 = sparse.linalg.LinearOperator(shape=X.shape, matvec=matvec, rmatvec=rmatvec)\n+ return X1\n+\n+\n def _solve_sparse_cg(\n X,\n y,\n@@ -54,25 +70,13 @@ def _solve_sparse_cg(\n if sample_weight_sqrt is None:\n sample_weight_sqrt = np.ones(X.shape[0], dtype=X.dtype)\n \n- def _get_rescaled_operator(X):\n-\n- X_offset_scale = X_offset / X_scale\n-\n- def matvec(b):\n- return X.dot(b) - sample_weight_sqrt * b.dot(X_offset_scale)\n-\n- def rmatvec(b):\n- return X.T.dot(b) - X_offset_scale * b.dot(sample_weight_sqrt)\n-\n- X1 = sparse.linalg.LinearOperator(shape=X.shape, matvec=matvec, rmatvec=rmatvec)\n- return X1\n-\n n_samples, n_features = X.shape\n \n if X_offset is None or X_scale is None:\n X1 = sp_linalg.aslinearoperator(X)\n else:\n- X1 = _get_rescaled_operator(X)\n+ X_offset_scale = X_offset / X_scale\n+ X1 = _get_rescaled_operator(X, X_offset_scale, sample_weight_sqrt)\n \n coefs = np.empty((y.shape[1], n_features), dtype=X.dtype)\n \n@@ -137,7 +141,44 @@ def _mv(x):\n return coefs\n \n \n-def _solve_lsqr(X, y, alpha, max_iter=None, tol=1e-3):\n+def _solve_lsqr(\n+ X,\n+ y,\n+ *,\n+ alpha,\n+ fit_intercept=True,\n+ max_iter=None,\n+ tol=1e-3,\n+ X_offset=None,\n+ X_scale=None,\n+ sample_weight_sqrt=None,\n+):\n+ \"\"\"Solve Ridge regression via LSQR.\n+\n+ We expect that y is always mean centered.\n+ If X is dense, we expect it to be mean centered such that we can solve\n+ ||y - Xw||_2^2 + alpha * ||w||_2^2\n+\n+ If X is sparse, we expect X_offset to be given such that we can solve\n+ ||y - (X - X_offset)w||_2^2 + alpha * ||w||_2^2\n+\n+ With sample weights S=diag(sample_weight), this becomes\n+ ||sqrt(S) (y - (X - X_offset) w)||_2^2 + alpha * ||w||_2^2\n+ and we expect y and X to already be rescaled, i.e. sqrt(S) @ y, sqrt(S) @ X. In\n+ this case, X_offset is the sample_weight weighted mean of X before scaling by\n+ sqrt(S). The objective then reads\n+ ||y - (X - sqrt(S) X_offset) w)||_2^2 + alpha * ||w||_2^2\n+ \"\"\"\n+ if sample_weight_sqrt is None:\n+ sample_weight_sqrt = np.ones(X.shape[0], dtype=X.dtype)\n+\n+ if sparse.issparse(X) and fit_intercept:\n+ X_offset_scale = X_offset / X_scale\n+ X1 = _get_rescaled_operator(X, X_offset_scale, sample_weight_sqrt)\n+ else:\n+ # No need to touch anything\n+ X1 = X\n+\n n_samples, n_features = X.shape\n coefs = np.empty((y.shape[1], n_features), dtype=X.dtype)\n n_iter = np.empty(y.shape[1], dtype=np.int32)\n@@ -148,7 +189,7 @@ def _solve_lsqr(X, y, alpha, max_iter=None, tol=1e-3):\n for i in range(y.shape[1]):\n y_column = y[:, i]\n info = sp_linalg.lsqr(\n- X, y_column, damp=sqrt_alpha[i], atol=tol, btol=tol, iter_lim=max_iter\n+ X1, y_column, damp=sqrt_alpha[i], atol=tol, btol=tol, iter_lim=max_iter\n )\n coefs[i] = info[0]\n n_iter[i] = info[2]\n@@ -351,7 +392,7 @@ def ridge_regression(\n ----------\n X : {ndarray, sparse matrix, LinearOperator} of shape \\\n (n_samples, n_features)\n- Training data\n+ Training data.\n \n y : ndarray of shape (n_samples,) or (n_samples, n_targets)\n Target values.\n@@ -409,9 +450,9 @@ def ridge_regression(\n `scipy.optimize.minimize`. It can be used only when `positive`\n is True.\n \n- All last six solvers support both dense and sparse data. However, only\n- 'sag', 'sparse_cg', and 'lbfgs' support sparse input when `fit_intercept`\n- is True.\n+ All solvers except 'svd' support both dense and sparse data. However, only\n+ 'lsqr', 'sag', 'sparse_cg', and 'lbfgs' support sparse input when\n+ `fit_intercept` is True.\n \n .. versionadded:: 0.17\n Stochastic Average Gradient descent solver.\n@@ -518,6 +559,7 @@ def _ridge_regression(\n X_scale=None,\n X_offset=None,\n check_input=True,\n+ fit_intercept=False,\n ):\n \n has_sw = sample_weight is not None\n@@ -629,7 +671,17 @@ def _ridge_regression(\n )\n \n elif solver == \"lsqr\":\n- coef, n_iter = _solve_lsqr(X, y, alpha, max_iter, tol)\n+ coef, n_iter = _solve_lsqr(\n+ X,\n+ y,\n+ alpha=alpha,\n+ fit_intercept=fit_intercept,\n+ max_iter=max_iter,\n+ tol=tol,\n+ X_offset=X_offset,\n+ X_scale=X_scale,\n+ sample_weight_sqrt=sample_weight_sqrt if has_sw else None,\n+ )\n \n elif solver == \"cholesky\":\n if n_features > n_samples:\n@@ -764,15 +816,15 @@ def fit(self, X, y, sample_weight=None):\n else:\n solver = self.solver\n elif sparse.issparse(X) and self.fit_intercept:\n- if self.solver not in [\"auto\", \"sparse_cg\", \"sag\", \"lbfgs\"]:\n+ if self.solver not in [\"auto\", \"lbfgs\", \"lsqr\", \"sag\", \"sparse_cg\"]:\n raise ValueError(\n \"solver='{}' does not support fitting the intercept \"\n \"on sparse data. Please set the solver to 'auto' or \"\n- \"'sparse_cg', 'sag', 'lbfgs' \"\n+ \"'lsqr', 'sparse_cg', 'sag', 'lbfgs' \"\n \"or set `fit_intercept=False`\".format(self.solver)\n )\n- if self.solver == \"lbfgs\":\n- solver = \"lbfgs\"\n+ if self.solver in [\"lsqr\", \"lbfgs\"]:\n+ solver = self.solver\n elif self.solver == \"sag\" and self.max_iter is None and self.tol > 1e-4:\n warnings.warn(\n '\"sag\" solver requires many iterations to fit '\n@@ -846,6 +898,7 @@ def fit(self, X, y, sample_weight=None):\n return_n_iter=True,\n return_intercept=False,\n check_input=False,\n+ fit_intercept=self.fit_intercept,\n **params,\n )\n self._set_intercept(X_offset, y_offset, X_scale)\n@@ -944,9 +997,9 @@ class Ridge(MultiOutputMixin, RegressorMixin, _BaseRidge):\n `scipy.optimize.minimize`. It can be used only when `positive`\n is True.\n \n- All last six solvers support both dense and sparse data. However, only\n- 'sag', 'sparse_cg', and 'lbfgs' support sparse input when `fit_intercept`\n- is True.\n+ All solvers except 'svd' support both dense and sparse data. However, only\n+ 'lsqr', 'sag', 'sparse_cg', and 'lbfgs' support sparse input when\n+ `fit_intercept` is True.\n \n .. versionadded:: 0.17\n Stochastic Average Gradient descent solver.\n", "test_patch": "diff --git a/sklearn/linear_model/tests/test_ridge.py b/sklearn/linear_model/tests/test_ridge.py\nindex 269952ddad659..e3bd6c6146ee9 100644\n--- a/sklearn/linear_model/tests/test_ridge.py\n+++ b/sklearn/linear_model/tests/test_ridge.py\n@@ -1362,7 +1362,7 @@ def test_n_iter():\n assert reg.n_iter_ is None\n \n \n-@pytest.mark.parametrize(\"solver\", [\"sparse_cg\", \"lbfgs\", \"auto\"])\n+@pytest.mark.parametrize(\"solver\", [\"lsqr\", \"sparse_cg\", \"lbfgs\", \"auto\"])\n @pytest.mark.parametrize(\"with_sample_weight\", [True, False])\n def test_ridge_fit_intercept_sparse(solver, with_sample_weight, global_random_seed):\n \"\"\"Check that ridge finds the same coefs and intercept on dense and sparse input\n@@ -1400,7 +1400,7 @@ def test_ridge_fit_intercept_sparse(solver, with_sample_weight, global_random_se\n assert_allclose(dense_ridge.coef_, sparse_ridge.coef_)\n \n \n-@pytest.mark.parametrize(\"solver\", [\"saga\", \"lsqr\", \"svd\", \"cholesky\"])\n+@pytest.mark.parametrize(\"solver\", [\"saga\", \"svd\", \"cholesky\"])\n def test_ridge_fit_intercept_sparse_error(solver):\n X, y = _make_sparse_offset_regression(n_features=20, random_state=0)\n X_csr = sp.csr_matrix(X)\n", "doc_changes": [{"path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex 732d2e8035aa6..4c61e08c15149 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -636,6 +636,10 @@ Changelog\n of sample weights when the input is sparse.\n :pr:`22899` by :user:`J\u00e9r\u00e9mie du Boisberranger `.\n \n+- |Feature| :class:`Ridge` with `solver=\"lsqr\"` now supports to fit sparse input with\n+ `fit_intercept=True`.\n+ :pr:`22950` by :user:`Christian Lorentzen `.\n+\n :mod:`sklearn.manifold`\n .......................\n \n"}], "version": "1.01", "base_commit": "48f363f35abec5b3611f96a2b91e9d4e2e1ce527", "PASS2PASS": ["sklearn/linear_model/tests/test_ridge.py::test_compute_gram[True-shape4]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_ground_truth_positive_test[0.001-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[svd-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-40-float32-1.0-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float64-0.2-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float32-0.1-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-40-float32-1.0-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_alphas_conversion[RidgeClassifierCV]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float32-0.1-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.001-True-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_int_alphas", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-40-float32-1.0-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape0-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weights", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[auto-svd-eigen-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge[sag]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float64-0.2-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[SPARSE_FILTER-None-None]", "sklearn/linear_model/tests/test_ridge.py::test_X_CenterStackOp[n_col1]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-csr_matrix-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_best_score[None-ridge1-make_classification]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sag_with_X_fortran", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.01-False-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-40-float32-1.0-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float64-0.2-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-csr_matrix-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-csr_matrix-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_dtype_stability[0-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape1-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-40-float32-1.0-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-array-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_error[True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-40-float32-1.0-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_class_weight_vs_sample_weight[RidgeClassifier]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.1-False-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float64-0.2-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[auto-svd-eigen-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape0-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_alphas_validation[params2-TypeError-alphas\\\\[2\\\\] must be an instance of float, not str-RidgeCV]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[svd-svd-svd-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_fit_intercept_sparse[42-False-auto]", "sklearn/linear_model/tests/test_ridge.py::test_X_CenterStackOp[n_col2]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float64-0.2-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[False-shape1]", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_ridge_classifiers]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_fit_intercept_sparse[42-True-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float32-0.1-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float64-0.2-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-40-float32-1.0-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float32-0.1-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[False-shape4]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float64-0.2-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[SPARSE_FILTER-None-_accuracy_callable]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_error[1]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float64-0.2-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-8-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_store_cv_values[_mean_squared_error_callable]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape1-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float64-0.2-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-40-float32-1.0-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_fit_intercept_sparse[42-True-sparse_cg]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-csr_matrix-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-20-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-csr_matrix-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-40-float32-1.0-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_custom_scoring[SPARSE_FILTER-cv1]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float32-0.1-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[True-shape0]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_error[5]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-csr_matrix-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lbfgs-array-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape1-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-csr_matrix-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-8-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-20-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float32-0.1-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape1-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_params_validation[params0-ValueError-alpha == -1, must be >= 0.0]", "sklearn/linear_model/tests/test_ridge.py::test_lbfgs_solver_consistency[0.01]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[lsqr-True]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match[lsqr]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[lbfgs-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-8-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_alphas_scalar[RidgeClassifierCV]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.01-True-auto]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape0-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float64-0.2-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-8-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_fit_intercept_sparse[42-False-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape1-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-csr_matrix-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_cv_values_not_stored[ridge1-make_classification]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_ground_truth_positive_test[0.01-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_params_validation[params1-TypeError-alpha must be an instance of float, not str]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-array-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[False-shape1]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape1-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float32-0.1-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-40-float32-1.0-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float64-0.2-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float32-0.1-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float32-0.1-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-40-float32-1.0-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_primal_dual_relationship", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_cv_store_cv_values[None]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-40-float32-1.0-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[None-svd-eigen-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-20-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_custom_scoring[DENSE_FILTER-None]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-40-float32-1.0-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_custom_scoring[SPARSE_FILTER-None]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-array-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape0-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape0-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[DENSE_FILTER-cv1-None]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-csr_matrix-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-8-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-40-float32-1.0-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape0-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.1-True-auto]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-40-float32-1.0-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[cholesky-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-csr_matrix-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float64-0.2-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[True-shape1]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_error_test[sparse_cg]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-8-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float64-0.2-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_ridge_loo]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[False-shape0]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float32-0.1-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-40-float32-1.0-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-40-float32-1.0-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_error[bad]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.1-False-auto]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float64-0.2-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_alphas_validation[params0-ValueError-alphas\\\\[1\\\\] == -1, must be > 0.0-RidgeClassifierCV]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float64-0.2-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_fit_intercept_sparse_error[saga]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[False-shape2]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lbfgs-csr_matrix-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_X_CenterStackOp[n_col0]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float32-0.1-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float32-0.1-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_ridge_cv_normalize]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-40-float32-1.0-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape0-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[True-shape3]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[False-shape2]", "sklearn/linear_model/tests/test_ridge.py::test_ridge[sparse_cg]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-40-float32-1.0-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lbfgs-csr_matrix-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-csr_matrix-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-csr_matrix-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_shapes", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float64-0.2-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float32-0.1-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-array-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match[lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-40-float32-1.0-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float32-0.1-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-40-float32-1.0-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[DENSE_FILTER-None-accuracy]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_vs_lstsq", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float64-0.2-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape0-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[False-shape0]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-8-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.1-True-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float32-0.1-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_store_cv_values[neg_mean_squared_error]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[1.0-True-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-40-float32-1.0-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float64-0.2-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-8-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_ground_truth_positive_test[1.0-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float32-0.1-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_raises_value_error_if_solver_not_supported", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float32-0.1-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float64-0.2-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-array-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-csr_matrix-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape1-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-array-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-array-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float64-0.2-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape1-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-array-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_best_score[3-ridge0-make_regression]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape0-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_sample_weight", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float64-0.2-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[True-shape4]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[DENSE_FILTER-None-_accuracy_callable]", "sklearn/linear_model/tests/test_ridge.py::test_sparse_design_with_sample_weights", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float32-0.1-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lbfgs-array-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_normalize_deprecated[RidgeClassifierCV]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float32-0.1-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float64-0.2-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-20-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float64-0.2-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape1-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float64-0.2-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[SPARSE_FILTER-cv1-_accuracy_callable]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_alphas_conversion[RidgeCV]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-array-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.001-False-auto]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_params_validation[params5-TypeError-tol must be an instance of float, not str]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match[sparse_cg]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float32-0.1-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-40-float32-1.0-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_class_weight_vs_sample_weight[RidgeClassifierCV]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[DENSE_FILTER-cv1-accuracy]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.001-False-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_alphas_validation[params2-TypeError-alphas\\\\[2\\\\] must be an instance of float, not str-RidgeClassifierCV]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[True-shape2]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_ground_truth_positive_test[0.1-True]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[eigen-eigen-eigen-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float64-0.2-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float64-0.2-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match_cholesky", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-40-float32-1.0-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-array-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[1.0-False-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.01-True-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float64-0.2-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float64-0.2-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[DENSE_FILTER-None-None]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape1-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_fit_intercept_sparse_sag[42-False]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[False-shape4]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-40-float32-1.0-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float32-0.1-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float64-0.2-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-20-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-array-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape1-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape1-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-csr_matrix-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape1-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float64-0.2-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_ridge_cv]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.001-True-auto]", "sklearn/linear_model/tests/test_ridge.py::test_positive_ridge_loss[0.1]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-array-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float64-0.2-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-20-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-40-float32-1.0-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_best_score[3-ridge1-make_classification]", "sklearn/linear_model/tests/test_ridge.py::test_ridge[cholesky]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape0-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape0-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-40-float32-1.0-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float64-0.2-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape0-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-8-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_individual_penalties", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape0-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_lbfgs_solver_consistency[0.1]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-40-float32-1.0-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-20-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_error_test[sag]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_sample_weights", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_sparse_cg_max_iter", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-array-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_dtype_stability[0-cholesky]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float32-0.1-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_fit_intercept_sparse_error[svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-40-float32-1.0-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_cv_values_not_stored[ridge0-make_regression]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sparse_svd", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape0-True-1.0-20-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_normalize_deprecated[RidgeCV]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match[svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_params_validation[params2-ValueError-max_iter == 0, must be >= 1.]", "sklearn/linear_model/tests/test_ridge.py::test_positive_ridge_loss[0.001]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[False-shape3]", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_ridge_diabetes]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float32-0.1-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[SPARSE_FILTER-None-accuracy]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-40-float32-1.0-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-8-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_lbfgs_solver_error", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-40-float32-1.0-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-array-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-20-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-csr_matrix-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sparse_cg-array-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-8-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float64-0.2-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float64-0.2-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-20-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridgeclassifier_multilabel[RidgeClassifierCV-params1]", "sklearn/linear_model/tests/test_ridge.py::test_compute_gram[True-shape0]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[True-shape3]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float32-0.1-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-40-float32-1.0-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-array-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[DENSE_FILTER-cv1-_accuracy_callable]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_fit_intercept_sparse[42-False-sparse_cg]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float32-0.1-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-20-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-40-float32-1.0-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lsqr-array-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-8-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_tolerance]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_alphas_validation[params0-ValueError-alphas\\\\[1\\\\] == -1, must be > 0.0-RidgeCV]", "sklearn/linear_model/tests/test_ridge.py::test_class_weights", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape1-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lbfgs-array-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-array-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_error_test[cholesky]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape1-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridgeclassifier_multilabel[RidgeClassifier-params0]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_alphas_scalar[RidgeCV]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float32-0.1-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float32-0.1-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_error_test[saga]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float32-0.1-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_alphas_validation[params1-ValueError-alphas\\\\[0\\\\] == -0.1, must be > 0.0-RidgeCV]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float32-0.1-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float32-0.1-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_loo_cv_asym_scoring", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match[saga]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float64-0.2-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-csr_matrix-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-20-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_singular", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-40-float32-1.0-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float32-0.1-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape1-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_alphas_validation[params1-ValueError-alphas\\\\[0\\\\] == -0.1, must be > 0.0-RidgeClassifierCV]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-20-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-csr_matrix-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-40-float32-1.0-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_fit_intercept_sparse[42-True-auto]", "sklearn/linear_model/tests/test_ridge.py::test_positive_ridge_loss[0.01]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-array-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float32-0.1-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape0-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float32-0.1-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridgecv_store_cv_values[None]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape0-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float32-0.1-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape0-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float32-0.1-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape0-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_intercept", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape1-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[1.0-True-auto]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[SPARSE_FILTER-cv1-accuracy]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float64-0.2-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match[cholesky]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-40-float32-1.0-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_ground_truth_positive_test[0.001-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-40-float32-1.0-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-40-float32-1.0-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_fit_intercept_sparse_error[cholesky]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_error_test[lsqr]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape0-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[1.0-False-auto]", "sklearn/linear_model/tests/test_ridge.py::test_positive_ridge_loss[1.0]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-8-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_cv_store_cv_values[accuracy]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[svd-svd-svd-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_params_validation[params3-TypeError-max_iter must be an instance of int, not str]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape0-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[svd-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-8-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float64-0.2-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-40-float32-1.0-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-array-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float64-0.2-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape1-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float32-0.1-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_dtype_stability[0-sag]", "sklearn/linear_model/tests/test_ridge.py::test_dense_sparse[_test_multi_ridge_diabetes]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-array-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-False-X_shape1-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-csr_matrix-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-40-float32-1.0-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape1-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lbfgs-csr_matrix-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float64-0.2-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float64-0.2-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-40-float32-1.0-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float32-0.1-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridgeclassifier_multilabel[RidgeClassifierCV-params2]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[True-shape2]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float64-0.2-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_error[gcv]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-20-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[eigen-eigen-eigen-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-array-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_dtype_stability[0-lbfgs]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[lbfgs-False]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[True-shape1]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float32-0.1-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape0-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_dtype_match[sag]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float32-0.1-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float32-0.1-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-csr_matrix-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-csr_matrix-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_check_gcv_mode_choice[None-svd-eigen-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_ground_truth_positive_test[0.1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_cv_individual_penalties", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lbfgs-csr_matrix-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float64-0.2-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_dtype_stability[0-saga]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-40-float32-1.0-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[lbfgs-array-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape1-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge[svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape1-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-False-X_shape1-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float32-0.1-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-csr_matrix-sample_weight1-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_dtype_stability[0-lsqr]", "sklearn/linear_model/tests/test_ridge.py::test_lbfgs_solver_consistency[1.0]", "sklearn/linear_model/tests/test_ridge.py::test_n_iter", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float32-0.1-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float64-0.2-cholesky-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_with_scoring[SPARSE_FILTER-cv1-None]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_sample_weight_invariance[sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-True-X_shape0-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[saga-csr_matrix-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_error_test[svd]", "sklearn/linear_model/tests/test_ridge.py::test_raises_value_error_if_sample_weights_greater_than_1d", "sklearn/linear_model/tests/test_ridge.py::test_ridge_fit_intercept_sparse_sag[42-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-csr_matrix-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape2-True-150.0-20-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-8-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape3-False-30.0-8-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape1-False-30.0-True-X_shape0-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float32-0.1-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_convergence_fail", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float32-0.1-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[auto-array-sample_weight1-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_sample_weights[y_shape1-True-20.0-20-asarray-svd]", "sklearn/linear_model/tests/test_ridge.py::test_toy_ridge_object", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-40-float32-1.0-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-40-float32-1.0-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_ground_truth_positive_test[1.0-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float32-0.1-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float32-0.1-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape2-False-150.0-True-X_shape0-csr_matrix-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-40-float32-1.0-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-40-float32-1.0-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape1-asarray-eigen]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float64-0.2-ridgecv-True]", "sklearn/linear_model/tests/test_ridge.py::test_lbfgs_solver_consistency[0.001]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_ground_truth_positive_test[0.01-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_params_validation[params4-ValueError-tol == -1.0, must be >= 0.]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-20-float64-0.2-saga-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-40-float32-1.0-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_positive_regression_test[0.01-False-auto]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[cholesky-array-None-True]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_gcv_vs_ridge_loo_cv[y_shape0-True-1.0-False-X_shape0-csr_matrix-svd]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_custom_scoring[DENSE_FILTER-cv1]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-True-40-float32-1.0-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed1-False-20-float32-0.1-sparse_cg-True]", "sklearn/linear_model/tests/test_ridge.py::test_compute_covariance[False-shape3]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-False-20-float64-0.2-sparse_cg-False]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-False-20-float64-0.2-sag-False]", "sklearn/linear_model/tests/test_ridge.py::test_class_weights_cv", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_dtype_stability[0-sparse_cg]", "sklearn/linear_model/tests/test_ridge.py::test_ridge[lsqr]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed2-True-20-float32-0.1-ridgecv-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_best_score[None-ridge0-make_regression]", "sklearn/linear_model/tests/test_ridge.py::test_solver_consistency[seed0-True-20-float64-0.2-lsqr-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_regression_check_arguments_validity[sag-csr_matrix-None-False]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_classifier_cv_store_cv_values[_accuracy_callable]"], "FAIL2PASS": ["sklearn/linear_model/tests/test_ridge.py::test_ridge_fit_intercept_sparse[42-False-lsqr]", "sklearn/linear_model/tests/test_ridge.py::test_ridge_fit_intercept_sparse[42-True-lsqr]"], "mask_doc_diff": [{"path": "doc/whats_new/v1.1.rst", "old_path": "a/doc/whats_new/v1.1.rst", "new_path": "b/doc/whats_new/v1.1.rst", "metadata": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex fab4ec850..31b4ea007 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -636,6 +636,9 @@ Changelog\n of sample weights when the input is sparse.\n :pr:`22899` by :user:`J\u00e9r\u00e9mie du Boisberranger `.\n \n+- |Feature| :class:`Ridge` with `solver=\"lsqr\"` now supports to fit sparse input with\n+ `fit_intercept=True`.\n+\n :mod:`sklearn.manifold`\n .......................\n \n"}], "augmentations": {"header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": []}, "problem_statement": "diff --git a/doc/whats_new/v1.1.rst b/doc/whats_new/v1.1.rst\nindex fab4ec850..31b4ea007 100644\n--- a/doc/whats_new/v1.1.rst\n+++ b/doc/whats_new/v1.1.rst\n@@ -636,6 +636,9 @@ Changelog\n of sample weights when the input is sparse.\n :pr:`22899` by :user:`J\u00e9r\u00e9mie du Boisberranger `.\n \n+- |Feature| :class:`Ridge` with `solver=\"lsqr\"` now supports to fit sparse input with\n+ `fit_intercept=True`.\n+\n :mod:`sklearn.manifold`\n .......................\n \n\n"} {"repo": "scikit-learn/scikit-learn", "instance_id": "scikit-learn__scikit-learn-23038", "html_url": "https://github.com/scikit-learn/scikit-learn/pull/23038", "feature_patch": "diff --git a/doc/whats_new/v1.2.rst b/doc/whats_new/v1.2.rst\nindex 8e5851cca632f..fdc7685395c62 100644\n--- a/doc/whats_new/v1.2.rst\n+++ b/doc/whats_new/v1.2.rst\n@@ -44,6 +44,13 @@ Changelog\n - |Enhancement| :class:`cluster.Birch` now preserves dtype for `numpy.float32`\n inputs. :pr:`22968` by `Meekail Zain `.\n \n+- |Enhancement| :class:`cluster.KMeans` and :class:`cluster.MiniBatchKMeans`\n+ now accept a new `'auto'` option for `n_init` which changes the number of\n+ random initializations to one when using `init='k-means++'` for efficiency.\n+ This begins deprecation for the default values of `n_init` in the two classes\n+ and both will have their defaults changed to `n_init='auto'` in 1.4.\n+ :pr:`23038` by :user:`Meekail Zain `.\n+\n :mod:`sklearn.datasets`\n .......................\n \ndiff --git a/sklearn/cluster/_kmeans.py b/sklearn/cluster/_kmeans.py\nindex 2eaee8529e14b..2f960ed7593ef 100644\n--- a/sklearn/cluster/_kmeans.py\n+++ b/sklearn/cluster/_kmeans.py\n@@ -272,7 +272,7 @@ def k_means(\n *,\n sample_weight=None,\n init=\"k-means++\",\n- n_init=10,\n+ n_init=\"warn\",\n max_iter=300,\n verbose=False,\n tol=1e-4,\n@@ -314,10 +314,19 @@ def k_means(\n - If a callable is passed, it should take arguments `X`, `n_clusters` and a\n random state and return an initialization.\n \n- n_init : int, default=10\n+ n_init : 'auto' or int, default=10\n Number of time the k-means algorithm will be run with different\n centroid seeds. The final results will be the best output of\n- `n_init` consecutive runs in terms of inertia.\n+ n_init consecutive runs in terms of inertia.\n+\n+ When `n_init='auto'`, the number of runs will be 10 if using\n+ `init='random'`, and 1 if using `init='kmeans++'`.\n+\n+ .. versionadded:: 1.2\n+ Added 'auto' option for `n_init`.\n+\n+ .. versionchanged:: 1.4\n+ Default value for `n_init` will change from 10 to `'auto'` in version 1.4.\n \n max_iter : int, default=300\n Maximum number of iterations of the k-means algorithm to run.\n@@ -803,7 +812,10 @@ class _BaseKMeans(\n _parameter_constraints = {\n \"n_clusters\": [Interval(Integral, 1, None, closed=\"left\")],\n \"init\": [StrOptions({\"k-means++\", \"random\"}), callable, \"array-like\"],\n- \"n_init\": [Interval(Integral, 1, None, closed=\"left\")],\n+ \"n_init\": [\n+ StrOptions({\"auto\", \"warn\"}),\n+ Interval(Integral, 1, None, closed=\"left\"),\n+ ],\n \"max_iter\": [Interval(Integral, 1, None, closed=\"left\")],\n \"tol\": [Interval(Real, 0, None, closed=\"left\")],\n \"verbose\": [Interval(Integral, 0, None, closed=\"left\"), bool],\n@@ -829,7 +841,7 @@ def __init__(\n self.verbose = verbose\n self.random_state = random_state\n \n- def _check_params_vs_input(self, X):\n+ def _check_params_vs_input(self, X, default_n_init=None):\n # n_clusters\n if X.shape[0] < self.n_clusters:\n raise ValueError(\n@@ -839,8 +851,23 @@ def _check_params_vs_input(self, X):\n # tol\n self._tol = _tolerance(X, self.tol)\n \n- # init\n+ # n-init\n+ # TODO(1.4): Remove\n self._n_init = self.n_init\n+ if self._n_init == \"warn\":\n+ warnings.warn(\n+ \"The default value of `n_init` will change from \"\n+ f\"{default_n_init} to 'auto' in 1.4. Set the value of `n_init`\"\n+ \" explicitly to suppress the warning\",\n+ FutureWarning,\n+ )\n+ self._n_init = default_n_init\n+ if self._n_init == \"auto\":\n+ if self.init == \"k-means++\":\n+ self._n_init = 1\n+ else:\n+ self._n_init = default_n_init\n+\n if _is_arraylike_not_scalar(self.init) and self._n_init != 1:\n warnings.warn(\n \"Explicit initial center position passed: performing only\"\n@@ -1150,11 +1177,20 @@ class KMeans(_BaseKMeans):\n If a callable is passed, it should take arguments X, n_clusters and a\n random state and return an initialization.\n \n- n_init : int, default=10\n+ n_init : 'auto' or int, default=10\n Number of time the k-means algorithm will be run with different\n centroid seeds. The final results will be the best output of\n n_init consecutive runs in terms of inertia.\n \n+ When `n_init='auto'`, the number of runs will be 10 if using\n+ `init='random'`, and 1 if using `init='kmeans++'`.\n+\n+ .. versionadded:: 1.2\n+ Added 'auto' option for `n_init`.\n+\n+ .. versionchanged:: 1.4\n+ Default value for `n_init` will change from 10 to `'auto'` in version 1.4.\n+\n max_iter : int, default=300\n Maximum number of iterations of the k-means algorithm for a\n single run.\n@@ -1263,7 +1299,7 @@ class KMeans(_BaseKMeans):\n >>> import numpy as np\n >>> X = np.array([[1, 2], [1, 4], [1, 0],\n ... [10, 2], [10, 4], [10, 0]])\n- >>> kmeans = KMeans(n_clusters=2, random_state=0).fit(X)\n+ >>> kmeans = KMeans(n_clusters=2, random_state=0, n_init=\"auto\").fit(X)\n >>> kmeans.labels_\n array([1, 1, 1, 0, 0, 0], dtype=int32)\n >>> kmeans.predict([[0, 0], [12, 3]])\n@@ -1286,7 +1322,7 @@ def __init__(\n n_clusters=8,\n *,\n init=\"k-means++\",\n- n_init=10,\n+ n_init=\"warn\",\n max_iter=300,\n tol=1e-4,\n verbose=0,\n@@ -1308,7 +1344,7 @@ def __init__(\n self.algorithm = algorithm\n \n def _check_params_vs_input(self, X):\n- super()._check_params_vs_input(X)\n+ super()._check_params_vs_input(X, default_n_init=10)\n \n self._algorithm = self.algorithm\n if self._algorithm in (\"auto\", \"full\"):\n@@ -1667,11 +1703,20 @@ class MiniBatchKMeans(_BaseKMeans):\n If `None`, the heuristic is `init_size = 3 * batch_size` if\n `3 * batch_size < n_clusters`, else `init_size = 3 * n_clusters`.\n \n- n_init : int, default=3\n+ n_init : 'auto' or int, default=3\n Number of random initializations that are tried.\n In contrast to KMeans, the algorithm is only run once, using the\n best of the ``n_init`` initializations as measured by inertia.\n \n+ When `n_init='auto'`, the number of runs will be 3 if using\n+ `init='random'`, and 1 if using `init='kmeans++'`.\n+\n+ .. versionadded:: 1.2\n+ Added 'auto' option for `n_init`.\n+\n+ .. versionchanged:: 1.4\n+ Default value for `n_init` will change from 3 to `'auto'` in version 1.4.\n+\n reassignment_ratio : float, default=0.01\n Control the fraction of the maximum number of counts for a center to\n be reassigned. A higher value means that low count centers are more\n@@ -1737,7 +1782,8 @@ class MiniBatchKMeans(_BaseKMeans):\n >>> # manually fit on batches\n >>> kmeans = MiniBatchKMeans(n_clusters=2,\n ... random_state=0,\n- ... batch_size=6)\n+ ... batch_size=6,\n+ ... n_init=\"auto\")\n >>> kmeans = kmeans.partial_fit(X[0:6,:])\n >>> kmeans = kmeans.partial_fit(X[6:12,:])\n >>> kmeans.cluster_centers_\n@@ -1749,12 +1795,13 @@ class MiniBatchKMeans(_BaseKMeans):\n >>> kmeans = MiniBatchKMeans(n_clusters=2,\n ... random_state=0,\n ... batch_size=6,\n- ... max_iter=10).fit(X)\n+ ... max_iter=10,\n+ ... n_init=\"auto\").fit(X)\n >>> kmeans.cluster_centers_\n- array([[1.19..., 1.22...],\n- [4.03..., 2.46...]])\n+ array([[3.97727273, 2.43181818],\n+ [1.125 , 1.6 ]])\n >>> kmeans.predict([[0, 0], [4, 4]])\n- array([0, 1], dtype=int32)\n+ array([1, 0], dtype=int32)\n \"\"\"\n \n _parameter_constraints = {\n@@ -1779,7 +1826,7 @@ def __init__(\n tol=0.0,\n max_no_improvement=10,\n init_size=None,\n- n_init=3,\n+ n_init=\"warn\",\n reassignment_ratio=0.01,\n ):\n \n@@ -1800,7 +1847,7 @@ def __init__(\n self.reassignment_ratio = reassignment_ratio\n \n def _check_params_vs_input(self, X):\n- super()._check_params_vs_input(X)\n+ super()._check_params_vs_input(X, default_n_init=3)\n \n self._batch_size = min(self.batch_size, X.shape[0])\n \n", "test_patch": "diff --git a/sklearn/cluster/tests/test_k_means.py b/sklearn/cluster/tests/test_k_means.py\nindex eabdb746e4dd5..9939852987775 100644\n--- a/sklearn/cluster/tests/test_k_means.py\n+++ b/sklearn/cluster/tests/test_k_means.py\n@@ -1,6 +1,7 @@\n \"\"\"Testing for K-means\"\"\"\n import re\n import sys\n+import warnings\n \n import numpy as np\n from scipy import sparse as sp\n@@ -31,6 +32,12 @@\n from sklearn.datasets import make_blobs\n from io import StringIO\n \n+# TODO(1.4): Remove\n+msg = (\n+ r\"The default value of `n_init` will change from \\d* to 'auto' in 1.4. Set the\"\n+ r\" value of `n_init` explicitly to suppress the warning:FutureWarning\"\n+)\n+pytestmark = pytest.mark.filterwarnings(\"ignore:\" + msg)\n \n # non centered, sparse centers to check the\n centers = np.array(\n@@ -1029,6 +1036,35 @@ def test_inertia(dtype):\n assert_allclose(inertia_sparse, expected, rtol=1e-6)\n \n \n+# TODO(1.4): Remove\n+@pytest.mark.parametrize(\"Klass, default_n_init\", [(KMeans, 10), (MiniBatchKMeans, 3)])\n+def test_change_n_init_future_warning(Klass, default_n_init):\n+ est = Klass(n_init=1)\n+ with warnings.catch_warnings():\n+ warnings.simplefilter(\"error\", FutureWarning)\n+ est.fit(X)\n+\n+ default_n_init = 10 if Klass.__name__ == \"KMeans\" else 3\n+ msg = (\n+ f\"The default value of `n_init` will change from {default_n_init} to 'auto'\"\n+ \" in 1.4\"\n+ )\n+ est = Klass()\n+ with pytest.warns(FutureWarning, match=msg):\n+ est.fit(X)\n+\n+\n+@pytest.mark.parametrize(\"Klass, default_n_init\", [(KMeans, 10), (MiniBatchKMeans, 3)])\n+def test_n_init_auto(Klass, default_n_init):\n+ est = Klass(n_init=\"auto\", init=\"k-means++\")\n+ est.fit(X)\n+ assert est._n_init == 1\n+\n+ est = Klass(n_init=\"auto\", init=\"random\")\n+ est.fit(X)\n+ assert est._n_init == 10 if Klass.__name__ == \"KMeans\" else 3\n+\n+\n @pytest.mark.parametrize(\"Estimator\", [KMeans, MiniBatchKMeans])\n def test_sample_weight_unchanged(Estimator):\n # Check that sample_weight is not modified in place by KMeans (#17204)\ndiff --git a/sklearn/inspection/tests/test_partial_dependence.py b/sklearn/inspection/tests/test_partial_dependence.py\nindex 4e62f140c6953..5fe5ddb5d6db1 100644\n--- a/sklearn/inspection/tests/test_partial_dependence.py\n+++ b/sklearn/inspection/tests/test_partial_dependence.py\n@@ -427,7 +427,7 @@ def fit(self, X, y):\n \"estimator, params, err_msg\",\n [\n (\n- KMeans(),\n+ KMeans(random_state=0, n_init=\"auto\"),\n {\"features\": [0]},\n \"'estimator' must be a fitted regressor or classifier\",\n ),\ndiff --git a/sklearn/manifold/tests/test_spectral_embedding.py b/sklearn/manifold/tests/test_spectral_embedding.py\nindex 935e5408a4159..38e555643b034 100644\n--- a/sklearn/manifold/tests/test_spectral_embedding.py\n+++ b/sklearn/manifold/tests/test_spectral_embedding.py\n@@ -329,7 +329,7 @@ def test_pipeline_spectral_clustering(seed=36):\n random_state=random_state,\n )\n for se in [se_rbf, se_knn]:\n- km = KMeans(n_clusters=n_clusters, random_state=random_state)\n+ km = KMeans(n_clusters=n_clusters, random_state=random_state, n_init=\"auto\")\n km.fit(se.fit_transform(S))\n assert_array_almost_equal(\n normalized_mutual_info_score(km.labels_, true_labels), 1.0, 2\ndiff --git a/sklearn/metrics/tests/test_score_objects.py b/sklearn/metrics/tests/test_score_objects.py\nindex 204a895742db7..b909e182624cf 100644\n--- a/sklearn/metrics/tests/test_score_objects.py\n+++ b/sklearn/metrics/tests/test_score_objects.py\n@@ -577,7 +577,7 @@ def test_supervised_cluster_scorers():\n # Test clustering scorers against gold standard labeling.\n X, y = make_blobs(random_state=0, centers=2)\n X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)\n- km = KMeans(n_clusters=3)\n+ km = KMeans(n_clusters=3, n_init=\"auto\")\n km.fit(X_train)\n for name in CLUSTER_SCORERS:\n score1 = get_scorer(name)(km, X_test, y_test)\ndiff --git a/sklearn/model_selection/tests/test_validation.py b/sklearn/model_selection/tests/test_validation.py\nindex 90b5a605ac2e4..8a3c5619c43e7 100644\n--- a/sklearn/model_selection/tests/test_validation.py\n+++ b/sklearn/model_selection/tests/test_validation.py\n@@ -930,7 +930,7 @@ def test_cross_val_predict():\n preds = cross_val_predict(est, Xsp, y)\n assert_array_almost_equal(len(preds), len(y))\n \n- preds = cross_val_predict(KMeans(), X)\n+ preds = cross_val_predict(KMeans(n_init=\"auto\"), X)\n assert len(preds) == len(y)\n \n class BadCV:\ndiff --git a/sklearn/tests/test_discriminant_analysis.py b/sklearn/tests/test_discriminant_analysis.py\nindex 9ef444c67b3e1..9f0ac68899add 100644\n--- a/sklearn/tests/test_discriminant_analysis.py\n+++ b/sklearn/tests/test_discriminant_analysis.py\n@@ -143,7 +143,7 @@ def test_lda_predict():\n \n # test bad covariance estimator\n clf = LinearDiscriminantAnalysis(\n- solver=\"lsqr\", covariance_estimator=KMeans(n_clusters=2)\n+ solver=\"lsqr\", covariance_estimator=KMeans(n_clusters=2, n_init=\"auto\")\n )\n with pytest.raises(\n ValueError, match=\"KMeans does not have a covariance_ attribute\"\ndiff --git a/sklearn/tests/test_docstring_parameters.py b/sklearn/tests/test_docstring_parameters.py\nindex 5e22b425be1ec..4355af286ac67 100644\n--- a/sklearn/tests/test_docstring_parameters.py\n+++ b/sklearn/tests/test_docstring_parameters.py\n@@ -262,6 +262,10 @@ def test_fit_docstring_attributes(name, Estimator):\n if Estimator.__name__ == \"MiniBatchDictionaryLearning\":\n est.set_params(batch_size=5)\n \n+ # TODO(1.4): TO BE REMOVED for 1.4 (avoid FutureWarning)\n+ if Estimator.__name__ in (\"KMeans\", \"MiniBatchKMeans\"):\n+ est.set_params(n_init=\"auto\")\n+\n # In case we want to deprecate some attributes in the future\n skipped_attributes = {}\n \ndiff --git a/sklearn/tests/test_pipeline.py b/sklearn/tests/test_pipeline.py\nindex 6913815191ea8..0ce71bf9b55f4 100644\n--- a/sklearn/tests/test_pipeline.py\n+++ b/sklearn/tests/test_pipeline.py\n@@ -422,11 +422,11 @@ def test_fit_predict_on_pipeline():\n # test that the fit_predict on pipeline yields same results as applying\n # transform and clustering steps separately\n scaler = StandardScaler()\n- km = KMeans(random_state=0)\n+ km = KMeans(random_state=0, n_init=\"auto\")\n # As pipeline doesn't clone estimators on construction,\n # it must have its own estimators\n scaler_for_pipeline = StandardScaler()\n- km_for_pipeline = KMeans(random_state=0)\n+ km_for_pipeline = KMeans(random_state=0, n_init=\"auto\")\n \n # first compute the transform and clustering step separately\n scaled = scaler.fit_transform(iris.data)\n", "doc_changes": [{"path": "doc/whats_new/v1.2.rst", "old_path": "a/doc/whats_new/v1.2.rst", "new_path": "b/doc/whats_new/v1.2.rst", "metadata": "diff --git a/doc/whats_new/v1.2.rst b/doc/whats_new/v1.2.rst\nindex 8e5851cca632f..fdc7685395c62 100644\n--- a/doc/whats_new/v1.2.rst\n+++ b/doc/whats_new/v1.2.rst\n@@ -44,6 +44,13 @@ Changelog\n - |Enhancement| :class:`cluster.Birch` now preserves dtype for `numpy.float32`\n inputs. :pr:`22968` by `Meekail Zain `.\n \n+- |Enhancement| :class:`cluster.KMeans` and :class:`cluster.MiniBatchKMeans`\n+ now accept a new `'auto'` option for `n_init` which changes the number of\n+ random initializations to one when using `init='k-means++'` for efficiency.\n+ This begins deprecation for the default values of `n_init` in the two classes\n+ and both will have their defaults changed to `n_init='auto'` in 1.4.\n+ :pr:`23038` by :user:`Meekail Zain `.\n+\n :mod:`sklearn.datasets`\n .......................\n \n"}], "version": "1.02", "base_commit": "996c7e2895db313dc7a5215473536f2b104121d0", "PASS2PASS": ["sklearn/manifold/tests/test_spectral_embedding.py::test_sparse_graph_connected_component", "sklearn/tests/test_discriminant_analysis.py::test_lda_predict_proba[lsqr-3]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_predict_proba_shape", "sklearn/tests/test_discriminant_analysis.py::test_lda_explained_variance_ratio", "sklearn/metrics/tests/test_score_objects.py::test_classification_multiclass_scores[f1_micro-metric4]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[roc_auc_ovr_weighted]", "sklearn/metrics/tests/test_score_objects.py::test_make_scorer", "sklearn/tests/test_discriminant_analysis.py::test_lda_scaling", "sklearn/manifold/tests/test_spectral_embedding.py::test_spectral_embedding_precomputed_affinity[float64-lobpcg-sparse]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[explained_variance]", "sklearn/tests/test_discriminant_analysis.py::test_lda_orthogonality", "sklearn/manifold/tests/test_spectral_embedding.py::test_spectral_embedding_precomputed_affinity[float32-arpack-sparse]", "sklearn/metrics/tests/test_score_objects.py::test_multiclass_roc_proba_scorer[roc_auc_ovr_weighted-metric2]", "sklearn/metrics/tests/test_score_objects.py::test_check_scoring_and_check_multimetric_scoring[dict_str]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[accuracy]", "sklearn/metrics/tests/test_score_objects.py::test_classification_binary_scores[precision_micro-metric7]", "sklearn/metrics/tests/test_score_objects.py::test_thresholded_scorers_multilabel_indicator_data", "sklearn/metrics/tests/test_score_objects.py::test_check_scoring_and_check_multimetric_scoring[multi_tuple]", "sklearn/tests/test_discriminant_analysis.py::test_lda_dtype_match[float32-float32]", "sklearn/model_selection/tests/test_validation.py::test_score_memmap", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[recall_samples]", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_some_failing_fits_warning[0]", "sklearn/metrics/tests/test_score_objects.py::test_classification_binary_scores[f1-f1_score]", "sklearn/metrics/tests/test_score_objects.py::test_classification_binary_scores[recall_macro-metric10]", "sklearn/manifold/tests/test_spectral_embedding.py::test_spectral_embedding_two_components[float32-arpack]", "sklearn/model_selection/tests/test_validation.py::test_validation_curve_clone_estimator", "sklearn/tests/test_discriminant_analysis.py::test_lda_ledoitwolf", "sklearn/tests/test_discriminant_analysis.py::test_lda_shrinkage[6]", "sklearn/metrics/tests/test_score_objects.py::test_classification_binary_scores[recall_weighted-metric9]", "sklearn/tests/test_discriminant_analysis.py::test_lda_shrinkage[7]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[balanced_accuracy]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[recall]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[neg_mean_absolute_error]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[r2]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[neg_mean_squared_log_error]", "sklearn/metrics/tests/test_score_objects.py::test_classification_binary_scores[precision_weighted-metric5]", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[True-True-0]", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[False-False-nan]", "sklearn/metrics/tests/test_score_objects.py::test_check_scoring_and_check_multimetric_scoring_errors[empty tuple]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[recall_micro]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[roc_auc]", "sklearn/metrics/tests/test_score_objects.py::test_classification_binary_scores[f1_macro-metric2]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_pandas", "sklearn/tests/test_discriminant_analysis.py::test_lda_coefs", "sklearn/tests/test_discriminant_analysis.py::test_qda", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[neg_brier_score]", "sklearn/manifold/tests/test_spectral_embedding.py::test_spectral_embedding_unknown_eigensolver", "sklearn/metrics/tests/test_score_objects.py::test_regression_scorers", "sklearn/metrics/tests/test_score_objects.py::test_classification_multiclass_scores[f1_macro-metric3]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[mutual_info_score]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[precision_macro]", "sklearn/model_selection/tests/test_validation.py::test_fit_and_score_verbosity[False-scorer2-10-split_prg2-cdt_prg2-\\\\[CV 2/3; 1/1\\\\] END ....... sc1: \\\\(test=3.421\\\\) sc2: \\\\(test=3.421\\\\) total time= 0.\\\\ds]", "sklearn/tests/test_discriminant_analysis.py::test_lda_predict_proba[eigen-2]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[jaccard_samples]", "sklearn/tests/test_discriminant_analysis.py::test_lda_shrinkage[1]", "sklearn/manifold/tests/test_spectral_embedding.py::test_spectral_embedding_preserves_dtype[float32-arpack]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_sparse_fit_params", "sklearn/metrics/tests/test_score_objects.py::test_check_scoring_and_check_multimetric_scoring_errors[non-string key dict]", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_all_failing_fits_error[0]", "sklearn/tests/test_discriminant_analysis.py::test_lda_shrinkage[3]", "sklearn/model_selection/tests/test_validation.py::test_validation_curve_cv_splits_consistency", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_verbose", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[neg_mean_squared_error]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[neg_mean_poisson_deviance]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[f1_weighted]", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[True-False-raise]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[neg_log_loss]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[rand_score]", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_invalid_scoring_param", "sklearn/manifold/tests/test_spectral_embedding.py::test_spectral_embedding_precomputed_affinity[float32-arpack-dense]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_class_subset", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[neg_median_absolute_error]", "sklearn/metrics/tests/test_score_objects.py::test_classification_multiclass_scores[precision_micro-metric7]", "sklearn/metrics/tests/test_score_objects.py::test_non_symmetric_metric_pos_label[precision_score]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_score_func", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_y_none", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_batch_and_incremental_learning_are_equal", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_failing_scorer[raise]", "sklearn/metrics/tests/test_score_objects.py::test_multiclass_roc_no_proba_scorer_errors[roc_auc_ovo]", "sklearn/metrics/tests/test_score_objects.py::test_non_symmetric_metric_pos_label[f1_score]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_with_method", "sklearn/metrics/tests/test_score_objects.py::test_classification_binary_scores[precision-precision_score]", "sklearn/tests/test_discriminant_analysis.py::test_get_feature_names_out", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[homogeneity_score]", "sklearn/tests/test_discriminant_analysis.py::test_qda_regularization", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_predict_groups", "sklearn/model_selection/tests/test_validation.py::test_permutation_test_score_pandas", "sklearn/manifold/tests/test_spectral_embedding.py::test_spectral_embedding_precomputed_affinity[float64-lobpcg-dense]", "sklearn/metrics/tests/test_score_objects.py::test_classification_multiclass_scores[precision_macro-metric6]", "sklearn/metrics/tests/test_score_objects.py::test_classification_multiclass_scores[jaccard_weighted-metric11]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_failing_scorer[0]", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[False-True-nan]", "sklearn/metrics/tests/test_score_objects.py::test_non_symmetric_metric_pos_label[recall_score]", "sklearn/model_selection/tests/test_validation.py::test_fit_and_score_working", "sklearn/model_selection/tests/test_validation.py::test_permutation_test_score_allow_nans", "sklearn/model_selection/tests/test_validation.py::test_fit_and_score_failing", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[f1_micro]", "sklearn/metrics/tests/test_score_objects.py::test_SCORERS_deprecated", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_all_failing_fits_error[nan]", "sklearn/metrics/tests/test_score_objects.py::test_multimetric_scorer_calls_method_once[scorers0-1-1-1]", "sklearn/manifold/tests/test_spectral_embedding.py::test_spectral_embedding_unknown_affinity", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_many_jobs", "sklearn/model_selection/tests/test_validation.py::test_fit_and_score_verbosity[True-scorer1-3-split_prg1-cdt_prg1-\\\\[CV 2/3\\\\] END sc1: \\\\(train=3.421, test=3.421\\\\) sc2: \\\\(train=3.421, test=3.421\\\\) total time= 0.\\\\ds]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[f1]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_fit_params", "sklearn/metrics/tests/test_score_objects.py::test_classification_multiclass_scores[recall_micro-metric10]", "sklearn/tests/test_discriminant_analysis.py::test_qda_store_covariance", "sklearn/metrics/tests/test_score_objects.py::test_multiclass_roc_proba_scorer_label", "sklearn/metrics/tests/test_score_objects.py::test_check_scoring_and_check_multimetric_scoring[single_tuple]", "sklearn/metrics/tests/test_score_objects.py::test_custom_scorer_pickling", "sklearn/manifold/tests/test_spectral_embedding.py::test_spectral_embedding_two_components[float64-arpack]", "sklearn/tests/test_discriminant_analysis.py::test_lda_shrinkage[2]", "sklearn/metrics/tests/test_score_objects.py::test_check_scoring_and_check_multimetric_scoring_errors[list of int]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[neg_root_mean_squared_error]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[roc_auc_ovo]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_select_proba_error[ThresholdScorer]", "sklearn/model_selection/tests/test_validation.py::test_permutation_score", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_allow_nans", "sklearn/tests/test_discriminant_analysis.py::test_lda_predict_proba[svd-2]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_select_proba_error[PredictScorer]", "sklearn/metrics/tests/test_score_objects.py::test_classification_binary_scores[f1_micro-metric3]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_with_score_func_regression", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_nested_estimator", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_with_method_multilabel_ovr", "sklearn/manifold/tests/test_spectral_embedding.py::test_spectral_embedding_preserves_dtype[float64-arpack]", "sklearn/tests/test_discriminant_analysis.py::test_lda_shrinkage[9]", "sklearn/metrics/tests/test_score_objects.py::test_multiclass_roc_no_proba_scorer_errors[roc_auc_ovr]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[f1_samples]", "sklearn/manifold/tests/test_spectral_embedding.py::test_spectral_embedding_first_eigen_vector", "sklearn/metrics/tests/test_score_objects.py::test_all_scorers_repr", "sklearn/metrics/tests/test_score_objects.py::test_multimetric_scorer_calls_method_once[scorers1-1-0-1]", "sklearn/model_selection/tests/test_validation.py::test_gridsearchcv_cross_val_predict_with_method", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[neg_negative_likelihood_ratio]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[precision]", "sklearn/model_selection/tests/test_validation.py::test_cross_validate", "sklearn/tests/test_discriminant_analysis.py::test_lda_dimension_warning[3-3]", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_n_sample_range_out_of_bounds", "sklearn/tests/test_discriminant_analysis.py::test_lda_numeric_consistency_float32_float64", "sklearn/manifold/tests/test_spectral_embedding.py::test_spectral_embedding_callable_affinity[sparse]", "sklearn/model_selection/tests/test_validation.py::test_learning_curve", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_with_method_rare_class", "sklearn/tests/test_discriminant_analysis.py::test_lda_predict_proba[svd-3]", "sklearn/metrics/tests/test_score_objects.py::test_multimetric_scorer_sanity_check", "sklearn/metrics/tests/test_score_objects.py::test_classification_binary_scores[jaccard_micro-metric15]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[f1_macro]", "sklearn/model_selection/tests/test_validation.py::test_score", "sklearn/metrics/tests/test_score_objects.py::test_check_scoring_and_check_multimetric_scoring_errors[empty dict]", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_incremental_learning", "sklearn/metrics/tests/test_score_objects.py::test_raises_on_score_list", "sklearn/metrics/tests/test_score_objects.py::test_classification_binary_scores[jaccard_macro-metric14]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[jaccard_macro]", "sklearn/tests/test_discriminant_analysis.py::test_lda_shrinkage[5]", "sklearn/metrics/tests/test_score_objects.py::test_classification_multiclass_scores[jaccard_macro-metric12]", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[False-False-raise]", "sklearn/metrics/tests/test_score_objects.py::test_regression_scorer_sample_weight", "sklearn/metrics/tests/test_score_objects.py::test_scoring_is_not_metric", "sklearn/model_selection/tests/test_validation.py::test_callable_multimetric_confusion_matrix_cross_validate", "sklearn/tests/test_discriminant_analysis.py::test_lda_dimension_warning[3-5]", "sklearn/manifold/tests/test_spectral_embedding.py::test_precomputed_nearest_neighbors_filtering", "sklearn/tests/test_discriminant_analysis.py::test_lda_shrinkage[4]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_decision_function_shape", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_with_shuffle", "sklearn/tests/test_discriminant_analysis.py::test_lda_predict_proba[eigen-3]", "sklearn/manifold/tests/test_spectral_embedding.py::test_spectral_embedding_preserves_dtype[float32-lobpcg]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[jaccard]", "sklearn/model_selection/tests/test_validation.py::test_validation_curve_fit_params", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_incremental_learning_unsupervised", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_precomputed", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[neg_mean_gamma_deviance]", "sklearn/tests/test_discriminant_analysis.py::test_lda_shrinkage[0]", "sklearn/metrics/tests/test_score_objects.py::test_classification_multiclass_scores[recall_macro-metric9]", "sklearn/metrics/tests/test_score_objects.py::test_check_scoring_gridsearchcv", "sklearn/metrics/tests/test_score_objects.py::test_classification_multiclass_scores[precision_weighted-metric5]", "sklearn/metrics/tests/test_score_objects.py::test_multiclass_roc_no_proba_scorer_errors[roc_auc_ovo_weighted]", "sklearn/tests/test_discriminant_analysis.py::test_raises_value_error_on_same_number_of_classes_and_samples[eigen]", "sklearn/metrics/tests/test_score_objects.py::test_classification_multiclass_scores[f1_weighted-metric2]", "sklearn/metrics/tests/test_score_objects.py::test_multimetric_scorer_calls_method_once_regressor_threshold", "sklearn/metrics/tests/test_score_objects.py::test_classification_binary_scores[jaccard-jaccard_score]", "sklearn/metrics/tests/test_score_objects.py::test_check_scoring_and_check_multimetric_scoring_errors[non-unique str]", "sklearn/metrics/tests/test_score_objects.py::test_classification_multiclass_scores[recall_weighted-metric8]", "sklearn/manifold/tests/test_spectral_embedding.py::test_spectral_embedding_precomputed_affinity[float32-lobpcg-sparse]", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[False-True-0]", "sklearn/metrics/tests/test_score_objects.py::test_classification_binary_scores[precision_macro-metric6]", "sklearn/metrics/tests/test_score_objects.py::test_classification_binary_scores[top_k_accuracy-top_k_accuracy_score]", "sklearn/model_selection/tests/test_validation.py::test_permutation_test_score_fit_params", "sklearn/model_selection/tests/test_validation.py::test_check_is_permutation", "sklearn/tests/test_discriminant_analysis.py::test_lda_transform", "sklearn/tests/test_discriminant_analysis.py::test_lda_dtype_match[int32-float64]", "sklearn/manifold/tests/test_spectral_embedding.py::test_spectral_embedding_two_components[float32-lobpcg]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[precision_micro]", "sklearn/manifold/tests/test_spectral_embedding.py::test_spectral_embedding_precomputed_affinity[float64-arpack-sparse]", "sklearn/metrics/tests/test_score_objects.py::test_multimetric_scorer_calls_method_once[scorers2-1-1-0]", "sklearn/metrics/tests/test_score_objects.py::test_classification_multiclass_scores[balanced_accuracy-balanced_accuracy_score]", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_incremental_learning_fit_params", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_with_score_func_classification", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[recall_macro]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_pandas", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_with_method_multilabel_rf", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[neg_mean_absolute_percentage_error]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[adjusted_rand_score]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[precision_weighted]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[roc_auc_ovo_weighted]", "sklearn/metrics/tests/test_score_objects.py::test_multimetric_scorer_calls_method_once_classifier_no_decision", "sklearn/metrics/tests/test_score_objects.py::test_check_scoring_and_check_multimetric_scoring[dict_callable]", "sklearn/metrics/tests/test_score_objects.py::test_non_symmetric_metric_pos_label[jaccard_score]", "sklearn/tests/test_discriminant_analysis.py::test_lda_dtype_match[float64-float64]", "sklearn/metrics/tests/test_score_objects.py::test_multiclass_roc_proba_scorer[roc_auc_ovo-metric1]", "sklearn/tests/test_discriminant_analysis.py::test_lda_dtype_match[int64-float64]", "sklearn/metrics/tests/test_score_objects.py::test_thresholded_scorers", "sklearn/manifold/tests/test_spectral_embedding.py::test_spectral_embedding_preserves_dtype[float64-lobpcg]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[top_k_accuracy]", "sklearn/metrics/tests/test_score_objects.py::test_multiclass_roc_proba_scorer[roc_auc_ovo_weighted-metric3]", "sklearn/metrics/tests/test_score_objects.py::test_check_scoring_and_check_multimetric_scoring_errors[tuple of one callable]", "sklearn/manifold/tests/test_spectral_embedding.py::test_connectivity", "sklearn/model_selection/tests/test_validation.py::test_fit_and_score_verbosity[False-three_params_scorer-2-split_prg0-cdt_prg0-\\\\[CV\\\\] END .................................................... total time= 0.\\\\ds]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_multilabel", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[average_precision]", "sklearn/tests/test_discriminant_analysis.py::test_lda_store_covariance", "sklearn/metrics/tests/test_score_objects.py::test_multiclass_roc_no_proba_scorer_errors[roc_auc_ovr_weighted]", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_unsupervised", "sklearn/metrics/tests/test_score_objects.py::test_classification_binary_scores[f1_weighted-metric1]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[normalized_mutual_info_score]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_predict_log_proba_shape", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_input_types", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_with_method_multilabel_rf_rare_class", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[max_error]", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_fit_params", "sklearn/metrics/tests/test_score_objects.py::test_classification_scorer_sample_weight", "sklearn/metrics/tests/test_score_objects.py::test_get_scorer_return_copy", "sklearn/tests/test_discriminant_analysis.py::test_lda_predict_proba[lsqr-2]", "sklearn/tests/test_discriminant_analysis.py::test_lda_priors", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[jaccard_micro]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[matthews_corrcoef]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_select_proba_error[ProbaScorer]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_mask", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_with_boolean_indices", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_errors", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[True-False-0]", "sklearn/tests/test_discriminant_analysis.py::test_lda_dimension_warning[5-5]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[recall_weighted]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_sparse_prediction", "sklearn/metrics/tests/test_score_objects.py::test_classification_multiclass_scores[accuracy-accuracy_score]", "sklearn/metrics/tests/test_score_objects.py::test_average_precision_pos_label", "sklearn/tests/test_discriminant_analysis.py::test_raises_value_error_on_same_number_of_classes_and_samples[svd, lsqr]", "sklearn/tests/test_discriminant_analysis.py::test_covariance", "sklearn/metrics/tests/test_score_objects.py::test_classification_binary_scores[recall_micro-metric11]", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_some_failing_fits_warning[nan]", "sklearn/metrics/tests/test_score_objects.py::test_check_scoring_and_check_multimetric_scoring[single_list]", "sklearn/metrics/tests/test_score_objects.py::test_multiclass_roc_proba_scorer[roc_auc_ovr-metric0]", "sklearn/metrics/tests/test_score_objects.py::test_brier_score_loss_pos_label", "sklearn/metrics/tests/test_score_objects.py::test_scorer_no_op_multiclass_select_proba", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_incremental_learning_not_possible", "sklearn/manifold/tests/test_spectral_embedding.py::test_spectral_embedding_two_components[float64-lobpcg]", "sklearn/metrics/tests/test_score_objects.py::test_classification_multiclass_scores[jaccard_micro-metric13]", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[False-False-0]", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[True-False-nan]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[positive_likelihood_ratio]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[jaccard_weighted]", "sklearn/manifold/tests/test_spectral_embedding.py::test_spectral_embedding_callable_affinity[dense]", "sklearn/metrics/tests/test_score_objects.py::test_check_scoring_and_check_multimetric_scoring_errors[tuple of callables]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[v_measure_score]", "sklearn/metrics/tests/test_score_objects.py::test_classification_binary_scores[matthews_corrcoef-matthews_corrcoef]", "sklearn/manifold/tests/test_spectral_embedding.py::test_spectral_embedding_unnormalized", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_method_checking", "sklearn/manifold/tests/test_spectral_embedding.py::test_error_pyamg_not_available", "sklearn/tests/test_discriminant_analysis.py::test_lda_dimension_warning[5-3]", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[False-True-raise]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[precision_samples]", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_remove_duplicate_sample_sizes", "sklearn/model_selection/tests/test_validation.py::test_cross_val_score_failing_scorer[nan]", "sklearn/metrics/tests/test_score_objects.py::test_classification_binary_scores[recall-recall_score]", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict_unbalanced", "sklearn/manifold/tests/test_spectral_embedding.py::test_spectral_embedding_deterministic", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[fowlkes_mallows_score]", "sklearn/model_selection/tests/test_validation.py::test_validation_curve", "sklearn/metrics/tests/test_score_objects.py::test_check_scoring_and_check_multimetric_scoring[multi_list]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[adjusted_mutual_info_score]", "sklearn/metrics/tests/test_score_objects.py::test_classification_binary_scores[jaccard_weighted-metric13]", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[True-True-raise]", "sklearn/model_selection/tests/test_validation.py::test_cross_validate_failing_scorer[True-True-nan]", "sklearn/manifold/tests/test_spectral_embedding.py::test_spectral_embedding_precomputed_affinity[float32-lobpcg-dense]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[completeness_score]", "sklearn/tests/test_discriminant_analysis.py::test_lda_shrinkage[8]", "sklearn/metrics/tests/test_score_objects.py::test_scorer_memmap_input[roc_auc_ovr]", "sklearn/model_selection/tests/test_validation.py::test_learning_curve_partial_fit_regressors", "sklearn/manifold/tests/test_spectral_embedding.py::test_spectral_embedding_precomputed_affinity[float64-arpack-dense]", "sklearn/tests/test_discriminant_analysis.py::test_qda_priors"], "FAIL2PASS": ["sklearn/manifold/tests/test_spectral_embedding.py::test_pipeline_spectral_clustering", "sklearn/model_selection/tests/test_validation.py::test_cross_val_predict", "sklearn/metrics/tests/test_score_objects.py::test_supervised_cluster_scorers", "sklearn/tests/test_discriminant_analysis.py::test_lda_predict"], "mask_doc_diff": [{"path": "doc/whats_new/v1.2.rst", "old_path": "a/doc/whats_new/v1.2.rst", "new_path": "b/doc/whats_new/v1.2.rst", "metadata": "diff --git a/doc/whats_new/v1.2.rst b/doc/whats_new/v1.2.rst\nindex 8e5851cca..6eed22c60 100644\n--- a/doc/whats_new/v1.2.rst\n+++ b/doc/whats_new/v1.2.rst\n@@ -44,6 +44,12 @@ Changelog\n - |Enhancement| :class:`cluster.Birch` now preserves dtype for `numpy.float32`\n inputs. :pr:`22968` by `Meekail Zain `.\n \n+- |Enhancement| :class:`cluster.KMeans` and :class:`cluster.MiniBatchKMeans`\n+ now accept a new `'auto'` option for `n_init` which changes the number of\n+ random initializations to one when using `init='k-means++'` for efficiency.\n+ This begins deprecation for the default values of `n_init` in the two classes\n+ and both will have their defaults changed to `n_init='auto'` in 1.4.\n+\n :mod:`sklearn.datasets`\n .......................\n \n"}], "augmentations": {"header": "If completing this task requires creating new files, classes, fields, or error messages, you may consider using the following suggested entity names:", "data": []}, "problem_statement": "diff --git a/doc/whats_new/v1.2.rst b/doc/whats_new/v1.2.rst\nindex 8e5851cca..6eed22c60 100644\n--- a/doc/whats_new/v1.2.rst\n+++ b/doc/whats_new/v1.2.rst\n@@ -44,6 +44,12 @@ Changelog\n - |Enhancement| :class:`cluster.Birch` now preserves dtype for `numpy.float32`\n inputs. :pr:`22968` by `Meekail Zain `.\n \n+- |Enhancement| :class:`cluster.KMeans` and :class:`cluster.MiniBatchKMeans`\n+ now accept a new `'auto'` option for `n_init` which changes the number of\n+ random initializations to one when using `init='k-means++'` for efficiency.\n+ This begins deprecation for the default values of `n_init` in the two classes\n+ and both will have their defaults changed to `n_init='auto'` in 1.4.\n+\n :mod:`sklearn.datasets`\n .......................\n \n\n"}