Skip to content

Commit

Permalink
feat(core): implement get_params() API for steps
Browse files Browse the repository at this point in the history
  • Loading branch information
deepyaman committed Aug 30, 2024
1 parent 0084273 commit d559fff
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 0 deletions.
72 changes: 72 additions & 0 deletions ibis_ml/core.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import copy
import inspect
import os
import pprint
from collections import defaultdict
Expand Down Expand Up @@ -290,6 +291,77 @@ def categorize(df: pd.DataFrame, categories: dict[str, list[Any]]) -> pd.DataFra


class Step:
@classmethod
def _get_param_names(cls) -> list[str]:
"""Get parameter names for the estimator.
Notes
-----
Copied from [1]_.
References
----------
.. [1] https://github.com/scikit-learn/scikit-learn/blob/ab2f539/sklearn/base.py#L148-L173
"""
# fetch the constructor or the original constructor before
# deprecation wrapping if any
init = getattr(cls.__init__, "deprecated_original", cls.__init__)
if init is object.__init__:
# No explicit constructor to introspect
return []

# introspect the constructor arguments to find the model parameters
# to represent
init_signature = inspect.signature(init)
# Consider the constructor parameters excluding 'self'
parameters = [
p
for p in init_signature.parameters.values()
if p.name != "self" and p.kind != p.VAR_KEYWORD
]
for p in parameters:
if p.kind == p.VAR_POSITIONAL:
raise RuntimeError(
"scikit-learn estimators should always "
"specify their parameters in the signature"
" of their __init__ (no varargs)."
f" {cls} with constructor {init_signature} doesn't "
" follow this convention."
)
# Extract and sort argument names excluding 'self'
return sorted([p.name for p in parameters])

def get_params(self, deep=True) -> dict[str, Any]:
"""Get parameters for this estimator.
Parameters
----------
deep : bool, default=True
If True, will return the parameters for this estimator and
contained subobjects that are estimators.
Returns
-------
params : dict
Parameter names mapped to their values.
Notes
-----
Copied from [1]_.
References
----------
.. [1] https://github.com/scikit-learn/scikit-learn/blob/626b460/sklearn/base.py#L145-L167
"""
out = {}
for key in self._get_param_names():
value = getattr(self, key)
if deep and hasattr(value, "get_params") and not isinstance(value, type):
deep_items = value.get_params().items()
out.update((key + "__" + k, val) for k, val in deep_items)
out[key] = value
return out

def __repr__(self) -> str:
return pprint.pformat(self)

Expand Down
7 changes: 7 additions & 0 deletions tests/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,13 @@ def test_errors_nicely_if_not_fitted(table, method):
getattr(r, method)(table)


def test_get_params():
rec = ml.Recipe(ml.ExpandDateTime(ml.timestamp()))

assert "expanddatetime__components" in rec.get_params(deep=True)
assert "expanddatetime__components" not in rec.get_params(deep=False)


@pytest.mark.parametrize(
("step", "url"),
[
Expand Down

0 comments on commit d559fff

Please sign in to comment.