Advertisement
Guest User

Untitled

a guest
Jul 2nd, 2016
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. class EuclideanLossLayer(caffe.Layer):
  2. """
  3. Compute the Euclidean Loss in the same manner as the C++ EuclideanLossLayer
  4. to demonstrate the class interface for developing layers in Python.
  5. """
  6.  
  7. def setup(self, bottom, top):
  8. # check input pair
  9. if len(bottom) != 2:
  10. raise Exception("Need two inputs to compute distance.")
  11.  
  12. def reshape(self, bottom, top):
  13. # check input dimensions match
  14. if bottom[0].count != bottom[1].count:
  15. raise Exception("Inputs must have the same dimension.")
  16. # difference is shape of inputs
  17. self.diff = np.zeros_like(bottom[0].data, dtype=np.float32)
  18. # loss output is scalar
  19. top[0].reshape(1)
  20.  
  21. def forward(self, bottom, top):
  22. self.diff[...] = bottom[0].data - bottom[1].data
  23. top[0].data[...] = np.sum(self.diff**2) / bottom[0].num / 2.
  24.  
  25. def backward(self, top, propagate_down, bottom):
  26. for i in range(2):
  27. if not propagate_down[i]:
  28. continue
  29. if i == 0:
  30. sign = 1
  31. else:
  32. sign = -1
  33. bottom[i].diff[...] = sign * self.diff / bottom[i].num
  34.  
  35. layer {
  36. type: 'Python'
  37. name: 'loss'
  38. top: 'loss'
  39. bottom: 'ipx'
  40. bottom: 'ipy'
  41. python_param {
  42. # the module name -- usually the filename -- that needs to be in $PYTHONPATH
  43. module: 'pyloss'
  44. # the layer name -- the class name in the module
  45. layer: 'EuclideanLossLayer'
  46. }
  47. # set loss weight so Caffe knows this is a loss layer.
  48. # since PythonLayer inherits directly from Layer, this isn't automatically
  49. # known to Caffe
  50. loss_weight: 1
  51. }
  52.  
  53. n.loss = L.Python(n.ipx, n.ipy,python_param=dict(module='pyloss',layer='EuclideanLossLayer'),
  54. loss_weight=1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement