test_sigmoid_cross_entropy_with_logits_op.py 2.2 KB
Newer Older
1 2 3 4
import numpy as np
from op_test import OpTest
from scipy.special import logit
from scipy.special import expit
5
import unittest
6 7 8


class TestSigmoidCrossEntropyWithLogitsOp1(OpTest):
9 10
    """Test sigmoid_cross_entropy_with_logit_op with binary label
    """
11 12 13 14 15 16 17 18 19

    def setUp(self):
        self.op_type = "sigmoid_cross_entropy_with_logits"
        batch_size = 64
        num_classes = 20
        self.inputs = {
            'X': logit(
                np.random.uniform(0, 1, (batch_size, num_classes))
                .astype("float32")),
20
            'Label': np.random.randint(0, 2, (batch_size, num_classes))
21 22 23 24 25
            .astype("float32")
        }

        # Fw Pass is implemented as elementwise sigmoid followed by
        # elementwise logistic loss
26
        # Label * -log(sigmoid(X)) + (1 - label) * -log(1 - sigmoid(X))
27
        sigmoid_X = expit(self.inputs['X'])
28 29
        term1 = self.inputs['Label'] * np.log(sigmoid_X)
        term2 = (1 - self.inputs['Label']) * np.log(1 - sigmoid_X)
30 31 32 33 34 35 36 37 38 39
        self.outputs = {'Out': -term1 - term2}

    def test_check_output(self):
        self.check_output()

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


class TestSigmoidCrossEntropyWithLogitsOp2(OpTest):
40 41
    """Test sigmoid_cross_entropy_with_logit_op with probabalistic label
    """
42 43 44 45 46 47 48 49 50

    def setUp(self):
        self.op_type = "sigmoid_cross_entropy_with_logits"
        batch_size = 64
        num_classes = 20
        self.inputs = {
            'X': logit(
                np.random.uniform(0, 1, (batch_size, num_classes))
                .astype("float32")),
51
            'Label': np.random.uniform(0, 1, (batch_size, num_classes))
52 53 54 55 56
            .astype("float32")
        }

        # Fw Pass is implemented as elementwise sigmoid followed by
        # elementwise logistic loss
57
        # Label * -log(sigmoid(X)) + (1 - label) * -log(1 - sigmoid(X))
58
        sigmoid_X = expit(self.inputs['X'])
59 60
        term1 = self.inputs['Label'] * np.log(sigmoid_X)
        term2 = (1 - self.inputs['Label']) * np.log(1 - sigmoid_X)
61 62 63 64 65 66 67
        self.outputs = {'Out': -term1 - term2}

    def test_check_output(self):
        self.check_output()

    def test_check_grad(self):
        self.check_grad(['X'], 'Out')
68 69 70 71


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