Can I achieve Sigmoid as the output with binary cross entropy as the loss function?
I want to use the Sigmoid as the output with binary cross entropy as the loss function, are there some ways I can achieve it? OR is there custom version of LogisticRegressionOutput layer or SoftmaxOutput layer, so that I can follow the examples to write one? Thanks.
class SigmoidOutput(mx.operator.CustomOp):
eps=1e-6 # Avoid -inf when taking log(0)
eps1 = 1. + eps
eps_1 = 1. - eps
def forward(self, is_train, req, in_data, out_data, aux):
x=in_data[0].asnumpy()
y=1./(1.+np.exp(-x))
self.assign(out_data[0], req[0], mx.nd.array(y))
def backward(self, req, out_grad, in_data, out_data, in_grad, aux):
p=out_data[0].asnumpy()
y = in_data[1].asnumpy()
grad=-(y * np.log(p+self.eps) + (1.-y) * np.log((self.eps1) - p))
self.assign(in_grad[0], req[0], mx.nd.array(grad))
@mx.operator.register("SigmoidOutput")
class SigmoidOPProp(mx.operator.CustomOpProp):
def __init__(self):
super(SigmoidOPProp, self).__init__(need_top_grad=False)
def list_arguments(self):
return ['data','label']
def list_outputs(self):
return ['output']
def create_operator(self, ctx, shapes, dtypes):
return SigmoidOutput()
def infer_shape(self, in_shape):
if in_shape[0] != in_shape[1]:
raise ValueError("Input shapes differ. data:%s. label:%s. must be same"
% (str(in_shape[0]),str(in_shape[1])))
output_shape = in_shape[0]
return in_shape, [output_shape], []
There is something wrong with my code, and it would leads to all output be 0. And it cannot calculate loss correctly. Could someone help me?
For LogisticRegressionOutput:
change self.assign(out_data[0], req[0], in_data[0]) to self.assign(out_data[0], req[0], mx.nd.array(y)) in def forward
change grad=-(y * np.log(p+self.eps) + (1.-y) * np.log((self.eps1) - p)) to grad = p - y in def backward
@CNevd but if I change the backward to grad = p - y, the loss function is not the binary cross entropy?
using python -m pdb you_train_command to invoke python debug mode, then you can set breakpoints and run step by step, check value of variables, which may be useful to find where is the bug
some tips
while writing you own operator, don't use asnumpy before you try all other possible way, it's time expensive