Class: DNN::Layers::MaxPool2D

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

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Layer

#built?, #prev_layer

Constructor Details

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

Returns a new instance of MaxPool2D.



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

def initialize(pool_size, strides: nil, padding: false)
  super()
  @pool_size = pool_size.is_a?(Integer) ? [pool_size, pool_size] : pool_size
  @strides = if strides
    strides.is_a?(Integer) ? [strides, strides] : strides
  else
    @pool_size.clone
  end
  @padding = padding
end

Class Method Details

.load_hash(hash) ⇒ Object



326
327
328
# File 'lib/dnn/core/layers.rb', line 326

def self.load_hash(hash)
  MaxPool2D.new(hash[:pool_size], strides: hash[:strides], padding: hash[:padding])
end

Instance Method Details

#backward(dout) ⇒ Object



351
352
353
354
355
356
357
# File 'lib/dnn/core/layers.rb', line 351

def backward(dout)
  dmax = SFloat.zeros(dout.size * @pool_size.reduce(:*))
  dmax[@max_index] = dout.flatten
  dcol = dmax.reshape(dout.shape[0..2].reduce(:*), dout.shape[3] * @pool_size.reduce(:*))
  dx = col2im(dcol, @x_shape, *@out_size, *@pool_size, @strides)
  @padding ? back_padding(dx, @pad) : dx
end

#build(model) ⇒ Object



330
331
332
333
334
335
336
337
338
339
340
# File 'lib/dnn/core/layers.rb', line 330

def build(model)
  super
  prev_w, prev_h = prev_layer.shape[0..1]
  @num_channel = prev_layer.shape[2]
  @out_size = out_size(prev_w, prev_h, *@pool_size, @strides)
  out_w, out_h = @out_size
  if @padding
    @pad = [prev_w - out_w, prev_h - out_h]
    @out_size = [prev_w, prev_h]
  end
end

#forward(x) ⇒ Object



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

def forward(x)
  x = padding(x, @pad) if @padding
  @x_shape = x.shape
  col = im2col(x, *@out_size, *@pool_size, @strides)
  col = col.reshape(x.shape[0] * @out_size.reduce(:*) * x.shape[3], @pool_size.reduce(:*))
  @max_index = col.max_index(1)
  col.max(1).reshape(x.shape[0], *@out_size, x.shape[3])
end

#shape ⇒ Object



359
360
361
# File 'lib/dnn/core/layers.rb', line 359

def shape
  [*@out_size, @num_channel]
end

#to_hash ⇒ Object



363
364
365
366
367
368
369
370
371
# File 'lib/dnn/core/layers.rb', line 363

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