test_center_loss.py 5.0 KB
Newer Older
H
HaoRen 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#   Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# 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
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# 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.

import unittest
import numpy as np
from op_test import OpTest
18
import paddle.fluid as fluid
H
HaoRen 已提交
19 20 21 22 23


class TestCenterLossOp(OpTest):
    def setUp(self):
        self.op_type = "center_loss"
24
        self.dtype = np.float64
H
HaoRen 已提交
25
        self.init_dtype_type()
26
        batch_size = 12
H
HaoRen 已提交
27 28 29 30 31 32 33 34
        feet_dim = 10
        cluster_num = 8
        self.attrs = {}
        self.attrs['cluster_num'] = cluster_num
        self.attrs['lambda'] = 0.1
        self.config()
        self.attrs['need_update'] = self.need_update
        labels = np.random.randint(cluster_num, size=batch_size, dtype='int64')
35 36 37
        feat = np.random.random((batch_size, feet_dim)).astype(np.float64)
        centers = np.random.random((cluster_num, feet_dim)).astype(np.float64)
        var_sum = np.zeros((cluster_num, feet_dim), dtype=np.float64)
H
HaoRen 已提交
38 39 40 41 42 43 44 45 46 47 48
        centers_select = centers[labels]
        output = feat - centers_select
        diff_square = np.square(output).reshape(batch_size, feet_dim)
        loss = 0.5 * np.sum(diff_square, axis=1).reshape(batch_size, 1)
        cout = []
        for i in range(cluster_num):
            cout.append(0)
        for i in range(batch_size):
            cout[labels[i]] += 1
            var_sum[labels[i]] += output[i]
        for i in range(cluster_num):
49
            var_sum[i] /= 1 + cout[i]
H
HaoRen 已提交
50 51
        var_sum *= 0.1
        result = centers + var_sum
52
        rate = np.array([0.1]).astype(np.float64)
H
HaoRen 已提交
53 54 55 56 57

        self.inputs = {
            'X': feat,
            'Label': labels,
            'Centers': centers,
58
            'CenterUpdateRate': rate,
H
HaoRen 已提交
59 60
        }

61
        if self.need_update:
H
HaoRen 已提交
62 63 64
            self.outputs = {
                'SampleCenterDiff': output,
                'Loss': loss,
65
                'CentersOut': result,
H
HaoRen 已提交
66 67 68 69 70
            }
        else:
            self.outputs = {
                'SampleCenterDiff': output,
                'Loss': loss,
71
                'CentersOut': centers,
H
HaoRen 已提交
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
            }

    def config(self):
        self.need_update = True

    def init_dtype_type(self):
        pass

    def test_check_output(self):
        self.check_output()

    def test_check_grad(self):
        self.check_grad(['X'], 'Loss')


class TestCenterLossOpNoUpdate(TestCenterLossOp):
    def config(self):
        self.need_update = False


92 93 94 95 96 97
class BadInputTestCenterLoss(unittest.TestCase):
    def test_error(self):
        with fluid.program_guard(fluid.Program()):

            def test_bad_x():
                data = [[1, 2, 3, 4], [5, 6, 7, 8]]
98 99 100
                label = fluid.layers.data(
                    name='label', shape=[2, 1], dtype='int32'
                )
101 102 103 104 105 106
                res = fluid.layers.center_loss(
                    data,
                    label,
                    num_classes=1000,
                    alpha=0.2,
                    param_attr=fluid.initializer.Xavier(uniform=False),
107 108
                    update_center=True,
                )
109 110 111 112

            self.assertRaises(TypeError, test_bad_x)

            def test_bad_y():
113 114 115
                data = fluid.layers.data(
                    name='data', shape=[2, 32], dtype='float32'
                )
116 117 118 119 120 121 122
                label = [[2], [3]]
                res = fluid.layers.center_loss(
                    data,
                    label,
                    num_classes=1000,
                    alpha=0.2,
                    param_attr=fluid.initializer.Xavier(uniform=False),
123 124
                    update_center=True,
                )
125 126 127 128

            self.assertRaises(TypeError, test_bad_y)

            def test_bad_alpha():
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
                data = fluid.layers.data(
                    name='data2',
                    shape=[2, 32],
                    dtype='float32',
                    append_batch_size=False,
                )
                label = fluid.layers.data(
                    name='label2',
                    shape=[2, 1],
                    dtype='int32',
                    append_batch_size=False,
                )
                alpha = fluid.layers.data(
                    name='alpha',
                    shape=[1],
                    dtype='int64',
                    append_batch_size=False,
                )
147 148 149 150 151 152
                res = fluid.layers.center_loss(
                    data,
                    label,
                    num_classes=1000,
                    alpha=alpha,
                    param_attr=fluid.initializer.Xavier(uniform=False),
153 154
                    update_center=True,
                )
155 156 157 158

            self.assertRaises(TypeError, test_bad_alpha)


H
HaoRen 已提交
159 160
if __name__ == "__main__":
    unittest.main()