test_cos_sim_op.py 4.9 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.

X
Xinghai Sun 已提交
15
import unittest
16

X
Xinghai Sun 已提交
17
import numpy as np
18
from op_test import OpTest
19

20 21
import paddle.fluid as fluid
from paddle.fluid import Program, program_guard
X
Xinghai Sun 已提交
22 23


Q
qijun 已提交
24
class TestCosSimOp(OpTest):
X
Xinghai Sun 已提交
25
    def setUp(self):
Q
qijun 已提交
26
        self.op_type = "cos_sim"
X
Xinghai Sun 已提交
27
        self.inputs = {
28
            'X': np.random.random((6, 20)).astype("float32"),
29
            'Y': np.random.random((6, 20)).astype("float32"),
30 31 32
        }
        expect_x_norm = np.linalg.norm(self.inputs['X'], axis=1)
        expect_y_norm = np.linalg.norm(self.inputs['Y'], axis=1)
33 34 35 36 37
        expect_out = (
            (self.inputs['X'] * self.inputs['Y']).sum(axis=1)
            / expect_x_norm
            / expect_y_norm
        )
38 39 40
        self.outputs = {
            'XNorm': np.expand_dims(expect_x_norm, 1),
            'YNorm': np.expand_dims(expect_y_norm, 1),
41
            'Out': np.expand_dims(expect_out, 1),
X
Xinghai Sun 已提交
42 43
        }

Q
qijun 已提交
44 45
    def test_check_output(self):
        self.check_output()
X
Xinghai Sun 已提交
46

Q
qijun 已提交
47
    def test_check_grad_normal(self):
48
        self.check_grad(['X', 'Y'], 'Out', max_relative_error=0.06)
X
Xinghai Sun 已提交
49

Q
qijun 已提交
50
    def test_check_grad_ingore_x(self):
51 52 53
        self.check_grad(
            ['Y'], 'Out', max_relative_error=0.06, no_grad_set=set("X")
        )
54

55
    def test_check_grad_ingore_y(self):
56 57 58
        self.check_grad(
            ['X'], 'Out', max_relative_error=0.06, no_grad_set=set('Y')
        )
59

X
Xinghai Sun 已提交
60

61
class TestCosSimOp2(TestCosSimOp):
62
    def setUp(self):
63
        self.op_type = "cos_sim"
64
        self.inputs = {
Z
zhupengyang 已提交
65
            'X': np.random.random((6, 100)).astype("float32"),
66
            'Y': np.random.random((1, 100)).astype("float32"),
67 68 69
        }
        expect_x_norm = np.linalg.norm(self.inputs['X'], axis=1)
        expect_y_norm = np.linalg.norm(self.inputs['Y'], axis=1)
70 71 72 73 74
        expect_out = (
            (self.inputs['X'] * self.inputs['Y']).sum(axis=1)
            / expect_x_norm
            / expect_y_norm
        )
75 76 77
        self.outputs = {
            'XNorm': np.expand_dims(expect_x_norm, 1),
            'YNorm': np.expand_dims(expect_y_norm, 1),
78
            'Out': np.expand_dims(expect_out, 1),
79 80 81
        }


82
class TestCosSimOp3(TestCosSimOp):
83
    def setUp(self):
84
        self.op_type = "cos_sim"
85
        self.inputs = {
Z
zhupengyang 已提交
86
            'X': np.random.random((6, 5, 4)).astype("float32"),
87
            'Y': np.random.random((6, 5, 4)).astype("float32"),
88 89 90
        }
        expect_x_norm = np.linalg.norm(self.inputs['X'], axis=(1, 2))
        expect_y_norm = np.linalg.norm(self.inputs['Y'], axis=(1, 2))
91 92 93 94 95
        expect_out = (
            (self.inputs['X'] * self.inputs['Y']).sum(axis=(1, 2))
            / expect_x_norm
            / expect_y_norm
        )
96 97 98
        self.outputs = {
            'XNorm': np.expand_dims(expect_x_norm, 1),
            'YNorm': np.expand_dims(expect_y_norm, 1),
99
            'Out': np.expand_dims(expect_out, 1),
100 101 102
        }


103
class TestCosSimOp4(TestCosSimOp):
104
    def setUp(self):
105
        self.op_type = "cos_sim"
106
        self.inputs = {
Z
zhupengyang 已提交
107
            'X': np.random.random((6, 5, 20)).astype("float32"),
108
            'Y': np.random.random((1, 5, 20)).astype("float32"),
109 110 111
        }
        expect_x_norm = np.linalg.norm(self.inputs['X'], axis=(1, 2))
        expect_y_norm = np.linalg.norm(self.inputs['Y'], axis=(1, 2))
112 113 114 115 116
        expect_out = (
            (self.inputs['X'] * self.inputs['Y']).sum(axis=(1, 2))
            / expect_x_norm
            / expect_y_norm
        )
117 118 119
        self.outputs = {
            'XNorm': np.expand_dims(expect_x_norm, 1),
            'YNorm': np.expand_dims(expect_y_norm, 1),
120
            'Out': np.expand_dims(expect_out, 1),
121 122 123
        }


124 125 126 127
class TestCosSimOpError(unittest.TestCase):
    def test_errors(self):
        with program_guard(Program(), Program()):
            # the input of batch_norm must be Variable.
128 129 130 131 132 133
            x1 = fluid.create_lod_tensor(
                np.array([-1, 3, 5, 5]), [[1, 1, 1, 1]], fluid.CPUPlace()
            )
            x2 = fluid.create_lod_tensor(
                np.array([-1, 3, 5, 5]), [[1, 1, 1, 1]], fluid.CPUPlace()
            )
134 135 136 137 138 139 140 141
            self.assertRaises(TypeError, fluid.layers.cos_sim, x1, x2)

            # the input dtype of batch_norm must be float32
            x3 = fluid.layers.data(name='x3', shape=[3, 4, 5, 6], dtype="int32")
            x4 = fluid.layers.data(name='x4', shape=[3, 4, 5, 6], dtype="int64")
            self.assertRaises(TypeError, fluid.layers.cos_sim, x3, x4)


X
Xinghai Sun 已提交
142 143
if __name__ == '__main__':
    unittest.main()