Class: DNN::Layers::MaxPool2D

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

Instance Method Summary collapse

Methods inherited from Layer

#builded?, #prev_layer

Constructor Details

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

Returns a new instance of MaxPool2D.



316
317
318
319
320
321
# File 'lib/dnn/core/layers.rb', line 316

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

Instance Method Details

#backward(dout) ⇒ Object



344
345
346
347
348
349
350
351
# File 'lib/dnn/core/layers.rb', line 344

def backward(dout)
  pool_size = @pool_width * @pool_height
  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)
  dx = col2im(dcol, @x_shape, @out_width, @out_height, @pool_width, @pool_height, @strides)
  @padding ? back_padding(dx, @pad) : dx
end

#build(model) ⇒ Object



323
324
325
326
327
328
329
330
331
332
333
# File 'lib/dnn/core/layers.rb', line 323

def build(model)
  super
  prev_width, prev_height = prev_layer.shape[0..1]
  @num_channel = prev_layer.shape[2]
  @out_width, @out_height = out_size(prev_width, prev_height, @pool_width, @pool_height, @strides)
  if @padding
    @pad = [prev_width - @out_width, prev_height - @out_height]
    @out_width = prev_width
    @out_height = prev_height
  end
end

#forward(x) ⇒ Object



335
336
337
338
339
340
341
342
# File 'lib/dnn/core/layers.rb', line 335

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

#shapeObject



353
354
355
# File 'lib/dnn/core/layers.rb', line 353

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

#to_hashObject



357
358
359
360
361
362
363
364
365
# File 'lib/dnn/core/layers.rb', line 357

def to_hash
  {
    name: self.class.name,
    pool_width: @pool_width,
    pool_height: @pool_height,
    strides: @strides,
    padding: @padding,
  }
end