test_softmax_op.py 717 字节
Newer Older
Q
qijun 已提交
1 2
import unittest
import numpy as np
Q
qijun 已提交
3
from op_test import OpTest
Q
qijun 已提交
4 5 6 7 8 9 10 11 12


def stable_softmax(x):
    """Compute the softmax of vector x in a numerically stable way."""
    shiftx = x - np.max(x)
    exps = np.exp(shiftx)
    return exps / np.sum(exps)


Q
qijun 已提交
13
class TestSoftmaxOp(OpTest):
Q
qijun 已提交
14 15
    def setUp(self):
        self.type = "softmax"
Q
qijun 已提交
16 17 18
        self.inputs = {
            'X': np.random.uniform(0.1, 1, [10, 10]).astype("float32")
        }
D
dangqingqing 已提交
19
        self.outputs = {
Q
qijun 已提交
20
            'Y': np.apply_along_axis(stable_softmax, 1, self.inputs['X'])
D
dangqingqing 已提交
21
        }
Q
qijun 已提交
22

Q
qijun 已提交
23 24
    def test_check_output(self):
        self.check_output()
Q
qijun 已提交
25

Q
qijun 已提交
26 27
    def test_check_grad(self):
        self.check_grad(['X'], 'Y')
Q
Qiao Longfei 已提交
28 29


C
caoying03 已提交
30
if __name__ == "__main__":
Q
qijun 已提交
31
    unittest.main()