Coverage for mlprodict/onnxrt/ops_cpu/op_reduce_l2.py: 92%

25 statements  

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

1# -*- encoding: utf-8 -*- 

2# pylint: disable=E0203,E1101,C0111 

3""" 

4@file 

5@brief Runtime operator. 

6""" 

7import numpy 

8from onnx.defs import onnx_opset_version 

9from ._op import OpRunReduceNumpy, OpRun 

10 

11 

12class ReduceL2_1(OpRunReduceNumpy): 

13 

14 atts = {'axes': [], 'keepdims': 1} 

15 

16 def __init__(self, onnx_node, desc=None, **options): 

17 OpRunReduceNumpy.__init__(self, onnx_node, desc=desc, 

18 expected_attributes=ReduceL2_1.atts, 

19 **options) 

20 

21 def _run(self, data, attributes=None, verbose=0, fLOG=None): # pylint: disable=W0221 

22 return ( 

23 numpy.sqrt( 

24 numpy.sum( 

25 numpy.square(data), axis=self.axes, 

26 keepdims=self.keepdims) 

27 ).astype(dtype=data.dtype), ) 

28 

29 

30class ReduceL2_18(OpRun): 

31 

32 atts = {'keepdims': 1, 'noop_with_empty_axes': 0} 

33 

34 def __init__(self, onnx_node, desc=None, **options): 

35 OpRun.__init__(self, onnx_node, desc=desc, 

36 expected_attributes=ReduceL2_18.atts, 

37 **options) 

38 

39 def _run(self, data, axes=None, attributes=None, verbose=0, fLOG=None): # pylint: disable=W0221 

40 if ((axes is None or len(axes.shape) == 0 or axes.shape[0] == 0) and 

41 self.noop_with_empty_axes): 

42 return (data, ) 

43 if ((axes is not None and len(axes.shape) > 0 and axes.shape[0] > 0) and 

44 not isinstance(axes, int)): 

45 if isinstance(axes, numpy.ndarray) and len(axes.shape) == 0: 

46 axes = int(axes) 

47 else: 

48 axes = tuple(axes.ravel().tolist()) if len(axes) > 0 else None 

49 try: 

50 return ( 

51 numpy.sqrt( 

52 numpy.sum( 

53 numpy.square(data), axis=self.axes, 

54 keepdims=self.keepdims) 

55 ).astype(dtype=data.dtype), ) 

56 except TypeError as e: # pragma: no cover 

57 raise TypeError( 

58 f"Unable to reduce shape {data.shape!r} with axes={axes!r}.") from e 

59 

60 

61if onnx_opset_version() >= 18: 

62 ReduceL2 = ReduceL2_18 

63else: # pragma: no cover 

64 ReduceL2 = ReduceL2_1