Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[tests][python-package] refactor list_to_1d_numpy test to run without pandas installed #4639

Merged
merged 3 commits into from
Oct 7, 2021
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 16 additions & 12 deletions tests/python_package_test/test_basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -510,19 +510,23 @@ def test_choose_param_value():
assert original_params == expected_params


@pytest.mark.skipif(not PANDAS_INSTALLED, reason='pandas is not installed')
@pytest.mark.parametrize(
'y',
[
np.random.rand(10),
np.random.rand(10, 1),
pd_Series(np.random.rand(10)),
pd_Series(['a', 'b']),
[1] * 10,
[[1], [2]]
])
@pytest.mark.parametrize('collection', ['1d_np', '2d_np', 'pd_float', 'pd_str', '1d_list', '2d_list'])
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I fear this construct might be hard to understand if the reason behind it is unknown.
Would it be an option to not change the test at all, but adapt the dummy implementation for pandas in lightgbm/compat.py

Current:

try:
    from pandas import DataFrame as pd_DataFrame
    from pandas import Series as pd_Series
    from pandas import concat
    from pandas.api.types import is_sparse as is_dtype_sparse
    PANDAS_INSTALLED = True
except ImportError:
    PANDAS_INSTALLED = False

    class pd_Series:  # type: ignore
        """Dummy class for pandas.Series."""

        pass

    class pd_DataFrame:  # type: ignore
        """Dummy class for pandas.DataFrame."""

        pass

Proposal:

try:
    from pandas import DataFrame as pd_DataFrame
    from pandas import Series as pd_Series
    from pandas import concat
    from pandas.api.types import is_sparse as is_dtype_sparse
    PANDAS_INSTALLED = True
except ImportError:
    PANDAS_INSTALLED = False

    class pd_Series:  # type: ignore
        """Dummy class for pandas.Series."""
        def __init__(self, *args):
            pass

    class pd_DataFrame:  # type: ignore
        """Dummy class for pandas.DataFrame."""
        def __init__(self, *args):
            pass

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree with @strobelTha . I believe that making all our dummy classes from compat.py creatable with any combination of arguments by adding catch-all constructor will be useful

class pd_Series:  # type: ignore
    """Dummy class for pandas.Series."""
    def __init__(self, *args, **kwargs):
        pass

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like the refactor because of the following reasons:

  • Moving the collection definition inside the function instead of having that big parametrize seems cleaner.
  • Now the test will run for lists and numpy arrays when pandas isn't installed, whereas previously the whole test was (supposed to be) skipped.
  • In case the test fails the message is more descriptive, i.e. FAILED tests/python_package_test/test_basic.py::test_list_to_1d_numpy[float32-2d_np] vs FAILED tests/python_package_test/test_basic.py::test_list_to_1d_numpy[float64-y1].
class pd_Series:  # type: ignore
    """Dummy class for pandas.Series."""
    def __init__(self, *args, **kwargs):
        pass

@strobelTha would you like to contribute those changes?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@jmoralez I liked reasons #2 and #3 you listed above. Thanks a lot for emphasizing advantages of the current refactor.

And indeed, we can add constructors for our dummy classes in a separate PR.

@pytest.mark.parametrize('dtype', [np.float32, np.float64])
def test_list_to_1d_numpy(y, dtype):
def test_list_to_1d_numpy(collection, dtype):
collection2y = {
'1d_np': np.random.rand(10),
'2d_np': np.random.rand(10, 1),
'pd_float': np.random.rand(10),
'pd_str': ['a', 'b'],
'1d_list': [1] * 10,
'2d_list': [[1], [2]],
}
y = collection2y[collection]
if collection.startswith('pd'):
if not PANDAS_INSTALLED:
pytest.skip('pandas is not installed')
else:
y = pd_Series(y)
if isinstance(y, np.ndarray) and len(y.shape) == 2:
with pytest.warns(UserWarning, match='column-vector'):
lgb.basic.list_to_1d_numpy(y)
Expand Down