Coverage for mlprodict/tools/asv_options_helper.py: 91%

35 statements  

« prev     ^ index     » next       coverage.py v7.1.0, created at 2023-02-04 02:28 +0100

1""" 

2@file 

3@brief Functions to show shortened options in :epkg:`asv` benchmarks. 

4""" 

5 

6 

7def expand_onnx_options(model, optim): 

8 """ 

9 Expands shortened options. Long names hide some part 

10 of graphs in :epkg:`asv` benchmark. This trick converts 

11 a string into real conversions options. 

12 

13 @param model model class (:epkg:`scikit-learn`) 

14 @param optim option 

15 @return expanded options 

16 

17 It is the reverse of function @see fn shorten_onnx_options. 

18 The following options are handled: 

19 

20 .. runpython:: 

21 :showcode: 

22 :warningout: DeprecationWarning 

23 

24 from sklearn.linear_model import LogisticRegression 

25 from mlprodict.tools.asv_options_helper import expand_onnx_options 

26 

27 for name in ['cdist', 'nozipmap', 'raw_scores']: 

28 print(name, ':', expand_onnx_options(LogisticRegression, name)) 

29 """ 

30 if optim == 'cdist': 

31 options = {model.__class__: {'optim': 'cdist'}} 

32 elif optim == 'nozipmap': 

33 options = {model.__class__: {'zipmap': False}} 

34 elif optim == 'raw_scores': 

35 options = {model.__class__: {'raw_scores': True, 'zipmap': False}} 

36 else: 

37 options = optim # pragma: no cover 

38 return options 

39 

40 

41def shorten_onnx_options(model, opts): 

42 """ 

43 Shortens onnx options into a string. 

44 Long names hide some part 

45 of graphs in :epkg:`asv` benchmark. 

46 

47 @param model model class (:epkg:`scikit-learn`) 

48 @param opts options 

49 @return shortened options 

50 

51 It is the reverse of function @see fn expand_onnx_options. 

52 """ 

53 if opts is None: 

54 return opts 

55 if opts == {model: {'optim': 'cdist'}}: 

56 return 'cdist' 

57 if opts == {model: {'zipmap': False}}: 

58 return 'nozipmap' 

59 if opts == {model: {'raw_scores': True, 'zipmap': False}}: 

60 return 'raw_scores' 

61 return None 

62 

63 

64def display_onnx(model_onnx, max_length=1000): 

65 """ 

66 Returns a shortened string of the model. 

67 

68 @param model_onnx onnx model 

69 @param max_length maximal string length 

70 @return string 

71 """ 

72 res = str(model_onnx) 

73 if max_length is None or len(res) <= max_length: 

74 return res 

75 begin = res[:max_length // 2] 

76 end = res[-max_length // 2:] 

77 return "\n".join([begin, '[...]', end]) 

78 

79 

80def version2number(vers): 

81 """ 

82 Converts a version number into a real number. 

83 """ 

84 spl = vers.split('.') 

85 r = 0 

86 for i, s in enumerate(spl): 

87 try: 

88 vi = int(s) 

89 except ValueError: 

90 vi = 0 

91 r += vi * 10 ** (-i * 3) 

92 return r