Class: DNN::Layers::MaxPool2D

Inherits:
Layer
  • Object
show all
Includes:
Convert
Defined in:
lib/dnn/core/layers.rb

Instance Method Summary collapse

Methods included from Convert

#col2im, #im2col, #padding

Methods inherited from Layer

#prev_layer

Constructor Details

#initialize(pool_height, pool_width, strides: nil, padding: 0) ⇒ MaxPool2D



229
230
231
232
233
234
# File 'lib/dnn/core/layers.rb', line 229

def initialize(pool_height, pool_width, strides: nil, padding: 0)
  @pool_height = pool_height
  @pool_width = pool_width
  @strides = strides ? strides : [@pool_height, @pool_width]
  @padding = padding
end

Instance Method Details

#backward(dout) ⇒ Object



252
253
254
255
256
257
258
259
# File 'lib/dnn/core/layers.rb', line 252

def backward(dout)
  dout = dout.transpose(0, 2, 3, 1)
  pool_size = @pool_height * @pool_width
  dmax = SFloat.zeros(dout.size * pool_size)
  dmax[@max_index] = dout.flatten
  dcol = dmax.reshape(dout.shape[0..2].reduce(:*), dout.shape[3] * pool_size)
  col2im(dcol, @x_shape, @out_height, @out_width, @pool_height, @pool_width, @strides)
end

#forward(x) ⇒ Object



244
245
246
247
248
249
250
# File 'lib/dnn/core/layers.rb', line 244

def forward(x)
  @x_shape = x.shape
  col = im2col(x, @out_height, @out_width, @pool_height, @pool_width, @strides)
  col = col.reshape(x.shape[0] * @out_height * @out_width * x.shape[1], @pool_height * @pool_width)
  @max_index = col.max_index(1)
  col.max(1).reshape(x.shape[0], @out_height, @out_width, x.shape[1]).transpose(0, 3, 1, 2)
end

#init(model) ⇒ Object



236
237
238
239
240
241
242
# File 'lib/dnn/core/layers.rb', line 236

def init(model)
  super
  prev_height, prev_width = prev_layer.shape[1], prev_layer.shape[2]
  @num_channel = prev_layer.shape[0]
  @out_height = (prev_height - @pool_height) / @strides[0] + 1
  @out_width = (prev_width - @pool_width) / @strides[1] + 1
end

#shapeObject



261
262
263
# File 'lib/dnn/core/layers.rb', line 261

def shape
  [@num_channel, @out_height, @out_width]
end