test_center_loss.py 5.2 KB
Newer Older
H
HaoRen 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#   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
import paddle.fluid.core as core
19
import paddle.fluid as fluid
H
HaoRen 已提交
20 21 22


class TestCenterLossOp(OpTest):
23

H
HaoRen 已提交
24 25
    def setUp(self):
        self.op_type = "center_loss"
26
        self.dtype = np.float64
H
HaoRen 已提交
27
        self.init_dtype_type()
28
        batch_size = 12
H
HaoRen 已提交
29 30 31 32 33 34 35 36
        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')
37 38 39
        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 已提交
40 41 42 43 44 45 46 47 48 49 50 51 52 53
        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):
            var_sum[i] /= (1 + cout[i])
        var_sum *= 0.1
        result = centers + var_sum
54
        rate = np.array([0.1]).astype(np.float64)
H
HaoRen 已提交
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89

        self.inputs = {
            'X': feat,
            'Label': labels,
            'Centers': centers,
            'CenterUpdateRate': rate
        }

        if self.need_update == True:
            self.outputs = {
                'SampleCenterDiff': output,
                'Loss': loss,
                'CentersOut': result
            }
        else:
            self.outputs = {
                'SampleCenterDiff': output,
                'Loss': loss,
                'CentersOut': centers
            }

    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):
90

H
HaoRen 已提交
91 92 93 94
    def config(self):
        self.need_update = False


95
class BadInputTestCenterLoss(unittest.TestCase):
96

97 98 99 100 101
    def test_error(self):
        with fluid.program_guard(fluid.Program()):

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

            self.assertRaises(TypeError, test_bad_x)

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

            self.assertRaises(TypeError, test_bad_y)

            def test_bad_alpha():
131 132 133 134 135 136 137 138 139 140 141 142
                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)
143 144 145 146 147 148 149 150 151 152 153
                res = fluid.layers.center_loss(
                    data,
                    label,
                    num_classes=1000,
                    alpha=alpha,
                    param_attr=fluid.initializer.Xavier(uniform=False),
                    update_center=True)

            self.assertRaises(TypeError, test_bad_alpha)


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