Coverage for mlinsights/sklapi/sklearn_parameters.py: 100%

24 statements  

« prev     ^ index     » next       coverage.py v6.4.2, created at 2022-08-09 08:45 +0200

1# -*- coding: utf-8 -*- 

2""" 

3@file 

4@brief Defines class @see cl SkLearnParameters. 

5""" 

6import textwrap 

7 

8 

9class SkException (Exception): 

10 

11 """ 

12 custom exception 

13 """ 

14 pass 

15 

16 

17class SkLearnParameters: 

18 

19 """ 

20 Defines a class to store parameters of a *learner* or a *transform*. 

21 """ 

22 

23 def __init__(self, **kwargs): 

24 """ 

25 Stores parameters as members of the class itself. 

26 """ 

27 self._keys = list(kwargs.keys()) 

28 for k, v in kwargs.items(): 

29 self.validate(k, v) 

30 setattr(self, k, v) 

31 

32 def validate(self, name, value): 

33 """ 

34 Verifies a parameter and its value. 

35 

36 @param name name 

37 @param value value 

38 @raises raises @see cl SkException if error 

39 """ 

40 if name.startswith("_") or name.endswith("_"): 

41 raise SkException( # pragma: no cover 

42 f"Parameter name must not start by '_': '{name}'") 

43 

44 @property 

45 def Keys(self): 

46 """ 

47 Returns parameter names. 

48 """ 

49 return self._keys 

50 

51 def __repr__(self): 

52 """ 

53 usual 

54 """ 

55 def fmt(v): 

56 "formatting function" 

57 if isinstance(v, str): 

58 return f"'{v}'" 

59 return repr(v) 

60 text = ", ".join(f"{k}={fmt(getattr(self, k))}" 

61 for k in sorted(self.Keys)) 

62 return "\n".join(textwrap.wrap(text, subsequent_indent=" ")) 

63 

64 def to_dict(self): 

65 """ 

66 Returns parameters as a dictionary. 

67 

68 @return dict 

69 """ 

70 return {k: getattr(self, k) for k in self.Keys}