test_modified_huber_loss_op.py 2.0 KB
Newer Older
1
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
D
dzhwinter 已提交
2
#
D
dzhwinter 已提交
3 4 5
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
D
dzhwinter 已提交
6
#
D
dzhwinter 已提交
7
#     http://www.apache.org/licenses/LICENSE-2.0
D
dzhwinter 已提交
8
#
D
dzhwinter 已提交
9 10 11 12 13 14
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

Y
yangyaming 已提交
15 16
import unittest
import numpy as np
Y
yangyaming 已提交
17
from op_test import OpTest
Y
yangyaming 已提交
18 19 20 21


def modified_huber_loss_forward(val):
    if val < -1:
22
        return -4. * val
Y
yangyaming 已提交
23
    elif val < 1:
24
        return (1. - val) * (1. - val)
Y
yangyaming 已提交
25
    else:
26
        return 0.
Y
yangyaming 已提交
27 28


Y
yangyaming 已提交
29
class TestModifiedHuberLossOp(OpTest):
Y
yangyaming 已提交
30
    def setUp(self):
Y
yangyaming 已提交
31
        self.op_type = 'modified_huber_loss'
Y
yangyaming 已提交
32
        samples_num = 32
33 34 35 36 37 38 39 40 41 42 43 44 45 46

        x_np = np.random.uniform(-2., 2., (samples_num, 1)).astype('float32')
        y_np = np.random.choice([0, 1], samples_num).reshape(
            (samples_num, 1)).astype('float32')
        product_res = x_np * (2. * y_np - 1.)
        # keep away from the junction of piecewise function
        for pos, val in np.ndenumerate(product_res):
            while abs(val - 1.) < 0.05:
                x_np[pos] = np.random.uniform(-2., 2.)
                y_np[pos] = np.random.choice([0, 1])
                product_res[pos] = x_np[pos] * (2 * y_np[pos] - 1)
                val = product_res[pos]

        self.inputs = {'X': x_np, 'Y': y_np}
Y
yangyaming 已提交
47 48 49
        loss = np.vectorize(modified_huber_loss_forward)(product_res)

        self.outputs = {
Y
Yu Yang 已提交
50 51
            'IntermediateVal': product_res.astype('float32'),
            'Out': loss.reshape((samples_num, 1)).astype('float32')
Y
yangyaming 已提交
52 53
        }

Y
yangyaming 已提交
54 55
    def test_check_output(self):
        self.check_output()
Y
yangyaming 已提交
56

Y
yangyaming 已提交
57
    def test_check_grad(self):
58
        self.check_grad(['X'], 'Out', max_relative_error=0.01)
Y
yangyaming 已提交
59 60 61 62


if __name__ == '__main__':
    unittest.main()