Source code for mlinsights.sklapi.sklearn_parameters

# -*- coding: utf-8 -*-
"""
Defines class :class:`SkLearnParameters <mlinsights.sklapi.sklearn_parameters.SkLearnParameters>`.


:githublink:`%|py|6`
"""
import textwrap


[docs]class SkException (Exception): """ custom exception :githublink:`%|py|13` """ pass
[docs]class SkLearnParameters: """ Defines a class to store parameters of a *learner* or a *transform*. :githublink:`%|py|21` """
[docs] def __init__(self, **kwargs): """ Stores parameters as members of the class itself. :githublink:`%|py|26` """ self._keys = list(kwargs.keys()) for k, v in kwargs.items(): self.validate(k, v) setattr(self, k, v)
[docs] def validate(self, name, value): """ Verifies a parameter and its value. :param name: name :param value: value @raises raises :class:`SkException <mlinsights.sklapi.sklearn_parameters.SkException>` if error :githublink:`%|py|39` """ if name.startswith("_") or name.endswith("_"): raise SkException( # pragma: no cover "Parameter name must not start by '_': '{0}'".format(name))
@property def Keys(self): """ Returns parameter names. :githublink:`%|py|48` """ return self._keys
[docs] def __repr__(self): """ usual :githublink:`%|py|54` """ def fmt(v): "formatting function" if isinstance(v, str): return "'{0}'".format(v) return repr(v) text = ", ".join("{0}={1}".format(k, fmt(getattr(self, k))) for k in sorted(self.Keys)) return "\n".join(textwrap.wrap(text, subsequent_indent=" "))
[docs] def to_dict(self): """ Returns parameters as a dictionary. :return: dict :githublink:`%|py|69` """ return {k: getattr(self, k) for k in self.Keys}