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 ._op import OpRunUnaryNum
11class Softmax(OpRunUnaryNum):
13 atts = {'axis': 1}
15 def __init__(self, onnx_node, desc=None, **options):
16 OpRunUnaryNum.__init__(self, onnx_node, desc=desc,
17 expected_attributes=Softmax.atts,
18 **options)
20 def _run(self, X): # pylint: disable=W0221
21 if self.inplaces.get(0, False):
22 return self._run_inplace(X)
23 tmp = X - X.max(axis=self.axis)[:, numpy.newaxis]
24 Y = numpy.exp(tmp)
25 Y /= Y.sum(axis=self.axis)[:, numpy.newaxis]
26 return (Y, )
28 def _run_inplace(self, X):
29 X -= X.max(axis=self.axis)[:, numpy.newaxis]
30 numpy.exp(X, out=X)
31 X /= X.sum(axis=self.axis)[:, numpy.newaxis]
32 return (X, )
34 def to_python(self, inputs):
35 lines = ["tmp = {0} - {0}.max(axis=axis)[:, numpy.newaxis]".format(
36 inputs[0]),
37 "Y = numpy.exp(tmp)",
38 "Y /= Y.sum(axis=axis)[:, numpy.newaxis]",
39 "return Y"]
40 return ("import numpy", "\n".join(lines))