簡體   English   中英

Caffe python層backword傳遞實現

[英]Caffe python layer backword pass implementation

我正在編寫一個caffe python層,該層轉售沿着特定軸[附加代碼]的[0 255]與正向傳遞之間的輸入正常。 該層是否需要向后傳遞? 如果是這樣,我該如何實施?

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

如果您願意忽略np.around ,則您的函數非常簡單:

在此處輸入圖片說明

對於x=x_min和對於x=x_max ,導數為零,對於所有其他x ,導數為255/(x_max-x_min)

這可以通過以下方式實現

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

不要忘記進行數字測試。 例如,可以使用test_gradient_for_python_layer來完成。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM