Reputation: 3
I am writing a caffe python layer that resale the input between [0 255] along specific axis (code attached) and the forward pass is working fine. Is the backward pass required for such layer? if so, how can i implement it?
caffe_root = 'caffe_root'
import sys
sys.path.insert(0, caffe_root + 'python')
import caffe
import numpy as np
class scale_layer(caffe.Layer):
def setup(self, bottom, top):
assert len(bottom)==1 and len(top)==1, "scale_layer expects a single input and a single output"
def reshape(self, bottom, top):
top[0].reshape(*bottom[0].data.shape)
def forward(self, bottom, top):
in_ = np.array(bottom[0].data)
x_min = in_.min(axis=(0, 1), keepdims=True)
x_max = in_.max(axis=(0, 1), keepdims=True)
top[0].data[...] = np.around(255*((in_-x_min)/(x_max-x_min)))
def backward(self, top, propagate_down, bottom):
# backward pass is not implemented!
???????????????????????????
pass
Upvotes: 0
Views: 67
Reputation: 114816
Your function is quite simple, if you are willing to ignore the np.around
:
For x=x_min
and for x=x_max
the derivative is zero, for all other x
the derivative is 255/(x_max-x_min)
.
This can be implemented by
def forward(self, bottom, top):
in_ = bottom[0].data
self.x_min = in_.min(axis=(0, 1), keepdims=True) # cache min/max for backward
self.x_max = in_.max(axis=(0, 1), keepdims=True)
top[0].data[...] = 255*((in_-self.x_min)/(self.x_max-self.x_min)))
def backward(self, top, propagate_down, bottom):
in_ = bottom[0].data
b, c = in_.shape[:2]
diff = np.tile( 255/(self.x_max-self.x_min), (b, c, 1, 1) )
diff[ in_ == self.x_min ] = 0
diff[ in_ == self.x_max ] = 0
bottom[0].diff[...] = diff * top[0].diff
Do not forget to test this numberically. This can be done, e.g., using test_gradient_for_python_layer
.
Upvotes: 1