Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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

2# pylint: disable=E0203,E1101,C0111 

3""" 

4@file 

5@brief Runtime operator. 

6""" 

7import numpy 

8from scipy.special import expit # pylint: disable=E0611 

9from ._op import OpRunClassifierProb 

10from ._op_classifier_string import _ClassifierCommon 

11from ._op_numpy_helper import numpy_dot_inplace 

12 

13 

14class LinearClassifier(OpRunClassifierProb, _ClassifierCommon): 

15 

16 atts = {'classlabels_ints': [], 'classlabels_strings': [], 

17 'coefficients': None, 'intercepts': None, 

18 'multi_class': 0, 'post_transform': b'NONE'} 

19 

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

21 OpRunClassifierProb.__init__(self, onnx_node, desc=desc, 

22 expected_attributes=LinearClassifier.atts, 

23 **options) 

24 self._post_process_label_attributes() 

25 if not isinstance(self.coefficients, numpy.ndarray): 

26 raise TypeError("coefficient must be an array not {}.".format( 

27 type(self.coefficients))) 

28 if len(getattr(self, "classlabels_ints", [])) == 0 and \ 

29 len(getattr(self, 'classlabels_strings', [])) == 0: 

30 raise ValueError( 

31 "Fields classlabels_ints or classlabels_strings must be specified.") 

32 self.nb_class = max(len(getattr(self, 'classlabels_ints', [])), 

33 len(getattr(self, 'classlabels_strings', []))) 

34 if len(self.coefficients.shape) != 1: 

35 raise ValueError("coefficient must be an array but has shape {}\n{}.".format( 

36 self.coefficients.shape, desc)) 

37 n = self.coefficients.shape[0] // self.nb_class 

38 self.coefficients = self.coefficients.reshape(self.nb_class, n).T 

39 

40 def _run(self, x): # pylint: disable=W0221 

41 scores = numpy_dot_inplace(self.inplaces, x, self.coefficients) 

42 if self.intercepts is not None: 

43 scores += self.intercepts 

44 

45 if self.post_transform == b'NONE': 

46 pass 

47 elif self.post_transform == b'LOGISTIC': 

48 expit(scores, out=scores) 

49 elif self.post_transform == b'SOFTMAX': 

50 numpy.subtract(scores, scores.max(axis=1)[ 

51 :, numpy.newaxis], out=scores) 

52 numpy.exp(scores, out=scores) 

53 numpy.divide(scores, scores.sum(axis=1)[ 

54 :, numpy.newaxis], out=scores) 

55 else: 

56 raise NotImplementedError("Unknown post_transform: '{}'.".format( 

57 self.post_transform)) 

58 

59 if self.nb_class == 1: 

60 label = numpy.zeros((scores.shape[0],), dtype=x.dtype) 

61 label[scores > 0] = 1 

62 else: 

63 label = numpy.argmax(scores, axis=1) 

64 return self._post_process_predicted_label(label, scores)